2 * sgen-gc.c: Simple generational GC.
5 * Paolo Molaro (lupus@ximian.com)
6 * Rodrigo Kumpera (kumpera@gmail.com)
8 * Copyright 2005-2011 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11 * Thread start/stop adapted from Boehm's GC:
12 * Copyright (c) 1994 by Xerox Corporation. All rights reserved.
13 * Copyright (c) 1996 by Silicon Graphics. All rights reserved.
14 * Copyright (c) 1998 by Fergus Henderson. All rights reserved.
15 * Copyright (c) 2000-2004 by Hewlett-Packard Company. All rights reserved.
16 * Copyright 2001-2003 Ximian, Inc
17 * Copyright 2003-2010 Novell, Inc.
18 * Copyright 2011 Xamarin, Inc.
19 * Copyright (C) 2012 Xamarin Inc
21 * This library is free software; you can redistribute it and/or
22 * modify it under the terms of the GNU Library General Public
23 * License 2.0 as published by the Free Software Foundation;
25 * This library is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 * Library General Public License for more details.
30 * You should have received a copy of the GNU Library General Public
31 * License 2.0 along with this library; if not, write to the Free
32 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
34 * Important: allocation provides always zeroed memory, having to do
35 * a memset after allocation is deadly for performance.
36 * Memory usage at startup is currently as follows:
38 * 64 KB internal space
40 * We should provide a small memory config with half the sizes
42 * We currently try to make as few mono assumptions as possible:
43 * 1) 2-word header with no GC pointers in it (first vtable, second to store the
45 * 2) gc descriptor is the second word in the vtable (first word in the class)
46 * 3) 8 byte alignment is the minimum and enough (not true for special structures (SIMD), FIXME)
47 * 4) there is a function to get an object's size and the number of
48 * elements in an array.
49 * 5) we know the special way bounds are allocated for complex arrays
50 * 6) we know about proxies and how to treat them when domains are unloaded
52 * Always try to keep stack usage to a minimum: no recursive behaviour
53 * and no large stack allocs.
55 * General description.
56 * Objects are initially allocated in a nursery using a fast bump-pointer technique.
57 * When the nursery is full we start a nursery collection: this is performed with a
59 * When the old generation is full we start a copying GC of the old generation as well:
60 * this will be changed to mark&sweep with copying when fragmentation becomes to severe
61 * in the future. Maybe we'll even do both during the same collection like IMMIX.
63 * The things that complicate this description are:
64 * *) pinned objects: we can't move them so we need to keep track of them
65 * *) no precise info of the thread stacks and registers: we need to be able to
66 * quickly find the objects that may be referenced conservatively and pin them
67 * (this makes the first issues more important)
68 * *) large objects are too expensive to be dealt with using copying GC: we handle them
69 * with mark/sweep during major collections
70 * *) some objects need to not move even if they are small (interned strings, Type handles):
71 * we use mark/sweep for them, too: they are not allocated in the nursery, but inside
72 * PinnedChunks regions
78 *) we could have a function pointer in MonoClass to implement
79 customized write barriers for value types
81 *) investigate the stuff needed to advance a thread to a GC-safe
82 point (single-stepping, read from unmapped memory etc) and implement it.
83 This would enable us to inline allocations and write barriers, for example,
84 or at least parts of them, like the write barrier checks.
85 We may need this also for handling precise info on stacks, even simple things
86 as having uninitialized data on the stack and having to wait for the prolog
87 to zero it. Not an issue for the last frame that we scan conservatively.
88 We could always not trust the value in the slots anyway.
90 *) modify the jit to save info about references in stack locations:
91 this can be done just for locals as a start, so that at least
92 part of the stack is handled precisely.
94 *) test/fix endianess issues
96 *) Implement a card table as the write barrier instead of remembered
97 sets? Card tables are not easy to implement with our current
98 memory layout. We have several different kinds of major heap
99 objects: Small objects in regular blocks, small objects in pinned
100 chunks and LOS objects. If we just have a pointer we have no way
101 to tell which kind of object it points into, therefore we cannot
102 know where its card table is. The least we have to do to make
103 this happen is to get rid of write barriers for indirect stores.
106 *) Get rid of write barriers for indirect stores. We can do this by
107 telling the GC to wbarrier-register an object once we do an ldloca
108 or ldelema on it, and to unregister it once it's not used anymore
109 (it can only travel downwards on the stack). The problem with
110 unregistering is that it needs to happen eventually no matter
111 what, even if exceptions are thrown, the thread aborts, etc.
112 Rodrigo suggested that we could do only the registering part and
113 let the collector find out (pessimistically) when it's safe to
114 unregister, namely when the stack pointer of the thread that
115 registered the object is higher than it was when the registering
116 happened. This might make for a good first implementation to get
117 some data on performance.
119 *) Some sort of blacklist support? Blacklists is a concept from the
120 Boehm GC: if during a conservative scan we find pointers to an
121 area which we might use as heap, we mark that area as unusable, so
122 pointer retention by random pinning pointers is reduced.
124 *) experiment with max small object size (very small right now - 2kb,
125 because it's tied to the max freelist size)
127 *) add an option to mmap the whole heap in one chunk: it makes for many
128 simplifications in the checks (put the nursery at the top and just use a single
129 check for inclusion/exclusion): the issue this has is that on 32 bit systems it's
130 not flexible (too much of the address space may be used by default or we can't
131 increase the heap as needed) and we'd need a race-free mechanism to return memory
132 back to the system (mprotect(PROT_NONE) will still keep the memory allocated if it
133 was written to, munmap is needed, but the following mmap may not find the same segment
136 *) memzero the major fragments after restarting the world and optionally a smaller
139 *) investigate having fragment zeroing threads
141 *) separate locks for finalization and other minor stuff to reduce
144 *) try a different copying order to improve memory locality
146 *) a thread abort after a store but before the write barrier will
147 prevent the write barrier from executing
149 *) specialized dynamically generated markers/copiers
151 *) Dynamically adjust TLAB size to the number of threads. If we have
152 too many threads that do allocation, we might need smaller TLABs,
153 and we might get better performance with larger TLABs if we only
154 have a handful of threads. We could sum up the space left in all
155 assigned TLABs and if that's more than some percentage of the
156 nursery size, reduce the TLAB size.
158 *) Explore placing unreachable objects on unused nursery memory.
159 Instead of memset'ng a region to zero, place an int[] covering it.
160 A good place to start is add_nursery_frag. The tricky thing here is
161 placing those objects atomically outside of a collection.
163 *) Allocation should use asymmetric Dekker synchronization:
164 http://blogs.oracle.com/dave/resource/Asymmetric-Dekker-Synchronization.txt
165 This should help weak consistency archs.
172 #define _XOPEN_SOURCE
173 #define _DARWIN_C_SOURCE
179 #ifdef HAVE_PTHREAD_H
182 #ifdef HAVE_PTHREAD_NP_H
183 #include <pthread_np.h>
185 #ifdef HAVE_SEMAPHORE_H
186 #include <semaphore.h>
194 #include "metadata/sgen-gc.h"
195 #include "metadata/metadata-internals.h"
196 #include "metadata/class-internals.h"
197 #include "metadata/gc-internal.h"
198 #include "metadata/object-internals.h"
199 #include "metadata/threads.h"
200 #include "metadata/sgen-cardtable.h"
201 #include "metadata/sgen-protocol.h"
202 #include "metadata/sgen-archdep.h"
203 #include "metadata/sgen-bridge.h"
204 #include "metadata/sgen-memory-governor.h"
205 #include "metadata/sgen-hash-table.h"
206 #include "metadata/mono-gc.h"
207 #include "metadata/method-builder.h"
208 #include "metadata/profiler-private.h"
209 #include "metadata/monitor.h"
210 #include "metadata/mempool-internals.h"
211 #include "metadata/marshal.h"
212 #include "metadata/runtime.h"
213 #include "metadata/sgen-cardtable.h"
214 #include "metadata/sgen-pinning.h"
215 #include "metadata/sgen-workers.h"
216 #include "metadata/sgen-layout-stats.h"
217 #include "utils/mono-mmap.h"
218 #include "utils/mono-time.h"
219 #include "utils/mono-semaphore.h"
220 #include "utils/mono-counters.h"
221 #include "utils/mono-proclib.h"
222 #include "utils/mono-memory-model.h"
223 #include "utils/mono-logger-internal.h"
224 #include "utils/dtrace.h"
226 #include <mono/utils/mono-logger-internal.h>
227 #include <mono/utils/memcheck.h>
229 #if defined(__MACH__)
230 #include "utils/mach-support.h"
233 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
237 #include "mono/cil/opcode.def"
243 #undef pthread_create
245 #undef pthread_detach
248 * ######################################################################
249 * ######## Types and constants used by the GC.
250 * ######################################################################
253 /* 0 means not initialized, 1 is initialized, -1 means in progress */
254 static int gc_initialized = 0;
255 /* If set, check if we need to do something every X allocations */
256 gboolean has_per_allocation_action;
257 /* If set, do a heap check every X allocation */
258 guint32 verify_before_allocs = 0;
259 /* If set, do a minor collection before every X allocation */
260 guint32 collect_before_allocs = 0;
261 /* If set, do a whole heap check before each collection */
262 static gboolean whole_heap_check_before_collection = FALSE;
263 /* If set, do a heap consistency check before each minor collection */
264 static gboolean consistency_check_at_minor_collection = FALSE;
265 /* If set, do a mod union consistency check before each finishing collection pause */
266 static gboolean mod_union_consistency_check = FALSE;
267 /* If set, check whether mark bits are consistent after major collections */
268 static gboolean check_mark_bits_after_major_collection = FALSE;
269 /* If set, check that all nursery objects are pinned/not pinned, depending on context */
270 static gboolean check_nursery_objects_pinned = FALSE;
271 /* If set, do a few checks when the concurrent collector is used */
272 static gboolean do_concurrent_checks = FALSE;
273 /* If set, check that there are no references to the domain left at domain unload */
274 static gboolean xdomain_checks = FALSE;
275 /* If not null, dump the heap after each collection into this file */
276 static FILE *heap_dump_file = NULL;
277 /* If set, mark stacks conservatively, even if precise marking is possible */
278 static gboolean conservative_stack_mark = FALSE;
279 /* If set, do a plausibility check on the scan_starts before and after
281 static gboolean do_scan_starts_check = FALSE;
283 * If the major collector is concurrent and this is FALSE, we will
284 * never initiate a synchronous major collection, unless requested via
287 static gboolean allow_synchronous_major = TRUE;
288 static gboolean nursery_collection_is_parallel = FALSE;
289 static gboolean disable_minor_collections = FALSE;
290 static gboolean disable_major_collections = FALSE;
291 gboolean do_pin_stats = FALSE;
292 static gboolean do_verify_nursery = FALSE;
293 static gboolean do_dump_nursery_content = FALSE;
295 #ifdef HEAVY_STATISTICS
296 long long stat_objects_alloced_degraded = 0;
297 long long stat_bytes_alloced_degraded = 0;
299 long long stat_copy_object_called_nursery = 0;
300 long long stat_objects_copied_nursery = 0;
301 long long stat_copy_object_called_major = 0;
302 long long stat_objects_copied_major = 0;
304 long long stat_scan_object_called_nursery = 0;
305 long long stat_scan_object_called_major = 0;
307 long long stat_slots_allocated_in_vain;
309 long long stat_nursery_copy_object_failed_from_space = 0;
310 long long stat_nursery_copy_object_failed_forwarded = 0;
311 long long stat_nursery_copy_object_failed_pinned = 0;
312 long long stat_nursery_copy_object_failed_to_space = 0;
314 static int stat_wbarrier_add_to_global_remset = 0;
315 static int stat_wbarrier_set_field = 0;
316 static int stat_wbarrier_set_arrayref = 0;
317 static int stat_wbarrier_arrayref_copy = 0;
318 static int stat_wbarrier_generic_store = 0;
319 static int stat_wbarrier_generic_store_atomic = 0;
320 static int stat_wbarrier_set_root = 0;
321 static int stat_wbarrier_value_copy = 0;
322 static int stat_wbarrier_object_copy = 0;
325 static long long stat_pinned_objects = 0;
327 static long long time_minor_pre_collection_fragment_clear = 0;
328 static long long time_minor_pinning = 0;
329 static long long time_minor_scan_remsets = 0;
330 static long long time_minor_scan_pinned = 0;
331 static long long time_minor_scan_registered_roots = 0;
332 static long long time_minor_scan_thread_data = 0;
333 static long long time_minor_finish_gray_stack = 0;
334 static long long time_minor_fragment_creation = 0;
336 static long long time_major_pre_collection_fragment_clear = 0;
337 static long long time_major_pinning = 0;
338 static long long time_major_scan_pinned = 0;
339 static long long time_major_scan_registered_roots = 0;
340 static long long time_major_scan_thread_data = 0;
341 static long long time_major_scan_alloc_pinned = 0;
342 static long long time_major_scan_finalized = 0;
343 static long long time_major_scan_big_objects = 0;
344 static long long time_major_finish_gray_stack = 0;
345 static long long time_major_free_bigobjs = 0;
346 static long long time_major_los_sweep = 0;
347 static long long time_major_sweep = 0;
348 static long long time_major_fragment_creation = 0;
350 int gc_debug_level = 0;
353 static MonoGCFinalizerCallbacks fin_callbacks;
357 mono_gc_flush_info (void)
359 fflush (gc_debug_file);
363 #define TV_DECLARE SGEN_TV_DECLARE
364 #define TV_GETTIME SGEN_TV_GETTIME
365 #define TV_ELAPSED SGEN_TV_ELAPSED
366 #define TV_ELAPSED_MS SGEN_TV_ELAPSED_MS
368 SGEN_TV_DECLARE (sgen_init_timestamp);
370 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
372 NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
374 #define object_is_forwarded SGEN_OBJECT_IS_FORWARDED
375 #define object_is_pinned SGEN_OBJECT_IS_PINNED
376 #define pin_object SGEN_PIN_OBJECT
377 #define unpin_object SGEN_UNPIN_OBJECT
379 #define ptr_in_nursery sgen_ptr_in_nursery
381 #define LOAD_VTABLE SGEN_LOAD_VTABLE
384 safe_name (void* obj)
386 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
387 return vt->klass->name;
390 #define safe_object_get_size sgen_safe_object_get_size
393 sgen_safe_name (void* obj)
395 return safe_name (obj);
399 * ######################################################################
400 * ######## Global data.
401 * ######################################################################
403 LOCK_DECLARE (gc_mutex);
404 gboolean sgen_try_free_some_memory;
406 #define SCAN_START_SIZE SGEN_SCAN_START_SIZE
408 static mword pagesize = 4096;
409 size_t degraded_mode = 0;
411 static mword bytes_pinned_from_failed_allocation = 0;
413 GCMemSection *nursery_section = NULL;
414 static mword lowest_heap_address = ~(mword)0;
415 static mword highest_heap_address = 0;
417 LOCK_DECLARE (sgen_interruption_mutex);
418 static LOCK_DECLARE (pin_queue_mutex);
420 #define LOCK_PIN_QUEUE mono_mutex_lock (&pin_queue_mutex)
421 #define UNLOCK_PIN_QUEUE mono_mutex_unlock (&pin_queue_mutex)
423 typedef struct _FinalizeReadyEntry FinalizeReadyEntry;
424 struct _FinalizeReadyEntry {
425 FinalizeReadyEntry *next;
429 typedef struct _EphemeronLinkNode EphemeronLinkNode;
431 struct _EphemeronLinkNode {
432 EphemeronLinkNode *next;
441 int current_collection_generation = -1;
442 volatile gboolean concurrent_collection_in_progress = FALSE;
444 /* objects that are ready to be finalized */
445 static FinalizeReadyEntry *fin_ready_list = NULL;
446 static FinalizeReadyEntry *critical_fin_list = NULL;
448 static EphemeronLinkNode *ephemeron_list;
450 /* registered roots: the key to the hash is the root start address */
452 * Different kinds of roots are kept separate to speed up pin_from_roots () for example.
454 SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
455 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
456 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
457 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL)
459 static mword roots_size = 0; /* amount of memory in the root set */
461 #define GC_ROOT_NUM 32
463 int count; /* must be the first field */
464 void *objects [GC_ROOT_NUM];
465 int root_types [GC_ROOT_NUM];
466 uintptr_t extra_info [GC_ROOT_NUM];
470 notify_gc_roots (GCRootReport *report)
474 mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
479 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
481 if (report->count == GC_ROOT_NUM)
482 notify_gc_roots (report);
483 report->objects [report->count] = object;
484 report->root_types [report->count] = rtype;
485 report->extra_info [report->count++] = (uintptr_t)((MonoVTable*)LOAD_VTABLE (object))->klass;
488 MonoNativeTlsKey thread_info_key;
490 #ifdef HAVE_KW_THREAD
491 __thread SgenThreadInfo *sgen_thread_info;
492 __thread char *stack_end;
495 /* The size of a TLAB */
496 /* The bigger the value, the less often we have to go to the slow path to allocate a new
497 * one, but the more space is wasted by threads not allocating much memory.
499 * FIXME: Make this self-tuning for each thread.
501 guint32 tlab_size = (1024 * 4);
503 #define MAX_SMALL_OBJ_SIZE SGEN_MAX_SMALL_OBJ_SIZE
505 /* Functions supplied by the runtime to be called by the GC */
506 static MonoGCCallbacks gc_callbacks;
508 #define ALLOC_ALIGN SGEN_ALLOC_ALIGN
509 #define ALLOC_ALIGN_BITS SGEN_ALLOC_ALIGN_BITS
511 #define ALIGN_UP SGEN_ALIGN_UP
513 #define MOVED_OBJECTS_NUM 64
514 static void *moved_objects [MOVED_OBJECTS_NUM];
515 static int moved_objects_idx = 0;
517 /* Vtable of the objects used to fill out nursery fragments before a collection */
518 static MonoVTable *array_fill_vtable;
520 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
521 MonoNativeThreadId main_gc_thread = NULL;
524 /*Object was pinned during the current collection*/
525 static mword objects_pinned;
528 * ######################################################################
529 * ######## Macros and function declarations.
530 * ######################################################################
534 align_pointer (void *ptr)
536 mword p = (mword)ptr;
537 p += sizeof (gpointer) - 1;
538 p &= ~ (sizeof (gpointer) - 1);
542 typedef SgenGrayQueue GrayQueue;
544 /* forward declarations */
545 static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue);
546 static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
547 static void scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx);
548 static void report_finalizer_roots (void);
549 static void report_registered_roots (void);
551 static void pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue);
552 static void finish_gray_stack (int generation, GrayQueue *queue);
554 void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise);
557 static void init_stats (void);
559 static int mark_ephemerons_in_range (ScanCopyContext ctx);
560 static void clear_unreachable_ephemerons (ScanCopyContext ctx);
561 static void null_ephemerons_for_domain (MonoDomain *domain);
563 static gboolean major_update_or_finish_concurrent_collection (gboolean force_finish);
565 SgenObjectOperations current_object_ops;
566 SgenMajorCollector major_collector;
567 SgenMinorCollector sgen_minor_collector;
568 static GrayQueue gray_queue;
570 static SgenRemeberedSet remset;
572 /* The gray queue to use from the main collection thread. */
573 #define WORKERS_DISTRIBUTE_GRAY_QUEUE (&gray_queue)
576 * The gray queue a worker job must use. If we're not parallel or
577 * concurrent, we use the main gray queue.
579 static SgenGrayQueue*
580 sgen_workers_get_job_gray_queue (WorkerData *worker_data)
582 return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
586 gray_queue_redirect (SgenGrayQueue *queue)
588 gboolean wake = FALSE;
592 GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
595 sgen_section_gray_queue_enqueue (queue->alloc_prepare_data, section);
600 g_assert (concurrent_collection_in_progress ||
601 (current_collection_generation == GENERATION_OLD && major_collector.is_parallel));
602 if (sgen_workers_have_started ()) {
603 sgen_workers_wake_up_all ();
605 if (concurrent_collection_in_progress)
606 g_assert (current_collection_generation == -1);
612 sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags)
614 while (start < end) {
618 if (!*(void**)start) {
619 start += sizeof (void*); /* should be ALLOC_ALIGN, really */
624 if (!(obj = SGEN_OBJECT_IS_FORWARDED (start)))
630 size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
632 if ((MonoVTable*)SGEN_LOAD_VTABLE (obj) != array_fill_vtable)
633 callback (obj, size, data);
640 need_remove_object_for_domain (char *start, MonoDomain *domain)
642 if (mono_object_domain (start) == domain) {
643 SGEN_LOG (4, "Need to cleanup object %p", start);
644 binary_protocol_cleanup (start, (gpointer)LOAD_VTABLE (start), safe_object_get_size ((MonoObject*)start));
651 process_object_for_domain_clearing (char *start, MonoDomain *domain)
653 GCVTable *vt = (GCVTable*)LOAD_VTABLE (start);
654 if (vt->klass == mono_defaults.internal_thread_class)
655 g_assert (mono_object_domain (start) == mono_get_root_domain ());
656 /* The object could be a proxy for an object in the domain
658 #ifndef DISABLE_REMOTING
659 if (mono_defaults.real_proxy_class->supertypes && mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
660 MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
662 /* The server could already have been zeroed out, so
663 we need to check for that, too. */
664 if (server && (!LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
665 SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
666 ((MonoRealProxy*)start)->unwrapped_server = NULL;
673 clear_domain_process_object (char *obj, MonoDomain *domain)
677 process_object_for_domain_clearing (obj, domain);
678 remove = need_remove_object_for_domain (obj, domain);
680 if (remove && ((MonoObject*)obj)->synchronisation) {
681 void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)obj);
683 sgen_register_disappearing_link (NULL, dislink, FALSE, TRUE);
690 clear_domain_process_minor_object_callback (char *obj, size_t size, MonoDomain *domain)
692 if (clear_domain_process_object (obj, domain))
693 memset (obj, 0, size);
697 clear_domain_process_major_object_callback (char *obj, size_t size, MonoDomain *domain)
699 clear_domain_process_object (obj, domain);
703 clear_domain_free_major_non_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
705 if (need_remove_object_for_domain (obj, domain))
706 major_collector.free_non_pinned_object (obj, size);
710 clear_domain_free_major_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
712 if (need_remove_object_for_domain (obj, domain))
713 major_collector.free_pinned_object (obj, size);
717 * When appdomains are unloaded we can easily remove objects that have finalizers,
718 * but all the others could still be present in random places on the heap.
719 * We need a sweep to get rid of them even though it's going to be costly
721 * The reason we need to remove them is because we access the vtable and class
722 * structures to know the object size and the reference bitmap: once the domain is
723 * unloaded the point to random memory.
726 mono_gc_clear_domain (MonoDomain * domain)
728 LOSObject *bigobj, *prev;
733 binary_protocol_domain_unload_begin (domain);
737 if (concurrent_collection_in_progress)
738 sgen_perform_collection (0, GENERATION_OLD, "clear domain", TRUE);
739 g_assert (!concurrent_collection_in_progress);
741 sgen_process_fin_stage_entries ();
742 sgen_process_dislink_stage_entries ();
744 sgen_clear_nursery_fragments ();
746 if (xdomain_checks && domain != mono_get_root_domain ()) {
747 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
748 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_WBARRIER);
749 sgen_check_for_xdomain_refs ();
752 /*Ephemerons and dislinks must be processed before LOS since they might end up pointing
753 to memory returned to the OS.*/
754 null_ephemerons_for_domain (domain);
756 for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
757 sgen_null_links_for_domain (domain, i);
759 for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
760 sgen_remove_finalizers_for_domain (domain, i);
762 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
763 (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain, FALSE);
765 /* We need two passes over major and large objects because
766 freeing such objects might give their memory back to the OS
767 (in the case of large objects) or obliterate its vtable
768 (pinned objects with major-copying or pinned and non-pinned
769 objects with major-mark&sweep), but we might need to
770 dereference a pointer from an object to another object if
771 the first object is a proxy. */
772 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
773 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
774 clear_domain_process_object (bigobj->data, domain);
777 for (bigobj = los_object_list; bigobj;) {
778 if (need_remove_object_for_domain (bigobj->data, domain)) {
779 LOSObject *to_free = bigobj;
781 prev->next = bigobj->next;
783 los_object_list = bigobj->next;
784 bigobj = bigobj->next;
785 SGEN_LOG (4, "Freeing large object %p", bigobj->data);
786 sgen_los_free_object (to_free);
790 bigobj = bigobj->next;
792 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
793 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
795 if (domain == mono_get_root_domain ()) {
796 if (G_UNLIKELY (do_pin_stats))
797 sgen_pin_stats_print_class_stats ();
798 sgen_object_layout_dump (stdout);
801 sgen_restart_world (0, NULL);
803 binary_protocol_domain_unload_end (domain);
809 * sgen_add_to_global_remset:
811 * The global remset contains locations which point into newspace after
812 * a minor collection. This can happen if the objects they point to are pinned.
814 * LOCKING: If called from a parallel collector, the global remset
815 * lock must be held. For serial collectors that is not necessary.
818 sgen_add_to_global_remset (gpointer ptr, gpointer obj)
820 SGEN_ASSERT (5, sgen_ptr_in_nursery (obj), "Target pointer of global remset must be in the nursery");
822 HEAVY_STAT (++stat_wbarrier_add_to_global_remset);
824 if (!major_collector.is_concurrent) {
825 SGEN_ASSERT (5, current_collection_generation != -1, "Global remsets can only be added during collections");
827 if (current_collection_generation == -1)
828 SGEN_ASSERT (5, sgen_concurrent_collection_in_progress (), "Global remsets outside of collection pauses can only be added by the concurrent collector");
831 if (!object_is_pinned (obj))
832 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");
833 else if (sgen_cement_lookup_or_register (obj))
836 remset.record_pointer (ptr);
838 if (G_UNLIKELY (do_pin_stats))
839 sgen_pin_stats_register_global_remset (obj);
841 SGEN_LOG (8, "Adding global remset for %p", ptr);
842 binary_protocol_global_remset (ptr, obj, (gpointer)SGEN_LOAD_VTABLE (obj));
846 if (G_UNLIKELY (MONO_GC_GLOBAL_REMSET_ADD_ENABLED ())) {
847 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
848 MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)obj, sgen_safe_object_get_size (obj),
849 vt->klass->name_space, vt->klass->name);
855 * sgen_drain_gray_stack:
857 * Scan objects in the gray stack until the stack is empty. This should be called
858 * frequently after each object is copied, to achieve better locality and cache
862 sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx)
865 ScanObjectFunc scan_func = ctx.scan_func;
866 GrayQueue *queue = ctx.queue;
868 if (max_objs == -1) {
870 GRAY_OBJECT_DEQUEUE (queue, &obj);
873 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
874 scan_func (obj, queue);
880 for (i = 0; i != max_objs; ++i) {
881 GRAY_OBJECT_DEQUEUE (queue, &obj);
884 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
885 scan_func (obj, queue);
887 } while (max_objs < 0);
893 * Addresses in the pin queue are already sorted. This function finds
894 * the object header for each address and pins the object. The
895 * addresses must be inside the nursery section. The (start of the)
896 * address array is overwritten with the addresses of the actually
897 * pinned objects. Return the number of pinned objects.
900 pin_objects_from_nursery_pin_queue (ScanCopyContext ctx)
902 GCMemSection *section = nursery_section;
903 void **start = section->pin_queue_start;
904 void **end = start + section->pin_queue_num_entries;
905 void *start_nursery = section->data;
906 void *end_nursery = section->next_data;
911 void *pinning_front = start_nursery;
913 void **definitely_pinned = start;
914 ScanObjectFunc scan_func = ctx.scan_func;
915 SgenGrayQueue *queue = ctx.queue;
917 sgen_nursery_allocator_prepare_for_pinning ();
919 while (start < end) {
920 void *obj_to_pin = NULL;
921 size_t obj_to_pin_size = 0;
925 SGEN_ASSERT (0, addr >= start_nursery && addr < end_nursery, "Potential pinning address out of range");
926 SGEN_ASSERT (0, addr >= last, "Pin queue not sorted");
933 SGEN_LOG (5, "Considering pinning addr %p", addr);
934 /* We've already processed everything up to pinning_front. */
935 if (addr < pinning_front) {
941 * Find the closest scan start <= addr. We might search backward in the
942 * scan_starts array because entries might be NULL. In the worst case we
943 * start at start_nursery.
945 idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
946 SGEN_ASSERT (0, idx < section->num_scan_start, "Scan start index out of range");
947 search_start = (void*)section->scan_starts [idx];
948 if (!search_start || search_start > addr) {
951 search_start = section->scan_starts [idx];
952 if (search_start && search_start <= addr)
955 if (!search_start || search_start > addr)
956 search_start = start_nursery;
960 * If the pinning front is closer than the scan start we found, start
961 * searching at the front.
963 if (search_start < pinning_front)
964 search_start = pinning_front;
967 * Now addr should be in an object a short distance from search_start.
969 * search_start must point to zeroed mem or point to an object.
975 if (!*(void**)search_start) {
976 search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
977 /* The loop condition makes sure we don't overrun addr. */
981 obj_size = ALIGN_UP (safe_object_get_size ((MonoObject*)search_start));
983 if (addr >= search_start && (char*)addr < (char*)search_start + obj_size) {
984 /* This is the object we're looking for. */
985 obj_to_pin = search_start;
986 obj_to_pin_size = obj_size;
990 /* Skip to the next object */
991 search_start = (void*)((char*)search_start + obj_size);
992 } while (search_start <= addr);
994 /* We've searched past the address we were looking for. */
996 pinning_front = search_start;
997 goto next_pin_queue_entry;
1001 * We've found an object to pin. It might still be a dummy array, but we
1002 * can advance the pinning front in any case.
1004 pinning_front = (char*)obj_to_pin + obj_to_pin_size;
1007 * If this is a dummy array marking the beginning of a nursery
1008 * fragment, we don't pin it.
1010 if (((MonoObject*)obj_to_pin)->synchronisation == GINT_TO_POINTER (-1))
1011 goto next_pin_queue_entry;
1014 * Finally - pin the object!
1017 scan_func (obj_to_pin, queue);
1019 SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
1020 obj_to_pin, *(void**)obj_to_pin, safe_name (obj_to_pin), count);
1021 binary_protocol_pin (obj_to_pin,
1022 (gpointer)LOAD_VTABLE (obj_to_pin),
1023 safe_object_get_size (obj_to_pin));
1025 #ifdef ENABLE_DTRACE
1026 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1027 int gen = sgen_ptr_in_nursery (obj_to_pin) ? GENERATION_NURSERY : GENERATION_OLD;
1028 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj_to_pin);
1029 MONO_GC_OBJ_PINNED ((mword)obj_to_pin,
1030 sgen_safe_object_get_size (obj_to_pin),
1031 vt->klass->name_space, vt->klass->name, gen);
1035 pin_object (obj_to_pin);
1036 GRAY_OBJECT_ENQUEUE (queue, obj_to_pin);
1037 if (G_UNLIKELY (do_pin_stats))
1038 sgen_pin_stats_register_object (obj_to_pin, obj_to_pin_size);
1039 definitely_pinned [count] = obj_to_pin;
1043 next_pin_queue_entry:
1047 //printf ("effective pinned: %d (at the end: %d)\n", count, (char*)end_nursery - (char*)last);
1048 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
1049 GCRootReport report;
1051 for (idx = 0; idx < count; ++idx)
1052 add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
1053 notify_gc_roots (&report);
1055 stat_pinned_objects += count;
1060 pin_objects_in_nursery (ScanCopyContext ctx)
1064 if (!nursery_section->pin_queue_num_entries)
1067 reduced_to = pin_objects_from_nursery_pin_queue (ctx);
1068 nursery_section->pin_queue_num_entries = reduced_to;
1070 nursery_section->pin_queue_start = NULL;
1075 sgen_pin_object (void *object, GrayQueue *queue)
1077 g_assert (!concurrent_collection_in_progress);
1079 if (sgen_collection_is_parallel ()) {
1081 /*object arrives pinned*/
1082 sgen_pin_stage_ptr (object);
1086 SGEN_PIN_OBJECT (object);
1087 sgen_pin_stage_ptr (object);
1089 if (G_UNLIKELY (do_pin_stats))
1090 sgen_pin_stats_register_object (object, safe_object_get_size (object));
1092 GRAY_OBJECT_ENQUEUE (queue, object);
1093 binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
1095 #ifdef ENABLE_DTRACE
1096 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1097 int gen = sgen_ptr_in_nursery (object) ? GENERATION_NURSERY : GENERATION_OLD;
1098 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (object);
1099 MONO_GC_OBJ_PINNED ((mword)object, sgen_safe_object_get_size (object), vt->klass->name_space, vt->klass->name, gen);
1105 sgen_parallel_pin_or_update (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue)
1109 gboolean major_pinned = FALSE;
1111 if (sgen_ptr_in_nursery (obj)) {
1112 if (SGEN_CAS_PTR (obj, (void*)((mword)vt | SGEN_PINNED_BIT), vt) == vt) {
1113 sgen_pin_object (obj, queue);
1117 major_collector.pin_major_object (obj, queue);
1118 major_pinned = TRUE;
1121 vtable_word = *(mword*)obj;
1122 /*someone else forwarded it, update the pointer and bail out*/
1123 if (vtable_word & SGEN_FORWARDED_BIT) {
1124 *ptr = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1128 /*someone pinned it, nothing to do.*/
1129 if (vtable_word & SGEN_PINNED_BIT || major_pinned)
1134 /* Sort the addresses in array in increasing order.
1135 * Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
1138 sgen_sort_addresses (void **array, size_t size)
1143 for (i = 1; i < size; ++i) {
1146 size_t parent = (child - 1) / 2;
1148 if (array [parent] >= array [child])
1151 tmp = array [parent];
1152 array [parent] = array [child];
1153 array [child] = tmp;
1159 for (i = size - 1; i > 0; --i) {
1162 array [i] = array [0];
1168 while (root * 2 + 1 <= end) {
1169 size_t child = root * 2 + 1;
1171 if (child < end && array [child] < array [child + 1])
1173 if (array [root] >= array [child])
1177 array [root] = array [child];
1178 array [child] = tmp;
1186 * Scan the memory between start and end and queue values which could be pointers
1187 * to the area between start_nursery and end_nursery for later consideration.
1188 * Typically used for thread stacks.
1191 conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
1195 #ifdef VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE
1196 VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
1199 while (start < end) {
1200 if (*start >= start_nursery && *start < end_nursery) {
1202 * *start can point to the middle of an object
1203 * note: should we handle pointing at the end of an object?
1204 * pinning in C# code disallows pointing at the end of an object
1205 * but there is some small chance that an optimizing C compiler
1206 * may keep the only reference to an object by pointing
1207 * at the end of it. We ignore this small chance for now.
1208 * Pointers to the end of an object are indistinguishable
1209 * from pointers to the start of the next object in memory
1210 * so if we allow that we'd need to pin two objects...
1211 * We queue the pointer in an array, the
1212 * array will then be sorted and uniqued. This way
1213 * we can coalesce several pinning pointers and it should
1214 * be faster since we'd do a memory scan with increasing
1215 * addresses. Note: we can align the address to the allocation
1216 * alignment, so the unique process is more effective.
1218 mword addr = (mword)*start;
1219 addr &= ~(ALLOC_ALIGN - 1);
1220 if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
1221 SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
1222 sgen_pin_stage_ptr ((void*)addr);
1225 if (G_UNLIKELY (do_pin_stats)) {
1226 if (ptr_in_nursery ((void*)addr))
1227 sgen_pin_stats_register_address ((char*)addr, pin_type);
1233 SGEN_LOG (7, "found %d potential pinned heap pointers", count);
1237 * The first thing we do in a collection is to identify pinned objects.
1238 * This function considers all the areas of memory that need to be
1239 * conservatively scanned.
1242 pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue)
1246 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);
1247 /* objects pinned from the API are inside these roots */
1248 SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], start_root, root) {
1249 SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
1250 conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
1251 } SGEN_HASH_TABLE_FOREACH_END;
1252 /* now deal with the thread stacks
1253 * in the future we should be able to conservatively scan only:
1254 * *) the cpu registers
1255 * *) the unmanaged stack frames
1256 * *) the _last_ managed stack frame
1257 * *) pointers slots in managed frames
1259 scan_thread_data (start_nursery, end_nursery, FALSE, queue);
1263 unpin_objects_from_queue (SgenGrayQueue *queue)
1267 GRAY_OBJECT_DEQUEUE (queue, &addr);
1270 g_assert (SGEN_OBJECT_IS_PINNED (addr));
1271 SGEN_UNPIN_OBJECT (addr);
1276 CopyOrMarkObjectFunc func;
1278 } UserCopyOrMarkData;
1281 single_arg_user_copy_or_mark (void **obj, void *gc_data)
1283 UserCopyOrMarkData *data = gc_data;
1285 data->func (obj, data->queue);
1289 * The memory area from start_root to end_root contains pointers to objects.
1290 * Their position is precisely described by @desc (this means that the pointer
1291 * can be either NULL or the pointer to the start of an object).
1292 * This functions copies them to to_space updates them.
1294 * This function is not thread-safe!
1297 precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, mword desc, ScanCopyContext ctx)
1299 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1300 SgenGrayQueue *queue = ctx.queue;
1302 switch (desc & ROOT_DESC_TYPE_MASK) {
1303 case ROOT_DESC_BITMAP:
1304 desc >>= ROOT_DESC_TYPE_SHIFT;
1306 if ((desc & 1) && *start_root) {
1307 copy_func (start_root, queue);
1308 SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
1309 sgen_drain_gray_stack (-1, ctx);
1315 case ROOT_DESC_COMPLEX: {
1316 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1317 gsize bwords = (*bitmap_data) - 1;
1318 void **start_run = start_root;
1320 while (bwords-- > 0) {
1321 gsize bmap = *bitmap_data++;
1322 void **objptr = start_run;
1324 if ((bmap & 1) && *objptr) {
1325 copy_func (objptr, queue);
1326 SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
1327 sgen_drain_gray_stack (-1, ctx);
1332 start_run += GC_BITS_PER_WORD;
1336 case ROOT_DESC_USER: {
1337 UserCopyOrMarkData data = { copy_func, queue };
1338 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1339 marker (start_root, single_arg_user_copy_or_mark, &data);
1342 case ROOT_DESC_RUN_LEN:
1343 g_assert_not_reached ();
1345 g_assert_not_reached ();
1350 reset_heap_boundaries (void)
1352 lowest_heap_address = ~(mword)0;
1353 highest_heap_address = 0;
1357 sgen_update_heap_boundaries (mword low, mword high)
1362 old = lowest_heap_address;
1365 } while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
1368 old = highest_heap_address;
1371 } while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
1375 * Allocate and setup the data structures needed to be able to allocate objects
1376 * in the nursery. The nursery is stored in nursery_section.
1379 alloc_nursery (void)
1381 GCMemSection *section;
1386 if (nursery_section)
1388 SGEN_LOG (2, "Allocating nursery size: %zu", (size_t)sgen_nursery_size);
1389 /* later we will alloc a larger area for the nursery but only activate
1390 * what we need. The rest will be used as expansion if we have too many pinned
1391 * objects in the existing nursery.
1393 /* FIXME: handle OOM */
1394 section = sgen_alloc_internal (INTERNAL_MEM_SECTION);
1396 alloc_size = sgen_nursery_size;
1398 /* If there isn't enough space even for the nursery we should simply abort. */
1399 g_assert (sgen_memgov_try_alloc_space (alloc_size, SPACE_NURSERY));
1401 #ifdef SGEN_ALIGN_NURSERY
1402 data = major_collector.alloc_heap (alloc_size, alloc_size, DEFAULT_NURSERY_BITS);
1404 data = major_collector.alloc_heap (alloc_size, 0, DEFAULT_NURSERY_BITS);
1406 sgen_update_heap_boundaries ((mword)data, (mword)(data + sgen_nursery_size));
1407 SGEN_LOG (4, "Expanding nursery size (%p-%p): %lu, total: %lu", data, data + alloc_size, (unsigned long)sgen_nursery_size, (unsigned long)mono_gc_get_heap_size ());
1408 section->data = section->next_data = data;
1409 section->size = alloc_size;
1410 section->end_data = data + sgen_nursery_size;
1411 scan_starts = (alloc_size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
1412 section->scan_starts = sgen_alloc_internal_dynamic (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS, TRUE);
1413 section->num_scan_start = scan_starts;
1415 nursery_section = section;
1417 sgen_nursery_allocator_set_nursery_bounds (data, data + sgen_nursery_size);
1421 mono_gc_get_nursery (int *shift_bits, size_t *size)
1423 *size = sgen_nursery_size;
1424 #ifdef SGEN_ALIGN_NURSERY
1425 *shift_bits = DEFAULT_NURSERY_BITS;
1429 return sgen_get_nursery_start ();
1433 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1435 SgenThreadInfo *info = mono_thread_info_current ();
1437 /* Could be called from sgen_thread_unregister () with a NULL info */
1440 info->stopped_domain = domain;
1445 mono_gc_precise_stack_mark_enabled (void)
1447 return !conservative_stack_mark;
1451 mono_gc_get_logfile (void)
1453 return gc_debug_file;
1457 report_finalizer_roots_list (FinalizeReadyEntry *list)
1459 GCRootReport report;
1460 FinalizeReadyEntry *fin;
1463 for (fin = list; fin; fin = fin->next) {
1466 add_profile_gc_root (&report, fin->object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1468 notify_gc_roots (&report);
1472 report_finalizer_roots (void)
1474 report_finalizer_roots_list (fin_ready_list);
1475 report_finalizer_roots_list (critical_fin_list);
1478 static GCRootReport *root_report;
1481 single_arg_report_root (void **obj, void *gc_data)
1484 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1488 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1490 switch (desc & ROOT_DESC_TYPE_MASK) {
1491 case ROOT_DESC_BITMAP:
1492 desc >>= ROOT_DESC_TYPE_SHIFT;
1494 if ((desc & 1) && *start_root) {
1495 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1501 case ROOT_DESC_COMPLEX: {
1502 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1503 gsize bwords = (*bitmap_data) - 1;
1504 void **start_run = start_root;
1506 while (bwords-- > 0) {
1507 gsize bmap = *bitmap_data++;
1508 void **objptr = start_run;
1510 if ((bmap & 1) && *objptr) {
1511 add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1516 start_run += GC_BITS_PER_WORD;
1520 case ROOT_DESC_USER: {
1521 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1522 root_report = report;
1523 marker (start_root, single_arg_report_root, NULL);
1526 case ROOT_DESC_RUN_LEN:
1527 g_assert_not_reached ();
1529 g_assert_not_reached ();
1534 report_registered_roots_by_type (int root_type)
1536 GCRootReport report;
1540 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1541 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1542 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1543 } SGEN_HASH_TABLE_FOREACH_END;
1544 notify_gc_roots (&report);
1548 report_registered_roots (void)
1550 report_registered_roots_by_type (ROOT_TYPE_NORMAL);
1551 report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
1555 scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx)
1557 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1558 SgenGrayQueue *queue = ctx.queue;
1559 FinalizeReadyEntry *fin;
1561 for (fin = list; fin; fin = fin->next) {
1564 SGEN_LOG (5, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object));
1565 copy_func (&fin->object, queue);
1570 generation_name (int generation)
1572 switch (generation) {
1573 case GENERATION_NURSERY: return "nursery";
1574 case GENERATION_OLD: return "old";
1575 default: g_assert_not_reached ();
1580 sgen_generation_name (int generation)
1582 return generation_name (generation);
1585 SgenObjectOperations *
1586 sgen_get_current_object_ops (void){
1587 return ¤t_object_ops;
1592 finish_gray_stack (int generation, GrayQueue *queue)
1596 int done_with_ephemerons, ephemeron_rounds = 0;
1597 CopyOrMarkObjectFunc copy_func = current_object_ops.copy_or_mark_object;
1598 ScanObjectFunc scan_func = current_object_ops.scan_object;
1599 ScanCopyContext ctx = { scan_func, copy_func, queue };
1600 char *start_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_start () : NULL;
1601 char *end_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_end () : (char*)-1;
1604 * We copied all the reachable objects. Now it's the time to copy
1605 * the objects that were not referenced by the roots, but by the copied objects.
1606 * we built a stack of objects pointed to by gray_start: they are
1607 * additional roots and we may add more items as we go.
1608 * We loop until gray_start == gray_objects which means no more objects have
1609 * been added. Note this is iterative: no recursion is involved.
1610 * We need to walk the LO list as well in search of marked big objects
1611 * (use a flag since this is needed only on major collections). We need to loop
1612 * here as well, so keep a counter of marked LO (increasing it in copy_object).
1613 * To achieve better cache locality and cache usage, we drain the gray stack
1614 * frequently, after each object is copied, and just finish the work here.
1616 sgen_drain_gray_stack (-1, ctx);
1618 SGEN_LOG (2, "%s generation done", generation_name (generation));
1621 Reset bridge data, we might have lingering data from a previous collection if this is a major
1622 collection trigged by minor overflow.
1624 We must reset the gathered bridges since their original block might be evacuated due to major
1625 fragmentation in the meanwhile and the bridge code should not have to deal with that.
1627 if (sgen_need_bridge_processing ())
1628 sgen_bridge_reset_data ();
1631 * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
1632 * before processing finalizable objects and non-tracking weak links to avoid finalizing/clearing
1633 * objects that are in fact reachable.
1635 done_with_ephemerons = 0;
1637 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1638 sgen_drain_gray_stack (-1, ctx);
1640 } while (!done_with_ephemerons);
1642 sgen_mark_togglerefs (start_addr, end_addr, ctx);
1644 if (sgen_need_bridge_processing ()) {
1645 /*Make sure the gray stack is empty before we process bridge objects so we get liveness right*/
1646 sgen_drain_gray_stack (-1, ctx);
1647 sgen_collect_bridge_objects (generation, ctx);
1648 if (generation == GENERATION_OLD)
1649 sgen_collect_bridge_objects (GENERATION_NURSERY, ctx);
1652 Do the first bridge step here, as the collector liveness state will become useless after that.
1654 An important optimization is to only proccess the possibly dead part of the object graph and skip
1655 over all live objects as we transitively know everything they point must be alive too.
1657 The above invariant is completely wrong if we let the gray queue be drained and mark/copy everything.
1659 This has the unfortunate side effect of making overflow collections perform the first step twice, but
1660 given we now have heuristics that perform major GC in anticipation of minor overflows this should not
1663 sgen_bridge_processing_stw_step ();
1667 Make sure we drain the gray stack before processing disappearing links and finalizers.
1668 If we don't make sure it is empty we might wrongly see a live object as dead.
1670 sgen_drain_gray_stack (-1, ctx);
1673 We must clear weak links that don't track resurrection before processing object ready for
1674 finalization so they can be cleared before that.
1676 sgen_null_link_in_range (generation, TRUE, ctx);
1677 if (generation == GENERATION_OLD)
1678 sgen_null_link_in_range (GENERATION_NURSERY, TRUE, ctx);
1681 /* walk the finalization queue and move also the objects that need to be
1682 * finalized: use the finalized objects as new roots so the objects they depend
1683 * on are also not reclaimed. As with the roots above, only objects in the nursery
1684 * are marked/copied.
1686 sgen_finalize_in_range (generation, ctx);
1687 if (generation == GENERATION_OLD)
1688 sgen_finalize_in_range (GENERATION_NURSERY, ctx);
1689 /* drain the new stack that might have been created */
1690 SGEN_LOG (6, "Precise scan of gray area post fin");
1691 sgen_drain_gray_stack (-1, ctx);
1694 * This must be done again after processing finalizable objects since CWL slots are cleared only after the key is finalized.
1696 done_with_ephemerons = 0;
1698 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1699 sgen_drain_gray_stack (-1, ctx);
1701 } while (!done_with_ephemerons);
1704 * Clear ephemeron pairs with unreachable keys.
1705 * We pass the copy func so we can figure out if an array was promoted or not.
1707 clear_unreachable_ephemerons (ctx);
1710 * We clear togglerefs only after all possible chances of revival are done.
1711 * This is semantically more inline with what users expect and it allows for
1712 * user finalizers to correctly interact with TR objects.
1714 sgen_clear_togglerefs (start_addr, end_addr, ctx);
1717 SGEN_LOG (2, "Finalize queue handling scan for %s generation: %d usecs %d ephemeron rounds", generation_name (generation), TV_ELAPSED (atv, btv), ephemeron_rounds);
1720 * handle disappearing links
1721 * Note we do this after checking the finalization queue because if an object
1722 * survives (at least long enough to be finalized) we don't clear the link.
1723 * This also deals with a possible issue with the monitor reclamation: with the Boehm
1724 * GC a finalized object my lose the monitor because it is cleared before the finalizer is
1727 g_assert (sgen_gray_object_queue_is_empty (queue));
1729 sgen_null_link_in_range (generation, FALSE, ctx);
1730 if (generation == GENERATION_OLD)
1731 sgen_null_link_in_range (GENERATION_NURSERY, FALSE, ctx);
1732 if (sgen_gray_object_queue_is_empty (queue))
1734 sgen_drain_gray_stack (-1, ctx);
1737 g_assert (sgen_gray_object_queue_is_empty (queue));
1741 sgen_check_section_scan_starts (GCMemSection *section)
1744 for (i = 0; i < section->num_scan_start; ++i) {
1745 if (section->scan_starts [i]) {
1746 mword size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
1747 g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
1753 check_scan_starts (void)
1755 if (!do_scan_starts_check)
1757 sgen_check_section_scan_starts (nursery_section);
1758 major_collector.check_scan_starts ();
1762 scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx)
1766 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1767 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1768 precisely_scan_objects_from (start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc, ctx);
1769 } SGEN_HASH_TABLE_FOREACH_END;
1773 sgen_dump_occupied (char *start, char *end, char *section_start)
1775 fprintf (heap_dump_file, "<occupied offset=\"%td\" size=\"%td\"/>\n", start - section_start, end - start);
1779 sgen_dump_section (GCMemSection *section, const char *type)
1781 char *start = section->data;
1782 char *end = section->data + section->size;
1783 char *occ_start = NULL;
1785 char *old_start = NULL; /* just for debugging */
1787 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%lu\">\n", type, (unsigned long)section->size);
1789 while (start < end) {
1793 if (!*(void**)start) {
1795 sgen_dump_occupied (occ_start, start, section->data);
1798 start += sizeof (void*); /* should be ALLOC_ALIGN, really */
1801 g_assert (start < section->next_data);
1806 vt = (GCVTable*)LOAD_VTABLE (start);
1809 size = ALIGN_UP (safe_object_get_size ((MonoObject*) start));
1812 fprintf (heap_dump_file, "<object offset=\"%d\" class=\"%s.%s\" size=\"%d\"/>\n",
1813 start - section->data,
1814 vt->klass->name_space, vt->klass->name,
1822 sgen_dump_occupied (occ_start, start, section->data);
1824 fprintf (heap_dump_file, "</section>\n");
1828 dump_object (MonoObject *obj, gboolean dump_location)
1830 static char class_name [1024];
1832 MonoClass *class = mono_object_class (obj);
1836 * Python's XML parser is too stupid to parse angle brackets
1837 * in strings, so we just ignore them;
1840 while (class->name [i] && j < sizeof (class_name) - 1) {
1841 if (!strchr ("<>\"", class->name [i]))
1842 class_name [j++] = class->name [i];
1845 g_assert (j < sizeof (class_name));
1848 fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%zd\"",
1849 class->name_space, class_name,
1850 safe_object_get_size (obj));
1851 if (dump_location) {
1852 const char *location;
1853 if (ptr_in_nursery (obj))
1854 location = "nursery";
1855 else if (safe_object_get_size (obj) <= MAX_SMALL_OBJ_SIZE)
1859 fprintf (heap_dump_file, " location=\"%s\"", location);
1861 fprintf (heap_dump_file, "/>\n");
1865 dump_heap (const char *type, int num, const char *reason)
1870 fprintf (heap_dump_file, "<collection type=\"%s\" num=\"%d\"", type, num);
1872 fprintf (heap_dump_file, " reason=\"%s\"", reason);
1873 fprintf (heap_dump_file, ">\n");
1874 fprintf (heap_dump_file, "<other-mem-usage type=\"mempools\" size=\"%ld\"/>\n", mono_mempool_get_bytes_allocated ());
1875 sgen_dump_internal_mem_usage (heap_dump_file);
1876 fprintf (heap_dump_file, "<pinned type=\"stack\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_STACK));
1877 /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */
1878 fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_OTHER));
1880 fprintf (heap_dump_file, "<pinned-objects>\n");
1881 for (list = sgen_pin_stats_get_object_list (); list; list = list->next)
1882 dump_object (list->obj, TRUE);
1883 fprintf (heap_dump_file, "</pinned-objects>\n");
1885 sgen_dump_section (nursery_section, "nursery");
1887 major_collector.dump_heap (heap_dump_file);
1889 fprintf (heap_dump_file, "<los>\n");
1890 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
1891 dump_object ((MonoObject*)bigobj->data, FALSE);
1892 fprintf (heap_dump_file, "</los>\n");
1894 fprintf (heap_dump_file, "</collection>\n");
1898 sgen_register_moved_object (void *obj, void *destination)
1900 g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
1902 /* FIXME: handle this for parallel collector */
1903 g_assert (!sgen_collection_is_parallel ());
1905 if (moved_objects_idx == MOVED_OBJECTS_NUM) {
1906 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
1907 moved_objects_idx = 0;
1909 moved_objects [moved_objects_idx++] = obj;
1910 moved_objects [moved_objects_idx++] = destination;
1916 static gboolean inited = FALSE;
1921 mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_pre_collection_fragment_clear);
1922 mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_pinning);
1923 mono_counters_register ("Minor scan remembered set", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_remsets);
1924 mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_pinned);
1925 mono_counters_register ("Minor scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_registered_roots);
1926 mono_counters_register ("Minor scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_thread_data);
1927 mono_counters_register ("Minor finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_finish_gray_stack);
1928 mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_fragment_creation);
1930 mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_pre_collection_fragment_clear);
1931 mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_pinning);
1932 mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_pinned);
1933 mono_counters_register ("Major scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_registered_roots);
1934 mono_counters_register ("Major scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_thread_data);
1935 mono_counters_register ("Major scan alloc_pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_alloc_pinned);
1936 mono_counters_register ("Major scan finalized", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_finalized);
1937 mono_counters_register ("Major scan big objects", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_big_objects);
1938 mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_finish_gray_stack);
1939 mono_counters_register ("Major free big objects", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_free_bigobjs);
1940 mono_counters_register ("Major LOS sweep", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_los_sweep);
1941 mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_sweep);
1942 mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_fragment_creation);
1944 mono_counters_register ("Number of pinned objects", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_pinned_objects);
1946 #ifdef HEAVY_STATISTICS
1947 mono_counters_register ("WBarrier remember pointer", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_add_to_global_remset);
1948 mono_counters_register ("WBarrier set field", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_field);
1949 mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_arrayref);
1950 mono_counters_register ("WBarrier arrayref copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_arrayref_copy);
1951 mono_counters_register ("WBarrier generic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store);
1952 mono_counters_register ("WBarrier generic atomic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store_atomic);
1953 mono_counters_register ("WBarrier set root", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_root);
1954 mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_value_copy);
1955 mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_object_copy);
1957 mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced_degraded);
1958 mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_degraded);
1960 mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_nursery);
1961 mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_nursery);
1962 mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_major);
1963 mono_counters_register ("# objects copied (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_major);
1965 mono_counters_register ("# scan_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_nursery);
1966 mono_counters_register ("# scan_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_major);
1968 mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
1970 mono_counters_register ("# nursery copy_object() failed from space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_from_space);
1971 mono_counters_register ("# nursery copy_object() failed forwarded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_forwarded);
1972 mono_counters_register ("# nursery copy_object() failed pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_pinned);
1973 mono_counters_register ("# nursery copy_object() failed to space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_to_space);
1975 sgen_nursery_allocator_init_heavy_stats ();
1976 sgen_alloc_init_heavy_stats ();
1984 reset_pinned_from_failed_allocation (void)
1986 bytes_pinned_from_failed_allocation = 0;
1990 sgen_set_pinned_from_failed_allocation (mword objsize)
1992 bytes_pinned_from_failed_allocation += objsize;
1996 sgen_collection_is_parallel (void)
1998 switch (current_collection_generation) {
1999 case GENERATION_NURSERY:
2000 return nursery_collection_is_parallel;
2001 case GENERATION_OLD:
2002 return major_collector.is_parallel;
2004 g_error ("Invalid current generation %d", current_collection_generation);
2009 sgen_collection_is_concurrent (void)
2011 switch (current_collection_generation) {
2012 case GENERATION_NURSERY:
2014 case GENERATION_OLD:
2015 return concurrent_collection_in_progress;
2017 g_error ("Invalid current generation %d", current_collection_generation);
2022 sgen_concurrent_collection_in_progress (void)
2024 return concurrent_collection_in_progress;
2031 } FinishRememberedSetScanJobData;
2034 job_finish_remembered_set_scan (WorkerData *worker_data, void *job_data_untyped)
2036 FinishRememberedSetScanJobData *job_data = job_data_untyped;
2038 remset.finish_scan_remsets (job_data->heap_start, job_data->heap_end, sgen_workers_get_job_gray_queue (worker_data));
2039 sgen_free_internal_dynamic (job_data, sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2044 CopyOrMarkObjectFunc copy_or_mark_func;
2045 ScanObjectFunc scan_func;
2049 } ScanFromRegisteredRootsJobData;
2052 job_scan_from_registered_roots (WorkerData *worker_data, void *job_data_untyped)
2054 ScanFromRegisteredRootsJobData *job_data = job_data_untyped;
2055 ScanCopyContext ctx = { job_data->scan_func, job_data->copy_or_mark_func,
2056 sgen_workers_get_job_gray_queue (worker_data) };
2058 scan_from_registered_roots (job_data->heap_start, job_data->heap_end, job_data->root_type, ctx);
2059 sgen_free_internal_dynamic (job_data, sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2066 } ScanThreadDataJobData;
2069 job_scan_thread_data (WorkerData *worker_data, void *job_data_untyped)
2071 ScanThreadDataJobData *job_data = job_data_untyped;
2073 scan_thread_data (job_data->heap_start, job_data->heap_end, TRUE,
2074 sgen_workers_get_job_gray_queue (worker_data));
2075 sgen_free_internal_dynamic (job_data, sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2080 FinalizeReadyEntry *list;
2081 } ScanFinalizerEntriesJobData;
2084 job_scan_finalizer_entries (WorkerData *worker_data, void *job_data_untyped)
2086 ScanFinalizerEntriesJobData *job_data = job_data_untyped;
2087 ScanCopyContext ctx = { NULL, current_object_ops.copy_or_mark_object, sgen_workers_get_job_gray_queue (worker_data) };
2089 scan_finalizer_entries (job_data->list, ctx);
2090 sgen_free_internal_dynamic (job_data, sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2094 job_scan_major_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2096 g_assert (concurrent_collection_in_progress);
2097 major_collector.scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2101 job_scan_los_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2103 g_assert (concurrent_collection_in_progress);
2104 sgen_los_scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2108 verify_scan_starts (char *start, char *end)
2112 for (i = 0; i < nursery_section->num_scan_start; ++i) {
2113 char *addr = nursery_section->scan_starts [i];
2114 if (addr > start && addr < end)
2115 SGEN_LOG (1, "NFC-BAD SCAN START [%zu] %p for obj [%p %p]", i, addr, start, end);
2120 verify_nursery (void)
2122 char *start, *end, *cur, *hole_start;
2124 if (!do_verify_nursery)
2127 /*This cleans up unused fragments */
2128 sgen_nursery_allocator_prepare_for_pinning ();
2130 hole_start = start = cur = sgen_get_nursery_start ();
2131 end = sgen_get_nursery_end ();
2136 if (!*(void**)cur) {
2137 cur += sizeof (void*);
2141 if (object_is_forwarded (cur))
2142 SGEN_LOG (1, "FORWARDED OBJ %p", cur);
2143 else if (object_is_pinned (cur))
2144 SGEN_LOG (1, "PINNED OBJ %p", cur);
2146 ss = safe_object_get_size ((MonoObject*)cur);
2147 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2148 verify_scan_starts (cur, cur + size);
2149 if (do_dump_nursery_content) {
2150 if (cur > hole_start)
2151 SGEN_LOG (1, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start));
2152 SGEN_LOG (1, "OBJ [%p %p %d %d %s %d]", cur, cur + size, (int)size, (int)ss, sgen_safe_name ((MonoObject*)cur), (gpointer)LOAD_VTABLE (cur) == sgen_get_array_fill_vtable ());
2160 * Checks that no objects in the nursery are fowarded or pinned. This
2161 * is a precondition to restarting the mutator while doing a
2162 * concurrent collection. Note that we don't clear fragments because
2163 * we depend on that having happened earlier.
2166 check_nursery_is_clean (void)
2168 char *start, *end, *cur;
2170 start = cur = sgen_get_nursery_start ();
2171 end = sgen_get_nursery_end ();
2176 if (!*(void**)cur) {
2177 cur += sizeof (void*);
2181 g_assert (!object_is_forwarded (cur));
2182 g_assert (!object_is_pinned (cur));
2184 ss = safe_object_get_size ((MonoObject*)cur);
2185 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2186 verify_scan_starts (cur, cur + size);
2193 init_gray_queue (void)
2195 if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ()) {
2196 sgen_workers_init_distribute_gray_queue ();
2197 sgen_gray_object_queue_init_with_alloc_prepare (&gray_queue, NULL,
2198 gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
2200 sgen_gray_object_queue_init (&gray_queue, NULL);
2205 pin_stage_object_callback (char *obj, size_t size, void *data)
2207 sgen_pin_stage_ptr (obj);
2208 /* FIXME: do pin stats if enabled */
2212 * Collect objects in the nursery. Returns whether to trigger a major
2216 collect_nursery (SgenGrayQueue *unpin_queue, gboolean finish_up_concurrent_mark)
2218 gboolean needs_major;
2219 size_t max_garbage_amount;
2221 FinishRememberedSetScanJobData *frssjd;
2222 ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2223 ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2224 ScanThreadDataJobData *stdjd;
2225 mword fragment_total;
2226 ScanCopyContext ctx;
2227 TV_DECLARE (all_atv);
2228 TV_DECLARE (all_btv);
2232 if (disable_minor_collections)
2235 MONO_GC_BEGIN (GENERATION_NURSERY);
2236 binary_protocol_collection_begin (gc_stats.minor_gc_count, GENERATION_NURSERY);
2240 #ifndef DISABLE_PERFCOUNTERS
2241 mono_perfcounters->gc_collections0++;
2244 current_collection_generation = GENERATION_NURSERY;
2245 if (sgen_collection_is_parallel ())
2246 current_object_ops = sgen_minor_collector.parallel_ops;
2248 current_object_ops = sgen_minor_collector.serial_ops;
2250 reset_pinned_from_failed_allocation ();
2252 check_scan_starts ();
2254 sgen_nursery_alloc_prepare_for_minor ();
2258 nursery_next = sgen_nursery_alloc_get_upper_alloc_bound ();
2259 /* FIXME: optimize later to use the higher address where an object can be present */
2260 nursery_next = MAX (nursery_next, sgen_get_nursery_end ());
2262 SGEN_LOG (1, "Start nursery collection %d %p-%p, size: %d", gc_stats.minor_gc_count, sgen_get_nursery_start (), nursery_next, (int)(nursery_next - sgen_get_nursery_start ()));
2263 max_garbage_amount = nursery_next - sgen_get_nursery_start ();
2264 g_assert (nursery_section->size >= max_garbage_amount);
2266 /* world must be stopped already */
2267 TV_GETTIME (all_atv);
2271 time_minor_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2273 if (xdomain_checks) {
2274 sgen_clear_nursery_fragments ();
2275 sgen_check_for_xdomain_refs ();
2278 nursery_section->next_data = nursery_next;
2280 major_collector.start_nursery_collection ();
2282 sgen_memgov_minor_collection_start ();
2286 gc_stats.minor_gc_count ++;
2288 MONO_GC_CHECKPOINT_1 (GENERATION_NURSERY);
2290 sgen_process_fin_stage_entries ();
2291 sgen_process_dislink_stage_entries ();
2293 MONO_GC_CHECKPOINT_2 (GENERATION_NURSERY);
2295 /* pin from pinned handles */
2296 sgen_init_pinning ();
2297 mono_profiler_gc_event (MONO_GC_EVENT_MARK_START, 0);
2298 pin_from_roots (sgen_get_nursery_start (), nursery_next, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2299 /* pin cemented objects */
2300 sgen_cement_iterate (pin_stage_object_callback, NULL);
2301 /* identify pinned objects */
2302 sgen_optimize_pin_queue (0);
2303 sgen_pinning_setup_section (nursery_section);
2304 ctx.scan_func = NULL;
2305 ctx.copy_func = NULL;
2306 ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2307 pin_objects_in_nursery (ctx);
2308 sgen_pinning_trim_queue_to_section (nursery_section);
2311 time_minor_pinning += TV_ELAPSED (btv, atv);
2312 SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (btv, atv));
2313 SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
2315 MONO_GC_CHECKPOINT_3 (GENERATION_NURSERY);
2317 if (whole_heap_check_before_collection) {
2318 sgen_clear_nursery_fragments ();
2319 sgen_check_whole_heap (finish_up_concurrent_mark);
2321 if (consistency_check_at_minor_collection)
2322 sgen_check_consistency ();
2324 sgen_workers_start_all_workers ();
2325 sgen_workers_start_marking ();
2327 frssjd = sgen_alloc_internal_dynamic (sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2328 frssjd->heap_start = sgen_get_nursery_start ();
2329 frssjd->heap_end = nursery_next;
2330 sgen_workers_enqueue_job (job_finish_remembered_set_scan, frssjd);
2332 /* we don't have complete write barrier yet, so we scan all the old generation sections */
2334 time_minor_scan_remsets += TV_ELAPSED (atv, btv);
2335 SGEN_LOG (2, "Old generation scan: %d usecs", TV_ELAPSED (atv, btv));
2337 MONO_GC_CHECKPOINT_4 (GENERATION_NURSERY);
2339 if (!sgen_collection_is_parallel ()) {
2340 ctx.scan_func = current_object_ops.scan_object;
2341 ctx.copy_func = NULL;
2342 ctx.queue = &gray_queue;
2343 sgen_drain_gray_stack (-1, ctx);
2346 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2347 report_registered_roots ();
2348 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2349 report_finalizer_roots ();
2351 time_minor_scan_pinned += TV_ELAPSED (btv, atv);
2353 MONO_GC_CHECKPOINT_5 (GENERATION_NURSERY);
2355 /* registered roots, this includes static fields */
2356 scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2357 scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2358 scrrjd_normal->scan_func = current_object_ops.scan_object;
2359 scrrjd_normal->heap_start = sgen_get_nursery_start ();
2360 scrrjd_normal->heap_end = nursery_next;
2361 scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2362 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2364 scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2365 scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2366 scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2367 scrrjd_wbarrier->heap_start = sgen_get_nursery_start ();
2368 scrrjd_wbarrier->heap_end = nursery_next;
2369 scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2370 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2373 time_minor_scan_registered_roots += TV_ELAPSED (atv, btv);
2375 MONO_GC_CHECKPOINT_6 (GENERATION_NURSERY);
2378 stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2379 stdjd->heap_start = sgen_get_nursery_start ();
2380 stdjd->heap_end = nursery_next;
2381 sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2384 time_minor_scan_thread_data += TV_ELAPSED (btv, atv);
2387 MONO_GC_CHECKPOINT_7 (GENERATION_NURSERY);
2389 g_assert (!sgen_collection_is_parallel () && !sgen_collection_is_concurrent ());
2391 if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ())
2392 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2394 /* Scan the list of objects ready for finalization. If */
2395 sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2396 sfejd_fin_ready->list = fin_ready_list;
2397 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2399 sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2400 sfejd_critical_fin->list = critical_fin_list;
2401 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2403 MONO_GC_CHECKPOINT_8 (GENERATION_NURSERY);
2405 finish_gray_stack (GENERATION_NURSERY, &gray_queue);
2407 time_minor_finish_gray_stack += TV_ELAPSED (btv, atv);
2408 mono_profiler_gc_event (MONO_GC_EVENT_MARK_END, 0);
2410 MONO_GC_CHECKPOINT_9 (GENERATION_NURSERY);
2413 * The (single-threaded) finalization code might have done
2414 * some copying/marking so we can only reset the GC thread's
2415 * worker data here instead of earlier when we joined the
2418 sgen_workers_reset_data ();
2420 if (objects_pinned) {
2421 sgen_optimize_pin_queue (0);
2422 sgen_pinning_setup_section (nursery_section);
2425 /* walk the pin_queue, build up the fragment list of free memory, unmark
2426 * pinned objects as we go, memzero() the empty fragments so they are ready for the
2429 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_START, 0);
2430 fragment_total = sgen_build_nursery_fragments (nursery_section,
2431 nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries,
2433 if (!fragment_total)
2436 /* Clear TLABs for all threads */
2437 sgen_clear_tlabs ();
2439 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_END, 0);
2441 time_minor_fragment_creation += TV_ELAPSED (atv, btv);
2442 SGEN_LOG (2, "Fragment creation: %d usecs, %lu bytes available", TV_ELAPSED (atv, btv), (unsigned long)fragment_total);
2444 if (consistency_check_at_minor_collection)
2445 sgen_check_major_refs ();
2447 major_collector.finish_nursery_collection ();
2449 TV_GETTIME (all_btv);
2450 gc_stats.minor_gc_time += TV_ELAPSED (all_atv, all_btv);
2453 dump_heap ("minor", gc_stats.minor_gc_count - 1, NULL);
2455 /* prepare the pin queue for the next collection */
2456 sgen_finish_pinning ();
2457 if (fin_ready_list || critical_fin_list) {
2458 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2459 mono_gc_finalize_notify ();
2461 sgen_pin_stats_reset ();
2462 /* clear cemented hash */
2463 sgen_cement_clear_below_threshold ();
2465 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2467 remset.finish_minor_collection ();
2469 check_scan_starts ();
2471 binary_protocol_flush_buffers (FALSE);
2473 sgen_memgov_minor_collection_end ();
2475 /*objects are late pinned because of lack of memory, so a major is a good call*/
2476 needs_major = objects_pinned > 0;
2477 current_collection_generation = -1;
2480 MONO_GC_END (GENERATION_NURSERY);
2481 binary_protocol_collection_end (gc_stats.minor_gc_count - 1, GENERATION_NURSERY);
2483 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2484 sgen_check_nursery_objects_pinned (unpin_queue != NULL);
2490 scan_nursery_objects_callback (char *obj, size_t size, ScanCopyContext *ctx)
2492 ctx->scan_func (obj, ctx->queue);
2496 scan_nursery_objects (ScanCopyContext ctx)
2498 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
2499 (IterateObjectCallbackFunc)scan_nursery_objects_callback, (void*)&ctx, FALSE);
2503 major_copy_or_mark_from_roots (size_t *old_next_pin_slot, gboolean finish_up_concurrent_mark, gboolean scan_mod_union)
2508 /* FIXME: only use these values for the precise scan
2509 * note that to_space pointers should be excluded anyway...
2511 char *heap_start = NULL;
2512 char *heap_end = (char*)-1;
2513 gboolean profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2514 GCRootReport root_report = { 0 };
2515 ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2516 ScanThreadDataJobData *stdjd;
2517 ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2518 ScanCopyContext ctx;
2520 if (concurrent_collection_in_progress) {
2521 /*This cleans up unused fragments */
2522 sgen_nursery_allocator_prepare_for_pinning ();
2524 if (do_concurrent_checks)
2525 check_nursery_is_clean ();
2527 /* The concurrent collector doesn't touch the nursery. */
2528 sgen_nursery_alloc_prepare_for_major ();
2535 /* Pinning depends on this */
2536 sgen_clear_nursery_fragments ();
2538 if (whole_heap_check_before_collection)
2539 sgen_check_whole_heap (finish_up_concurrent_mark);
2542 time_major_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2544 if (!sgen_collection_is_concurrent ())
2545 nursery_section->next_data = sgen_get_nursery_end ();
2546 /* we should also coalesce scanning from sections close to each other
2547 * and deal with pointers outside of the sections later.
2551 *major_collector.have_swept = FALSE;
2553 if (xdomain_checks) {
2554 sgen_clear_nursery_fragments ();
2555 sgen_check_for_xdomain_refs ();
2558 if (!concurrent_collection_in_progress) {
2559 /* Remsets are not useful for a major collection */
2560 remset.prepare_for_major_collection ();
2563 sgen_process_fin_stage_entries ();
2564 sgen_process_dislink_stage_entries ();
2567 sgen_init_pinning ();
2568 SGEN_LOG (6, "Collecting pinned addresses");
2569 pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2571 if (!concurrent_collection_in_progress || finish_up_concurrent_mark) {
2572 if (major_collector.is_concurrent) {
2574 * The concurrent major collector cannot evict
2575 * yet, so we need to pin cemented objects to
2576 * not break some asserts.
2578 * FIXME: We could evict now!
2580 sgen_cement_iterate (pin_stage_object_callback, NULL);
2583 if (!concurrent_collection_in_progress)
2584 sgen_cement_reset ();
2587 sgen_optimize_pin_queue (0);
2590 * The concurrent collector doesn't move objects, neither on
2591 * the major heap nor in the nursery, so we can mark even
2592 * before pinning has finished. For the non-concurrent
2593 * collector we start the workers after pinning.
2595 if (concurrent_collection_in_progress) {
2596 sgen_workers_start_all_workers ();
2597 sgen_workers_start_marking ();
2601 * pin_queue now contains all candidate pointers, sorted and
2602 * uniqued. We must do two passes now to figure out which
2603 * objects are pinned.
2605 * The first is to find within the pin_queue the area for each
2606 * section. This requires that the pin_queue be sorted. We
2607 * also process the LOS objects and pinned chunks here.
2609 * The second, destructive, pass is to reduce the section
2610 * areas to pointers to the actually pinned objects.
2612 SGEN_LOG (6, "Pinning from sections");
2613 /* first pass for the sections */
2614 sgen_find_section_pin_queue_start_end (nursery_section);
2615 major_collector.find_pin_queue_start_ends (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2616 /* identify possible pointers to the insize of large objects */
2617 SGEN_LOG (6, "Pinning from large objects");
2618 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
2620 if (sgen_find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + sgen_los_object_size (bigobj), &dummy)) {
2621 binary_protocol_pin (bigobj->data, (gpointer)LOAD_VTABLE (bigobj->data), safe_object_get_size (((MonoObject*)(bigobj->data))));
2623 #ifdef ENABLE_DTRACE
2624 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
2625 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (bigobj->data);
2626 MONO_GC_OBJ_PINNED ((mword)bigobj->data, sgen_safe_object_get_size ((MonoObject*)bigobj->data), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
2630 if (sgen_los_object_is_pinned (bigobj->data)) {
2631 g_assert (finish_up_concurrent_mark);
2634 sgen_los_pin_object (bigobj->data);
2635 if (SGEN_OBJECT_HAS_REFERENCES (bigobj->data))
2636 GRAY_OBJECT_ENQUEUE (WORKERS_DISTRIBUTE_GRAY_QUEUE, bigobj->data);
2637 if (G_UNLIKELY (do_pin_stats))
2638 sgen_pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
2639 SGEN_LOG (6, "Marked large object %p (%s) size: %lu from roots", bigobj->data, safe_name (bigobj->data), (unsigned long)sgen_los_object_size (bigobj));
2642 add_profile_gc_root (&root_report, bigobj->data, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2646 notify_gc_roots (&root_report);
2647 /* second pass for the sections */
2648 ctx.scan_func = concurrent_collection_in_progress ? current_object_ops.scan_object : NULL;
2649 ctx.copy_func = NULL;
2650 ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2653 * Concurrent mark never follows references into the nursery.
2654 * In the start and finish pauses we must scan live nursery
2655 * objects, though. We could simply scan all nursery objects,
2656 * but that would be conservative. The easiest way is to do a
2657 * nursery collection, which copies all live nursery objects
2658 * (except pinned ones, with the simple nursery) to the major
2659 * heap. Scanning the mod union table later will then scan
2660 * those promoted objects, provided they're reachable. Pinned
2661 * objects in the nursery - which we can trivially find in the
2662 * pinning queue - are treated as roots in the mark pauses.
2664 * The split nursery complicates the latter part because
2665 * non-pinned objects can survive in the nursery. That's why
2666 * we need to do a full front-to-back scan of the nursery,
2667 * marking all objects.
2669 * Non-concurrent mark evacuates from the nursery, so it's
2670 * sufficient to just scan pinned nursery objects.
2672 if (concurrent_collection_in_progress && sgen_minor_collector.is_split) {
2673 scan_nursery_objects (ctx);
2675 pin_objects_in_nursery (ctx);
2676 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2677 sgen_check_nursery_objects_pinned (!concurrent_collection_in_progress || finish_up_concurrent_mark);
2680 major_collector.pin_objects (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2681 if (old_next_pin_slot)
2682 *old_next_pin_slot = sgen_get_pinned_count ();
2685 time_major_pinning += TV_ELAPSED (atv, btv);
2686 SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (atv, btv));
2687 SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
2689 major_collector.init_to_space ();
2691 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2692 main_gc_thread = mono_native_thread_self ();
2695 if (!concurrent_collection_in_progress && major_collector.is_parallel) {
2696 sgen_workers_start_all_workers ();
2697 sgen_workers_start_marking ();
2700 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2701 report_registered_roots ();
2703 time_major_scan_pinned += TV_ELAPSED (btv, atv);
2705 /* registered roots, this includes static fields */
2706 scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2707 scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2708 scrrjd_normal->scan_func = current_object_ops.scan_object;
2709 scrrjd_normal->heap_start = heap_start;
2710 scrrjd_normal->heap_end = heap_end;
2711 scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2712 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2714 scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2715 scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2716 scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2717 scrrjd_wbarrier->heap_start = heap_start;
2718 scrrjd_wbarrier->heap_end = heap_end;
2719 scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2720 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2723 time_major_scan_registered_roots += TV_ELAPSED (atv, btv);
2726 stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2727 stdjd->heap_start = heap_start;
2728 stdjd->heap_end = heap_end;
2729 sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2732 time_major_scan_thread_data += TV_ELAPSED (btv, atv);
2735 time_major_scan_alloc_pinned += TV_ELAPSED (atv, btv);
2737 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2738 report_finalizer_roots ();
2740 /* scan the list of objects ready for finalization */
2741 sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2742 sfejd_fin_ready->list = fin_ready_list;
2743 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2745 sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2746 sfejd_critical_fin->list = critical_fin_list;
2747 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2749 if (scan_mod_union) {
2750 g_assert (finish_up_concurrent_mark);
2752 /* Mod union card table */
2753 sgen_workers_enqueue_job (job_scan_major_mod_union_cardtable, NULL);
2754 sgen_workers_enqueue_job (job_scan_los_mod_union_cardtable, NULL);
2758 time_major_scan_finalized += TV_ELAPSED (btv, atv);
2759 SGEN_LOG (2, "Root scan: %d usecs", TV_ELAPSED (btv, atv));
2762 time_major_scan_big_objects += TV_ELAPSED (atv, btv);
2764 if (concurrent_collection_in_progress) {
2765 /* prepare the pin queue for the next collection */
2766 sgen_finish_pinning ();
2768 sgen_pin_stats_reset ();
2770 if (do_concurrent_checks)
2771 check_nursery_is_clean ();
2776 major_start_collection (gboolean concurrent, size_t *old_next_pin_slot)
2778 MONO_GC_BEGIN (GENERATION_OLD);
2779 binary_protocol_collection_begin (gc_stats.major_gc_count, GENERATION_OLD);
2781 current_collection_generation = GENERATION_OLD;
2782 #ifndef DISABLE_PERFCOUNTERS
2783 mono_perfcounters->gc_collections1++;
2786 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2789 g_assert (major_collector.is_concurrent);
2790 concurrent_collection_in_progress = TRUE;
2792 sgen_cement_concurrent_start ();
2794 current_object_ops = major_collector.major_concurrent_ops;
2796 current_object_ops = major_collector.major_ops;
2799 reset_pinned_from_failed_allocation ();
2801 sgen_memgov_major_collection_start ();
2803 //count_ref_nonref_objs ();
2804 //consistency_check ();
2806 check_scan_starts ();
2809 SGEN_LOG (1, "Start major collection %d", gc_stats.major_gc_count);
2810 gc_stats.major_gc_count ++;
2812 if (major_collector.start_major_collection)
2813 major_collector.start_major_collection ();
2815 major_copy_or_mark_from_roots (old_next_pin_slot, FALSE, FALSE);
2819 wait_for_workers_to_finish (void)
2821 while (!sgen_workers_all_done ())
2828 if (concurrent_collection_in_progress || major_collector.is_parallel) {
2829 gray_queue_redirect (&gray_queue);
2830 sgen_workers_join ();
2833 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2835 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2836 main_gc_thread = NULL;
2841 major_finish_collection (const char *reason, size_t old_next_pin_slot, gboolean scan_mod_union)
2843 LOSObject *bigobj, *prevbo;
2849 if (concurrent_collection_in_progress || major_collector.is_parallel)
2852 if (concurrent_collection_in_progress) {
2853 current_object_ops = major_collector.major_concurrent_ops;
2855 major_copy_or_mark_from_roots (NULL, TRUE, scan_mod_union);
2858 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2860 if (do_concurrent_checks)
2861 check_nursery_is_clean ();
2863 current_object_ops = major_collector.major_ops;
2867 * The workers have stopped so we need to finish gray queue
2868 * work that might result from finalization in the main GC
2869 * thread. Redirection must therefore be turned off.
2871 sgen_gray_object_queue_disable_alloc_prepare (&gray_queue);
2872 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2874 /* all the objects in the heap */
2875 finish_gray_stack (GENERATION_OLD, &gray_queue);
2877 time_major_finish_gray_stack += TV_ELAPSED (btv, atv);
2880 * The (single-threaded) finalization code might have done
2881 * some copying/marking so we can only reset the GC thread's
2882 * worker data here instead of earlier when we joined the
2885 sgen_workers_reset_data ();
2887 if (objects_pinned) {
2888 g_assert (!concurrent_collection_in_progress);
2890 /*This is slow, but we just OOM'd*/
2891 sgen_pin_queue_clear_discarded_entries (nursery_section, old_next_pin_slot);
2892 sgen_optimize_pin_queue (0);
2893 sgen_find_section_pin_queue_start_end (nursery_section);
2897 reset_heap_boundaries ();
2898 sgen_update_heap_boundaries ((mword)sgen_get_nursery_start (), (mword)sgen_get_nursery_end ());
2900 if (check_mark_bits_after_major_collection)
2901 sgen_check_major_heap_marked ();
2903 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, !major_collector.sweeps_lazily);
2905 /* sweep the big objects list */
2907 for (bigobj = los_object_list; bigobj;) {
2908 g_assert (!object_is_pinned (bigobj->data));
2909 if (sgen_los_object_is_pinned (bigobj->data)) {
2910 sgen_los_unpin_object (bigobj->data);
2911 sgen_update_heap_boundaries ((mword)bigobj->data, (mword)bigobj->data + sgen_los_object_size (bigobj));
2914 /* not referenced anywhere, so we can free it */
2916 prevbo->next = bigobj->next;
2918 los_object_list = bigobj->next;
2920 bigobj = bigobj->next;
2921 sgen_los_free_object (to_free);
2925 bigobj = bigobj->next;
2929 time_major_free_bigobjs += TV_ELAPSED (atv, btv);
2934 time_major_los_sweep += TV_ELAPSED (btv, atv);
2936 major_collector.sweep ();
2938 MONO_GC_SWEEP_END (GENERATION_OLD, !major_collector.sweeps_lazily);
2941 time_major_sweep += TV_ELAPSED (atv, btv);
2943 if (!concurrent_collection_in_progress) {
2944 /* walk the pin_queue, build up the fragment list of free memory, unmark
2945 * pinned objects as we go, memzero() the empty fragments so they are ready for the
2948 if (!sgen_build_nursery_fragments (nursery_section, nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries, NULL))
2951 /* prepare the pin queue for the next collection */
2952 sgen_finish_pinning ();
2954 /* Clear TLABs for all threads */
2955 sgen_clear_tlabs ();
2957 sgen_pin_stats_reset ();
2960 if (concurrent_collection_in_progress)
2961 sgen_cement_concurrent_finish ();
2962 sgen_cement_clear_below_threshold ();
2965 time_major_fragment_creation += TV_ELAPSED (btv, atv);
2968 dump_heap ("major", gc_stats.major_gc_count - 1, reason);
2970 if (fin_ready_list || critical_fin_list) {
2971 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2972 mono_gc_finalize_notify ();
2975 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2977 sgen_memgov_major_collection_end ();
2978 current_collection_generation = -1;
2980 major_collector.finish_major_collection ();
2982 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2984 if (concurrent_collection_in_progress)
2985 concurrent_collection_in_progress = FALSE;
2987 check_scan_starts ();
2989 binary_protocol_flush_buffers (FALSE);
2991 //consistency_check ();
2993 MONO_GC_END (GENERATION_OLD);
2994 binary_protocol_collection_end (gc_stats.major_gc_count - 1, GENERATION_OLD);
2998 major_do_collection (const char *reason)
3000 TV_DECLARE (all_atv);
3001 TV_DECLARE (all_btv);
3002 size_t old_next_pin_slot;
3004 if (disable_major_collections)
3007 if (major_collector.get_and_reset_num_major_objects_marked) {
3008 long long num_marked = major_collector.get_and_reset_num_major_objects_marked ();
3009 g_assert (!num_marked);
3012 /* world must be stopped already */
3013 TV_GETTIME (all_atv);
3015 major_start_collection (FALSE, &old_next_pin_slot);
3016 major_finish_collection (reason, old_next_pin_slot, FALSE);
3018 TV_GETTIME (all_btv);
3019 gc_stats.major_gc_time += TV_ELAPSED (all_atv, all_btv);
3021 /* FIXME: also report this to the user, preferably in gc-end. */
3022 if (major_collector.get_and_reset_num_major_objects_marked)
3023 major_collector.get_and_reset_num_major_objects_marked ();
3025 return bytes_pinned_from_failed_allocation > 0;
3029 major_start_concurrent_collection (const char *reason)
3031 long long num_objects_marked;
3033 if (disable_major_collections)
3036 num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3037 g_assert (num_objects_marked == 0);
3039 MONO_GC_CONCURRENT_START_BEGIN (GENERATION_OLD);
3040 binary_protocol_concurrent_start ();
3042 // FIXME: store reason and pass it when finishing
3043 major_start_collection (TRUE, NULL);
3045 gray_queue_redirect (&gray_queue);
3046 sgen_workers_wait_for_jobs ();
3048 num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3049 MONO_GC_CONCURRENT_START_END (GENERATION_OLD, num_objects_marked);
3051 current_collection_generation = -1;
3055 major_update_or_finish_concurrent_collection (gboolean force_finish)
3057 SgenGrayQueue unpin_queue;
3058 memset (&unpin_queue, 0, sizeof (unpin_queue));
3060 MONO_GC_CONCURRENT_UPDATE_FINISH_BEGIN (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3061 binary_protocol_concurrent_update_finish ();
3063 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3065 if (!force_finish && !sgen_workers_all_done ()) {
3066 major_collector.update_cardtable_mod_union ();
3067 sgen_los_update_cardtable_mod_union ();
3069 MONO_GC_CONCURRENT_UPDATE_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3074 * The major collector can add global remsets which are processed in the finishing
3075 * nursery collection, below. That implies that the workers must have finished
3076 * marking before the nursery collection is allowed to run, otherwise we might miss
3079 wait_for_workers_to_finish ();
3081 major_collector.update_cardtable_mod_union ();
3082 sgen_los_update_cardtable_mod_union ();
3084 collect_nursery (&unpin_queue, TRUE);
3086 if (mod_union_consistency_check)
3087 sgen_check_mod_union_consistency ();
3089 current_collection_generation = GENERATION_OLD;
3090 major_finish_collection ("finishing", -1, TRUE);
3092 if (whole_heap_check_before_collection)
3093 sgen_check_whole_heap (FALSE);
3095 unpin_objects_from_queue (&unpin_queue);
3096 sgen_gray_object_queue_deinit (&unpin_queue);
3098 MONO_GC_CONCURRENT_FINISH_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3100 current_collection_generation = -1;
3106 * Ensure an allocation request for @size will succeed by freeing enough memory.
3108 * LOCKING: The GC lock MUST be held.
3111 sgen_ensure_free_space (size_t size)
3113 int generation_to_collect = -1;
3114 const char *reason = NULL;
3117 if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
3118 if (sgen_need_major_collection (size)) {
3119 reason = "LOS overflow";
3120 generation_to_collect = GENERATION_OLD;
3123 if (degraded_mode) {
3124 if (sgen_need_major_collection (size)) {
3125 reason = "Degraded mode overflow";
3126 generation_to_collect = GENERATION_OLD;
3128 } else if (sgen_need_major_collection (size)) {
3129 reason = "Minor allowance";
3130 generation_to_collect = GENERATION_OLD;
3132 generation_to_collect = GENERATION_NURSERY;
3133 reason = "Nursery full";
3137 if (generation_to_collect == -1) {
3138 if (concurrent_collection_in_progress && sgen_workers_all_done ()) {
3139 generation_to_collect = GENERATION_OLD;
3140 reason = "Finish concurrent collection";
3144 if (generation_to_collect == -1)
3146 sgen_perform_collection (size, generation_to_collect, reason, FALSE);
3150 * LOCKING: Assumes the GC lock is held.
3153 sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish)
3155 TV_DECLARE (gc_end);
3156 GGTimingInfo infos [2];
3157 int overflow_generation_to_collect = -1;
3158 int oldest_generation_collected = generation_to_collect;
3159 const char *overflow_reason = NULL;
3161 MONO_GC_REQUESTED (generation_to_collect, requested_size, wait_to_finish ? 1 : 0);
3163 binary_protocol_collection_force (generation_to_collect);
3165 g_assert (generation_to_collect == GENERATION_NURSERY || generation_to_collect == GENERATION_OLD);
3167 memset (infos, 0, sizeof (infos));
3168 mono_profiler_gc_event (MONO_GC_EVENT_START, generation_to_collect);
3170 infos [0].generation = generation_to_collect;
3171 infos [0].reason = reason;
3172 infos [0].is_overflow = FALSE;
3173 TV_GETTIME (infos [0].total_time);
3174 infos [1].generation = -1;
3176 sgen_stop_world (generation_to_collect);
3178 if (concurrent_collection_in_progress) {
3179 if (major_update_or_finish_concurrent_collection (wait_to_finish && generation_to_collect == GENERATION_OLD)) {
3180 oldest_generation_collected = GENERATION_OLD;
3183 if (generation_to_collect == GENERATION_OLD)
3186 if (generation_to_collect == GENERATION_OLD &&
3187 allow_synchronous_major &&
3188 major_collector.want_synchronous_collection &&
3189 *major_collector.want_synchronous_collection) {
3190 wait_to_finish = TRUE;
3194 //FIXME extract overflow reason
3195 if (generation_to_collect == GENERATION_NURSERY) {
3196 if (collect_nursery (NULL, FALSE)) {
3197 overflow_generation_to_collect = GENERATION_OLD;
3198 overflow_reason = "Minor overflow";
3201 if (major_collector.is_concurrent) {
3202 g_assert (!concurrent_collection_in_progress);
3203 if (!wait_to_finish)
3204 collect_nursery (NULL, FALSE);
3207 if (major_collector.is_concurrent && !wait_to_finish) {
3208 major_start_concurrent_collection (reason);
3209 // FIXME: set infos[0] properly
3212 if (major_do_collection (reason)) {
3213 overflow_generation_to_collect = GENERATION_NURSERY;
3214 overflow_reason = "Excessive pinning";
3219 TV_GETTIME (gc_end);
3220 infos [0].total_time = SGEN_TV_ELAPSED (infos [0].total_time, gc_end);
3223 if (!major_collector.is_concurrent && overflow_generation_to_collect != -1) {
3224 mono_profiler_gc_event (MONO_GC_EVENT_START, overflow_generation_to_collect);
3225 infos [1].generation = overflow_generation_to_collect;
3226 infos [1].reason = overflow_reason;
3227 infos [1].is_overflow = TRUE;
3228 infos [1].total_time = gc_end;
3230 if (overflow_generation_to_collect == GENERATION_NURSERY)
3231 collect_nursery (NULL, FALSE);
3233 major_do_collection (overflow_reason);
3235 TV_GETTIME (gc_end);
3236 infos [1].total_time = SGEN_TV_ELAPSED (infos [1].total_time, gc_end);
3238 /* keep events symmetric */
3239 mono_profiler_gc_event (MONO_GC_EVENT_END, overflow_generation_to_collect);
3241 oldest_generation_collected = MAX (oldest_generation_collected, overflow_generation_to_collect);
3244 SGEN_LOG (2, "Heap size: %lu, LOS size: %lu", (unsigned long)mono_gc_get_heap_size (), (unsigned long)los_memory_usage);
3246 /* this also sets the proper pointers for the next allocation */
3247 if (generation_to_collect == GENERATION_NURSERY && !sgen_can_alloc_size (requested_size)) {
3248 /* TypeBuilder and MonoMethod are killing mcs with fragmentation */
3249 SGEN_LOG (1, "nursery collection didn't find enough room for %zd alloc (%zd pinned)", requested_size, sgen_get_pinned_count ());
3250 sgen_dump_pin_queue ();
3255 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3257 sgen_restart_world (oldest_generation_collected, infos);
3259 mono_profiler_gc_event (MONO_GC_EVENT_END, generation_to_collect);
3263 * ######################################################################
3264 * ######## Memory allocation from the OS
3265 * ######################################################################
3266 * This section of code deals with getting memory from the OS and
3267 * allocating memory for GC-internal data structures.
3268 * Internal memory can be handled with a freelist for small objects.
3274 G_GNUC_UNUSED static void
3275 report_internal_mem_usage (void)
3277 printf ("Internal memory usage:\n");
3278 sgen_report_internal_mem_usage ();
3279 printf ("Pinned memory usage:\n");
3280 major_collector.report_pinned_memory_usage ();
3284 * ######################################################################
3285 * ######## Finalization support
3286 * ######################################################################
3289 static inline gboolean
3290 sgen_major_is_object_alive (void *object)
3294 /* Oldgen objects can be pinned and forwarded too */
3295 if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
3299 * FIXME: major_collector.is_object_live() also calculates the
3300 * size. Avoid the double calculation.
3302 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)object));
3303 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
3304 return sgen_los_object_is_pinned (object);
3306 return major_collector.is_object_live (object);
3310 * If the object has been forwarded it means it's still referenced from a root.
3311 * If it is pinned it's still alive as well.
3312 * A LOS object is only alive if we have pinned it.
3313 * Return TRUE if @obj is ready to be finalized.
3315 static inline gboolean
3316 sgen_is_object_alive (void *object)
3318 if (ptr_in_nursery (object))
3319 return sgen_nursery_is_object_alive (object);
3321 return sgen_major_is_object_alive (object);
3325 * This function returns true if @object is either alive or it belongs to the old gen
3326 * and we're currently doing a minor collection.
3329 sgen_is_object_alive_for_current_gen (char *object)
3331 if (ptr_in_nursery (object))
3332 return sgen_nursery_is_object_alive (object);
3334 if (current_collection_generation == GENERATION_NURSERY)
3337 return sgen_major_is_object_alive (object);
3341 * This function returns true if @object is either alive and belongs to the
3342 * current collection - major collections are full heap, so old gen objects
3343 * are never alive during a minor collection.
3346 sgen_is_object_alive_and_on_current_collection (char *object)
3348 if (ptr_in_nursery (object))
3349 return sgen_nursery_is_object_alive (object);
3351 if (current_collection_generation == GENERATION_NURSERY)
3354 return sgen_major_is_object_alive (object);
3359 sgen_gc_is_object_ready_for_finalization (void *object)
3361 return !sgen_is_object_alive (object);
3365 has_critical_finalizer (MonoObject *obj)
3369 if (!mono_defaults.critical_finalizer_object)
3372 class = ((MonoVTable*)LOAD_VTABLE (obj))->klass;
3374 return mono_class_has_parent_fast (class, mono_defaults.critical_finalizer_object);
3378 is_finalization_aware (MonoObject *obj)
3380 MonoVTable *vt = ((MonoVTable*)LOAD_VTABLE (obj));
3381 return (vt->gc_bits & SGEN_GC_BIT_FINALIZER_AWARE) == SGEN_GC_BIT_FINALIZER_AWARE;
3385 sgen_queue_finalization_entry (MonoObject *obj)
3387 FinalizeReadyEntry *entry = sgen_alloc_internal (INTERNAL_MEM_FINALIZE_READY_ENTRY);
3388 gboolean critical = has_critical_finalizer (obj);
3389 entry->object = obj;
3391 entry->next = critical_fin_list;
3392 critical_fin_list = entry;
3394 entry->next = fin_ready_list;
3395 fin_ready_list = entry;
3398 if (fin_callbacks.object_queued_for_finalization && is_finalization_aware (obj))
3399 fin_callbacks.object_queued_for_finalization (obj);
3401 #ifdef ENABLE_DTRACE
3402 if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
3403 int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
3404 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
3405 MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
3406 vt->klass->name_space, vt->klass->name, gen, critical);
3412 sgen_object_is_live (void *obj)
3414 return sgen_is_object_alive_and_on_current_collection (obj);
3417 /* LOCKING: requires that the GC lock is held */
3419 null_ephemerons_for_domain (MonoDomain *domain)
3421 EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3424 MonoObject *object = (MonoObject*)current->array;
3426 if (object && !object->vtable) {
3427 EphemeronLinkNode *tmp = current;
3430 prev->next = current->next;
3432 ephemeron_list = current->next;
3434 current = current->next;
3435 sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3438 current = current->next;
3443 /* LOCKING: requires that the GC lock is held */
3445 clear_unreachable_ephemerons (ScanCopyContext ctx)
3447 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3448 GrayQueue *queue = ctx.queue;
3449 EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3451 Ephemeron *cur, *array_end;
3455 char *object = current->array;
3457 if (!sgen_is_object_alive_for_current_gen (object)) {
3458 EphemeronLinkNode *tmp = current;
3460 SGEN_LOG (5, "Dead Ephemeron array at %p", object);
3463 prev->next = current->next;
3465 ephemeron_list = current->next;
3467 current = current->next;
3468 sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3473 copy_func ((void**)&object, queue);
3474 current->array = object;
3476 SGEN_LOG (5, "Clearing unreachable entries for ephemeron array at %p", object);
3478 array = (MonoArray*)object;
3479 cur = mono_array_addr (array, Ephemeron, 0);
3480 array_end = cur + mono_array_length_fast (array);
3481 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3483 for (; cur < array_end; ++cur) {
3484 char *key = (char*)cur->key;
3486 if (!key || key == tombstone)
3489 SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3490 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3491 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3493 if (!sgen_is_object_alive_for_current_gen (key)) {
3494 cur->key = tombstone;
3500 current = current->next;
3505 LOCKING: requires that the GC lock is held
3507 Limitations: We scan all ephemerons on every collection since the current design doesn't allow for a simple nursery/mature split.
3510 mark_ephemerons_in_range (ScanCopyContext ctx)
3512 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3513 GrayQueue *queue = ctx.queue;
3514 int nothing_marked = 1;
3515 EphemeronLinkNode *current = ephemeron_list;
3517 Ephemeron *cur, *array_end;
3520 for (current = ephemeron_list; current; current = current->next) {
3521 char *object = current->array;
3522 SGEN_LOG (5, "Ephemeron array at %p", object);
3524 /*It has to be alive*/
3525 if (!sgen_is_object_alive_for_current_gen (object)) {
3526 SGEN_LOG (5, "\tnot reachable");
3530 copy_func ((void**)&object, queue);
3532 array = (MonoArray*)object;
3533 cur = mono_array_addr (array, Ephemeron, 0);
3534 array_end = cur + mono_array_length_fast (array);
3535 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3537 for (; cur < array_end; ++cur) {
3538 char *key = cur->key;
3540 if (!key || key == tombstone)
3543 SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3544 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3545 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3547 if (sgen_is_object_alive_for_current_gen (key)) {
3548 char *value = cur->value;
3550 copy_func ((void**)&cur->key, queue);
3552 if (!sgen_is_object_alive_for_current_gen (value))
3554 copy_func ((void**)&cur->value, queue);
3560 SGEN_LOG (5, "Ephemeron run finished. Is it done %d", nothing_marked);
3561 return nothing_marked;
3565 mono_gc_invoke_finalizers (void)
3567 FinalizeReadyEntry *entry = NULL;
3568 gboolean entry_is_critical = FALSE;
3571 /* FIXME: batch to reduce lock contention */
3572 while (fin_ready_list || critical_fin_list) {
3576 FinalizeReadyEntry **list = entry_is_critical ? &critical_fin_list : &fin_ready_list;
3578 /* We have finalized entry in the last
3579 interation, now we need to remove it from
3582 *list = entry->next;
3584 FinalizeReadyEntry *e = *list;
3585 while (e->next != entry)
3587 e->next = entry->next;
3589 sgen_free_internal (entry, INTERNAL_MEM_FINALIZE_READY_ENTRY);
3593 /* Now look for the first non-null entry. */
3594 for (entry = fin_ready_list; entry && !entry->object; entry = entry->next)
3597 entry_is_critical = FALSE;
3599 entry_is_critical = TRUE;
3600 for (entry = critical_fin_list; entry && !entry->object; entry = entry->next)
3605 g_assert (entry->object);
3606 num_ready_finalizers--;
3607 obj = entry->object;
3608 entry->object = NULL;
3609 SGEN_LOG (7, "Finalizing object %p (%s)", obj, safe_name (obj));
3617 g_assert (entry->object == NULL);
3619 /* the object is on the stack so it is pinned */
3620 /*g_print ("Calling finalizer for object: %p (%s)\n", entry->object, safe_name (entry->object));*/
3621 mono_gc_run_finalize (obj, NULL);
3628 mono_gc_pending_finalizers (void)
3630 return fin_ready_list || critical_fin_list;
3634 * ######################################################################
3635 * ######## registered roots support
3636 * ######################################################################
3640 * We do not coalesce roots.
3643 mono_gc_register_root_inner (char *start, size_t size, void *descr, int root_type)
3645 RootRecord new_root;
3648 for (i = 0; i < ROOT_TYPE_NUM; ++i) {
3649 RootRecord *root = sgen_hash_table_lookup (&roots_hash [i], start);
3650 /* we allow changing the size and the descriptor (for thread statics etc) */
3652 size_t old_size = root->end_root - start;
3653 root->end_root = start + size;
3654 g_assert (((root->root_desc != 0) && (descr != NULL)) ||
3655 ((root->root_desc == 0) && (descr == NULL)));
3656 root->root_desc = (mword)descr;
3658 roots_size -= old_size;
3664 new_root.end_root = start + size;
3665 new_root.root_desc = (mword)descr;
3667 sgen_hash_table_replace (&roots_hash [root_type], start, &new_root, NULL);
3670 SGEN_LOG (3, "Added root for range: %p-%p, descr: %p (%d/%d bytes)", start, new_root.end_root, descr, (int)size, (int)roots_size);
3677 mono_gc_register_root (char *start, size_t size, void *descr)
3679 return mono_gc_register_root_inner (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED);
3683 mono_gc_register_root_wbarrier (char *start, size_t size, void *descr)
3685 return mono_gc_register_root_inner (start, size, descr, ROOT_TYPE_WBARRIER);
3689 mono_gc_deregister_root (char* addr)
3695 for (root_type = 0; root_type < ROOT_TYPE_NUM; ++root_type) {
3696 if (sgen_hash_table_remove (&roots_hash [root_type], addr, &root))
3697 roots_size -= (root.end_root - addr);
3703 * ######################################################################
3704 * ######## Thread handling (stop/start code)
3705 * ######################################################################
3708 unsigned int sgen_global_stop_count = 0;
3711 sgen_get_current_collection_generation (void)
3713 return current_collection_generation;
3717 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
3719 gc_callbacks = *callbacks;
3723 mono_gc_get_gc_callbacks ()
3725 return &gc_callbacks;
3728 /* Variables holding start/end nursery so it won't have to be passed at every call */
3729 static void *scan_area_arg_start, *scan_area_arg_end;
3732 mono_gc_conservatively_scan_area (void *start, void *end)
3734 conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
3738 mono_gc_scan_object (void *obj, void *gc_data)
3740 UserCopyOrMarkData *data = gc_data;
3741 current_object_ops.copy_or_mark_object (&obj, data->queue);
3746 * Mark from thread stacks and registers.
3749 scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue)
3751 SgenThreadInfo *info;
3753 scan_area_arg_start = start_nursery;
3754 scan_area_arg_end = end_nursery;
3756 FOREACH_THREAD (info) {
3758 SGEN_LOG (3, "Skipping dead thread %p, range: %p-%p, size: %td", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start);
3761 if (info->gc_disabled) {
3762 SGEN_LOG (3, "GC disabled for thread %p, range: %p-%p, size: %td", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start);
3765 if (mono_thread_info_run_state (info) != STATE_RUNNING) {
3766 SGEN_LOG (3, "Skipping non-running thread %p, range: %p-%p, size: %td (state %d)", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, mono_thread_info_run_state (info));
3769 SGEN_LOG (3, "Scanning thread %p, range: %p-%p, size: %td, pinned=%zd", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, sgen_get_pinned_count ());
3770 if (gc_callbacks.thread_mark_func && !conservative_stack_mark) {
3771 UserCopyOrMarkData data = { NULL, queue };
3772 gc_callbacks.thread_mark_func (info->runtime_data, info->stack_start, info->stack_end, precise, &data);
3773 } else if (!precise) {
3774 if (!conservative_stack_mark) {
3775 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
3776 conservative_stack_mark = TRUE;
3778 conservatively_pin_objects_from (info->stack_start, info->stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
3783 conservatively_pin_objects_from ((void**)&info->ctx, (void**)&info->ctx + ARCH_NUM_REGS,
3784 start_nursery, end_nursery, PIN_TYPE_STACK);
3786 conservatively_pin_objects_from ((void**)&info->regs, (void**)&info->regs + ARCH_NUM_REGS,
3787 start_nursery, end_nursery, PIN_TYPE_STACK);
3790 } END_FOREACH_THREAD
3794 ptr_on_stack (void *ptr)
3796 gpointer stack_start = &stack_start;
3797 SgenThreadInfo *info = mono_thread_info_current ();
3799 if (ptr >= stack_start && ptr < (gpointer)info->stack_end)
3805 sgen_thread_register (SgenThreadInfo* info, void *addr)
3808 guint8 *staddr = NULL;
3810 #ifndef HAVE_KW_THREAD
3811 info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
3813 g_assert (!mono_native_tls_get_value (thread_info_key));
3814 mono_native_tls_set_value (thread_info_key, info);
3816 sgen_thread_info = info;
3819 #ifdef SGEN_POSIX_STW
3820 info->stop_count = -1;
3824 info->stack_start = NULL;
3825 info->stopped_ip = NULL;
3826 info->stopped_domain = NULL;
3828 memset (&info->ctx, 0, sizeof (MonoContext));
3830 memset (&info->regs, 0, sizeof (info->regs));
3833 sgen_init_tlab_info (info);
3835 binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
3837 /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
3839 mono_thread_info_get_stack_bounds (&staddr, &stsize);
3842 info->stack_start_limit = staddr;
3843 info->stack_end = staddr + stsize;
3845 gsize stack_bottom = (gsize)addr;
3846 stack_bottom += 4095;
3847 stack_bottom &= ~4095;
3848 info->stack_end = (char*)stack_bottom;
3851 #ifdef HAVE_KW_THREAD
3852 stack_end = info->stack_end;
3855 SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->stack_end);
3857 if (gc_callbacks.thread_attach_func)
3858 info->runtime_data = gc_callbacks.thread_attach_func ();
3863 sgen_thread_detach (SgenThreadInfo *p)
3865 /* If a delegate is passed to native code and invoked on a thread we dont
3866 * know about, the jit will register it with mono_jit_thread_attach, but
3867 * we have no way of knowing when that thread goes away. SGen has a TSD
3868 * so we assume that if the domain is still registered, we can detach
3871 if (mono_domain_get ())
3872 mono_thread_detach_internal (mono_thread_internal_current ());
3876 sgen_thread_unregister (SgenThreadInfo *p)
3878 MonoNativeThreadId tid;
3880 tid = mono_thread_info_get_tid (p);
3881 binary_protocol_thread_unregister ((gpointer)tid);
3882 SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
3884 #ifndef HAVE_KW_THREAD
3885 mono_native_tls_set_value (thread_info_key, NULL);
3887 sgen_thread_info = NULL;
3890 if (p->info.runtime_thread)
3891 mono_threads_add_joinable_thread ((gpointer)tid);
3893 if (gc_callbacks.thread_detach_func) {
3894 gc_callbacks.thread_detach_func (p->runtime_data);
3895 p->runtime_data = NULL;
3901 sgen_thread_attach (SgenThreadInfo *info)
3904 /*this is odd, can we get attached before the gc is inited?*/
3908 if (gc_callbacks.thread_attach_func && !info->runtime_data)
3909 info->runtime_data = gc_callbacks.thread_attach_func ();
3912 mono_gc_register_thread (void *baseptr)
3914 return mono_thread_info_attach (baseptr) != NULL;
3918 * mono_gc_set_stack_end:
3920 * Set the end of the current threads stack to STACK_END. The stack space between
3921 * STACK_END and the real end of the threads stack will not be scanned during collections.
3924 mono_gc_set_stack_end (void *stack_end)
3926 SgenThreadInfo *info;
3929 info = mono_thread_info_current ();
3931 g_assert (stack_end < info->stack_end);
3932 info->stack_end = stack_end;
3937 #if USE_PTHREAD_INTERCEPT
3941 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
3943 return pthread_create (new_thread, attr, start_routine, arg);
3947 mono_gc_pthread_join (pthread_t thread, void **retval)
3949 return pthread_join (thread, retval);
3953 mono_gc_pthread_detach (pthread_t thread)
3955 return pthread_detach (thread);
3959 mono_gc_pthread_exit (void *retval)
3961 mono_thread_info_detach ();
3962 pthread_exit (retval);
3963 g_assert_not_reached ();
3966 #endif /* USE_PTHREAD_INTERCEPT */
3969 * ######################################################################
3970 * ######## Write barriers
3971 * ######################################################################
3975 * Note: the write barriers first do the needed GC work and then do the actual store:
3976 * this way the value is visible to the conservative GC scan after the write barrier
3977 * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
3978 * the conservative scan, otherwise by the remembered set scan.
3981 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
3983 HEAVY_STAT (++stat_wbarrier_set_field);
3984 if (ptr_in_nursery (field_ptr)) {
3985 *(void**)field_ptr = value;
3988 SGEN_LOG (8, "Adding remset at %p", field_ptr);
3990 binary_protocol_wbarrier (field_ptr, value, value->vtable);
3992 remset.wbarrier_set_field (obj, field_ptr, value);
3996 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
3998 HEAVY_STAT (++stat_wbarrier_set_arrayref);
3999 if (ptr_in_nursery (slot_ptr)) {
4000 *(void**)slot_ptr = value;
4003 SGEN_LOG (8, "Adding remset at %p", slot_ptr);
4005 binary_protocol_wbarrier (slot_ptr, value, value->vtable);
4007 remset.wbarrier_set_arrayref (arr, slot_ptr, value);
4011 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
4013 HEAVY_STAT (++stat_wbarrier_arrayref_copy);
4014 /*This check can be done without taking a lock since dest_ptr array is pinned*/
4015 if (ptr_in_nursery (dest_ptr) || count <= 0) {
4016 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
4020 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4021 if (binary_protocol_is_heavy_enabled ()) {
4023 for (i = 0; i < count; ++i) {
4024 gpointer dest = (gpointer*)dest_ptr + i;
4025 gpointer obj = *((gpointer*)src_ptr + i);
4027 binary_protocol_wbarrier (dest, obj, (gpointer)LOAD_VTABLE (obj));
4032 remset.wbarrier_arrayref_copy (dest_ptr, src_ptr, count);
4035 static char *found_obj;
4038 find_object_for_ptr_callback (char *obj, size_t size, void *user_data)
4040 char *ptr = user_data;
4042 if (ptr >= obj && ptr < obj + size) {
4043 g_assert (!found_obj);
4048 /* for use in the debugger */
4049 char* find_object_for_ptr (char *ptr);
4051 find_object_for_ptr (char *ptr)
4053 if (ptr >= nursery_section->data && ptr < nursery_section->end_data) {
4055 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
4056 find_object_for_ptr_callback, ptr, TRUE);
4062 sgen_los_iterate_objects (find_object_for_ptr_callback, ptr);
4067 * Very inefficient, but this is debugging code, supposed to
4068 * be called from gdb, so we don't care.
4071 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, find_object_for_ptr_callback, ptr);
4076 mono_gc_wbarrier_generic_nostore (gpointer ptr)
4080 HEAVY_STAT (++stat_wbarrier_generic_store);
4082 #ifdef XDOMAIN_CHECKS_IN_WBARRIER
4083 /* FIXME: ptr_in_heap must be called with the GC lock held */
4084 if (xdomain_checks && *(MonoObject**)ptr && ptr_in_heap (ptr)) {
4085 char *start = find_object_for_ptr (ptr);
4086 MonoObject *value = *(MonoObject**)ptr;
4090 MonoObject *obj = (MonoObject*)start;
4091 if (obj->vtable->domain != value->vtable->domain)
4092 g_assert (is_xdomain_ref_allowed (ptr, start, obj->vtable->domain));
4098 obj = *(gpointer*)ptr;
4100 binary_protocol_wbarrier (ptr, obj, (gpointer)LOAD_VTABLE (obj));
4102 if (ptr_in_nursery (ptr) || ptr_on_stack (ptr)) {
4103 SGEN_LOG (8, "Skipping remset at %p", ptr);
4108 * We need to record old->old pointer locations for the
4109 * concurrent collector.
4111 if (!ptr_in_nursery (obj) && !concurrent_collection_in_progress) {
4112 SGEN_LOG (8, "Skipping remset at %p", ptr);
4116 SGEN_LOG (8, "Adding remset at %p", ptr);
4118 remset.wbarrier_generic_nostore (ptr);
4122 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
4124 SGEN_LOG (8, "Wbarrier store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
4125 *(void**)ptr = value;
4126 if (ptr_in_nursery (value))
4127 mono_gc_wbarrier_generic_nostore (ptr);
4128 sgen_dummy_use (value);
4131 /* Same as mono_gc_wbarrier_generic_store () but performs the store
4132 * as an atomic operation with release semantics.
4135 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, MonoObject *value)
4137 HEAVY_STAT (++stat_wbarrier_generic_store_atomic);
4139 SGEN_LOG (8, "Wbarrier atomic store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
4141 InterlockedWritePointer (ptr, value);
4143 if (ptr_in_nursery (value))
4144 mono_gc_wbarrier_generic_nostore (ptr);
4146 sgen_dummy_use (value);
4149 void mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
4151 mword *dest = _dest;
4156 mono_gc_wbarrier_generic_store (dest, (MonoObject*)*src);
4161 size -= SIZEOF_VOID_P;
4166 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4168 #define HANDLE_PTR(ptr,obj) do { \
4169 gpointer o = *(gpointer*)(ptr); \
4171 gpointer d = ((char*)dest) + ((char*)(ptr) - (char*)(obj)); \
4172 binary_protocol_wbarrier (d, o, (gpointer) LOAD_VTABLE (o)); \
4177 scan_object_for_binary_protocol_copy_wbarrier (gpointer dest, char *start, mword desc)
4179 #define SCAN_OBJECT_NOVTABLE
4180 #include "sgen-scan-object.h"
4185 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
4187 HEAVY_STAT (++stat_wbarrier_value_copy);
4188 g_assert (klass->valuetype);
4190 SGEN_LOG (8, "Adding value remset at %p, count %d, descr %p for class %s (%p)", dest, count, klass->gc_descr, klass->name, klass);
4192 if (ptr_in_nursery (dest) || ptr_on_stack (dest) || !SGEN_CLASS_HAS_REFERENCES (klass)) {
4193 size_t element_size = mono_class_value_size (klass, NULL);
4194 size_t size = count * element_size;
4195 mono_gc_memmove_atomic (dest, src, size);
4199 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4200 if (binary_protocol_is_heavy_enabled ()) {
4201 size_t element_size = mono_class_value_size (klass, NULL);
4203 for (i = 0; i < count; ++i) {
4204 scan_object_for_binary_protocol_copy_wbarrier ((char*)dest + i * element_size,
4205 (char*)src + i * element_size - sizeof (MonoObject),
4206 (mword) klass->gc_descr);
4211 remset.wbarrier_value_copy (dest, src, count, klass);
4215 * mono_gc_wbarrier_object_copy:
4217 * Write barrier to call when obj is the result of a clone or copy of an object.
4220 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
4224 HEAVY_STAT (++stat_wbarrier_object_copy);
4226 if (ptr_in_nursery (obj) || ptr_on_stack (obj)) {
4227 size = mono_object_class (obj)->instance_size;
4228 mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
4229 size - sizeof (MonoObject));
4233 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4234 if (binary_protocol_is_heavy_enabled ())
4235 scan_object_for_binary_protocol_copy_wbarrier (obj, (char*)src, (mword) src->vtable->gc_descr);
4238 remset.wbarrier_object_copy (obj, src);
4243 * ######################################################################
4244 * ######## Other mono public interface functions.
4245 * ######################################################################
4248 #define REFS_SIZE 128
4251 MonoGCReferences callback;
4255 MonoObject *refs [REFS_SIZE];
4256 uintptr_t offsets [REFS_SIZE];
4260 #define HANDLE_PTR(ptr,obj) do { \
4262 if (hwi->count == REFS_SIZE) { \
4263 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data); \
4267 hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start; \
4268 hwi->refs [hwi->count++] = *(ptr); \
4273 collect_references (HeapWalkInfo *hwi, char *start, size_t size)
4275 #include "sgen-scan-object.h"
4279 walk_references (char *start, size_t size, void *data)
4281 HeapWalkInfo *hwi = data;
4284 collect_references (hwi, start, size);
4285 if (hwi->count || !hwi->called)
4286 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
4290 * mono_gc_walk_heap:
4291 * @flags: flags for future use
4292 * @callback: a function pointer called for each object in the heap
4293 * @data: a user data pointer that is passed to callback
4295 * This function can be used to iterate over all the live objects in the heap:
4296 * for each object, @callback is invoked, providing info about the object's
4297 * location in memory, its class, its size and the objects it references.
4298 * For each referenced object it's offset from the object address is
4299 * reported in the offsets array.
4300 * The object references may be buffered, so the callback may be invoked
4301 * multiple times for the same object: in all but the first call, the size
4302 * argument will be zero.
4303 * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
4304 * profiler event handler.
4306 * Returns: a non-zero value if the GC doesn't support heap walking
4309 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
4314 hwi.callback = callback;
4317 sgen_clear_nursery_fragments ();
4318 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE);
4320 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
4321 sgen_los_iterate_objects (walk_references, &hwi);
4327 mono_gc_collect (int generation)
4332 sgen_perform_collection (0, generation, "user request", TRUE);
4337 mono_gc_max_generation (void)
4343 mono_gc_collection_count (int generation)
4345 if (generation == 0)
4346 return gc_stats.minor_gc_count;
4347 return gc_stats.major_gc_count;
4351 mono_gc_get_used_size (void)
4355 tot = los_memory_usage;
4356 tot += nursery_section->next_data - nursery_section->data;
4357 tot += major_collector.get_used_size ();
4358 /* FIXME: account for pinned objects */
4364 mono_gc_get_los_limit (void)
4366 return MAX_SMALL_OBJ_SIZE;
4370 mono_gc_user_markers_supported (void)
4376 mono_object_is_alive (MonoObject* o)
4382 mono_gc_get_generation (MonoObject *obj)
4384 if (ptr_in_nursery (obj))
4390 mono_gc_enable_events (void)
4395 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
4397 sgen_register_disappearing_link (obj, link_addr, track, FALSE);
4401 mono_gc_weak_link_remove (void **link_addr, gboolean track)
4403 sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
4407 mono_gc_weak_link_get (void **link_addr)
4409 void * volatile *link_addr_volatile;
4413 link_addr_volatile = link_addr;
4414 ptr = (void*)*link_addr_volatile;
4416 * At this point we have a hidden pointer. If the GC runs
4417 * here, it will not recognize the hidden pointer as a
4418 * reference, and if the object behind it is not referenced
4419 * elsewhere, it will be freed. Once the world is restarted
4420 * we reveal the pointer, giving us a pointer to a freed
4421 * object. To make sure we don't return it, we load the
4422 * hidden pointer again. If it's still the same, we can be
4423 * sure the object reference is valid.
4426 obj = (MonoObject*) REVEAL_POINTER (ptr);
4430 mono_memory_barrier ();
4433 * During the second bridge processing step the world is
4434 * running again. That step processes all weak links once
4435 * more to null those that refer to dead objects. Before that
4436 * is completed, those links must not be followed, so we
4437 * conservatively wait for bridge processing when any weak
4438 * link is dereferenced.
4440 if (G_UNLIKELY (bridge_processing_in_progress))
4441 mono_gc_wait_for_bridge_processing ();
4443 if ((void*)*link_addr_volatile != ptr)
4450 mono_gc_ephemeron_array_add (MonoObject *obj)
4452 EphemeronLinkNode *node;
4456 node = sgen_alloc_internal (INTERNAL_MEM_EPHEMERON_LINK);
4461 node->array = (char*)obj;
4462 node->next = ephemeron_list;
4463 ephemeron_list = node;
4465 SGEN_LOG (5, "Registered ephemeron array %p", obj);
4472 mono_gc_set_allow_synchronous_major (gboolean flag)
4474 if (!major_collector.is_concurrent)
4477 allow_synchronous_major = flag;
4482 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
4486 result = func (data);
4487 UNLOCK_INTERRUPTION;
4492 mono_gc_is_gc_thread (void)
4496 result = mono_thread_info_current () != NULL;
4502 is_critical_method (MonoMethod *method)
4504 return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
4508 sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...)
4512 va_start (ap, description_format);
4514 fprintf (stderr, "Warning: In environment variable `%s': ", env_var);
4515 vfprintf (stderr, description_format, ap);
4517 fprintf (stderr, " - %s", fallback);
4518 fprintf (stderr, "\n");
4524 parse_double_in_interval (const char *env_var, const char *opt_name, const char *opt, double min, double max, double *result)
4527 double val = strtod (opt, &endptr);
4528 if (endptr == opt) {
4529 sgen_env_var_error (env_var, "Using default value.", "`%s` must be a number.", opt_name);
4532 else if (val < min || val > max) {
4533 sgen_env_var_error (env_var, "Using default value.", "`%s` must be between %.2f - %.2f.", opt_name, min, max);
4541 mono_gc_base_init (void)
4543 MonoThreadInfoCallbacks cb;
4546 char *major_collector_opt = NULL;
4547 char *minor_collector_opt = NULL;
4548 size_t max_heap = 0;
4549 size_t soft_limit = 0;
4553 gboolean debug_print_allowance = FALSE;
4554 double allowance_ratio = 0, save_target = 0;
4555 gboolean have_split_nursery = FALSE;
4556 gboolean cement_enabled = TRUE;
4559 result = InterlockedCompareExchange (&gc_initialized, -1, 0);
4562 /* already inited */
4565 /* being inited by another thread */
4569 /* we will init it */
4572 g_assert_not_reached ();
4574 } while (result != 0);
4576 SGEN_TV_GETTIME (sgen_init_timestamp);
4578 LOCK_INIT (gc_mutex);
4580 pagesize = mono_pagesize ();
4581 gc_debug_file = stderr;
4583 cb.thread_register = sgen_thread_register;
4584 cb.thread_detach = sgen_thread_detach;
4585 cb.thread_unregister = sgen_thread_unregister;
4586 cb.thread_attach = sgen_thread_attach;
4587 cb.mono_method_is_critical = (gpointer)is_critical_method;
4589 cb.thread_exit = mono_gc_pthread_exit;
4590 cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
4593 mono_threads_init (&cb, sizeof (SgenThreadInfo));
4595 LOCK_INIT (sgen_interruption_mutex);
4596 LOCK_INIT (pin_queue_mutex);
4598 if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
4599 opts = g_strsplit (env, ",", -1);
4600 for (ptr = opts; *ptr; ++ptr) {
4602 if (g_str_has_prefix (opt, "major=")) {
4603 opt = strchr (opt, '=') + 1;
4604 major_collector_opt = g_strdup (opt);
4605 } else if (g_str_has_prefix (opt, "minor=")) {
4606 opt = strchr (opt, '=') + 1;
4607 minor_collector_opt = g_strdup (opt);
4615 sgen_init_internal_allocator ();
4616 sgen_init_nursery_allocator ();
4617 sgen_init_fin_weak_hash ();
4619 sgen_init_hash_table ();
4621 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_SECTION, SGEN_SIZEOF_GC_MEM_SECTION);
4622 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_FINALIZE_READY_ENTRY, sizeof (FinalizeReadyEntry));
4623 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_GRAY_QUEUE, sizeof (GrayQueueSection));
4624 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
4626 #ifndef HAVE_KW_THREAD
4627 mono_native_tls_alloc (&thread_info_key, NULL);
4628 #if defined(__APPLE__) || defined (HOST_WIN32)
4630 * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
4631 * where the two are the same.
4633 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, thread_info_key);
4637 int tls_offset = -1;
4638 MONO_THREAD_VAR_OFFSET (sgen_thread_info, tls_offset);
4639 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, tls_offset);
4644 * This needs to happen before any internal allocations because
4645 * it inits the small id which is required for hazard pointer
4650 mono_thread_info_attach (&dummy);
4652 if (!minor_collector_opt) {
4653 sgen_simple_nursery_init (&sgen_minor_collector);
4655 if (!strcmp (minor_collector_opt, "simple")) {
4657 sgen_simple_nursery_init (&sgen_minor_collector);
4658 } else if (!strcmp (minor_collector_opt, "split")) {
4659 sgen_split_nursery_init (&sgen_minor_collector);
4660 have_split_nursery = TRUE;
4662 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `simple` instead.", "Unknown minor collector `%s'.", minor_collector_opt);
4663 goto use_simple_nursery;
4667 if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep")) {
4668 use_marksweep_major:
4669 sgen_marksweep_init (&major_collector);
4670 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed")) {
4671 sgen_marksweep_fixed_init (&major_collector);
4672 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-par")) {
4673 sgen_marksweep_par_init (&major_collector);
4674 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed-par")) {
4675 sgen_marksweep_fixed_par_init (&major_collector);
4676 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-conc")) {
4677 sgen_marksweep_conc_init (&major_collector);
4679 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `marksweep` instead.", "Unknown major collector `%s'.", major_collector_opt);
4680 goto use_marksweep_major;
4683 if (have_split_nursery && major_collector.is_parallel) {
4684 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Disabling split minor collector.", "`minor=split` is not supported with the parallel collector yet.");
4685 have_split_nursery = FALSE;
4688 num_workers = mono_cpu_count ();
4689 g_assert (num_workers > 0);
4690 if (num_workers > 16)
4693 ///* Keep this the default for now */
4694 /* Precise marking is broken on all supported targets. Disable until fixed. */
4695 conservative_stack_mark = TRUE;
4697 sgen_nursery_size = DEFAULT_NURSERY_SIZE;
4700 gboolean usage_printed = FALSE;
4702 for (ptr = opts; *ptr; ++ptr) {
4704 if (!strcmp (opt, ""))
4706 if (g_str_has_prefix (opt, "major="))
4708 if (g_str_has_prefix (opt, "minor="))
4710 if (g_str_has_prefix (opt, "max-heap-size=")) {
4711 size_t max_heap_candidate = 0;
4712 opt = strchr (opt, '=') + 1;
4713 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap_candidate)) {
4714 max_heap = (max_heap_candidate + mono_pagesize () - 1) & ~(size_t)(mono_pagesize () - 1);
4715 if (max_heap != max_heap_candidate)
4716 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Rounding up.", "`max-heap-size` size must be a multiple of %d.", mono_pagesize ());
4718 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`max-heap-size` must be an integer.");
4722 if (g_str_has_prefix (opt, "soft-heap-limit=")) {
4723 opt = strchr (opt, '=') + 1;
4724 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &soft_limit)) {
4725 if (soft_limit <= 0) {
4726 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be positive.");
4730 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be an integer.");
4734 if (g_str_has_prefix (opt, "workers=")) {
4737 if (!major_collector.is_parallel) {
4738 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "The `workers` option can only be used for parallel collectors.");
4741 opt = strchr (opt, '=') + 1;
4742 val = strtol (opt, &endptr, 10);
4743 if (!*opt || *endptr) {
4744 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Cannot parse the `workers` option value.");
4747 if (val <= 0 || val > 16) {
4748 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "The number of `workers` must be in the range 1 to 16.");
4751 num_workers = (int)val;
4754 if (g_str_has_prefix (opt, "stack-mark=")) {
4755 opt = strchr (opt, '=') + 1;
4756 if (!strcmp (opt, "precise")) {
4757 conservative_stack_mark = FALSE;
4758 } else if (!strcmp (opt, "conservative")) {
4759 conservative_stack_mark = TRUE;
4761 sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
4762 "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
4766 if (g_str_has_prefix (opt, "bridge-implementation=")) {
4767 opt = strchr (opt, '=') + 1;
4768 sgen_set_bridge_implementation (opt);
4771 if (g_str_has_prefix (opt, "toggleref-test")) {
4772 sgen_register_test_toggleref_callback ();
4777 if (g_str_has_prefix (opt, "nursery-size=")) {
4779 opt = strchr (opt, '=') + 1;
4780 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &val)) {
4781 #ifdef SGEN_ALIGN_NURSERY
4782 if ((val & (val - 1))) {
4783 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be a power of two.");
4787 if (val < SGEN_MAX_NURSERY_WASTE) {
4788 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.",
4789 "`nursery-size` must be at least %d bytes.", SGEN_MAX_NURSERY_WASTE);
4793 sgen_nursery_size = val;
4794 sgen_nursery_bits = 0;
4795 while (ONE_P << (++ sgen_nursery_bits) != sgen_nursery_size)
4798 sgen_nursery_size = val;
4801 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be an integer.");
4807 if (g_str_has_prefix (opt, "save-target-ratio=")) {
4809 opt = strchr (opt, '=') + 1;
4810 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "save-target-ratio", opt,
4811 SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO, &val)) {
4816 if (g_str_has_prefix (opt, "default-allowance-ratio=")) {
4818 opt = strchr (opt, '=') + 1;
4819 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "default-allowance-ratio", opt,
4820 SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, &val)) {
4821 allowance_ratio = val;
4825 if (g_str_has_prefix (opt, "allow-synchronous-major=")) {
4826 if (!major_collector.is_concurrent) {
4827 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`allow-synchronous-major` is only valid for the concurrent major collector.");
4831 opt = strchr (opt, '=') + 1;
4833 if (!strcmp (opt, "yes")) {
4834 allow_synchronous_major = TRUE;
4835 } else if (!strcmp (opt, "no")) {
4836 allow_synchronous_major = FALSE;
4838 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`allow-synchronous-major` must be either `yes' or `no'.");
4843 if (!strcmp (opt, "cementing")) {
4844 if (major_collector.is_parallel) {
4845 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`cementing` is not supported for the parallel major collector.");
4848 cement_enabled = TRUE;
4851 if (!strcmp (opt, "no-cementing")) {
4852 cement_enabled = FALSE;
4856 if (major_collector.handle_gc_param && major_collector.handle_gc_param (opt))
4859 if (sgen_minor_collector.handle_gc_param && sgen_minor_collector.handle_gc_param (opt))
4862 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Unknown option `%s`.", opt);
4867 fprintf (stderr, "\n%s must be a comma-delimited list of one or more of the following:\n", MONO_GC_PARAMS_NAME);
4868 fprintf (stderr, " max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4869 fprintf (stderr, " soft-heap-limit=n (where N is an integer, possibly with a k, m or a g suffix)\n");
4870 fprintf (stderr, " nursery-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4871 fprintf (stderr, " major=COLLECTOR (where COLLECTOR is `marksweep', `marksweep-conc', `marksweep-par', 'marksweep-fixed' or 'marksweep-fixed-par')\n");
4872 fprintf (stderr, " minor=COLLECTOR (where COLLECTOR is `simple' or `split')\n");
4873 fprintf (stderr, " wbarrier=WBARRIER (where WBARRIER is `remset' or `cardtable')\n");
4874 fprintf (stderr, " stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
4875 fprintf (stderr, " [no-]cementing\n");
4876 if (major_collector.is_concurrent)
4877 fprintf (stderr, " allow-synchronous-major=FLAG (where FLAG is `yes' or `no')\n");
4878 if (major_collector.print_gc_param_usage)
4879 major_collector.print_gc_param_usage ();
4880 if (sgen_minor_collector.print_gc_param_usage)
4881 sgen_minor_collector.print_gc_param_usage ();
4882 fprintf (stderr, " Experimental options:\n");
4883 fprintf (stderr, " save-target-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
4884 fprintf (stderr, " default-allowance-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MAX_ALLOWANCE_NURSERY_SIZE_RATIO);
4885 fprintf (stderr, "\n");
4887 usage_printed = TRUE;
4892 if (major_collector.is_parallel) {
4893 cement_enabled = FALSE;
4894 sgen_workers_init (num_workers);
4895 } else if (major_collector.is_concurrent) {
4896 sgen_workers_init (1);
4899 if (major_collector_opt)
4900 g_free (major_collector_opt);
4902 if (minor_collector_opt)
4903 g_free (minor_collector_opt);
4907 sgen_cement_init (cement_enabled);
4909 if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
4910 gboolean usage_printed = FALSE;
4912 opts = g_strsplit (env, ",", -1);
4913 for (ptr = opts; ptr && *ptr; ptr ++) {
4915 if (!strcmp (opt, ""))
4917 if (opt [0] >= '0' && opt [0] <= '9') {
4918 gc_debug_level = atoi (opt);
4924 char *rf = g_strdup_printf ("%s.%d", opt, GetCurrentProcessId ());
4926 char *rf = g_strdup_printf ("%s.%d", opt, getpid ());
4928 gc_debug_file = fopen (rf, "wb");
4930 gc_debug_file = stderr;
4933 } else if (!strcmp (opt, "print-allowance")) {
4934 debug_print_allowance = TRUE;
4935 } else if (!strcmp (opt, "print-pinning")) {
4936 do_pin_stats = TRUE;
4937 } else if (!strcmp (opt, "verify-before-allocs")) {
4938 verify_before_allocs = 1;
4939 has_per_allocation_action = TRUE;
4940 } else if (g_str_has_prefix (opt, "verify-before-allocs=")) {
4941 char *arg = strchr (opt, '=') + 1;
4942 verify_before_allocs = atoi (arg);
4943 has_per_allocation_action = TRUE;
4944 } else if (!strcmp (opt, "collect-before-allocs")) {
4945 collect_before_allocs = 1;
4946 has_per_allocation_action = TRUE;
4947 } else if (g_str_has_prefix (opt, "collect-before-allocs=")) {
4948 char *arg = strchr (opt, '=') + 1;
4949 has_per_allocation_action = TRUE;
4950 collect_before_allocs = atoi (arg);
4951 } else if (!strcmp (opt, "verify-before-collections")) {
4952 whole_heap_check_before_collection = TRUE;
4953 } else if (!strcmp (opt, "check-at-minor-collections")) {
4954 consistency_check_at_minor_collection = TRUE;
4955 nursery_clear_policy = CLEAR_AT_GC;
4956 } else if (!strcmp (opt, "mod-union-consistency-check")) {
4957 if (!major_collector.is_concurrent) {
4958 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`mod-union-consistency-check` only works with concurrent major collector.");
4961 mod_union_consistency_check = TRUE;
4962 } else if (!strcmp (opt, "check-mark-bits")) {
4963 check_mark_bits_after_major_collection = TRUE;
4964 } else if (!strcmp (opt, "check-nursery-pinned")) {
4965 check_nursery_objects_pinned = TRUE;
4966 } else if (!strcmp (opt, "xdomain-checks")) {
4967 xdomain_checks = TRUE;
4968 } else if (!strcmp (opt, "clear-at-gc")) {
4969 nursery_clear_policy = CLEAR_AT_GC;
4970 } else if (!strcmp (opt, "clear-nursery-at-gc")) {
4971 nursery_clear_policy = CLEAR_AT_GC;
4972 } else if (!strcmp (opt, "clear-at-tlab-creation")) {
4973 nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
4974 } else if (!strcmp (opt, "debug-clear-at-tlab-creation")) {
4975 nursery_clear_policy = CLEAR_AT_TLAB_CREATION_DEBUG;
4976 } else if (!strcmp (opt, "check-scan-starts")) {
4977 do_scan_starts_check = TRUE;
4978 } else if (!strcmp (opt, "verify-nursery-at-minor-gc")) {
4979 do_verify_nursery = TRUE;
4980 } else if (!strcmp (opt, "check-concurrent")) {
4981 if (!major_collector.is_concurrent) {
4982 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`check-concurrent` only works with concurrent major collectors.");
4985 do_concurrent_checks = TRUE;
4986 } else if (!strcmp (opt, "dump-nursery-at-minor-gc")) {
4987 do_dump_nursery_content = TRUE;
4988 } else if (!strcmp (opt, "no-managed-allocator")) {
4989 sgen_set_use_managed_allocator (FALSE);
4990 } else if (!strcmp (opt, "disable-minor")) {
4991 disable_minor_collections = TRUE;
4992 } else if (!strcmp (opt, "disable-major")) {
4993 disable_major_collections = TRUE;
4994 } else if (g_str_has_prefix (opt, "heap-dump=")) {
4995 char *filename = strchr (opt, '=') + 1;
4996 nursery_clear_policy = CLEAR_AT_GC;
4997 heap_dump_file = fopen (filename, "w");
4998 if (heap_dump_file) {
4999 fprintf (heap_dump_file, "<sgen-dump>\n");
5000 do_pin_stats = TRUE;
5002 } else if (g_str_has_prefix (opt, "binary-protocol=")) {
5003 char *filename = strchr (opt, '=') + 1;
5004 char *colon = strrchr (filename, ':');
5007 if (!mono_gc_parse_environment_string_extract_number (colon + 1, &limit)) {
5008 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring limit.", "Binary protocol file size limit must be an integer.");
5013 binary_protocol_init (filename, (long long)limit);
5014 } else if (!sgen_bridge_handle_gc_debug (opt)) {
5015 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "Unknown option `%s`.", opt);
5020 fprintf (stderr, "\n%s must be of the format [<l>[:<filename>]|<option>]+ where <l> is a debug level 0-9.\n", MONO_GC_DEBUG_NAME);
5021 fprintf (stderr, "Valid <option>s are:\n");
5022 fprintf (stderr, " collect-before-allocs[=<n>]\n");
5023 fprintf (stderr, " verify-before-allocs[=<n>]\n");
5024 fprintf (stderr, " check-at-minor-collections\n");
5025 fprintf (stderr, " check-mark-bits\n");
5026 fprintf (stderr, " check-nursery-pinned\n");
5027 fprintf (stderr, " verify-before-collections\n");
5028 fprintf (stderr, " verify-nursery-at-minor-gc\n");
5029 fprintf (stderr, " dump-nursery-at-minor-gc\n");
5030 fprintf (stderr, " disable-minor\n");
5031 fprintf (stderr, " disable-major\n");
5032 fprintf (stderr, " xdomain-checks\n");
5033 fprintf (stderr, " check-concurrent\n");
5034 fprintf (stderr, " clear-[nursery-]at-gc\n");
5035 fprintf (stderr, " clear-at-tlab-creation\n");
5036 fprintf (stderr, " debug-clear-at-tlab-creation\n");
5037 fprintf (stderr, " check-scan-starts\n");
5038 fprintf (stderr, " no-managed-allocator\n");
5039 fprintf (stderr, " print-allowance\n");
5040 fprintf (stderr, " print-pinning\n");
5041 fprintf (stderr, " heap-dump=<filename>\n");
5042 fprintf (stderr, " binary-protocol=<filename>[:<file-size-limit>]\n");
5043 sgen_bridge_print_gc_debug_usage ();
5044 fprintf (stderr, "\n");
5046 usage_printed = TRUE;
5052 if (major_collector.is_parallel) {
5053 if (heap_dump_file) {
5054 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Disabling.", "Cannot do `heap-dump` with the parallel collector.");
5055 fclose (heap_dump_file);
5056 heap_dump_file = NULL;
5059 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Disabling.", "`print-pinning` is not supported with the parallel collector.");
5060 do_pin_stats = FALSE;
5064 if (major_collector.post_param_init)
5065 major_collector.post_param_init (&major_collector);
5067 sgen_memgov_init (max_heap, soft_limit, debug_print_allowance, allowance_ratio, save_target);
5069 memset (&remset, 0, sizeof (remset));
5071 sgen_card_table_init (&remset);
5077 mono_gc_get_gc_name (void)
5082 static MonoMethod *write_barrier_method;
5085 sgen_is_critical_method (MonoMethod *method)
5087 return (method == write_barrier_method || sgen_is_managed_allocator (method));
5091 sgen_has_critical_method (void)
5093 return write_barrier_method || sgen_has_managed_allocator ();
5099 emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels)
5101 memset (nursery_check_return_labels, 0, sizeof (int) * 3);
5102 #ifdef SGEN_ALIGN_NURSERY
5103 // if (ptr_in_nursery (ptr)) return;
5105 * Masking out the bits might be faster, but we would have to use 64 bit
5106 * immediates, which might be slower.
5108 mono_mb_emit_ldarg (mb, 0);
5109 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5110 mono_mb_emit_byte (mb, CEE_SHR_UN);
5111 mono_mb_emit_ptr (mb, (gpointer)((mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS));
5112 nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
5114 if (!major_collector.is_concurrent) {
5115 // if (!ptr_in_nursery (*ptr)) return;
5116 mono_mb_emit_ldarg (mb, 0);
5117 mono_mb_emit_byte (mb, CEE_LDIND_I);
5118 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5119 mono_mb_emit_byte (mb, CEE_SHR_UN);
5120 mono_mb_emit_ptr (mb, (gpointer)((mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS));
5121 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
5124 int label_continue1, label_continue2;
5125 int dereferenced_var;
5127 // if (ptr < (sgen_get_nursery_start ())) goto continue;
5128 mono_mb_emit_ldarg (mb, 0);
5129 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5130 label_continue_1 = mono_mb_emit_branch (mb, CEE_BLT);
5132 // if (ptr >= sgen_get_nursery_end ())) goto continue;
5133 mono_mb_emit_ldarg (mb, 0);
5134 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5135 label_continue_2 = mono_mb_emit_branch (mb, CEE_BGE);
5138 nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BR);
5141 mono_mb_patch_branch (mb, label_continue_1);
5142 mono_mb_patch_branch (mb, label_continue_2);
5144 // Dereference and store in local var
5145 dereferenced_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5146 mono_mb_emit_ldarg (mb, 0);
5147 mono_mb_emit_byte (mb, CEE_LDIND_I);
5148 mono_mb_emit_stloc (mb, dereferenced_var);
5150 if (!major_collector.is_concurrent) {
5151 // if (*ptr < sgen_get_nursery_start ()) return;
5152 mono_mb_emit_ldloc (mb, dereferenced_var);
5153 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5154 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BLT);
5156 // if (*ptr >= sgen_get_nursery_end ()) return;
5157 mono_mb_emit_ldloc (mb, dereferenced_var);
5158 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5159 nursery_check_return_labels [2] = mono_mb_emit_branch (mb, CEE_BGE);
5166 mono_gc_get_write_barrier (void)
5169 MonoMethodBuilder *mb;
5170 MonoMethodSignature *sig;
5171 #ifdef MANAGED_WBARRIER
5172 int i, nursery_check_labels [3];
5174 #ifdef HAVE_KW_THREAD
5175 int stack_end_offset = -1;
5177 MONO_THREAD_VAR_OFFSET (stack_end, stack_end_offset);
5178 g_assert (stack_end_offset != -1);
5182 // FIXME: Maybe create a separate version for ctors (the branch would be
5183 // correctly predicted more times)
5184 if (write_barrier_method)
5185 return write_barrier_method;
5187 /* Create the IL version of mono_gc_barrier_generic_store () */
5188 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5189 sig->ret = &mono_defaults.void_class->byval_arg;
5190 sig->params [0] = &mono_defaults.int_class->byval_arg;
5192 mb = mono_mb_new (mono_defaults.object_class, "wbarrier", MONO_WRAPPER_WRITE_BARRIER);
5195 #ifdef MANAGED_WBARRIER
5196 emit_nursery_check (mb, nursery_check_labels);
5198 addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
5202 LDC_PTR sgen_cardtable
5204 address >> CARD_BITS
5208 if (SGEN_HAVE_OVERLAPPING_CARDS) {
5209 LDC_PTR card_table_mask
5216 mono_mb_emit_ptr (mb, sgen_cardtable);
5217 mono_mb_emit_ldarg (mb, 0);
5218 mono_mb_emit_icon (mb, CARD_BITS);
5219 mono_mb_emit_byte (mb, CEE_SHR_UN);
5220 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
5221 mono_mb_emit_ptr (mb, (gpointer)CARD_MASK);
5222 mono_mb_emit_byte (mb, CEE_AND);
5224 mono_mb_emit_byte (mb, CEE_ADD);
5225 mono_mb_emit_icon (mb, 1);
5226 mono_mb_emit_byte (mb, CEE_STIND_I1);
5229 for (i = 0; i < 3; ++i) {
5230 if (nursery_check_labels [i])
5231 mono_mb_patch_branch (mb, nursery_check_labels [i]);
5233 mono_mb_emit_byte (mb, CEE_RET);
5235 mono_mb_emit_ldarg (mb, 0);
5236 mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
5237 mono_mb_emit_byte (mb, CEE_RET);
5240 res = mono_mb_create_method (mb, sig, 16);
5244 if (write_barrier_method) {
5245 /* Already created */
5246 mono_free_method (res);
5248 /* double-checked locking */
5249 mono_memory_barrier ();
5250 write_barrier_method = res;
5254 return write_barrier_method;
5258 mono_gc_get_description (void)
5260 return g_strdup ("sgen");
5264 mono_gc_set_desktop_mode (void)
5269 mono_gc_is_moving (void)
5275 mono_gc_is_disabled (void)
5281 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
5288 sgen_get_nursery_clear_policy (void)
5290 return nursery_clear_policy;
5294 sgen_get_array_fill_vtable (void)
5296 if (!array_fill_vtable) {
5297 static MonoClass klass;
5298 static MonoVTable vtable;
5301 MonoDomain *domain = mono_get_root_domain ();
5304 klass.element_class = mono_defaults.byte_class;
5306 klass.instance_size = sizeof (MonoArray);
5307 klass.sizes.element_size = 1;
5308 klass.name = "array_filler_type";
5310 vtable.klass = &klass;
5312 vtable.gc_descr = mono_gc_make_descr_for_array (TRUE, &bmap, 0, 1);
5315 array_fill_vtable = &vtable;
5317 return array_fill_vtable;
5327 sgen_gc_unlock (void)
5329 gboolean try_free = sgen_try_free_some_memory;
5330 sgen_try_free_some_memory = FALSE;
5331 mono_mutex_unlock (&gc_mutex);
5332 MONO_GC_UNLOCKED ();
5334 mono_thread_hazardous_try_free_some ();
5338 sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
5340 major_collector.iterate_live_block_ranges (callback);
5344 sgen_major_collector_scan_card_table (SgenGrayQueue *queue)
5346 major_collector.scan_card_table (FALSE, queue);
5350 sgen_get_major_collector (void)
5352 return &major_collector;
5355 void mono_gc_set_skip_thread (gboolean skip)
5357 SgenThreadInfo *info = mono_thread_info_current ();
5360 info->gc_disabled = skip;
5365 sgen_get_remset (void)
5371 mono_gc_get_vtable_bits (MonoClass *class)
5374 /* FIXME move this to the bridge code */
5375 if (sgen_need_bridge_processing ()) {
5376 switch (sgen_bridge_class_kind (class)) {
5377 case GC_BRIDGE_TRANSPARENT_BRIDGE_CLASS:
5378 case GC_BRIDGE_OPAQUE_BRIDGE_CLASS:
5379 res = SGEN_GC_BIT_BRIDGE_OBJECT;
5381 case GC_BRIDGE_OPAQUE_CLASS:
5382 res = SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT;
5386 if (fin_callbacks.is_class_finalization_aware) {
5387 if (fin_callbacks.is_class_finalization_aware (class))
5388 res |= SGEN_GC_BIT_FINALIZER_AWARE;
5394 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
5401 sgen_check_whole_heap_stw (void)
5403 sgen_stop_world (0);
5404 sgen_clear_nursery_fragments ();
5405 sgen_check_whole_heap (FALSE);
5406 sgen_restart_world (0, NULL);
5410 sgen_gc_event_moves (void)
5412 if (moved_objects_idx) {
5413 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
5414 moved_objects_idx = 0;
5419 sgen_timestamp (void)
5421 SGEN_TV_DECLARE (timestamp);
5422 SGEN_TV_GETTIME (timestamp);
5423 return SGEN_TV_ELAPSED (sgen_init_timestamp, timestamp);
5427 mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
5429 if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
5430 g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
5432 fin_callbacks = *callbacks;
5435 #endif /* HAVE_SGEN_GC */