-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
gc.c
2910 lines (2756 loc) · 91.6 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
/**
* Cyclone Scheme
* https://github.com/justinethier/cyclone
*
* Copyright (c) 2015-2016, Justin Ethier
* All rights reserved.
*
* Heap garbage collector used by the Cyclone runtime for major collections.
*
* Concurrent Mark-Sweep GC algorithm is based on the one from
* "Implementing an on-the-fly garbage collector for Java", by Domani et al.
*
* Data structures for the heap implementation are based on code from Chibi Scheme.
*
* Note there is also a minor GC (in runtime.c) that collects objects allocated
* on the stack, based on "Cheney on the MTA".
*/
#include <ck_array.h>
#include <ck_pr.h>
#include "cyclone/types.h"
#include <stdint.h>
#include <time.h>
//#define DEBUG_THREADS // Debugging!!!
#ifdef DEBUG_THREADS
#include <sys/syscall.h> /* Linux-only? */
#endif
// 64-bit is 3, 32-bit is 2
#define GC_BLOCK_BITS 5
/* HEAP definitions, based off heap from Chibi scheme */
#define gc_heap_first_block(h) ((object)(h->data + gc_heap_align(gc_free_chunk_size)))
#define gc_heap_end(h) ((object)((char*)h->data + h->size))
#define gc_heap_pad_size(s) (sizeof(struct gc_heap_t) + (s) + gc_heap_align(1))
#define gc_free_chunk_size (sizeof(gc_free_list))
#define gc_align(n, bits) (((n)+(1<<(bits))-1)&(((uintptr_t)-1)-((1<<(bits))-1)))
// Align to 8 byte block size (EG: 8, 16, etc)
#define gc_word_align(n) gc_align((n), 3)
// Align on GC_BLOCK_BITS, currently block size of 32 bytes
#define gc_heap_align(n) gc_align(n, GC_BLOCK_BITS)
////////////////////
// Global variables
// Note: will need to use atomics and/or locking to access any
// variables shared between threads
static unsigned char gc_color_mark = 5; // Black, is swapped during GC
static unsigned char gc_color_clear = 3; // White, is swapped during GC
static unsigned char gc_color_purple = 1; // There are many "shades" of purple, this is the most recent one
// unfortunately this had to be split up; const colors are located in types.h
static int gc_status_col = STATUS_SYNC1;
static int gc_stage = STAGE_RESTING;
// Does not need sync, only used by collector thread
static void **mark_stack = NULL;
static int mark_stack_len = 0;
static int mark_stack_i = 0;
// Data for the "main" thread which is guaranteed to always be there.
// Per SRFI 18:
// All threads are terminated when the primordial
// thread terminates (normally or not).
static gc_thread_data *primordial_thread = NULL;
/** Data new mutator threads that are not running yet */
static ck_array_t new_mutators;
/** Data for each individual mutator thread */
static ck_array_t Cyc_mutators;
static ck_array_t old_mutators;
static pthread_mutex_t mutators_lock;
static void my_free(void *p, size_t m, bool d)
{
free(p);
return;
}
static void *my_malloc(size_t b)
{
return malloc(b);
}
static void *my_realloc(void *r, size_t a, size_t b, bool d)
{
return realloc(r, b);
}
static struct ck_malloc my_allocator = {
.malloc = my_malloc,
.free = my_free,
.realloc = my_realloc
};
/** Mark buffers
*
* For these, we need a buffer than can grow as needed but that can also be
* used concurrently by both a mutator thread and a collector thread.
*/
static mark_buffer *mark_buffer_init(unsigned initial_size)
{
mark_buffer *mb = malloc(sizeof(mark_buffer));
mb->buf = malloc(sizeof(void *) * initial_size);
mb->buf_len = initial_size;
mb->next = NULL;
return mb;
}
static void *mark_buffer_get(mark_buffer * mb, unsigned i) // TODO: macro?
{
while (i >= mb->buf_len) {
// Not on this page, try the next one
i -= mb->buf_len;
mb = mb->next;
if (mb == NULL) { // Safety check
// For now this is a fatal error, could return NULL instead
fprintf(stderr, "mark_buffer_get ran out of mark buffers, exiting\n");
exit(1);
}
}
return mb->buf[i];
}
static void mark_buffer_set(mark_buffer * mb, unsigned i, void *obj)
{
// Find index i
while (i >= mb->buf_len) {
// Not on this page, try the next one
i -= mb->buf_len;
if (mb->next == NULL) {
// If it does not exist, allocate a new buffer
mb->next = mark_buffer_init(mb->buf_len * 2);
}
mb = mb->next;
}
mb->buf[i] = obj;
}
static void mark_buffer_free(mark_buffer * mb)
{
mark_buffer *next;
while (mb) {
next = mb->next;
free(mb->buf);
free(mb);
mb = next;
}
}
// END mark buffer
#if GC_DEBUG_TRACE
const int NUM_ALLOC_SIZES = 10;
static double allocated_size_counts[10] = {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
static double allocated_obj_counts[25] = {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
// TODO: allocated object sizes (EG: 32, 64, etc).
static double allocated_heap_counts[4] = { 0, 0, 0, 0 };
void print_allocated_obj_counts()
{
int i;
fprintf(stderr, "Allocated sizes:\n");
fprintf(stderr, "Size, Allocations\n");
for (i = 0; i < NUM_ALLOC_SIZES; i++) {
fprintf(stderr, "%d, %lf\n", 32 + (i * 32), allocated_size_counts[i]);
}
fprintf(stderr, "Allocated objects:\n");
fprintf(stderr, "Tag, Allocations\n");
for (i = 0; i < 25; i++) {
fprintf(stderr, "%d, %lf\n", i, allocated_obj_counts[i]);
}
fprintf(stderr, "Allocated heaps:\n");
fprintf(stderr, "Heap, Allocations\n");
for (i = 0; i < 4; i++) {
fprintf(stderr, "%d, %lf\n", i, allocated_heap_counts[i]);
}
}
void gc_log(FILE * stream, const char *format, ...)
{
va_list vargs;
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
fprintf(stream, "%.2d:%.2d:%.2d - ",
timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
va_start(vargs, format);
vfprintf(stream, format, vargs);
fprintf(stream, "\n");
va_end(vargs);
}
#endif
/////////////
// Functions
/**
* @brief Perform one-time initialization before mutators can be executed
*/
void gc_initialize(void)
{
if (ck_array_init(&Cyc_mutators, CK_ARRAY_MODE_SPMC, &my_allocator, 10) == 0) {
fprintf(stderr, "Unable to initialize mutator array\n");
exit(1);
}
if (ck_array_init(&new_mutators, CK_ARRAY_MODE_SPMC, &my_allocator, 10) == 0) {
fprintf(stderr, "Unable to initialize mutator array\n");
exit(1);
}
if (ck_array_init(&old_mutators, CK_ARRAY_MODE_SPMC, &my_allocator, 10) == 0) {
fprintf(stderr, "Unable to initialize mutator array\n");
exit(1);
}
// Initialize collector's mark stack
mark_stack_len = 128;
mark_stack = vpbuffer_realloc(mark_stack, &(mark_stack_len));
// Here is as good a place as any to do this...
if (pthread_mutex_init(&(mutators_lock), NULL) != 0) {
fprintf(stderr, "Unable to initialize mutators_lock mutex\n");
exit(1);
}
}
/**
* @brief Add data for a new mutator that is not yet scheduled to run.
* This is done so there is a record in the system even if the
* thread is not running, to prevent race conditions for any
* functions (EG: thread-join!) that need to access the thread.
* @param thd Thread data for the mutator
*/
void gc_add_new_unrunning_mutator(gc_thread_data * thd)
{
pthread_mutex_lock(&mutators_lock);
if (ck_array_put_unique(&new_mutators, (void *)thd) < 0) {
fprintf(stderr, "Unable to allocate memory for a new thread, exiting\n");
exit(1);
}
ck_array_commit(&new_mutators);
pthread_mutex_unlock(&mutators_lock);
}
/**
* @brief Add data for a new mutator that is starting to run.
* @param thd Thread data for the mutator
*/
void gc_add_mutator(gc_thread_data * thd)
{
pthread_mutex_lock(&mutators_lock);
if (ck_array_put_unique(&Cyc_mutators, (void *)thd) < 0) {
fprintf(stderr, "Unable to allocate memory for a new thread, exiting\n");
exit(1);
}
ck_array_commit(&Cyc_mutators);
pthread_mutex_unlock(&mutators_lock);
// Main thread is always the first one added
if (primordial_thread == NULL) {
primordial_thread = thd;
} else {
// At this point the mutator is running, so remove it from the new list
pthread_mutex_lock(&mutators_lock);
ck_array_remove(&new_mutators, (void *)thd);
ck_array_commit(&new_mutators);
pthread_mutex_unlock(&mutators_lock);
}
}
/**
* @brief Remove selected mutator from the mutator list.
* This is done for terminated threads. Note data is queued to be
* freed, to prevent accidentally freeing it while the collector
* thread is potentially accessing it.
* @param thd Thread data for the mutator
*/
void gc_remove_mutator(gc_thread_data * thd)
{
pthread_mutex_lock(&mutators_lock);
if (!ck_array_remove(&Cyc_mutators, (void *)thd)) {
fprintf(stderr, "Unable to remove thread data, exiting\n");
exit(1);
}
ck_array_commit(&Cyc_mutators);
// Place on list of old mutators to cleanup
if (ck_array_put_unique(&old_mutators, (void *)thd) < 0) {
fprintf(stderr, "Unable to add thread data to GC list, exiting\n");
exit(1);
}
ck_array_commit(&old_mutators);
pthread_mutex_unlock(&mutators_lock);
}
/**
* @brief Determine if the given mutator is in the list of active threads.
* @param thd Thread data object of the m
* @return A true value if the mutator is active, 0 otherwise.
*/
int gc_is_mutator_active(gc_thread_data * thd)
{
ck_array_iterator_t iterator;
gc_thread_data *m;
CK_ARRAY_FOREACH(&Cyc_mutators, &iterator, &m) {
if (m == thd) {
return 1;
}
}
return 0;
}
/**
* @brief Determine if the given mutator is in the list of new threads.
* @param thd Thread data object of the m
* @return A true value if the mutator is found, 0 otherwise.
*/
int gc_is_mutator_new(gc_thread_data * thd)
{
ck_array_iterator_t iterator;
gc_thread_data *m;
CK_ARRAY_FOREACH(&new_mutators, &iterator, &m) {
if (m == thd) {
return 1;
}
}
return 0;
}
/**
* @brief Free thread data for all terminated mutators
*/
void gc_free_old_thread_data()
{
ck_array_iterator_t iterator;
gc_thread_data *m;
int freed = 0;
pthread_mutex_lock(&mutators_lock);
CK_ARRAY_FOREACH(&old_mutators, &iterator, &m) {
//printf("JAE DEBUG - freeing old thread data...");
gc_thread_data_free(m);
if (!ck_array_remove(&old_mutators, (void *)m)) {
fprintf(stderr, "Error removing old mutator data\n");
exit(1);
}
freed = 1;
//printf(" done\n");
}
if (freed) {
ck_array_commit(&old_mutators);
//printf("commited old mutator data deletions\n");
}
pthread_mutex_unlock(&mutators_lock);
}
/**
* @brief Return the amount of free space on the heap
* @param gc_heap Root of the heap
* @return Free space in bytes
*/
uint64_t gc_heap_free_size(gc_heap * h)
{
uint64_t free_size = 0;
for (; h; h = h->next) {
if (h->is_unswept == 1) { // Assume all free prior to sweep
free_size += h->size;
} else {
free_size += (h->free_size);
}
}
return free_size;
}
/**
* @brief Create a new heap page.
* The caller must hold the necessary locks.
* @param heap_type Define the size of objects that will be allocated on this heap
* @param size Requested size (unpadded) of the heap
* @param thd Calling mutator's thread data object
* @return Pointer to the newly allocated heap page, or NULL
* if the allocation failed.
*/
gc_heap *gc_heap_create(int heap_type, size_t size, gc_thread_data * thd)
{
gc_free_list *free, *next;
gc_heap *h;
size_t padded_size;
size = gc_heap_align(size);
padded_size = gc_heap_pad_size(size);
h = malloc(padded_size);
if (!h)
return NULL;
h->type = heap_type;
h->size = size;
h->ttl = 10;
h->next_free = h;
h->last_alloc_size = 0;
thd->cached_heap_total_sizes[heap_type] += size;
thd->cached_heap_free_sizes[heap_type] += size;
h->data = (char *)gc_heap_align(sizeof(h->data) + (uintptr_t) & (h->data));
h->next = NULL;
h->num_unswept_children = 0;
free = h->free_list = (gc_free_list *) h->data;
next = (gc_free_list *) (((char *)free) + gc_heap_align(gc_free_chunk_size));
free->size = 0; // First one is just a dummy record
free->next = next;
next->size = size - gc_heap_align(gc_free_chunk_size);
next->next = NULL;
#if GC_DEBUG_TRACE
fprintf(stderr, "DEBUG h->data addr: %p\n", &(h->data));
fprintf(stderr, "DEBUG h->data addr: %p\n", h->data);
fprintf(stderr, ("heap: %p-%p data: %p-%p size: %zu\n"),
h, ((char *)h) + gc_heap_pad_size(size), h->data, h->data + size,
size);
fprintf(stderr, ("first: %p end: %p\n"), (object) gc_heap_first_block(h),
(object) gc_heap_end(h));
fprintf(stderr, ("free1: %p-%p free2: %p-%p\n"), free,
((char *)free) + free->size, next, ((char *)next) + next->size);
#endif
if (heap_type <= LAST_FIXED_SIZE_HEAP_TYPE) {
h->block_size = (heap_type + 1) * 32;
//
h->remaining = size - (size % h->block_size);
h->data_end = h->data + h->remaining;
h->free_list = NULL; // No free lists with bump&pop
// This is for starting with a free list, but we want bump&pop instead
// h->remaining = 0;
// h->data_end = NULL;
// gc_init_fixed_size_free_list(h);
} else {
h->block_size = 0;
h->remaining = 0;
h->data_end = NULL;
}
// Lazy sweeping
h->free_size = size;
h->is_full = 0;
h->is_unswept = 0;
return h;
}
/**
* @brief Initialize free lists within a single heap page.
* Assumes that there is no data currently on the heap page!
* @param h Heap page to initialize
*/
void gc_init_fixed_size_free_list(gc_heap * h)
{
// for this flavor, just layer a free list on top of unitialized memory
gc_free_list *next;
//int i = 0;
size_t remaining = h->size - (h->size % h->block_size) - h->block_size; // Starting at first one so skip it
next = h->free_list = (gc_free_list *) h->data;
//printf("data start = %p\n", h->data);
//printf("data end = %p\n", h->data + h->size);
while (remaining >= h->block_size) {
//printf("%d init remaining=%d next = %p\n", i++, remaining, next);
next->next = (gc_free_list *) (((char *)next) + h->block_size);
next = next->next;
remaining -= h->block_size;
}
next->next = NULL;
h->data_end = NULL; // Indicate we are using free lists
}
/**
* @brief Diagnostic function to print all free lists on a fixed-size heap page
* @param h Heap page to output
*/
void gc_print_fixed_size_free_list(gc_heap * h)
{
gc_free_list *f = h->free_list;
fprintf(stderr, "printing free list:\n");
while (f) {
fprintf(stderr, "%p\n", f);
f = f->next;
}
fprintf(stderr, "done\n");
}
/**
* @brief Essentially this is half of the sweep code, for sweeping bump&pop
* @param h Heap page to convert
*/
static size_t gc_convert_heap_page_to_free_list(gc_heap * h,
gc_thread_data * thd)
{
size_t freed = 0;
object p;
gc_free_list *next;
int remaining = h->size - (h->size % h->block_size);
if (h->data_end == NULL)
return 0; // Already converted
next = h->free_list = NULL;
while (remaining > h->remaining) {
p = h->data_end - remaining;
//int tag = type_of(p);
int color = mark(p);
// printf("found object %d color %d at %p with remaining=%lu\n", tag, color, p, remaining);
// free space, add it to the free list
if (color != thd->gc_alloc_color && color != thd->gc_trace_color) { //gc_color_clear)
// Run any finalizers
if (type_of(p) == mutex_tag) {
#if GC_DEBUG_VERBOSE
fprintf(stderr, "pthread_mutex_destroy from sweep\n");
#endif
if (pthread_mutex_destroy(&(((mutex) p)->lock)) != 0) {
fprintf(stderr, "Error destroying mutex\n");
exit(1);
}
} else if (type_of(p) == cond_var_tag) {
#if GC_DEBUG_VERBOSE
fprintf(stderr, "pthread_cond_destroy from sweep\n");
#endif
if (pthread_cond_destroy(&(((cond_var) p)->cond)) != 0) {
fprintf(stderr, "Error destroying condition variable\n");
exit(1);
}
} else if (type_of(p) == bignum_tag) {
// TODO: this is no good if we abandon bignum's on the stack
// in that case the finalizer is never called
#if GC_DEBUG_VERBOSE
fprintf(stderr, "mp_clear from sweep\n");
#endif
mp_clear(&(((bignum_type *) p)->bn));
} else if (type_of(p) == c_opaque_tag && opaque_collect_ptr(p)) {
#if GC_DEBUG_VERBOSE
fprintf(stderr, "free opaque pointer %p from sweep\n", opaque_ptr(p));
#endif
free(opaque_ptr(p));
}
// Free block
freed += h->block_size;
if (next == NULL) {
next = h->free_list = p;
} else {
next->next = p;
next = next->next;
}
h->free_size += h->block_size;
}
remaining -= h->block_size;
}
// Convert any empty space at the end
while (remaining) {
p = h->data_end - remaining;
// printf("no object at %p fill with free list\n", p);
if (next == NULL) {
next = h->free_list = p;
} else {
next->next = p; //(gc_free_list *)(((char *) next) + h->block_size);
next = next->next;
}
remaining -= h->block_size;
}
if (next) {
next->next = NULL;
}
// Let GC know this heap is not bump&pop
h->remaining = 0;
h->data_end = NULL;
return freed;
}
/**
* @brief Sweep portion of the GC algorithm
* @param h Heap to sweep
* @param thd Thread data object for the mutator using this heap
* @return Return the size of the largest object freed, in bytes
*
* This portion of the major GC algorithm is responsible for returning unused
* memory slots to the heap. It is only called by the collector thread after
* the heap has been traced to identify live objects.
*/
static gc_heap *gc_sweep_fixed_size(gc_heap * h, gc_thread_data * thd)
{
short heap_is_empty;
object p, end;
gc_free_list *q, *r, *s;
#if GC_DEBUG_SHOW_SWEEP_DIAG
gc_heap *orig_heap_ptr = h;
#endif
gc_heap *rv = h;
h->next_free = h;
h->is_unswept = 0;
#if GC_DEBUG_SHOW_SWEEP_DIAG
fprintf(stderr, "\nBefore sweep -------------------------\n");
fprintf(stderr, "Heap %d diagnostics:\n", h->type);
gc_print_stats(orig_heap_ptr);
#endif
if (h->data_end != NULL) {
// Special case, bump&pop heap
gc_convert_heap_page_to_free_list(h, thd);
heap_is_empty = 0; // For now, don't try to free bump&pop
} else {
//gc_free_list *next;
size_t remaining = h->size - (h->size % h->block_size); // - h->block_size; // Remove first one??
char *data_end = h->data + remaining;
heap_is_empty = 1; // Base case is an empty heap
end = (object) data_end;
p = h->data;
q = h->free_list;
while (p < end) {
// find preceding/succeeding free list pointers for p
for (r = (q ? q->next : NULL); r && ((char *)r < (char *)p);
q = r, r = r->next) ;
if ((char *)q == (char *)p || (char *)r == (char *)p) { // this is a free block, skip it
//printf("Sweep skip free block %p remaining=%lu\n", p, remaining);
p = (object) (((char *)p) + h->block_size);
continue;
}
#if GC_SAFETY_CHECKS
if (!is_object_type(p)) {
fprintf(stderr, "sweep: invalid object at %p", p);
exit(1);
}
if (type_of(p) > 21) {
fprintf(stderr, "sweep: invalid object tag %d at %p", type_of(p), p);
exit(1);
}
#endif
if (mark(p) != thd->gc_alloc_color && mark(p) != thd->gc_trace_color) { //gc_color_clear)
#if GC_DEBUG_VERBOSE
fprintf(stderr, "sweep is freeing unmarked obj: %p with tag %d\n", p,
type_of(p));
#endif
// Run finalizers
if (type_of(p) == mutex_tag) {
#if GC_DEBUG_VERBOSE
fprintf(stderr, "pthread_mutex_destroy from sweep\n");
#endif
if (pthread_mutex_destroy(&(((mutex) p)->lock)) != 0) {
fprintf(stderr, "Error destroying mutex\n");
exit(1);
}
} else if (type_of(p) == cond_var_tag) {
#if GC_DEBUG_VERBOSE
fprintf(stderr, "pthread_cond_destroy from sweep\n");
#endif
if (pthread_cond_destroy(&(((cond_var) p)->cond)) != 0) {
fprintf(stderr, "Error destroying condition variable\n");
exit(1);
}
} else if (type_of(p) == bignum_tag) {
// TODO: this is no good if we abandon bignum's on the stack
// in that case the finalizer is never called
#if GC_DEBUG_VERBOSE
fprintf(stderr, "mp_clear from sweep\n");
#endif
mp_clear(&(((bignum_type *) p)->bn));
}
// free p
//heap_freed += h->block_size;
if (h->free_list == NULL) {
// No free list, start one at p
q = h->free_list = p;
h->free_list->next = NULL;
//printf("sweep reclaimed remaining=%d, %p, assign h->free_list\n", remaining, p);
} else if ((char *)p < (char *)h->free_list) {
// p is before the free list, prepend it as the start
// note if this is the case, either there is no free_list (see above case) or
// the free list is after p, which is handled now. these are the only situations
// where there is no q
s = (gc_free_list *) p;
s->next = h->free_list;
q = h->free_list = p;
//printf("sweep reclaimed remaining=%d, %p, assign h->free_list which was %p\n", remaining, p, h->free_list);
} else {
s = (gc_free_list *) p;
s->next = r;
q->next = s;
//printf("sweep reclaimed remaining=%d, %p, q=%p, r=%p\n", remaining, p, q, r);
}
h->free_size += h->block_size;
} else {
//printf("sweep block is still used remaining=%d p = %p\n", remaining, p);
heap_is_empty = 0;
}
//next->next = (gc_free_list *)(((char *) next) + h->block_size);
//next = next->next;
p = (object) (((char *)p) + h->block_size);
}
}
// Free the heap page if possible.
if (heap_is_empty) {
if (h->type == HEAP_HUGE || (h->ttl--) <= 0) {
rv = NULL; // Let caller know heap needs to be freed
} else {
// Convert back to bump&pop
h->remaining = h->size - (h->size % h->block_size);
h->data_end = h->data + h->remaining;
h->free_list = NULL; // No free lists with bump&pop
}
} else {
//(thd->heap->heap[h->type])->num_unswept_children--;
}
#if GC_DEBUG_SHOW_SWEEP_DIAG
fprintf(stderr, "\nAfter sweep -------------------------\n");
fprintf(stderr, "Heap %d diagnostics:\n", h->type);
gc_print_stats(orig_heap_ptr);
#endif
return rv;
}
/**
* @brief Free a page of the heap
* @param page Page to free
* @param prev_page Previous page in the heap
* @return Previous page if successful, NULL otherwise
*/
gc_heap *gc_heap_free(gc_heap * page, gc_heap * prev_page)
{
// At least for now, do not free first page
if (prev_page == NULL || page == NULL) {
return NULL;
}
#if GC_DEBUG_TRACE
fprintf(stderr, "DEBUG freeing heap type %d page at addr: %p\n", page->type,
page);
#endif
prev_page->next = page->next;
free(page);
return prev_page;
}
/**
* @brief Determine if a heap page is empty.
* @param h Heap to inspect. The caller should acquire any necessary locks.
* @return A truthy value if the heap is empty, 0 otherwise.
*/
static int gc_is_heap_empty(gc_heap * h)
{
gc_free_list *f;
if (!h)
return 0;
if (h->data_end) { // Fixed-size bump&pop
return (h->remaining == (h->size - (h->size % h->block_size)));
}
if (!h->free_list)
return 0;
f = h->free_list;
if (f->size != 0 || !f->next)
return 0;
f = f->next;
return (f->size + gc_heap_align(gc_free_chunk_size)) == h->size;
}
/**
* @brief Print heap usage information. Before calling this function the
* current thread must have the heap lock
* @param h Heap to analyze.
*/
void gc_print_stats(gc_heap * h)
{
gc_free_list *f;
unsigned int free, free_chunks, free_min, free_max;
int heap_is_empty;
for (; h; h = h->next) {
free = 0;
free_chunks = 0;
free_min = h->size;
free_max = 0;
for (f = h->free_list; f; f = f->next) {
free += f->size;
free_chunks++;
if (f->size < free_min && f->size > 0)
free_min = f->size;
if (f->size > free_max)
free_max = f->size;
}
if (free == 0) { // No free chunks
free_min = 0;
}
heap_is_empty = gc_is_heap_empty(h);
fprintf(stderr,
"Heap type=%d, page size=%u, is empty=%d, used=%u, free=%u, free chunks=%u, min=%u, max=%u\n",
h->type, h->size, heap_is_empty, h->size - free, free, free_chunks,
free_min, free_max);
}
}
/**
* @brief Copy given object into given heap object
* @param dest Pointer to destination heap memory slot
* @param obj Object to copy
* @param thd Thread data object for the applicable mutator
* @return The appropriate pointer to use for `obj`
*
* NOTE: There is no additional type checking because this function is
* called from `gc_move` which already does that.
*/
char *gc_copy_obj(object dest, char *obj, gc_thread_data * thd)
{
#if GC_DEBUG_TRACE
allocated_obj_counts[type_of(obj)]++;
#endif
switch (type_of(obj)) {
case closureN_tag:{
closureN_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = closureN_tag;
hp->fn = ((closureN) obj)->fn;
hp->num_args = ((closureN) obj)->num_args;
hp->num_elements = ((closureN) obj)->num_elements;
hp->elements = (object *) (((char *)hp) + sizeof(closureN_type));
memcpy(hp->elements, ((closureN) obj)->elements,
sizeof(object *) * hp->num_elements);
return (char *)hp;
}
case pair_tag:{
list hp = dest;
hp->hdr.mark = thd->gc_alloc_color;
hp->hdr.immutable = immutable(obj);
type_of(hp) = pair_tag;
car(hp) = car(obj);
cdr(hp) = cdr(obj);
return (char *)hp;
}
case string_tag:{
char *s;
string_type *hp = dest;
s = ((char *)hp) + sizeof(string_type);
memcpy(s, string_str(obj), string_len(obj) + 1);
mark(hp) = thd->gc_alloc_color;
immutable(hp) = immutable(obj);
type_of(hp) = string_tag;
string_num_cp(hp) = string_num_cp(obj);
string_len(hp) = string_len(obj);
string_str(hp) = s;
return (char *)hp;
}
case double_tag:{
double_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = double_tag;
hp->value = ((double_type *) obj)->value;
return (char *)hp;
}
case vector_tag:{
vector_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
immutable(hp) = immutable(obj);
type_of(hp) = vector_tag;
hp->num_elements = ((vector) obj)->num_elements;
hp->elements = (object *) (((char *)hp) + sizeof(vector_type));
memcpy(hp->elements, ((vector) obj)->elements,
sizeof(object *) * hp->num_elements);
return (char *)hp;
}
case bytevector_tag:{
bytevector_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
immutable(hp) = immutable(obj);
type_of(hp) = bytevector_tag;
hp->len = ((bytevector) obj)->len;
hp->data = (((char *)hp) + sizeof(bytevector_type));
memcpy(hp->data, ((bytevector) obj)->data, hp->len);
return (char *)hp;
}
case port_tag:{
port_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = port_tag;
hp->fp = ((port_type *) obj)->fp;
hp->mode = ((port_type *) obj)->mode;
hp->flags = ((port_type *) obj)->flags;
hp->line_num = ((port_type *) obj)->line_num;
hp->col_num = ((port_type *) obj)->col_num;
hp->buf_idx = ((port_type *) obj)->buf_idx;
hp->tok_start = ((port_type *) obj)->tok_start;
hp->tok_end = ((port_type *) obj)->tok_end;
hp->tok_buf = ((port_type *) obj)->tok_buf;
hp->tok_buf_len = ((port_type *) obj)->tok_buf_len;
hp->mem_buf = ((port_type *) obj)->mem_buf;
hp->mem_buf_len = ((port_type *) obj)->mem_buf_len;
hp->str_bv_in_mem_buf = ((port_type *) obj)->str_bv_in_mem_buf;
hp->str_bv_in_mem_buf_len = ((port_type *) obj)->str_bv_in_mem_buf_len;
hp->read_len = ((port_type *) obj)->read_len;
return (char *)hp;
}
case bignum_tag:{
bignum_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = bignum_tag;
((bignum_type *) hp)->bn.used = ((bignum_type *) obj)->bn.used;
((bignum_type *) hp)->bn.alloc = ((bignum_type *) obj)->bn.alloc;
((bignum_type *) hp)->bn.sign = ((bignum_type *) obj)->bn.sign;
((bignum_type *) hp)->bn.dp = ((bignum_type *) obj)->bn.dp;
return (char *)hp;
}
case cvar_tag:{
cvar_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = cvar_tag;
hp->pvar = ((cvar_type *) obj)->pvar;
return (char *)hp;
}
case mutex_tag:{
mutex_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = mutex_tag;
// NOTE: don't copy mutex itself, caller will do that (this is a special case)
return (char *)hp;
}
case cond_var_tag:{
cond_var_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = cond_var_tag;
// NOTE: don't copy cond_var itself, caller will do that (this is a special case)
return (char *)hp;
}
case atomic_tag:{
atomic_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = atomic_tag;
hp->obj = ((atomic_type *) obj)->obj; // TODO: should access via CK atomic operations, though this may not be needed at all since we alloc directly on heap
return (char *)hp;
}
case macro_tag:{
macro_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = macro_tag;
hp->fn = ((macro) obj)->fn;
hp->num_args = ((macro) obj)->num_args;
return (char *)hp;
}
case closure1_tag:{
closure1_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = closure1_tag;
hp->fn = ((closure1) obj)->fn;
hp->num_args = ((closure1) obj)->num_args;
hp->element = ((closure1) obj)->element;
return (char *)hp;
}
case c_opaque_tag:{
c_opaque_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
immutable(hp) = immutable(obj);
type_of(hp) = c_opaque_tag;
hp->collect_ptr = ((c_opaque_type *) obj)->collect_ptr;
hp->ptr = ((c_opaque_type *) obj)->ptr;
return (char *)hp;
}
case forward_tag:
return (char *)forward(obj);
case eof_tag:
case void_tag:
case record_tag:
case primitive_tag:
case boolean_tag:
case symbol_tag:
case closure0_tag:
break;
case integer_tag:{
integer_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = integer_tag;
hp->value = ((integer_type *) obj)->value;
return (char *)hp;
}
case complex_num_tag:{
complex_num_type *hp = dest;
mark(hp) = thd->gc_alloc_color;
type_of(hp) = complex_num_tag;
hp->value = ((complex_num_type *) obj)->value;
return (char *)hp;