-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgc.c
More file actions
1357 lines (1219 loc) · 38.5 KB
/
Copy pathgc.c
File metadata and controls
1357 lines (1219 loc) · 38.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2026 HardenedLinux Community
* Nala Ginrut <roy@hardenedlinux.org>
* Animula is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* Animula is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_OBG_GC
# include "list.h"
# include "obg_gc.h"
// Ensure active_root_compare is visible for RB_GENERATE_STATIC
// It's defined as static inline in obg_gc.h, which is fine
RB_GENERATE_STATIC(ActiveRoot, ActiveRootNode, entry, active_root_compare);
static int get_gc_from_node (otype_t type, void *value);
static void set_gc_to_node (otype_t type, void *value, int gc);
static void object_list_node_recycle (list_node_t node);
static void free_object_from_pool (ListHead *head, void *o);
static void free_list_nodes (list_t l, void (*visit) (object_t obj));
/* X-Macro table of every "inner" object kind that lives in its own
* fixed-size free pool and is registered/collected in a uniform way.
*
* X(enum_tag, c_type, free_pool_variable)
*
* Closures are deliberately NOT in this table: closure_on_heap and
* closure_on_stack are two otype_t tags that share a single pool
* (closure_free_pool), so the few functions below that need closure
* handling add it by hand right after the generated cases.
*
* This is the answer to "C99 has no generics, so this is repetitive":
* every place that used to hand-write the same 5-way (or 6-way, with
* closures) switch now expands from this one list instead.
*/
# define GC_INNER_TYPE_LIST(X) \
X (pair, pair_t, pair_free_pool) \
X (vector, vector_t, vector_free_pool) \
X (list, list_t, list_free_pool) \
X (bytevector, bytevector_t, bytevector_free_pool) \
X (mut_bytevector, mut_bytevector_t, mut_bytevector_free_pool)
/* Same 5, plus closure (represented by closure_on_heap alone -- fine for
* call sites that just need "the pool" and "a" type tag for it, unlike
* get_gc_from_node/set_gc_to_node/gc_inner_obj_book which must list both
* closure_on_heap and closure_on_stack as separate case labels).
*/
# define GC_ALL_POOLS_LIST(X) \
GC_INNER_TYPE_LIST (X) \
X (closure_on_heap, closure_t, closure_free_pool)
/* The GC in Animula is "object-based generational GC".
We don't perform mark/sweep, or any reference counting.
The meaning of `gc' field in Object:
* 3 means permarnent.
* 1~2 means the generation, 0 means free.
* The `gc' will increase by 1 when it survives from GC.
* For stack-allocated object, `gc' field is always 0.
*/
// Active root: a red-black tree keyed by pointer value, giving O(log n)
// membership checks instead of the O(n) linear scan this used to be.
static struct ActiveRoot active_root_tree = {NULL};
// See obg_gc.h: set once by the person via gc_bind_vm(vm), right after
// creating/initializing their VM. Deliberately NOT wired up inside
// vm.c -- reaching a global VM state into a shared, backend-agnostic
// file just to serve this one GC backend's internals would be the
// wrong direction of coupling.
vm_t g_current_vm = NULL;
void gc_bind_vm (vm_t vm)
{
g_current_vm = vm;
}
// Set only by gc_teardown(), for the duration of its one-time final
// pass. free_object/free_inner_object each have their own independent
// "PERMANENT_OBJ objects are never touched" guard -- correct for every
// normal collection, but it silently defeats gc_teardown's whole
// purpose: collect_inner(force=true) bypasses *its own* permanent
// check fine and calls free_inner_object, which then immediately bails
// on *its own*, separate check before ever tearing down internal
// structures (e.g. a list_t's ListNode chain). sweep(true) then
// physically os_frees the outer struct anyway via
// release_all_free_objects's own independent force check (which never
// calls free_inner_object at all), orphaning whatever internal
// structure was never torn down. This flag lets gc_teardown()
// override just those two guards, without touching collect/
// collect_inner's own force semantics or recycle_object's guard
// (recycle_object is never called from gc_teardown, so it's left
// as-is).
static bool g_gc_force_teardown = false;
// Proactive GC trigger. Counts allocation attempts since the last
// collection (of any kind); once GC_ALLOC_THRESHOLD is reached, tells
// the caller to collect and resets. Without this, GC only ever ran
// reactively -- when an allocation had already failed -- which means a
// long-running target that never happens to hit that condition would
// never run a single collection, no matter how much garbage piled up.
//
// Builders may tune this for their target's RAM budget in compiling.
// -D GC_ALLOC_THRESHOLD=1024
#ifndef GC_ALLOC_THRESHOLD
# define GC_ALLOC_THRESHOLD 256
#endif
static size_t alloc_since_last_gc = 0;
bool gc_alloc_budget_exceeded (void)
{
if (++alloc_since_last_gc >= GC_ALLOC_THRESHOLD)
{
alloc_since_last_gc = 0;
return true;
}
return false;
}
static ListHead pair_free_pool;
static ListHead vector_free_pool;
static ListHead list_free_pool;
static ListHead closure_free_pool;
static ListHead bytevector_free_pool;
static ListHead mut_bytevector_free_pool;
static ListHead obj_free_pool;
static struct Pre_ARN _arn = {0};
// TODO: static
struct Pre_OLN _oln = {0};
static void pre_allocate_active_nodes (void)
{
for (int i = 0; i < PRE_ARN; i++)
{
_arn.arn[i] = (ActiveRootNode *)os_malloc (sizeof (ActiveRootNode));
if (NULL == _arn.arn[i])
{
os_printk ("GC: We're doomed! Did you set a too large PRE_ARN?");
PANIC ("Try to set PRE_ARN smaller!");
}
}
_arn.index = 0;
VM_DEBUG ("PRE_ARN: %d, pre-allocate %d bytes.\n", PRE_ARN,
PRE_ARN * sizeof (ActiveRootNode));
}
static ActiveRootNode *arn_alloc (void)
{
if (PRE_ARN == _arn.index)
{
PANIC ("GC: We're doomed! Did you set a too small PRE_ARN?"
"Try to set PRE_ARN larger!");
}
return _arn.arn[_arn.index++];
}
static void object_list_node_pre_allocate (void)
{
int i = 0;
for (; i < PRE_OLN; i++)
{
list_node_t ptr = (list_node_t)os_malloc (sizeof (ListNode));
if (NULL == ptr)
{
PANIC ("GC: We're doomed! Did you set a too large PRE_OLN?"
"Try to set PRE_OLN smaller!");
}
else
{
_oln.oln[i] = ptr;
}
}
_oln.index = 0;
VM_DEBUG ("PRE_OLN: %d, cnt: %d, pre-allocate %d bytes.\n", PRE_OLN, i - 1,
PRE_OLN * sizeof (ListNode));
}
list_node_t object_list_node_alloc (void)
{
list_node_t ret = NULL;
if (!object_list_node_available ())
{
return NULL;
}
ret = _oln.oln[_oln.index];
// do not delete the following line which worth $2000 USD at least
_oln.oln[_oln.index] = (void *)0xDEAD0001;
if (NULL == ret)
{
os_printk ("BUG: there's no obj_list node, but cnt is %d\n", _oln.index);
PANIC ("Maybe it's not recycled correctly?");
}
_oln.index++;
return ret;
}
// put list_node_t back into OLN for future use
static void object_list_node_recycle (list_node_t node)
{
_oln.oln[--_oln.index] = node;
}
size_t object_list_node_available (void)
{
return (PRE_OLN - _oln.index);
}
static void active_nodes_clean (void)
{
for (int i = 0; i < PRE_ARN; i++)
{
os_free (_arn.arn[i]);
}
_arn.index = 0;
VM_DEBUG ("ARN clean!\n");
}
static void object_list_node_clean (void)
{
// do not modify i to start from 0, which will cost you at least $2000 USD
if (0 != _oln.index)
{
PANIC ("Not all nodes returned to OLN");
}
for (int i = _oln.index; i < PRE_OLN; i++)
{
void *ptr = _oln.oln[i];
if (NULL != ptr)
{
os_free (ptr);
_oln.oln[i] = NULL;
}
else
{
PANIC ("Available OLN shall not be NULL\n");
}
}
_oln.index = 0;
VM_DEBUG ("OLN clean!\n");
}
static inline void insert (ActiveRootNode *an)
{
RB_INSERT (ActiveRoot, &active_root_tree, an);
}
static inline bool exist (object_t obj)
{
ActiveRootNode key = {.value = (void *)obj};
return NULL != RB_FIND (ActiveRoot, &active_root_tree, &key);
}
static void insert_value (void *value)
{
ActiveRootNode *an = arn_alloc ();
an->value = value;
insert (an);
}
// Free (for free_object/free_inner_object) or recycle (for
// recycle_object) the privately-owned prefix of a list_t's internal
// ListNode chain, calling `visit` on each element's object_t before
// removing and os_free'ing its node.
//
// non_shared is a literal count: exactly this many nodes from the
// head are privately owned by this list_t and safe to free here.
// Anything beyond that is a shared tail borrowed from another list_t's
// own chain -- e.g. `_cdr` (list.c) points a new list_t directly at an
// existing list's second node without allocating anything of its own
// (non_shared=0: nothing here is private, free none of it), or
// `_list_append` builds a fresh private prefix then links its last
// node directly into the second list's existing chain (non_shared =
// length of the fresh prefix). Freeing anything past non_shared here
// would free memory another list_t still owns, causing a
// use-after-free (or double-free) when that other list_t is later
// torn down independently. Every constructor of a fully
// privately-owned list (list literals, map) must set non_shared to
// its own real node count, not 0 -- 0 here specifically means "zero
// private nodes", not "no sharing at all".
static void free_list_nodes (list_t l, void (*visit) (object_t obj))
{
ListHead *head = &l->list;
u16_t to_free = l->non_shared;
if (SLIST_EMPTY (head))
return;
list_node_t node = SLIST_FIRST (head);
for (u16_t i = 0; i < to_free && node; i++)
{
// call visit recursively since node->obj can be a composite object
visit (node->obj);
list_node_t next_node = SLIST_NEXT (node, next);
SLIST_REMOVE (head, node, ListNode, next);
os_free (node);
node = next_node;
}
}
void free_object (object_t obj)
{
if (0xDEADBEEF == (uintptr_t)obj)
{
os_printk ("active_root_insert: oh a half list node!\n");
os_printk ("let's skip it safely!\n");
return;
}
if (!obj)
{
PANIC ("BUG: free a null object!");
}
if (PERMANENT_OBJ == obj->attr.gc && !g_gc_force_teardown)
return;
switch (obj->attr.type)
{
case imm_int:
case character:
case real:
case rational_pos:
case rational_neg:
case boolean:
case null_obj:
case none:
case string:
case symbol:
case primitive:
case procedure:
{
// simple object, we don't need to free its value
// no need to free string
// symbol should never be recycled
break;
}
case pair:
{
free_object ((object_t)((pair_t)obj->value)->car);
free_object ((object_t)((pair_t)obj->value)->cdr);
break;
}
case list:
{
free_list_nodes ((list_t)obj->value, free_object);
break;
}
case vector:
{
vector_t v = (vector_t)obj->value;
for (u16_t i = 0; i < v->size; i++)
{
free_object (v->vec[i]);
}
// Tracked in its own pool (vector_free_pool); that pool's own
// collect_inner + sweep cycle owns the actual os_free of both
// the Vector struct and its .vec array (see
// free_inner_object's vector case) -- just mark it dead here.
set_gc_to_node (obj->attr.type, obj->value, FREE_OBJ);
break;
}
case continuation:
case mut_string:
{
// Not tracked in any inner free_pool (see gc_inner_obj_book),
// so this Object wrapper is the sole owner of the memory.
os_free ((void *)obj->value);
break;
}
case closure_on_heap:
case closure_on_stack:
case bytevector:
case mut_bytevector:
{
// These ARE tracked in their own pool (closure_free_pool /
// bytevector_free_pool / mut_bytevector_free_pool), whose own
// collect_inner + sweep cycle owns the actual os_free. Freeing
// the memory here too would double-free it -- just mark it
// dead and let that pool take it from here.
set_gc_to_node (obj->attr.type, obj->value, FREE_OBJ);
break;
}
default:
{
PANIC ("free_object: Invalid type %d!\n", obj->attr.type);
}
}
obj->attr.gc = FREE_OBJ;
}
void free_inner_object (otype_t type, void *value)
{
/* NOTE: Integers are self-contained object, so we can just release the
* object
*/
if (!value)
{
PANIC ("BUG: free a null object!");
}
u8_t gc = get_gc_from_node (type, value);
if (PERMANENT_OBJ == gc && !g_gc_force_teardown)
return;
switch (type)
{
case pair:
{
free_object ((object_t)((pair_t)value)->car);
free_object ((object_t)((pair_t)value)->cdr);
((pair_t)value)->attr.gc = FREE_OBJ;
break;
}
case list:
{
list_t l = (list_t)value;
free_list_nodes (l, free_object);
l->attr.gc = FREE_OBJ;
break;
}
case vector:
{
// Elements were already recursively torn down by free_object's
// vector case (called on the outer wrapper before this inner
// value's own turn comes up) -- here we only own .vec itself.
vector_t v = (vector_t)value;
os_free (v->vec);
v->attr.gc = FREE_OBJ;
break;
}
case closure_on_heap:
case closure_on_stack:
{
((closure_t)value)->attr.gc = FREE_OBJ;
break;
}
case bytevector:
{
((bytevector_t)value)->attr.gc = FREE_OBJ;
break;
}
case mut_bytevector:
{
((mut_bytevector_t)value)->attr.gc = FREE_OBJ;
os_free (((mut_bytevector_t)value)->vec);
break;
}
default:
{
PANIC ("free_inner_object: Invalid type %d!\n", type);
}
}
}
static void recycle_object (object_t obj)
{
if (PERMANENT_OBJ == obj->attr.gc)
return;
switch (obj->attr.type)
{
case imm_int:
case character:
case real:
case rational_pos:
case rational_neg:
case boolean:
case null_obj:
case none:
case string:
case symbol:
case primitive:
case procedure:
{
// These objects don't have to be recycled recursively.
break;
}
case pair:
{
recycle_object (((pair_t)obj->value)->car);
recycle_object (((pair_t)obj->value)->cdr);
break;
}
case list:
{
free_list_nodes ((list_t)obj->value, recycle_object);
break;
}
case vector:
{
vector_t v = (vector_t)obj->value;
for (u16_t i = 0; i < v->size; i++)
{
recycle_object (v->vec[i]);
}
free_object_from_pool (&vector_free_pool, obj->value);
break;
}
case closure_on_heap:
case closure_on_stack:
{
free_object_from_pool (&closure_free_pool, obj->value);
break;
}
case bytevector:
{
free_object_from_pool (&bytevector_free_pool, obj->value);
break;
}
case mut_bytevector:
{
free_object_from_pool (&mut_bytevector_free_pool, obj->value);
break;
}
case mut_string:
{
// Not tracked in any pool (see gc_inner_obj_book) -- this
// Object is the sole owner of the buffer, same as
// free_object's own treatment of mut_string.
os_free ((void *)obj->value);
break;
}
default:
{
os_printk ("Invalid object type %d\n", obj->attr.type);
PANIC ("recycle_object is down!");
}
}
obj->attr.gc = FREE_OBJ;
}
static void active_root_insert (object_t obj);
static void active_root_inner_insert (otype_t type, void *value)
{
if (NULL == value)
{
// Some self-contain object may have NULL value
return;
}
if (exist (value))
return;
switch (type)
{
case imm_int:
case character:
case real:
case rational_pos:
case rational_neg:
case boolean:
case null_obj:
case none:
case string:
case symbol:
case primitive:
case procedure:
case mut_string:
{
// Not pool-tracked, nothing to mark alive.
break;
}
case pair:
{
pair_t p = (pair_t)value;
active_root_insert (p->car);
active_root_insert (p->cdr);
insert_value (value);
break;
}
case vector:
{
vector_t v = (vector_t)value;
for (u16_t i = 0; i < v->size; i++)
{
active_root_insert (v->vec[i]);
}
insert_value (value);
break;
}
case list:
{
ListHead *head = &((list_t)value)->list;
list_node_t node;
for (node = SLIST_FIRST(head); node != NULL; node = SLIST_NEXT(node, next)) {
active_root_insert (node->obj);
}
insert_value (value);
break;
}
case closure_on_heap:
case closure_on_stack:
{
// The closure's own persistent captured-variable storage
// (env[], sized to frame_size -- see make_closure) must be
// walked here regardless of *how* this closure was reached
// (a global binding, nested in a pair/list, or on the active
// call chain) -- it's the closure's permanent state, not
// something tied to any one particular invocation.
closure_t c = (closure_t)value;
for (u8_t i = 0; i < c->frame_size; i++)
{
active_root_insert (&c->env[i]);
}
insert_value (value);
break;
}
case bytevector:
case mut_bytevector:
{
// Raw bytes, no further object_t sub-references to walk.
insert_value (value);
break;
}
default:
{
PANIC ("BUG: active_root_inner_insert encountered a wrong type %d!\n",
type);
break;
}
}
}
static void active_root_insert (object_t obj)
{
if (0xDEADBEEF == (uintptr_t)obj)
{
return;
}
if (!obj)
{
PANIC ("BUG: active_root_insert - null obj!\n");
}
if (exist (obj))
return;
// Delegate the type-specific walk (and marking the *inner* value
// alive, when there is one) to active_root_inner_insert, so there's
// a single place that knows how to walk each otype_t. Then mark the
// outer wrapper itself alive too, since obj_free_pool's liveness
// check (in collect()) looks up outer object_t pointers.
active_root_inner_insert (obj->attr.type, obj->value);
insert_value ((void *)obj);
}
static void active_root_insert_frame (const u8_t *stack, u32_t local, u8_t cnt)
{
/* printf ("insert frame %d, %d\n", local, cnt); */
/* os_getchar (); */
for (u8_t i = 0; i < cnt; i++)
{
object_t obj = (object_t)(stack + local + i * sizeof (Object));
if (!obj)
PANIC ("active_root_insert_frame: Invalid object address!");
active_root_inner_insert (obj->attr.type, obj->value);
}
}
static void build_active_root (const gc_info_t gci)
{
// 1. Count frames and get each fp
// 2. Generate Active Root Tree
u8_t *stack = gci->stack;
reg_t fp = gci->fp;
reg_t sp = gci->sp;
bool run = true;
for (; ((fp > 0) && (NO_PREV_FP != fp)); sp = fp, fp = NEXT_FP ())
{
reg_t local = fp + FPS;
u8_t obj_cnt = (sp - local) / sizeof (Object);
active_root_insert_frame (stack, local, obj_cnt);
/* NOTE: The closure captured heap-allocated object should be in
* active_root too.
*/
closure_t closure = *((closure_t *)(stack + local - sizeof (closure_t)));
if (closure && closure->frame_size)
{
for (int i = 0; i < closure->frame_size; i++)
{
object_t obj = (&((object_t)(stack + closure->local))[i]);
active_root_inner_insert (obj->attr.type, obj->value);
}
}
}
// After walking every active call frame (if any -- there may be
// none, e.g. between top-level forms), `sp` bounds the outermost
// region: the top-level code's own locals. fp==0 there is the base
// case, not "nothing exists" -- top-level `define`s/values live
// directly in [0, sp) on the ordinary stack, with no call prelude to
// skip (nothing ever "called" the top level). The loop above only
// ever scans *inside* an active call chain, so this region -- where
// e.g. `z` in `(define z (func 123))` lives the moment control
// returns to the top level -- was never scanned as a root at all.
u8_t top_level_cnt = sp / sizeof (Object);
active_root_insert_frame (stack, 0, top_level_cnt);
// Runtime-created globals (top-level `define`s) are roots too --
// without this, anything reachable only via vm->globals (e.g. a
// closure bound to a global, per the comment on
// GLOBAL_REF(VM_GLOBALSEG_SIZE)'s definition site in vm.c) looks
// unreachable to every collect_inner/collect call below, and gets
// freed out from under the global that still points to it.
if (g_current_vm && g_current_vm->globals)
{
size_t globals_cnt = GLOBAL_REF (VM_GLOBALSEG_SIZE) / sizeof (Object);
for (size_t i = 0; i < globals_cnt; i++)
{
object_t obj = &g_current_vm->globals[i];
active_root_inner_insert (obj->attr.type, obj->value);
}
}
}
static void clean_active_root ()
{
/* NOTE: Don't waste time to clean one by one -- the ARN slots get
* reused from index 0 again on the next gc() cycle, and resetting
* the tree root is O(1), same as the old list-head reset was. */
_arn.index = 0;
RB_INIT (&active_root_tree);
}
static void collect (size_t *count, ListHead *head, bool hurt, bool force)
{
/* GC algo:
1. Skip permanent object.
2. If it 's in active root, it get aged if it' s gen-1, keep age if it's
gen-2.
3. If it's not in active root, release it.
4. Collect all gen-2 object in hurt collect.
*/
list_node_t node;
for (node = SLIST_FIRST(head); node != NULL; node = SLIST_NEXT(node, next)) {
if (force)
{
node->obj->attr.gc = FREE_OBJ;
}
else
{
int gc = node->obj->attr.gc;
if (PERMANENT_OBJ == gc)
{
continue;
}
else if (exist (node->obj))
{
if (GEN_1_OBJ == gc)
{
// younger object aged
node->obj->attr.gc = GEN_2_OBJ;
}
else if (GEN_2_OBJ == gc && hurt)
{
// hurtfully collect
node->obj->attr.gc = FREE_OBJ;
}
}
else
{
// Not alive, release it
node->obj->attr.gc = FREE_OBJ;
}
}
if (FREE_OBJ == node->obj->attr.gc)
{
free_object (node->obj);
(*count)++;
}
}
}
static int get_gc_from_node (otype_t type, void *value)
{
switch (type)
{
# define X(tag, ctype, pool) \
case tag: \
return ((ctype)value)->attr.gc;
GC_INNER_TYPE_LIST (X)
# undef X
case closure_on_heap:
case closure_on_stack:
return ((closure_t)value)->attr.gc;
default:
PANIC ("Invalid node type %d\n", type);
}
return FREE_OBJ; // unreachable, PANIC never returns; silences -Wreturn-type
}
static void set_gc_to_node (otype_t type, void *value, int gc)
{
switch (type)
{
# define X(tag, ctype, pool) \
case tag: \
{ \
((ctype)value)->attr.gc = gc; \
break; \
}
GC_INNER_TYPE_LIST (X)
# undef X
case closure_on_heap:
case closure_on_stack:
{
((closure_t)value)->attr.gc = gc;
break;
}
default:
{
PANIC ("Invalid node type %d\n", type);
}
}
}
static void collect_inner (size_t *count, ListHead *head, otype_t type,
bool hurt, bool force)
{
/* GC algo:
1. Skip permanent object.
2. If it's in active root, it get aged if it's gen-1, keep age if it's
gen-2.
3. If it's not in active root, release it.
4. Collect all gen-2 object in hurt collect.
*/
list_node_t node;
for (node = SLIST_FIRST(head); node != NULL; node = SLIST_NEXT(node, next)) {
u8_t gc = force ? FREE_OBJ : get_gc_from_node (type, (void *)node->obj);
if (PERMANENT_OBJ == gc)
{
continue;
}
else if (exist (node->obj))
{
if (GEN_1_OBJ == gc)
{
// younger object aged
gc = GEN_2_OBJ;
}
else if (GEN_2_OBJ == gc && hurt)
{
// hurtfully collect
gc = FREE_OBJ;
}
}
else
{
// Not alive, release it
gc = FREE_OBJ;
}
if (FREE_OBJ == gc)
{
free_inner_object (type, (void *)node->obj);
(*count)++;
}
else
{
set_gc_to_node (type, (void *)node->obj, gc);
}
}
}
static size_t count_me (ListHead *head)
{
size_t cnt = 0;
list_node_t node;
for (node = SLIST_FIRST(head); node != NULL; node = SLIST_NEXT(node, next)) {
cnt++;
}
return cnt;
}
static void release_all_free_objects (ListHead *head, bool force)
{
if (!SLIST_EMPTY (head))
{
list_node_t node = SLIST_FIRST (head);
while (node)
{
list_node_t next_node = SLIST_NEXT(node, next);
// call free_object recursively since node->obj can be a
// composite object
if ((FREE_OBJ == node->obj->attr.gc) || force)
{
/* printf ("release node: %p, obj: %p, value: %p\n", node,
* node->obj, */
/* node->obj->value); */
os_free (node->obj);
// instead of free node, put node into OLN for future use
SLIST_REMOVE (head, node, ListNode, next);
object_list_node_recycle (node);
}
node = next_node;
}
}
}
static void sweep (bool force)
{
# define X(tag, ctype, pool) \
VM_DEBUG ("sweep " #pool "\n"); \
release_all_free_objects (&pool, force);
GC_ALL_POOLS_LIST (X)
# undef X
VM_DEBUG ("sweep obj\n");
release_all_free_objects (&obj_free_pool, force);
}
bool gc (const gc_info_t gci)
{
// Any collection, regardless of what triggered it, counts as
// "caught up" for the proactive budget-based trigger.
alloc_since_last_gc = 0;
/* TODO:
* 1. Obj pool is empty, goto 3
* 2. Free all unused obj:
* a. move from ref_list to free_list (obj pool)
* b. if no collectable obj, then goto 3
* 3. Free obj pool
*/
// usleep (10000);
uint64_t t0 = os_timestamp ();
build_active_root (gci);
uint64_t t1 = os_timestamp ();
size_t count = 0;
# define X(tag, ctype, pool) collect_inner (&count, &pool, tag, false, false);
GC_ALL_POOLS_LIST (X)
# undef X
collect (&count, &obj_free_pool, false, false);
uint64_t t2 = os_timestamp ();
if (0 == count && gci->hurt)
{
/*
NOTE: No memory and no freed object, hurtly collect to release all
active gen-2 object.
FIXME: Hurt collect will cause the active node collected intendedly,
however, this is the edge case if there's no memory to alloc.
Do we have better approach to avoid big hurt?
Or do we really need hurt collect in embedded system?
*/
# define X(tag, ctype, pool) collect_inner (&count, &pool, tag, true, false);
GC_ALL_POOLS_LIST (X)
# undef X
collect (&count, &obj_free_pool, false, false);
}
sweep (false);
uint64_t t3 = os_timestamp ();