-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
gc.c
2629 lines (2378 loc) · 79.2 KB
/
gc.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
// This file is a part of Julia. License is MIT: http://julialang.org/license
/*
allocation and garbage collection
. non-moving, precise mark and sweep collector
. pool-allocates small objects, keeps big objects on a simple list
*/
// use mmap instead of malloc to allocate pages. default = off.
//#define USE_MMAP
// free pages as soon as they are empty. if not defined, then we
// will wait for the next GC, to allow the space to be reused more
// efficiently. default = on.
#define FREE_PAGES_EAGER
#include <stdlib.h>
#include <string.h>
#ifndef _MSC_VER
#include <strings.h>
#endif
#include <assert.h>
#include <inttypes.h>
#include "julia.h"
#include "julia_internal.h"
#ifndef _OS_WINDOWS_
#include <sys/mman.h>
#ifdef _OS_DARWIN_
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
// manipulating mark bits
#define GC_CLEAN 0 // freshly allocated
#define GC_MARKED 1 // reachable and old
#define GC_QUEUED 2 // if it is reachable it will be marked as old
#define GC_MARKED_NOESC (GC_MARKED | GC_QUEUED) // reachable and young
#define jl_valueof(v) (&((jl_taggedvalue_t*)(v))->value)
// This struct must be kept in sync with the Julia type of the same name in base/util.jl
typedef struct {
int64_t allocd;
int64_t freed;
uint64_t malloc;
uint64_t realloc;
uint64_t poolalloc;
uint64_t bigalloc;
uint64_t freecall;
uint64_t total_time;
uint64_t total_allocd;
uint64_t since_sweep;
size_t collect;
int pause;
int full_sweep;
} GC_Num;
static GC_Num gc_num = {0,0,0,0,0,0,0,0,0,0,0,0,0};
#define collect_interval gc_num.collect
#define n_pause gc_num.pause
#define n_full_sweep gc_num.full_sweep
#define allocd_bytes gc_num.allocd
#define freed_bytes gc_num.freed
#define total_gc_time gc_num.total_time
#define total_allocd_bytes gc_num.total_allocd
#define allocd_bytes_since_sweep gc_num.since_sweep
typedef struct _buff_t {
union {
uintptr_t header;
struct _buff_t *next;
uptrint_t flags;
jl_value_t *type; // 16-bytes aligned
struct {
uintptr_t gc_bits:2;
uintptr_t pooled:1;
};
};
// Work around a bug affecting gcc up to (at least) version 4.4.7
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36839
#if !defined(_COMPILER_MICROSOFT_)
int _dummy[0];
#endif
char data[];
} buff_t;
typedef buff_t gcval_t;
// layout for big (>2k) objects
typedef struct _bigval_t {
struct _bigval_t *next;
struct _bigval_t **prev; // pointer to the next field of the prev entry
union {
size_t sz;
uptrint_t age : 2;
};
//struct buff_t <>;
union {
uptrint_t header;
uptrint_t flags;
uptrint_t gc_bits:2;
};
// Work around a bug affecting gcc up to (at least) version 4.4.7
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36839
#if !defined(_COMPILER_MICROSOFT_)
int _dummy[0];
#endif
// must be 16-aligned here, in 32 & 64b
char data[];
} bigval_t;
#define bigval_header(data) container_of((data), bigval_t, header)
// data structure for tracking malloc'd arrays.
typedef struct _mallocarray_t {
jl_array_t *a;
struct _mallocarray_t *next;
} mallocarray_t;
typedef struct _pool_t {
gcval_t *freelist; // root of list of free objects
gcval_t *newpages; // root of list of chunks of free objects
uint16_t end_offset; // stored to avoid computing it at each allocation
uint16_t osize; // size of objects in this pool
uint16_t nfree; // number of free objects in page pointed into by free_list
} pool_t;
// layout for small (<2k) objects
#define GC_PAGE_LG2 14 // log2(size of a page)
#define GC_PAGE_SZ (1 << GC_PAGE_LG2) // 16k
#define GC_PAGE_OFFSET (16 - (sizeof_jl_taggedvalue_t % 16))
// pool page metadata
typedef struct _gcpage_t {
struct {
uint16_t pool_n : 8; // index (into norm_pool) of pool that owns this page
uint16_t allocd : 1; // true if an allocation happened in this page since last sweep
uint16_t gc_bits : 2; // this is a bitwise | of all gc_bits in this page
};
uint16_t nfree; // number of free objects in this page.
// invalid if pool that owns this page is allocating objects from this page.
uint16_t osize; // size of each object in this page
uint16_t fl_begin_offset; // offset of first free object in this page
uint16_t fl_end_offset; // offset of last free object in this page
char *data;
uint8_t *ages;
} gcpage_t;
#define PAGE_PFL_BEG(p) ((gcval_t**)((p->data) + (p)->fl_begin_offset))
#define PAGE_PFL_END(p) ((gcval_t**)((p->data) + (p)->fl_end_offset))
// round an address inside a gcpage's data to its beginning
#define GC_PAGE_DATA(x) ((char*)((uintptr_t)(x) >> GC_PAGE_LG2 << GC_PAGE_LG2))
// A region is contiguous storage for up to REGION_PG_COUNT naturally aligned GC_PAGE_SZ pages
// It uses a very naive allocator (see malloc_page & free_page)
#if defined(_P64) && !defined(_COMPILER_MICROSOFT_)
#define REGION_PG_COUNT 16*8*4096 // 8G because virtual memory is cheap
#else
#define REGION_PG_COUNT 8*4096 // 512M
#endif
#define REGION_COUNT 8
typedef struct {
// Page layout:
// Padding: GC_PAGE_OFFSET
// Blocks: osize * n
// Tag: sizeof_jl_taggedvalue_t
// Data: <= osize - sizeof_jl_taggedvalue_t
char pages[REGION_PG_COUNT][GC_PAGE_SZ]; // must be first, to preserve page alignment
uint32_t freemap[REGION_PG_COUNT/32];
gcpage_t meta[REGION_PG_COUNT];
} region_t
#ifndef _COMPILER_MICROSOFT_
__attribute__((aligned(GC_PAGE_SZ)))
#endif
;
static region_t *regions[REGION_COUNT] = {NULL};
// store a lower bound of the first free page in each region
static int regions_lb[REGION_COUNT] = {0};
// an upper bound of the last non-free page
static int regions_ub[REGION_COUNT] = {REGION_PG_COUNT/32-1};
// Variables that become fields of a thread-local struct in the thread-safe
// version.
#define HEAP_DECL static
// variable for tracking preserved values.
HEAP_DECL arraylist_t preserved_values;
// variable for tracking weak references
HEAP_DECL arraylist_t weak_refs;
// variables for tracking malloc'd arrays
HEAP_DECL mallocarray_t *mallocarrays;
HEAP_DECL mallocarray_t *mafreelist;
// variables for tracking big objects
HEAP_DECL bigval_t *big_objects;
// variables for tracking "remembered set"
HEAP_DECL arraylist_t rem_bindings;
HEAP_DECL arraylist_t _remset[2]; // contains jl_value_t*
HEAP_DECL arraylist_t *remset;
HEAP_DECL arraylist_t *last_remset;
// variables for allocating objects from pools
#ifdef _P64
#define N_POOLS 41
#else
#define N_POOLS 43
#endif
HEAP_DECL pool_t norm_pools[N_POOLS];
// End of Variables that become fields of a thread-local struct in the thread-safe version.
// The following macros are used for accessing these variables.
// In the future multi-threaded version, they establish the desired thread context.
// In the single-threaded version, they are essentially noops, but nonetheless
// serve to check that the thread context macros are being used.
#define FOR_CURRENT_HEAP {void *current_heap=NULL;
#define END }
#define FOR_EACH_HEAP {void *current_heap=NULL;
/*}*/
#define HEAP(x) (*((void)current_heap,&(x)))
#define preserved_values HEAP(preserved_values)
#define weak_refs HEAP(weak_refs)
#define big_objects HEAP(big_objects)
#define mallocarrays HEAP(mallocarrays)
#define mafreelist HEAP(mafreelist)
#define remset HEAP(remset)
#define last_remset HEAP(last_remset)
#define rem_bindings HEAP(rem_bindings)
#define pools norm_pools
// List of marked big objects. Not per-thread. Accessed only by master thread.
static bigval_t *big_objects_marked = NULL;
// finalization
static arraylist_t finalizer_list;
static arraylist_t finalizer_list_marked;
static arraylist_t to_finalize;
static int check_timeout = 0;
#define should_timeout() 0
#define gc_bits(o) (((gcval_t*)(o))->gc_bits)
#define gc_marked(o) (((gcval_t*)(o))->gc_bits & GC_MARKED)
#define _gc_setmark(o, mark_mode) (((gcval_t*)(o))->gc_bits = mark_mode)
static gcpage_t *page_metadata(void *data);
static void pre_mark(void);
static void post_mark(arraylist_t *list, int dryrun);
static region_t *find_region(void *ptr, int maybe);
#define PAGE_INDEX(region, data) \
((GC_PAGE_DATA((data) - GC_PAGE_OFFSET) - \
&(region)->pages[0][0])/GC_PAGE_SZ)
NOINLINE static uintptr_t gc_get_stack_ptr()
{
void *dummy = NULL;
// The mask is to suppress the compiler warning about returning
// address of local variable
return (uintptr_t)&dummy & ~(uintptr_t)15;
}
#include "gc-debug.c"
int jl_in_gc; // referenced from switchto task.c
static int jl_gc_finalizers_inhibited; // don't run finalizers during codegen #11956
// malloc wrappers, aligned allocation
#if defined(_P64) || defined(__APPLE__)
#define malloc_a16(sz) malloc(sz)
#define realloc_a16(p, sz, oldsz) realloc((p), (sz))
#define free_a16(p) free(p)
#elif defined(_OS_WINDOWS_) /* 32-bit OS is implicit here. */
#define malloc_a16(sz) _aligned_malloc((sz)?(sz):1, 16)
#define realloc_a16(p, sz, oldsz) _aligned_realloc((p), (sz)?(sz):1, 16)
#define free_a16(p) _aligned_free(p)
#else
static inline void *malloc_a16(size_t sz)
{
void *ptr;
if (posix_memalign(&ptr, 16, sz))
return NULL;
return ptr;
}
static inline void *realloc_a16(void *d, size_t sz, size_t oldsz)
{
void *b = malloc_a16(sz);
if (b != NULL) {
memcpy(b, d, oldsz);
free(d);
}
return b;
}
#define free_a16(p) free(p)
#endif
static void schedule_finalization(void *o, void *f)
{
arraylist_push(&to_finalize, o);
arraylist_push(&to_finalize, f);
}
static void run_finalizer(jl_value_t *o, jl_value_t *ff)
{
jl_function_t *f = (jl_function_t*)ff;
assert(jl_is_function(f));
JL_TRY {
jl_apply(f, (jl_value_t**)&o, 1);
}
JL_CATCH {
jl_printf(JL_STDERR, "error in running finalizer: ");
jl_static_show(JL_STDERR, jl_exception_in_transit);
jl_printf(JL_STDERR, "\n");
}
}
static int finalize_object(jl_value_t *o)
{
int success = 0;
jl_value_t *f = NULL;
JL_GC_PUSH1(&f);
for(int i = 0; i < finalizer_list.len; i+=2) {
if (o == (jl_value_t*)finalizer_list.items[i]) {
f = (jl_value_t*)finalizer_list.items[i+1];
if (i < finalizer_list.len - 2) {
finalizer_list.items[i] = finalizer_list.items[finalizer_list.len-2];
finalizer_list.items[i+1] = finalizer_list.items[finalizer_list.len-1];
i -= 2;
}
finalizer_list.len -= 2;
run_finalizer(o, f);
success = 1;
}
}
JL_GC_POP();
return success;
}
static void run_finalizers(void)
{
void *o = NULL, *f = NULL;
JL_GC_PUSH2(&o, &f);
while (to_finalize.len > 0) {
f = arraylist_pop(&to_finalize);
o = arraylist_pop(&to_finalize);
run_finalizer((jl_value_t*)o, (jl_value_t*)f);
}
JL_GC_POP();
}
void jl_gc_inhibit_finalizers(int state)
{
if (jl_gc_finalizers_inhibited && !state && !jl_in_gc) {
jl_in_gc = 1;
run_finalizers();
jl_in_gc = 0;
}
jl_gc_finalizers_inhibited = state;
}
static void schedule_all_finalizers(arraylist_t* flist)
{
// Multi-thread version should steal the entire list while holding a lock.
for(size_t i=0; i < flist->len; i+=2) {
jl_value_t *f = (jl_value_t*)flist->items[i+1];
if (f != HT_NOTFOUND && !jl_is_cpointer(f)) {
schedule_finalization(flist->items[i], flist->items[i+1]);
}
}
flist->len = 0;
}
void jl_gc_run_all_finalizers(void)
{
schedule_all_finalizers(&finalizer_list);
schedule_all_finalizers(&finalizer_list_marked);
run_finalizers();
}
DLLEXPORT void jl_gc_add_finalizer(jl_value_t *v, jl_function_t *f)
{
arraylist_push(&finalizer_list, (void*)v);
arraylist_push(&finalizer_list, (void*)f);
}
void jl_finalize(jl_value_t *o)
{
(void)finalize_object(o);
}
static region_t *find_region(void *ptr, int maybe)
{
// on 64bit systems we could probably use a single region and remove this loop
for (int i = 0; i < REGION_COUNT && regions[i]; i++) {
char *begin = ®ions[i]->pages[0][0];
char *end = begin + sizeof(regions[i]->pages);
if ((char*)ptr >= begin && (char*)ptr <= end)
return regions[i];
}
(void)maybe;
assert(maybe && "find_region failed");
return NULL;
}
static gcpage_t *page_metadata(void *data)
{
region_t *r = find_region(data, 0);
int pg_idx = PAGE_INDEX(r, (char*)data);
return &r->meta[pg_idx];
}
static uint8_t *page_age(gcpage_t *pg)
{
return pg->ages;
}
#define GC_POOL_END_OFS(osize) ((((GC_PAGE_SZ - GC_PAGE_OFFSET)/(osize)) - 1)*(osize) + GC_PAGE_OFFSET)
// GC knobs and self-measurement variables
static int64_t last_gc_total_bytes = 0;
static int gc_inc_steps = 1;
#ifdef _P64
#define default_collect_interval (5600*1024*sizeof(void*))
static size_t max_collect_interval = 1250000000UL;
#else
#define default_collect_interval (3200*1024*sizeof(void*))
static size_t max_collect_interval = 500000000UL;
#endif
// global variables for GC stats
#define NS_TO_S(t) ((double)(t/1000)/(1000*1000))
#define NS2MS(t) ((double)(t/1000)/1000)
static int64_t live_bytes = 0;
static int64_t promoted_bytes = 0;
static size_t current_pg_count = 0;
static size_t max_pg_count = 0;
#ifdef OBJPROFILE
static htable_t obj_counts[3];
static htable_t obj_sizes[3];
#endif
#ifdef GC_FINAL_STATS
static size_t total_freed_bytes = 0;
static uint64_t max_pause = 0;
static uint64_t total_sweep_time = 0;
static uint64_t total_mark_time = 0;
static uint64_t total_fin_time = 0;
#endif
int sweeping = 0;
/*
* The state transition looks like :
*
* ([(quick)sweep] means either a sweep or a quicksweep)
*
* <-[(quick)sweep]-
* |
* ---> GC_QUEUED <--[(quick)sweep && age>promotion]--
* | | ^ |
* | [mark] | |
* [sweep] | [write barrier] |
* | v | |
* ----- GC_MARKED <-------- |
* | | |
* --[quicksweep]-- |
* |
* ========= above this line objects are old ========= |
* |
* ----[new]------> GC_CLEAN ------[mark]--------> GC_MARKED_NOESC
* | ^ |
* <-[(quick)sweep]--- | |
* --[(quick)sweep && age<=promotion]---
*/
// A quick sweep is a sweep where sweep_mask == GC_MARKED_NOESC.
// It means we won't touch GC_MARKED objects (old gen).
// When a reachable object has survived more than PROMOTE_AGE+1 collections
// it is tagged with GC_QUEUED during sweep and will be promoted on next mark
// because at that point we can know easily if it references young objects.
// Marked old objects that reference young ones are kept in the remset.
// When a write barrier triggers, the offending marked object is both queued,
// so as not to trigger the barrier again, and put in the remset.
#define PROMOTE_AGE 1
// this cannot be increased as is without changing :
// - sweep_page which is specialized for 1bit age
// - the size of the age storage in region_t
static int64_t scanned_bytes; // young bytes scanned while marking
static int64_t perm_scanned_bytes; // old bytes scanned while marking
static int prev_sweep_mask = GC_MARKED;
static size_t scanned_bytes_goal;
#ifdef OBJPROFILE
static void *BUFFTY = (void*)0xdeadb00f;
#endif
static void *MATY = (void*)0xdeadaa01;
static size_t array_nbytes(jl_array_t*);
static inline void objprofile_count(void* ty, int old, int sz)
{
#ifdef OBJPROFILE
#ifdef GC_VERIFY
if (verifying) return;
#endif
if ((intptr_t)ty <= 0x10)
ty = BUFFTY;
void **bp = ptrhash_bp(&obj_counts[old], ty);
if (*bp == HT_NOTFOUND)
*bp = (void*)2;
else
(*((ptrint_t*)bp))++;
bp = ptrhash_bp(&obj_sizes[old], ty);
if (*bp == HT_NOTFOUND)
*bp = (void*)(1 + sz);
else
*((ptrint_t*)bp) += sz;
#endif
}
//static inline void gc_setmark_other(jl_value_t *v, int mark_mode) // unused function
//{
// jl_taggedvalue_t *o = jl_astaggedvalue(v);
// _gc_setmark(o, mark_mode);
// verify_val(o);
//}
#define inc_sat(v,s) v = (v) >= s ? s : (v)+1
static inline int gc_setmark_big(void *o, int mark_mode)
{
#ifdef GC_VERIFY
if (verifying) {
_gc_setmark(o, mark_mode);
return 0;
}
#endif
bigval_t* hdr = bigval_header(o);
int bits = gc_bits(o);
if (bits == GC_QUEUED || bits == GC_MARKED)
mark_mode = GC_MARKED;
if ((mark_mode == GC_MARKED) & (bits != GC_MARKED)) {
// Move hdr from big_objects list to big_objects_marked list
*hdr->prev = hdr->next;
if (hdr->next)
hdr->next->prev = hdr->prev;
hdr->next = big_objects_marked;
hdr->prev = &big_objects_marked;
if (big_objects_marked)
big_objects_marked->prev = &hdr->next;
big_objects_marked = hdr;
}
if (!(bits & GC_MARKED)) {
if (mark_mode == GC_MARKED)
perm_scanned_bytes += hdr->sz&~3;
else
scanned_bytes += hdr->sz&~3;
#ifdef OBJPROFILE
objprofile_count(jl_typeof(o), mark_mode == GC_MARKED, hdr->sz&~3);
#endif
}
_gc_setmark(o, mark_mode);
verify_val(jl_valueof(o));
return mark_mode;
}
static inline int gc_setmark_pool(void *o, int mark_mode)
{
#ifdef GC_VERIFY
if (verifying) {
_gc_setmark(o, mark_mode);
return mark_mode;
}
#endif
gcpage_t* page = page_metadata(o);
int bits = gc_bits(o);
if (bits == GC_QUEUED || bits == GC_MARKED) {
mark_mode = GC_MARKED;
}
if (!(bits & GC_MARKED)) {
if (mark_mode == GC_MARKED)
perm_scanned_bytes += page->osize;
else
scanned_bytes += page->osize;
#ifdef OBJPROFILE
objprofile_count(jl_typeof(o), mark_mode == GC_MARKED, page->osize);
#endif
}
_gc_setmark(o, mark_mode);
page->gc_bits |= mark_mode;
verify_val(jl_valueof(o));
return mark_mode;
}
static inline int gc_setmark(jl_value_t *v, int sz, int mark_mode)
{
jl_taggedvalue_t *o = jl_astaggedvalue(v);
sz += sizeof_jl_taggedvalue_t;
#ifdef MEMDEBUG
return gc_setmark_big(o, mark_mode);
#endif
if (sz <= GC_MAX_SZCLASS + sizeof(buff_t))
return gc_setmark_pool(o, mark_mode);
else
return gc_setmark_big(o, mark_mode);
}
#define gc_typeof(v) jl_typeof(v)
#define gc_val_buf(o) ((buff_t*)(((void**)(o))-1))
inline void gc_setmark_buf(void *o, int mark_mode)
{
buff_t *buf = gc_val_buf(o);
#ifdef MEMDEBUG
gc_setmark_big(buf, mark_mode);
return;
#endif
if (buf->pooled)
gc_setmark_pool(buf, mark_mode);
else
gc_setmark_big(buf, mark_mode);
}
static NOINLINE void *malloc_page(void)
{
void *ptr = (void*)0;
int i;
region_t* region;
int region_i = 0;
while(region_i < REGION_COUNT) {
region = regions[region_i];
if (region == NULL) {
size_t alloc_size = sizeof(region_t);
#ifdef _OS_WINDOWS_
char* mem = (char*)VirtualAlloc(NULL, sizeof(region_t) + GC_PAGE_SZ, MEM_RESERVE, PAGE_READWRITE);
#else
if (GC_PAGE_SZ > jl_page_size)
alloc_size += GC_PAGE_SZ;
char* mem = (char*)mmap(0, alloc_size, PROT_READ | PROT_WRITE, MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
mem = mem == MAP_FAILED ? NULL : mem;
#endif
if (mem == NULL) {
jl_printf(JL_STDERR, "could not allocate pools\n");
abort();
}
if (GC_PAGE_SZ > jl_page_size) {
// round data pointer up to the nearest GC_PAGE_DATA-aligned boundary
// if mmap didn't already do so
alloc_size += GC_PAGE_SZ;
region = (region_t*)((char*)GC_PAGE_DATA(mem + GC_PAGE_SZ - 1));
}
else {
region = (region_t*)mem;
}
#ifdef _OS_WINDOWS_
VirtualAlloc(region->freemap, REGION_PG_COUNT/8, MEM_COMMIT, PAGE_READWRITE);
VirtualAlloc(region->meta, REGION_PG_COUNT*sizeof(gcpage_t), MEM_COMMIT, PAGE_READWRITE);
#endif
memset(region->freemap, 0xff, REGION_PG_COUNT/8);
regions[region_i] = region;
}
for(i = regions_lb[region_i]; i < REGION_PG_COUNT/32; i++) {
if (region->freemap[i]) break;
}
if (i == REGION_PG_COUNT/32) {
// region full
region_i++;
continue;
}
break;
}
if (region_i >= REGION_COUNT) {
jl_printf(JL_STDERR, "increase REGION_COUNT or allocate less memory\n");
abort();
}
if (regions_lb[region_i] < i)
regions_lb[region_i] = i;
if (regions_ub[region_i] < i)
regions_ub[region_i] = i;
#if defined(_COMPILER_MINGW_)
int j = __builtin_ffs(region->freemap[i]) - 1;
#elif defined(_COMPILER_MICROSOFT_)
unsigned long j;
_BitScanForward(&j, region->freemap[i]);
#else
int j = ffs(region->freemap[i]) - 1;
#endif
region->freemap[i] &= ~(uint32_t)(1 << j);
ptr = region->pages[i*32 + j];
#ifdef _OS_WINDOWS_
VirtualAlloc(ptr, GC_PAGE_SZ, MEM_COMMIT, PAGE_READWRITE);
#endif
current_pg_count++;
max_pg_count = max_pg_count < current_pg_count ? current_pg_count : max_pg_count;
return ptr;
}
static void free_page(void *p)
{
int pg_idx = -1;
int i;
for(i = 0; i < REGION_COUNT && regions[i] != NULL; i++) {
pg_idx = PAGE_INDEX(regions[i], (char*)p+GC_PAGE_OFFSET);
if (pg_idx >= 0 && pg_idx < REGION_PG_COUNT) break;
}
assert(i < REGION_COUNT && regions[i] != NULL);
region_t *region = regions[i];
uint32_t msk = (uint32_t)(1 << ((pg_idx % 32)));
assert(!(region->freemap[pg_idx/32] & msk));
region->freemap[pg_idx/32] ^= msk;
free(region->meta[pg_idx].ages);
// tell the OS we don't need these pages right now
size_t decommit_size = GC_PAGE_SZ;
if (GC_PAGE_SZ < jl_page_size) {
// ensure so we don't release more memory than intended
size_t n_pages = (GC_PAGE_SZ + jl_page_size - 1) / GC_PAGE_SZ;
decommit_size = jl_page_size;
p = (void*)((uintptr_t)®ion->pages[pg_idx][0] & ~(jl_page_size - 1)); // round down to the nearest page
pg_idx = PAGE_INDEX(region, (char*)p+GC_PAGE_OFFSET);
if (pg_idx + n_pages > REGION_PG_COUNT) goto no_decommit;
for (; n_pages--; pg_idx++) {
msk = (uint32_t)(1 << ((pg_idx % 32)));
if (!(region->freemap[pg_idx/32] & msk)) goto no_decommit;
}
}
#ifdef _OS_WINDOWS_
VirtualFree(p, decommit_size, MEM_DECOMMIT);
#else
madvise(p, decommit_size, MADV_DONTNEED);
#endif
no_decommit:
if (regions_lb[i] > pg_idx/32) regions_lb[i] = pg_idx/32;
current_pg_count--;
}
#define should_collect() (__unlikely(allocd_bytes>0))
static inline int maybe_collect(void)
{
if (should_collect() || gc_debug_check_other()) {
jl_gc_collect(0);
return 1;
}
return 0;
}
// preserved values
DLLEXPORT int jl_gc_n_preserved_values(void)
{
FOR_CURRENT_HEAP
return preserved_values.len;
END
}
DLLEXPORT void jl_gc_preserve(jl_value_t *v)
{
FOR_CURRENT_HEAP
arraylist_push(&preserved_values, (void*)v);
END
}
DLLEXPORT void jl_gc_unpreserve(void)
{
FOR_CURRENT_HEAP
(void)arraylist_pop(&preserved_values);
END
}
// weak references
DLLEXPORT jl_weakref_t *jl_gc_new_weakref(jl_value_t *value)
{
jl_weakref_t *wr = (jl_weakref_t*)jl_gc_alloc_1w();
jl_set_typeof(wr, jl_weakref_type);
wr->value = value;
FOR_CURRENT_HEAP
arraylist_push(&weak_refs, wr);
END
return wr;
}
static void sweep_weak_refs(void)
{
FOR_EACH_HEAP
size_t n=0, ndel=0, l=weak_refs.len;
jl_weakref_t *wr;
void **lst = weak_refs.items;
void *tmp;
#define SWAP_wr(a,b) (tmp=a,a=b,b=tmp,1)
if (l == 0)
return;
do {
wr = (jl_weakref_t*)lst[n];
if (gc_marked(jl_astaggedvalue(wr))) {
// weakref itself is alive
if (!gc_marked(jl_astaggedvalue(wr->value)))
wr->value = (jl_value_t*)jl_nothing;
n++;
}
else {
ndel++;
}
} while ((n < l-ndel) && SWAP_wr(lst[n],lst[n+ndel]));
weak_refs.len -= ndel;
END
}
// big value list
static NOINLINE void *alloc_big(size_t sz)
{
maybe_collect();
size_t offs = offsetof(bigval_t, header);
size_t allocsz = LLT_ALIGN(sz + offs, 16);
if (allocsz < sz) // overflow in adding offs, size was "negative"
jl_throw(jl_memory_exception);
bigval_t *v = (bigval_t*)malloc_a16(allocsz);
if (v == NULL)
jl_throw(jl_memory_exception);
allocd_bytes += allocsz;
gc_num.bigalloc++;
#ifdef MEMDEBUG
memset(v, 0xee, allocsz);
#endif
v->sz = allocsz;
v->flags = 0;
v->age = 0;
FOR_CURRENT_HEAP
v->next = big_objects;
v->prev = &big_objects;
if (v->next)
v->next->prev = &v->next;
big_objects = v;
END
return (void*)&v->header;
}
static int big_total;
static int big_freed;
static int big_reset;
// Sweep list rooted at *pv, removing and freeing any unmarked objects.
// Return pointer to last `next` field in the culled list.
static bigval_t** sweep_big_list(int sweep_mask, bigval_t** pv)
{
bigval_t *v = *pv;
while (v != NULL) {
bigval_t *nxt = v->next;
if (gc_marked(&v->header)) {
pv = &v->next;
int age = v->age;
int bits = gc_bits(&v->header);
if (age >= PROMOTE_AGE) {
if (sweep_mask == GC_MARKED || bits == GC_MARKED_NOESC) {
bits = GC_QUEUED;
}
}
else {
inc_sat(age, PROMOTE_AGE);
v->age = age;
if ((sweep_mask & bits) == sweep_mask) {
bits = GC_CLEAN;
big_reset++;
}
}
gc_bits(&v->header) = bits;
}
else {
// Remove v from list and free it
*pv = nxt;
if (nxt)
nxt->prev = pv;
freed_bytes += v->sz&~3;
#ifdef MEMDEBUG
memset(v, 0xbb, v->sz&~3);
#endif
free_a16(v);
big_freed++;
}
big_total++;
v = nxt;
}
return pv;
}
static void sweep_big(int sweep_mask)
{
FOR_EACH_HEAP
sweep_big_list(sweep_mask, &big_objects);
END
if (sweep_mask == GC_MARKED) {
bigval_t** last_next = sweep_big_list(sweep_mask, &big_objects_marked);
// Move all survivors from big_objects_marked list to big_objects list.
FOR_CURRENT_HEAP
if (big_objects)
big_objects->prev = last_next;
*last_next = big_objects;
big_objects = big_objects_marked;
if (big_objects)
big_objects->prev = &big_objects;
END
big_objects_marked = NULL;
}
}
// tracking Arrays with malloc'd storage
void jl_gc_track_malloced_array(jl_array_t *a)
{
FOR_CURRENT_HEAP
mallocarray_t *ma;
if (mafreelist == NULL) {
ma = (mallocarray_t*)malloc(sizeof(mallocarray_t));
}
else {
ma = mafreelist;
mafreelist = ma->next;
}
ma->a = a;
ma->next = mallocarrays;
mallocarrays = ma;
END
}
void jl_gc_count_allocd(size_t sz)
{
allocd_bytes += sz;
}
static size_t array_nbytes(jl_array_t *a)
{
size_t sz = 0;
if (jl_array_ndims(a)==1)
sz = a->elsize * a->maxsize + (a->elsize == 1 ? 1 : 0);
else
sz = a->elsize * jl_array_len(a);
return sz;
}
void jl_gc_free_array(jl_array_t *a)
{
if (a->how == 2) {
char *d = (char*)a->data - a->offset*a->elsize;
if (a->isaligned)
free_a16(d);
else
free(d);
freed_bytes += array_nbytes(a);
}
}
static int mallocd_array_total;
static int mallocd_array_freed;
static void sweep_malloced_arrays(void)
{
FOR_EACH_HEAP
mallocarray_t *ma = mallocarrays;
mallocarray_t **pma = &mallocarrays;
while (ma != NULL) {
mallocarray_t *nxt = ma->next;
if (gc_marked(jl_astaggedvalue(ma->a))) {
pma = &ma->next;
}
else {
*pma = nxt;
assert(ma->a->how == 2);
jl_gc_free_array(ma->a);
ma->next = mafreelist;
mafreelist = ma;