/
sgen-gc.c
3361 lines (2773 loc) · 108 KB
/
sgen-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
/*
* sgen-gc.c: Simple generational GC.
*
* Author:
* Paolo Molaro (lupus@ximian.com)
* Rodrigo Kumpera (kumpera@gmail.com)
*
* Copyright 2005-2011 Novell, Inc (http://www.novell.com)
* Copyright 2011 Xamarin Inc (http://www.xamarin.com)
*
* Thread start/stop adapted from Boehm's GC:
* Copyright (c) 1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1996 by Silicon Graphics. All rights reserved.
* Copyright (c) 1998 by Fergus Henderson. All rights reserved.
* Copyright (c) 2000-2004 by Hewlett-Packard Company. All rights reserved.
* Copyright 2001-2003 Ximian, Inc
* Copyright 2003-2010 Novell, Inc.
* Copyright 2011 Xamarin, Inc.
* Copyright (C) 2012 Xamarin Inc
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License 2.0 as published by the Free Software Foundation;
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License 2.0 along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Important: allocation provides always zeroed memory, having to do
* a memset after allocation is deadly for performance.
* Memory usage at startup is currently as follows:
* 64 KB pinned space
* 64 KB internal space
* size of nursery
* We should provide a small memory config with half the sizes
*
* We currently try to make as few mono assumptions as possible:
* 1) 2-word header with no GC pointers in it (first vtable, second to store the
* forwarding ptr)
* 2) gc descriptor is the second word in the vtable (first word in the class)
* 3) 8 byte alignment is the minimum and enough (not true for special structures (SIMD), FIXME)
* 4) there is a function to get an object's size and the number of
* elements in an array.
* 5) we know the special way bounds are allocated for complex arrays
* 6) we know about proxies and how to treat them when domains are unloaded
*
* Always try to keep stack usage to a minimum: no recursive behaviour
* and no large stack allocs.
*
* General description.
* Objects are initially allocated in a nursery using a fast bump-pointer technique.
* When the nursery is full we start a nursery collection: this is performed with a
* copying GC.
* When the old generation is full we start a copying GC of the old generation as well:
* this will be changed to mark&sweep with copying when fragmentation becomes to severe
* in the future. Maybe we'll even do both during the same collection like IMMIX.
*
* The things that complicate this description are:
* *) pinned objects: we can't move them so we need to keep track of them
* *) no precise info of the thread stacks and registers: we need to be able to
* quickly find the objects that may be referenced conservatively and pin them
* (this makes the first issues more important)
* *) large objects are too expensive to be dealt with using copying GC: we handle them
* with mark/sweep during major collections
* *) some objects need to not move even if they are small (interned strings, Type handles):
* we use mark/sweep for them, too: they are not allocated in the nursery, but inside
* PinnedChunks regions
*/
/*
* TODO:
*) we could have a function pointer in MonoClass to implement
customized write barriers for value types
*) investigate the stuff needed to advance a thread to a GC-safe
point (single-stepping, read from unmapped memory etc) and implement it.
This would enable us to inline allocations and write barriers, for example,
or at least parts of them, like the write barrier checks.
We may need this also for handling precise info on stacks, even simple things
as having uninitialized data on the stack and having to wait for the prolog
to zero it. Not an issue for the last frame that we scan conservatively.
We could always not trust the value in the slots anyway.
*) modify the jit to save info about references in stack locations:
this can be done just for locals as a start, so that at least
part of the stack is handled precisely.
*) test/fix endianess issues
*) Implement a card table as the write barrier instead of remembered
sets? Card tables are not easy to implement with our current
memory layout. We have several different kinds of major heap
objects: Small objects in regular blocks, small objects in pinned
chunks and LOS objects. If we just have a pointer we have no way
to tell which kind of object it points into, therefore we cannot
know where its card table is. The least we have to do to make
this happen is to get rid of write barriers for indirect stores.
(See next item)
*) Get rid of write barriers for indirect stores. We can do this by
telling the GC to wbarrier-register an object once we do an ldloca
or ldelema on it, and to unregister it once it's not used anymore
(it can only travel downwards on the stack). The problem with
unregistering is that it needs to happen eventually no matter
what, even if exceptions are thrown, the thread aborts, etc.
Rodrigo suggested that we could do only the registering part and
let the collector find out (pessimistically) when it's safe to
unregister, namely when the stack pointer of the thread that
registered the object is higher than it was when the registering
happened. This might make for a good first implementation to get
some data on performance.
*) Some sort of blacklist support? Blacklists is a concept from the
Boehm GC: if during a conservative scan we find pointers to an
area which we might use as heap, we mark that area as unusable, so
pointer retention by random pinning pointers is reduced.
*) experiment with max small object size (very small right now - 2kb,
because it's tied to the max freelist size)
*) add an option to mmap the whole heap in one chunk: it makes for many
simplifications in the checks (put the nursery at the top and just use a single
check for inclusion/exclusion): the issue this has is that on 32 bit systems it's
not flexible (too much of the address space may be used by default or we can't
increase the heap as needed) and we'd need a race-free mechanism to return memory
back to the system (mprotect(PROT_NONE) will still keep the memory allocated if it
was written to, munmap is needed, but the following mmap may not find the same segment
free...)
*) memzero the major fragments after restarting the world and optionally a smaller
chunk at a time
*) investigate having fragment zeroing threads
*) separate locks for finalization and other minor stuff to reduce
lock contention
*) try a different copying order to improve memory locality
*) a thread abort after a store but before the write barrier will
prevent the write barrier from executing
*) specialized dynamically generated markers/copiers
*) Dynamically adjust TLAB size to the number of threads. If we have
too many threads that do allocation, we might need smaller TLABs,
and we might get better performance with larger TLABs if we only
have a handful of threads. We could sum up the space left in all
assigned TLABs and if that's more than some percentage of the
nursery size, reduce the TLAB size.
*) Explore placing unreachable objects on unused nursery memory.
Instead of memset'ng a region to zero, place an int[] covering it.
A good place to start is add_nursery_frag. The tricky thing here is
placing those objects atomically outside of a collection.
*) Allocation should use asymmetric Dekker synchronization:
http://blogs.oracle.com/dave/resource/Asymmetric-Dekker-Synchronization.txt
This should help weak consistency archs.
*/
#include "config.h"
#ifdef HAVE_SGEN_GC
#ifdef __MACH__
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#define _DARWIN_C_SOURCE
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif
#ifdef HAVE_PTHREAD_NP_H
#include <pthread_np.h>
#endif
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include "mono/sgen/sgen-gc.h"
#include "mono/sgen/sgen-cardtable.h"
#include "mono/sgen/sgen-protocol.h"
#include "mono/sgen/sgen-memory-governor.h"
#include "mono/sgen/sgen-hash-table.h"
#include "mono/sgen/sgen-cardtable.h"
#include "mono/sgen/sgen-pinning.h"
#include "mono/sgen/sgen-workers.h"
#include "mono/sgen/sgen-client.h"
#include "mono/sgen/sgen-pointer-queue.h"
#include "mono/sgen/gc-internal-agnostic.h"
#include "mono/utils/mono-proclib.h"
#include "mono/utils/mono-memory-model.h"
#include "mono/utils/hazard-pointer.h"
#include <mono/utils/memcheck.h>
#undef pthread_create
#undef pthread_join
#undef pthread_detach
/*
* ######################################################################
* ######## Types and constants used by the GC.
* ######################################################################
*/
/* 0 means not initialized, 1 is initialized, -1 means in progress */
static int gc_initialized = 0;
/* If set, check if we need to do something every X allocations */
gboolean has_per_allocation_action;
/* If set, do a heap check every X allocation */
guint32 verify_before_allocs = 0;
/* If set, do a minor collection before every X allocation */
guint32 collect_before_allocs = 0;
/* If set, do a whole heap check before each collection */
static gboolean whole_heap_check_before_collection = FALSE;
/* If set, do a heap consistency check before each minor collection */
static gboolean consistency_check_at_minor_collection = FALSE;
/* If set, do a mod union consistency check before each finishing collection pause */
static gboolean mod_union_consistency_check = FALSE;
/* If set, check whether mark bits are consistent after major collections */
static gboolean check_mark_bits_after_major_collection = FALSE;
/* If set, check that all nursery objects are pinned/not pinned, depending on context */
static gboolean check_nursery_objects_pinned = FALSE;
/* If set, do a few checks when the concurrent collector is used */
static gboolean do_concurrent_checks = FALSE;
/* If set, do a plausibility check on the scan_starts before and after
each collection */
static gboolean do_scan_starts_check = FALSE;
/*
* If the major collector is concurrent and this is FALSE, we will
* never initiate a synchronous major collection, unless requested via
* GC.Collect().
*/
static gboolean allow_synchronous_major = TRUE;
static gboolean disable_minor_collections = FALSE;
static gboolean disable_major_collections = FALSE;
static gboolean do_verify_nursery = FALSE;
static gboolean do_dump_nursery_content = FALSE;
static gboolean enable_nursery_canaries = FALSE;
#ifdef HEAVY_STATISTICS
guint64 stat_objects_alloced_degraded = 0;
guint64 stat_bytes_alloced_degraded = 0;
guint64 stat_copy_object_called_nursery = 0;
guint64 stat_objects_copied_nursery = 0;
guint64 stat_copy_object_called_major = 0;
guint64 stat_objects_copied_major = 0;
guint64 stat_scan_object_called_nursery = 0;
guint64 stat_scan_object_called_major = 0;
guint64 stat_slots_allocated_in_vain;
guint64 stat_nursery_copy_object_failed_from_space = 0;
guint64 stat_nursery_copy_object_failed_forwarded = 0;
guint64 stat_nursery_copy_object_failed_pinned = 0;
guint64 stat_nursery_copy_object_failed_to_space = 0;
static guint64 stat_wbarrier_add_to_global_remset = 0;
static guint64 stat_wbarrier_arrayref_copy = 0;
static guint64 stat_wbarrier_generic_store = 0;
static guint64 stat_wbarrier_generic_store_atomic = 0;
static guint64 stat_wbarrier_set_root = 0;
#endif
static guint64 stat_pinned_objects = 0;
static guint64 time_minor_pre_collection_fragment_clear = 0;
static guint64 time_minor_pinning = 0;
static guint64 time_minor_scan_remsets = 0;
static guint64 time_minor_scan_pinned = 0;
static guint64 time_minor_scan_roots = 0;
static guint64 time_minor_finish_gray_stack = 0;
static guint64 time_minor_fragment_creation = 0;
static guint64 time_major_pre_collection_fragment_clear = 0;
static guint64 time_major_pinning = 0;
static guint64 time_major_scan_pinned = 0;
static guint64 time_major_scan_roots = 0;
static guint64 time_major_scan_mod_union = 0;
static guint64 time_major_finish_gray_stack = 0;
static guint64 time_major_free_bigobjs = 0;
static guint64 time_major_los_sweep = 0;
static guint64 time_major_sweep = 0;
static guint64 time_major_fragment_creation = 0;
static guint64 time_max = 0;
static SGEN_TV_DECLARE (time_major_conc_collection_start);
static SGEN_TV_DECLARE (time_major_conc_collection_end);
static SGEN_TV_DECLARE (last_minor_collection_start_tv);
static SGEN_TV_DECLARE (last_minor_collection_end_tv);
int gc_debug_level = 0;
FILE* gc_debug_file;
/*
void
mono_gc_flush_info (void)
{
fflush (gc_debug_file);
}
*/
#define TV_DECLARE SGEN_TV_DECLARE
#define TV_GETTIME SGEN_TV_GETTIME
#define TV_ELAPSED SGEN_TV_ELAPSED
static SGEN_TV_DECLARE (sgen_init_timestamp);
NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
#define object_is_forwarded SGEN_OBJECT_IS_FORWARDED
#define object_is_pinned SGEN_OBJECT_IS_PINNED
#define pin_object SGEN_PIN_OBJECT
#define ptr_in_nursery sgen_ptr_in_nursery
#define LOAD_VTABLE SGEN_LOAD_VTABLE
gboolean
nursery_canaries_enabled (void)
{
return enable_nursery_canaries;
}
#define safe_object_get_size sgen_safe_object_get_size
/*
* ######################################################################
* ######## Global data.
* ######################################################################
*/
LOCK_DECLARE (gc_mutex);
gboolean sgen_try_free_some_memory;
#define SCAN_START_SIZE SGEN_SCAN_START_SIZE
size_t degraded_mode = 0;
static mword bytes_pinned_from_failed_allocation = 0;
GCMemSection *nursery_section = NULL;
static volatile mword lowest_heap_address = ~(mword)0;
static volatile mword highest_heap_address = 0;
LOCK_DECLARE (sgen_interruption_mutex);
int current_collection_generation = -1;
static volatile gboolean concurrent_collection_in_progress = FALSE;
/* objects that are ready to be finalized */
static SgenPointerQueue fin_ready_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_FINALIZE_READY);
static SgenPointerQueue critical_fin_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_FINALIZE_READY);
/* registered roots: the key to the hash is the root start address */
/*
* Different kinds of roots are kept separate to speed up pin_from_roots () for example.
*/
SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL),
SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL),
SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL)
};
static mword roots_size = 0; /* amount of memory in the root set */
/* The size of a TLAB */
/* The bigger the value, the less often we have to go to the slow path to allocate a new
* one, but the more space is wasted by threads not allocating much memory.
* FIXME: Tune this.
* FIXME: Make this self-tuning for each thread.
*/
guint32 tlab_size = (1024 * 4);
#define MAX_SMALL_OBJ_SIZE SGEN_MAX_SMALL_OBJ_SIZE
#define ALLOC_ALIGN SGEN_ALLOC_ALIGN
#define ALIGN_UP SGEN_ALIGN_UP
#ifdef SGEN_DEBUG_INTERNAL_ALLOC
MonoNativeThreadId main_gc_thread = NULL;
#endif
/*Object was pinned during the current collection*/
static mword objects_pinned;
/*
* ######################################################################
* ######## Macros and function declarations.
* ######################################################################
*/
typedef SgenGrayQueue GrayQueue;
/* forward declarations */
static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
static void pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx);
static void finish_gray_stack (int generation, ScanCopyContext ctx);
SgenMajorCollector major_collector;
SgenMinorCollector sgen_minor_collector;
/* FIXME: get rid of this */
static GrayQueue gray_queue;
static SgenRememberedSet remset;
/* The gray queue to use from the main collection thread. */
#define WORKERS_DISTRIBUTE_GRAY_QUEUE (&gray_queue)
/*
* The gray queue a worker job must use. If we're not parallel or
* concurrent, we use the main gray queue.
*/
static SgenGrayQueue*
sgen_workers_get_job_gray_queue (WorkerData *worker_data)
{
return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
}
static void
gray_queue_redirect (SgenGrayQueue *queue)
{
gboolean wake = FALSE;
for (;;) {
GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
if (!section)
break;
sgen_section_gray_queue_enqueue (queue->alloc_prepare_data, section);
wake = TRUE;
}
if (wake) {
g_assert (concurrent_collection_in_progress);
sgen_workers_ensure_awake ();
}
}
static void
gray_queue_enable_redirect (SgenGrayQueue *queue)
{
if (!concurrent_collection_in_progress)
return;
sgen_gray_queue_set_alloc_prepare (queue, gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
gray_queue_redirect (queue);
}
void
sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags, gboolean fail_on_canaries)
{
while (start < end) {
size_t size;
char *obj;
if (!*(void**)start) {
start += sizeof (void*); /* should be ALLOC_ALIGN, really */
continue;
}
if (allow_flags) {
if (!(obj = SGEN_OBJECT_IS_FORWARDED (start)))
obj = start;
} else {
obj = start;
}
if (!sgen_client_object_is_array_fill ((GCObject*)obj)) {
CHECK_CANARY_FOR_OBJECT ((GCObject*)obj, fail_on_canaries);
size = ALIGN_UP (safe_object_get_size ((GCObject*)obj));
callback ((GCObject*)obj, size, data);
CANARIFY_SIZE (size);
} else {
size = ALIGN_UP (safe_object_get_size ((GCObject*)obj));
}
start += size;
}
}
/*
* sgen_add_to_global_remset:
*
* The global remset contains locations which point into newspace after
* a minor collection. This can happen if the objects they point to are pinned.
*
* LOCKING: If called from a parallel collector, the global remset
* lock must be held. For serial collectors that is not necessary.
*/
void
sgen_add_to_global_remset (gpointer ptr, gpointer obj)
{
SGEN_ASSERT (5, sgen_ptr_in_nursery (obj), "Target pointer of global remset must be in the nursery");
HEAVY_STAT (++stat_wbarrier_add_to_global_remset);
if (!major_collector.is_concurrent) {
SGEN_ASSERT (5, current_collection_generation != -1, "Global remsets can only be added during collections");
} else {
if (current_collection_generation == -1)
SGEN_ASSERT (5, sgen_concurrent_collection_in_progress (), "Global remsets outside of collection pauses can only be added by the concurrent collector");
}
if (!object_is_pinned (obj))
SGEN_ASSERT (5, sgen_minor_collector.is_split || sgen_concurrent_collection_in_progress (), "Non-pinned objects can only remain in nursery if it is a split nursery");
else if (sgen_cement_lookup_or_register (obj))
return;
remset.record_pointer (ptr);
sgen_pin_stats_register_global_remset (obj);
SGEN_LOG (8, "Adding global remset for %p", ptr);
binary_protocol_global_remset (ptr, obj, (gpointer)SGEN_LOAD_VTABLE (obj));
}
/*
* sgen_drain_gray_stack:
*
* Scan objects in the gray stack until the stack is empty. This should be called
* frequently after each object is copied, to achieve better locality and cache
* usage.
*
* max_objs is the maximum number of objects to scan, or -1 to scan until the stack is
* empty.
*/
gboolean
sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx)
{
ScanObjectFunc scan_func = ctx.ops->scan_object;
GrayQueue *queue = ctx.queue;
if (current_collection_generation == GENERATION_OLD && major_collector.drain_gray_stack)
return major_collector.drain_gray_stack (ctx);
do {
int i;
for (i = 0; i != max_objs; ++i) {
GCObject *obj;
SgenDescriptor desc;
GRAY_OBJECT_DEQUEUE (queue, &obj, &desc);
if (!obj)
return TRUE;
SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
scan_func (obj, desc, queue);
}
} while (max_objs < 0);
return FALSE;
}
/*
* Addresses in the pin queue are already sorted. This function finds
* the object header for each address and pins the object. The
* addresses must be inside the nursery section. The (start of the)
* address array is overwritten with the addresses of the actually
* pinned objects. Return the number of pinned objects.
*/
static int
pin_objects_from_nursery_pin_queue (gboolean do_scan_objects, ScanCopyContext ctx)
{
GCMemSection *section = nursery_section;
void **start = sgen_pinning_get_entry (section->pin_queue_first_entry);
void **end = sgen_pinning_get_entry (section->pin_queue_last_entry);
void *start_nursery = section->data;
void *end_nursery = section->next_data;
void *last = NULL;
int count = 0;
void *search_start;
void *addr;
void *pinning_front = start_nursery;
size_t idx;
void **definitely_pinned = start;
ScanObjectFunc scan_func = ctx.ops->scan_object;
SgenGrayQueue *queue = ctx.queue;
sgen_nursery_allocator_prepare_for_pinning ();
while (start < end) {
GCObject *obj_to_pin = NULL;
size_t obj_to_pin_size = 0;
SgenDescriptor desc;
addr = *start;
SGEN_ASSERT (0, addr >= start_nursery && addr < end_nursery, "Potential pinning address out of range");
SGEN_ASSERT (0, addr >= last, "Pin queue not sorted");
if (addr == last) {
++start;
continue;
}
SGEN_LOG (5, "Considering pinning addr %p", addr);
/* We've already processed everything up to pinning_front. */
if (addr < pinning_front) {
start++;
continue;
}
/*
* Find the closest scan start <= addr. We might search backward in the
* scan_starts array because entries might be NULL. In the worst case we
* start at start_nursery.
*/
idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
SGEN_ASSERT (0, idx < section->num_scan_start, "Scan start index out of range");
search_start = (void*)section->scan_starts [idx];
if (!search_start || search_start > addr) {
while (idx) {
--idx;
search_start = section->scan_starts [idx];
if (search_start && search_start <= addr)
break;
}
if (!search_start || search_start > addr)
search_start = start_nursery;
}
/*
* If the pinning front is closer than the scan start we found, start
* searching at the front.
*/
if (search_start < pinning_front)
search_start = pinning_front;
/*
* Now addr should be in an object a short distance from search_start.
*
* search_start must point to zeroed mem or point to an object.
*/
do {
size_t obj_size, canarified_obj_size;
/* Skip zeros. */
if (!*(void**)search_start) {
search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
/* The loop condition makes sure we don't overrun addr. */
continue;
}
canarified_obj_size = obj_size = ALIGN_UP (safe_object_get_size ((GCObject*)search_start));
/*
* Filler arrays are marked by an invalid sync word. We don't
* consider them for pinning. They are not delimited by canaries,
* either.
*/
if (!sgen_client_object_is_array_fill ((GCObject*)search_start)) {
CHECK_CANARY_FOR_OBJECT (search_start, TRUE);
CANARIFY_SIZE (canarified_obj_size);
if (addr >= search_start && (char*)addr < (char*)search_start + obj_size) {
/* This is the object we're looking for. */
obj_to_pin = (GCObject*)search_start;
obj_to_pin_size = canarified_obj_size;
break;
}
}
/* Skip to the next object */
search_start = (void*)((char*)search_start + canarified_obj_size);
} while (search_start <= addr);
/* We've searched past the address we were looking for. */
if (!obj_to_pin) {
pinning_front = search_start;
goto next_pin_queue_entry;
}
/*
* We've found an object to pin. It might still be a dummy array, but we
* can advance the pinning front in any case.
*/
pinning_front = (char*)obj_to_pin + obj_to_pin_size;
/*
* If this is a dummy array marking the beginning of a nursery
* fragment, we don't pin it.
*/
if (sgen_client_object_is_array_fill (obj_to_pin))
goto next_pin_queue_entry;
/*
* Finally - pin the object!
*/
desc = sgen_obj_get_descriptor_safe (obj_to_pin);
if (do_scan_objects) {
scan_func (obj_to_pin, desc, queue);
} else {
SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
obj_to_pin, *(void**)obj_to_pin, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj_to_pin)), count);
binary_protocol_pin (obj_to_pin,
(gpointer)LOAD_VTABLE (obj_to_pin),
safe_object_get_size (obj_to_pin));
pin_object (obj_to_pin);
GRAY_OBJECT_ENQUEUE (queue, obj_to_pin, desc);
sgen_pin_stats_register_object (obj_to_pin, obj_to_pin_size);
definitely_pinned [count] = obj_to_pin;
count++;
}
next_pin_queue_entry:
last = addr;
++start;
}
sgen_client_nursery_objects_pinned (definitely_pinned, count);
stat_pinned_objects += count;
return count;
}
static void
pin_objects_in_nursery (gboolean do_scan_objects, ScanCopyContext ctx)
{
size_t reduced_to;
if (nursery_section->pin_queue_first_entry == nursery_section->pin_queue_last_entry)
return;
reduced_to = pin_objects_from_nursery_pin_queue (do_scan_objects, ctx);
nursery_section->pin_queue_last_entry = nursery_section->pin_queue_first_entry + reduced_to;
}
/*
* This function is only ever called (via `collector_pin_object()` in `sgen-copy-object.h`)
* when we can't promote an object because we're out of memory.
*/
void
sgen_pin_object (GCObject *object, GrayQueue *queue)
{
/*
* All pinned objects are assumed to have been staged, so we need to stage as well.
* Also, the count of staged objects shows that "late pinning" happened.
*/
sgen_pin_stage_ptr (object);
SGEN_PIN_OBJECT (object);
binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
++objects_pinned;
sgen_pin_stats_register_object (object, safe_object_get_size (object));
GRAY_OBJECT_ENQUEUE (queue, object, sgen_obj_get_descriptor_safe (object));
}
/* Sort the addresses in array in increasing order.
* Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
*/
void
sgen_sort_addresses (void **array, size_t size)
{
size_t i;
void *tmp;
for (i = 1; i < size; ++i) {
size_t child = i;
while (child > 0) {
size_t parent = (child - 1) / 2;
if (array [parent] >= array [child])
break;
tmp = array [parent];
array [parent] = array [child];
array [child] = tmp;
child = parent;
}
}
for (i = size - 1; i > 0; --i) {
size_t end, root;
tmp = array [i];
array [i] = array [0];
array [0] = tmp;
end = i - 1;
root = 0;
while (root * 2 + 1 <= end) {
size_t child = root * 2 + 1;
if (child < end && array [child] < array [child + 1])
++child;
if (array [root] >= array [child])
break;
tmp = array [root];
array [root] = array [child];
array [child] = tmp;
root = child;
}
}
}
/*
* Scan the memory between start and end and queue values which could be pointers
* to the area between start_nursery and end_nursery for later consideration.
* Typically used for thread stacks.
*/
void
sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
{
int count = 0;
#if defined(VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE) && !defined(_WIN64)
VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
#endif
while (start < end) {
/*
* *start can point to the middle of an object
* note: should we handle pointing at the end of an object?
* pinning in C# code disallows pointing at the end of an object
* but there is some small chance that an optimizing C compiler
* may keep the only reference to an object by pointing
* at the end of it. We ignore this small chance for now.
* Pointers to the end of an object are indistinguishable
* from pointers to the start of the next object in memory
* so if we allow that we'd need to pin two objects...
* We queue the pointer in an array, the
* array will then be sorted and uniqued. This way
* we can coalesce several pinning pointers and it should
* be faster since we'd do a memory scan with increasing
* addresses. Note: we can align the address to the allocation
* alignment, so the unique process is more effective.
*/
mword addr = (mword)*start;
addr &= ~(ALLOC_ALIGN - 1);
if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
sgen_pin_stage_ptr ((void*)addr);
binary_protocol_pin_stage (start, (void*)addr);
sgen_pin_stats_register_address ((char*)addr, pin_type);
count++;
}
start++;
}
if (count)
SGEN_LOG (7, "found %d potential pinned heap pointers", count);
}
/*
* The first thing we do in a collection is to identify pinned objects.
* This function considers all the areas of memory that need to be
* conservatively scanned.
*/
static void
pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx)
{
void **start_root;
RootRecord *root;
SGEN_LOG (2, "Scanning pinned roots (%d bytes, %d/%d entries)", (int)roots_size, roots_hash [ROOT_TYPE_NORMAL].num_entries, roots_hash [ROOT_TYPE_PINNED].num_entries);
/* objects pinned from the API are inside these roots */
SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], start_root, root) {
SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
sgen_conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
} SGEN_HASH_TABLE_FOREACH_END;
/* now deal with the thread stacks
* in the future we should be able to conservatively scan only:
* *) the cpu registers
* *) the unmanaged stack frames
* *) the _last_ managed stack frame
* *) pointers slots in managed frames
*/
sgen_client_scan_thread_data (start_nursery, end_nursery, FALSE, ctx);
}
static void
single_arg_user_copy_or_mark (GCObject **obj, void *gc_data)
{
ScanCopyContext *ctx = gc_data;
ctx->ops->copy_or_mark_object (obj, ctx->queue);
}
/*
* The memory area from start_root to end_root contains pointers to objects.
* Their position is precisely described by @desc (this means that the pointer
* can be either NULL or the pointer to the start of an object).
* This functions copies them to to_space updates them.
*
* This function is not thread-safe!
*/
static void
precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, SgenDescriptor desc, ScanCopyContext ctx)
{
CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
SgenGrayQueue *queue = ctx.queue;
switch (desc & ROOT_DESC_TYPE_MASK) {
case ROOT_DESC_BITMAP:
desc >>= ROOT_DESC_TYPE_SHIFT;
while (desc) {
if ((desc & 1) && *start_root) {
copy_func ((GCObject**)start_root, queue);
SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
}
desc >>= 1;
start_root++;
}
return;
case ROOT_DESC_COMPLEX: {
gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
gsize bwords = (*bitmap_data) - 1;
void **start_run = start_root;
bitmap_data++;
while (bwords-- > 0) {
gsize bmap = *bitmap_data++;
void **objptr = start_run;
while (bmap) {
if ((bmap & 1) && *objptr) {
copy_func ((GCObject**)objptr, queue);
SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
}
bmap >>= 1;
++objptr;
}
start_run += GC_BITS_PER_WORD;
}
break;
}
case ROOT_DESC_USER: {
SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
marker (start_root, single_arg_user_copy_or_mark, &ctx);
break;
}
case ROOT_DESC_RUN_LEN:
g_assert_not_reached ();
default:
g_assert_not_reached ();
}
}
static void
reset_heap_boundaries (void)
{
lowest_heap_address = ~(mword)0;
highest_heap_address = 0;
}
void
sgen_update_heap_boundaries (mword low, mword high)
{
mword old;
do {
old = lowest_heap_address;
if (low >= old)
break;
} while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
do {
old = highest_heap_address;
if (high <= old)
break;
} while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
}
/*
* Allocate and setup the data structures needed to be able to allocate objects
* in the nursery. The nursery is stored in nursery_section.
*/
static void
alloc_nursery (void)
{
GCMemSection *section;
char *data;
size_t scan_starts;
size_t alloc_size;
if (nursery_section)
return;
SGEN_LOG (2, "Allocating nursery size: %zu", (size_t)sgen_nursery_size);
/* later we will alloc a larger area for the nursery but only activate
* what we need. The rest will be used as expansion if we have too many pinned
* objects in the existing nursery.
*/
/* FIXME: handle OOM */
section = sgen_alloc_internal (INTERNAL_MEM_SECTION);
alloc_size = sgen_nursery_size;