/
sgen-gc.c
5606 lines (4732 loc) · 170 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
#ifdef HAVE_SEMAPHORE_H
#include <semaphore.h>
#endif
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <assert.h>
#include "metadata/sgen-gc.h"
#include "metadata/metadata-internals.h"
#include "metadata/class-internals.h"
#include "metadata/gc-internal.h"
#include "metadata/object-internals.h"
#include "metadata/threads.h"
#include "metadata/sgen-cardtable.h"
#include "metadata/sgen-protocol.h"
#include "metadata/sgen-archdep.h"
#include "metadata/sgen-bridge.h"
#include "metadata/sgen-memory-governor.h"
#include "metadata/sgen-hash-table.h"
#include "metadata/mono-gc.h"
#include "metadata/method-builder.h"
#include "metadata/profiler-private.h"
#include "metadata/monitor.h"
#include "metadata/threadpool-internals.h"
#include "metadata/mempool-internals.h"
#include "metadata/marshal.h"
#include "metadata/runtime.h"
#include "metadata/sgen-cardtable.h"
#include "metadata/sgen-pinning.h"
#include "metadata/sgen-workers.h"
#include "metadata/sgen-layout-stats.h"
#include "utils/mono-mmap.h"
#include "utils/mono-time.h"
#include "utils/mono-semaphore.h"
#include "utils/mono-counters.h"
#include "utils/mono-proclib.h"
#include "utils/mono-memory-model.h"
#include "utils/mono-logger-internal.h"
#include "utils/dtrace.h"
#include <mono/utils/mono-logger-internal.h>
#include <mono/utils/memcheck.h>
#if defined(__MACH__)
#include "utils/mach-support.h"
#endif
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
a = i,
enum {
#include "mono/cil/opcode.def"
CEE_LAST
};
#undef OPDEF
#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, check that there are no references to the domain left at domain unload */
static gboolean xdomain_checks = FALSE;
/* If not null, dump the heap after each collection into this file */
static FILE *heap_dump_file = NULL;
/* If set, mark stacks conservatively, even if precise marking is possible */
static gboolean conservative_stack_mark = 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 nursery_collection_is_parallel = FALSE;
static gboolean disable_minor_collections = FALSE;
static gboolean disable_major_collections = FALSE;
gboolean do_pin_stats = FALSE;
static gboolean do_verify_nursery = FALSE;
static gboolean do_dump_nursery_content = FALSE;
#ifdef HEAVY_STATISTICS
long long stat_objects_alloced_degraded = 0;
long long stat_bytes_alloced_degraded = 0;
long long stat_copy_object_called_nursery = 0;
long long stat_objects_copied_nursery = 0;
long long stat_copy_object_called_major = 0;
long long stat_objects_copied_major = 0;
long long stat_scan_object_called_nursery = 0;
long long stat_scan_object_called_major = 0;
long long stat_slots_allocated_in_vain;
long long stat_nursery_copy_object_failed_from_space = 0;
long long stat_nursery_copy_object_failed_forwarded = 0;
long long stat_nursery_copy_object_failed_pinned = 0;
long long stat_nursery_copy_object_failed_to_space = 0;
static int stat_wbarrier_add_to_global_remset = 0;
static int stat_wbarrier_set_field = 0;
static int stat_wbarrier_set_arrayref = 0;
static int stat_wbarrier_arrayref_copy = 0;
static int stat_wbarrier_generic_store = 0;
static int stat_wbarrier_set_root = 0;
static int stat_wbarrier_value_copy = 0;
static int stat_wbarrier_object_copy = 0;
#endif
int stat_minor_gcs = 0;
int stat_major_gcs = 0;
static long long stat_pinned_objects = 0;
static long long time_minor_pre_collection_fragment_clear = 0;
static long long time_minor_pinning = 0;
static long long time_minor_scan_remsets = 0;
static long long time_minor_scan_pinned = 0;
static long long time_minor_scan_registered_roots = 0;
static long long time_minor_scan_thread_data = 0;
static long long time_minor_finish_gray_stack = 0;
static long long time_minor_fragment_creation = 0;
static long long time_major_pre_collection_fragment_clear = 0;
static long long time_major_pinning = 0;
static long long time_major_scan_pinned = 0;
static long long time_major_scan_registered_roots = 0;
static long long time_major_scan_thread_data = 0;
static long long time_major_scan_alloc_pinned = 0;
static long long time_major_scan_finalized = 0;
static long long time_major_scan_big_objects = 0;
static long long time_major_finish_gray_stack = 0;
static long long time_major_free_bigobjs = 0;
static long long time_major_los_sweep = 0;
static long long time_major_sweep = 0;
static long long time_major_fragment_creation = 0;
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
#define TV_ELAPSED_MS SGEN_TV_ELAPSED_MS
#define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
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 unpin_object SGEN_UNPIN_OBJECT
#define ptr_in_nursery sgen_ptr_in_nursery
#define LOAD_VTABLE SGEN_LOAD_VTABLE
static const char*
safe_name (void* obj)
{
MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
return vt->klass->name;
}
#define safe_object_get_size sgen_safe_object_get_size
const char*
sgen_safe_name (void* obj)
{
return safe_name (obj);
}
/*
* ######################################################################
* ######## Global data.
* ######################################################################
*/
LOCK_DECLARE (gc_mutex);
#define SCAN_START_SIZE SGEN_SCAN_START_SIZE
static mword pagesize = 4096;
int degraded_mode = 0;
static mword bytes_pinned_from_failed_allocation = 0;
GCMemSection *nursery_section = NULL;
static mword lowest_heap_address = ~(mword)0;
static mword highest_heap_address = 0;
LOCK_DECLARE (sgen_interruption_mutex);
static LOCK_DECLARE (pin_queue_mutex);
#define LOCK_PIN_QUEUE mono_mutex_lock (&pin_queue_mutex)
#define UNLOCK_PIN_QUEUE mono_mutex_unlock (&pin_queue_mutex)
typedef struct _FinalizeReadyEntry FinalizeReadyEntry;
struct _FinalizeReadyEntry {
FinalizeReadyEntry *next;
void *object;
};
typedef struct _EphemeronLinkNode EphemeronLinkNode;
struct _EphemeronLinkNode {
EphemeronLinkNode *next;
char *array;
};
typedef struct {
void *key;
void *value;
} Ephemeron;
int current_collection_generation = -1;
volatile gboolean concurrent_collection_in_progress = FALSE;
/* objects that are ready to be finalized */
static FinalizeReadyEntry *fin_ready_list = NULL;
static FinalizeReadyEntry *critical_fin_list = NULL;
static EphemeronLinkNode *ephemeron_list;
/* 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), mono_aligned_addr_hash, NULL),
SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL)
};
static mword roots_size = 0; /* amount of memory in the root set */
#define GC_ROOT_NUM 32
typedef struct {
int count; /* must be the first field */
void *objects [GC_ROOT_NUM];
int root_types [GC_ROOT_NUM];
uintptr_t extra_info [GC_ROOT_NUM];
} GCRootReport;
static void
notify_gc_roots (GCRootReport *report)
{
if (!report->count)
return;
mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
report->count = 0;
}
static void
add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
{
if (report->count == GC_ROOT_NUM)
notify_gc_roots (report);
report->objects [report->count] = object;
report->root_types [report->count] = rtype;
report->extra_info [report->count++] = (uintptr_t)((MonoVTable*)LOAD_VTABLE (object))->klass;
}
MonoNativeTlsKey thread_info_key;
#ifdef HAVE_KW_THREAD
__thread SgenThreadInfo *sgen_thread_info;
__thread char *stack_end;
#endif
/* 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
/* Functions supplied by the runtime to be called by the GC */
static MonoGCCallbacks gc_callbacks;
#define ALLOC_ALIGN SGEN_ALLOC_ALIGN
#define ALLOC_ALIGN_BITS SGEN_ALLOC_ALIGN_BITS
#define ALIGN_UP SGEN_ALIGN_UP
#define MOVED_OBJECTS_NUM 64
static void *moved_objects [MOVED_OBJECTS_NUM];
static int moved_objects_idx = 0;
/* Vtable of the objects used to fill out nursery fragments before a collection */
static MonoVTable *array_fill_vtable;
#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.
* ######################################################################
*/
inline static void*
align_pointer (void *ptr)
{
mword p = (mword)ptr;
p += sizeof (gpointer) - 1;
p &= ~ (sizeof (gpointer) - 1);
return (void*)p;
}
typedef SgenGrayQueue GrayQueue;
/* forward declarations */
static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue);
static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
static void scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx);
static void report_finalizer_roots (void);
static void report_registered_roots (void);
static void pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue);
static int pin_objects_from_addresses (GCMemSection *section, void **start, void **end, void *start_nursery, void *end_nursery, ScanCopyContext ctx);
static void finish_gray_stack (int generation, GrayQueue *queue);
void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise);
static void init_stats (void);
static int mark_ephemerons_in_range (ScanCopyContext ctx);
static void clear_unreachable_ephemerons (ScanCopyContext ctx);
static void null_ephemerons_for_domain (MonoDomain *domain);
static gboolean major_update_or_finish_concurrent_collection (gboolean force_finish);
SgenObjectOperations current_object_ops;
SgenMajorCollector major_collector;
SgenMinorCollector sgen_minor_collector;
static GrayQueue gray_queue;
static SgenRemeberedSet 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 ||
(current_collection_generation == GENERATION_OLD && major_collector.is_parallel));
if (sgen_workers_have_started ()) {
sgen_workers_wake_up_all ();
} else {
if (concurrent_collection_in_progress)
g_assert (current_collection_generation == -1);
}
}
}
static gboolean
is_xdomain_ref_allowed (gpointer *ptr, char *obj, MonoDomain *domain)
{
MonoObject *o = (MonoObject*)(obj);
MonoObject *ref = (MonoObject*)*(ptr);
int offset = (char*)(ptr) - (char*)o;
if (o->vtable->klass == mono_defaults.thread_class && offset == G_STRUCT_OFFSET (MonoThread, internal_thread))
return TRUE;
if (o->vtable->klass == mono_defaults.internal_thread_class && offset == G_STRUCT_OFFSET (MonoInternalThread, current_appcontext))
return TRUE;
#ifndef DISABLE_REMOTING
if (mono_class_has_parent_fast (o->vtable->klass, mono_defaults.real_proxy_class) &&
offset == G_STRUCT_OFFSET (MonoRealProxy, unwrapped_server))
return TRUE;
#endif
/* Thread.cached_culture_info */
if (!strcmp (ref->vtable->klass->name_space, "System.Globalization") &&
!strcmp (ref->vtable->klass->name, "CultureInfo") &&
!strcmp(o->vtable->klass->name_space, "System") &&
!strcmp(o->vtable->klass->name, "Object[]"))
return TRUE;
/*
* at System.IO.MemoryStream.InternalConstructor (byte[],int,int,bool,bool) [0x0004d] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.IO/MemoryStream.cs:121
* at System.IO.MemoryStream..ctor (byte[]) [0x00017] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.IO/MemoryStream.cs:81
* at (wrapper remoting-invoke-with-check) System.IO.MemoryStream..ctor (byte[]) <IL 0x00020, 0xffffffff>
* at System.Runtime.Remoting.Messaging.CADMethodCallMessage.GetArguments () [0x0000d] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Messaging/CADMessages.cs:327
* at System.Runtime.Remoting.Messaging.MethodCall..ctor (System.Runtime.Remoting.Messaging.CADMethodCallMessage) [0x00017] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Messaging/MethodCall.cs:87
* at System.AppDomain.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage,byte[]&,System.Runtime.Remoting.Messaging.CADMethodReturnMessage&) [0x00018] in /home/schani/Work/novell/trunk/mcs/class/corlib/System/AppDomain.cs:1213
* at (wrapper remoting-invoke-with-check) System.AppDomain.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage,byte[]&,System.Runtime.Remoting.Messaging.CADMethodReturnMessage&) <IL 0x0003d, 0xffffffff>
* at System.Runtime.Remoting.Channels.CrossAppDomainSink.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage) [0x00008] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Channels/CrossAppDomainChannel.cs:198
* at (wrapper runtime-invoke) object.runtime_invoke_CrossAppDomainSink/ProcessMessageRes_object_object (object,intptr,intptr,intptr) <IL 0x0004c, 0xffffffff>
*/
if (!strcmp (ref->vtable->klass->name_space, "System") &&
!strcmp (ref->vtable->klass->name, "Byte[]") &&
!strcmp (o->vtable->klass->name_space, "System.IO") &&
!strcmp (o->vtable->klass->name, "MemoryStream"))
return TRUE;
/* append_job() in threadpool.c */
if (!strcmp (ref->vtable->klass->name_space, "System.Runtime.Remoting.Messaging") &&
!strcmp (ref->vtable->klass->name, "AsyncResult") &&
!strcmp (o->vtable->klass->name_space, "System") &&
!strcmp (o->vtable->klass->name, "Object[]") &&
mono_thread_pool_is_queue_array ((MonoArray*) o))
return TRUE;
return FALSE;
}
static void
check_reference_for_xdomain (gpointer *ptr, char *obj, MonoDomain *domain)
{
MonoObject *o = (MonoObject*)(obj);
MonoObject *ref = (MonoObject*)*(ptr);
int offset = (char*)(ptr) - (char*)o;
MonoClass *class;
MonoClassField *field;
char *str;
if (!ref || ref->vtable->domain == domain)
return;
if (is_xdomain_ref_allowed (ptr, obj, domain))
return;
field = NULL;
for (class = o->vtable->klass; class; class = class->parent) {
int i;
for (i = 0; i < class->field.count; ++i) {
if (class->fields[i].offset == offset) {
field = &class->fields[i];
break;
}
}
if (field)
break;
}
if (ref->vtable->klass == mono_defaults.string_class)
str = mono_string_to_utf8 ((MonoString*)ref);
else
str = NULL;
g_print ("xdomain reference in %p (%s.%s) at offset %d (%s) to %p (%s.%s) (%s) - pointed to by:\n",
o, o->vtable->klass->name_space, o->vtable->klass->name,
offset, field ? field->name : "",
ref, ref->vtable->klass->name_space, ref->vtable->klass->name, str ? str : "");
mono_gc_scan_for_specific_ref (o, TRUE);
if (str)
g_free (str);
}
#undef HANDLE_PTR
#define HANDLE_PTR(ptr,obj) check_reference_for_xdomain ((ptr), (obj), domain)
static void
scan_object_for_xdomain_refs (char *start, mword size, void *data)
{
MonoDomain *domain = ((MonoObject*)start)->vtable->domain;
#include "sgen-scan-object.h"
}
static gboolean scan_object_for_specific_ref_precise = TRUE;
#undef HANDLE_PTR
#define HANDLE_PTR(ptr,obj) do { \
if ((MonoObject*)*(ptr) == key) { \
g_print ("found ref to %p in object %p (%s) at offset %td\n", \
key, (obj), safe_name ((obj)), ((char*)(ptr) - (char*)(obj))); \
} \
} while (0)
static void
scan_object_for_specific_ref (char *start, MonoObject *key)
{
char *forwarded;
if ((forwarded = SGEN_OBJECT_IS_FORWARDED (start)))
start = forwarded;
if (scan_object_for_specific_ref_precise) {
#include "sgen-scan-object.h"
} else {
mword *words = (mword*)start;
size_t size = safe_object_get_size ((MonoObject*)start);
int i;
for (i = 0; i < size / sizeof (mword); ++i) {
if (words [i] == (mword)key) {
g_print ("found possible ref to %p in object %p (%s) at offset %td\n",
key, start, safe_name (start), i * sizeof (mword));
}
}
}
}
void
sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags)
{
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;
}
size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
if ((MonoVTable*)SGEN_LOAD_VTABLE (obj) != array_fill_vtable)
callback (obj, size, data);
start += size;
}
}
static void
scan_object_for_specific_ref_callback (char *obj, size_t size, MonoObject *key)
{
scan_object_for_specific_ref (obj, key);
}
static void
check_root_obj_specific_ref (RootRecord *root, MonoObject *key, MonoObject *obj)
{
if (key != obj)
return;
g_print ("found ref to %p in root record %p\n", key, root);
}
static MonoObject *check_key = NULL;
static RootRecord *check_root = NULL;
static void
check_root_obj_specific_ref_from_marker (void **obj)
{
check_root_obj_specific_ref (check_root, check_key, *obj);
}
static void
scan_roots_for_specific_ref (MonoObject *key, int root_type)
{
void **start_root;
RootRecord *root;
check_key = key;
SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
mword desc = root->root_desc;
check_root = root;
switch (desc & ROOT_DESC_TYPE_MASK) {
case ROOT_DESC_BITMAP:
desc >>= ROOT_DESC_TYPE_SHIFT;
while (desc) {
if (desc & 1)
check_root_obj_specific_ref (root, key, *start_root);
desc >>= 1;
start_root++;
}
return;
case ROOT_DESC_COMPLEX: {
gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
int 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)
check_root_obj_specific_ref (root, key, *objptr);
bmap >>= 1;
++objptr;
}
start_run += GC_BITS_PER_WORD;
}
break;
}
case ROOT_DESC_USER: {
MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
marker (start_root, check_root_obj_specific_ref_from_marker);
break;
}
case ROOT_DESC_RUN_LEN:
g_assert_not_reached ();
default:
g_assert_not_reached ();
}
} SGEN_HASH_TABLE_FOREACH_END;
check_key = NULL;
check_root = NULL;
}
void
mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise)
{
void **ptr;
RootRecord *root;
scan_object_for_specific_ref_precise = precise;
sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
(IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key, TRUE);
major_collector.iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
scan_roots_for_specific_ref (key, ROOT_TYPE_NORMAL);
scan_roots_for_specific_ref (key, ROOT_TYPE_WBARRIER);
SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], ptr, root) {
while (ptr < (void**)root->end_root) {
check_root_obj_specific_ref (root, *ptr, key);
++ptr;
}
} SGEN_HASH_TABLE_FOREACH_END;
}
static gboolean
need_remove_object_for_domain (char *start, MonoDomain *domain)
{
if (mono_object_domain (start) == domain) {
SGEN_LOG (4, "Need to cleanup object %p", start);
binary_protocol_cleanup (start, (gpointer)LOAD_VTABLE (start), safe_object_get_size ((MonoObject*)start));
return TRUE;
}
return FALSE;
}
static void
process_object_for_domain_clearing (char *start, MonoDomain *domain)
{
GCVTable *vt = (GCVTable*)LOAD_VTABLE (start);
if (vt->klass == mono_defaults.internal_thread_class)
g_assert (mono_object_domain (start) == mono_get_root_domain ());
/* The object could be a proxy for an object in the domain
we're deleting. */
#ifndef DISABLE_REMOTING
if (mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
/* The server could already have been zeroed out, so
we need to check for that, too. */
if (server && (!LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
((MonoRealProxy*)start)->unwrapped_server = NULL;
}
}
#endif
}
static MonoDomain *check_domain = NULL;
static void
check_obj_not_in_domain (void **o)
{
g_assert (((MonoObject*)(*o))->vtable->domain != check_domain);
}
static void
scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type)
{
void **start_root;
RootRecord *root;
check_domain = domain;
SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
mword desc = root->root_desc;
/* The MonoDomain struct is allowed to hold
references to objects in its own domain. */
if (start_root == (void**)domain)
continue;
switch (desc & ROOT_DESC_TYPE_MASK) {
case ROOT_DESC_BITMAP:
desc >>= ROOT_DESC_TYPE_SHIFT;
while (desc) {
if ((desc & 1) && *start_root)
check_obj_not_in_domain (*start_root);
desc >>= 1;
start_root++;
}
break;
case ROOT_DESC_COMPLEX: {
gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
int 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)
check_obj_not_in_domain (*objptr);
bmap >>= 1;
++objptr;
}
start_run += GC_BITS_PER_WORD;
}
break;
}
case ROOT_DESC_USER: {
MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
marker (start_root, check_obj_not_in_domain);
break;
}
case ROOT_DESC_RUN_LEN:
g_assert_not_reached ();
default:
g_assert_not_reached ();
}
} SGEN_HASH_TABLE_FOREACH_END;
check_domain = NULL;
}
static void
check_for_xdomain_refs (void)
{
LOSObject *bigobj;
sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
(IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL, FALSE);
major_collector.iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL);
for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
scan_object_for_xdomain_refs (bigobj->data, sgen_los_object_size (bigobj), NULL);
}
static gboolean
clear_domain_process_object (char *obj, MonoDomain *domain)
{
gboolean remove;
process_object_for_domain_clearing (obj, domain);
remove = need_remove_object_for_domain (obj, domain);
if (remove && ((MonoObject*)obj)->synchronisation) {
void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)obj);
if (dislink)