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>
193 #include "metadata/sgen-gc.h"
194 #include "metadata/metadata-internals.h"
195 #include "metadata/class-internals.h"
196 #include "metadata/gc-internal.h"
197 #include "metadata/object-internals.h"
198 #include "metadata/threads.h"
199 #include "metadata/sgen-cardtable.h"
200 #include "metadata/sgen-protocol.h"
201 #include "metadata/sgen-archdep.h"
202 #include "metadata/sgen-bridge.h"
203 #include "metadata/sgen-memory-governor.h"
204 #include "metadata/sgen-hash-table.h"
205 #include "metadata/mono-gc.h"
206 #include "metadata/method-builder.h"
207 #include "metadata/profiler-private.h"
208 #include "metadata/mempool-internals.h"
209 #include "metadata/marshal.h"
210 #include "metadata/runtime.h"
211 #include "metadata/sgen-cardtable.h"
212 #include "metadata/sgen-pinning.h"
213 #include "metadata/sgen-workers.h"
214 #include "metadata/sgen-client.h"
215 #include "utils/mono-mmap.h"
216 #include "utils/mono-time.h"
217 #include "utils/mono-semaphore.h"
218 #include "utils/mono-counters.h"
219 #include "utils/mono-proclib.h"
220 #include "utils/mono-memory-model.h"
221 #include "utils/mono-logger-internal.h"
222 #include "utils/dtrace.h"
224 #include <mono/utils/mono-logger-internal.h>
225 #include <mono/utils/memcheck.h>
227 #if defined(__MACH__)
228 #include "utils/mach-support.h"
231 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
235 #include "mono/cil/opcode.def"
241 #undef pthread_create
243 #undef pthread_detach
246 * ######################################################################
247 * ######## Types and constants used by the GC.
248 * ######################################################################
251 /* 0 means not initialized, 1 is initialized, -1 means in progress */
252 static int gc_initialized = 0;
253 /* If set, check if we need to do something every X allocations */
254 gboolean has_per_allocation_action;
255 /* If set, do a heap check every X allocation */
256 guint32 verify_before_allocs = 0;
257 /* If set, do a minor collection before every X allocation */
258 guint32 collect_before_allocs = 0;
259 /* If set, do a whole heap check before each collection */
260 static gboolean whole_heap_check_before_collection = FALSE;
261 /* If set, do a heap consistency check before each minor collection */
262 static gboolean consistency_check_at_minor_collection = FALSE;
263 /* If set, do a mod union consistency check before each finishing collection pause */
264 static gboolean mod_union_consistency_check = FALSE;
265 /* If set, check whether mark bits are consistent after major collections */
266 static gboolean check_mark_bits_after_major_collection = FALSE;
267 /* If set, check that all nursery objects are pinned/not pinned, depending on context */
268 static gboolean check_nursery_objects_pinned = FALSE;
269 /* If set, do a few checks when the concurrent collector is used */
270 static gboolean do_concurrent_checks = FALSE;
271 /* If set, mark stacks conservatively, even if precise marking is possible */
272 static gboolean conservative_stack_mark = FALSE;
273 /* If set, do a plausibility check on the scan_starts before and after
275 static gboolean do_scan_starts_check = FALSE;
278 * If the major collector is concurrent and this is FALSE, we will
279 * never initiate a synchronous major collection, unless requested via
282 static gboolean allow_synchronous_major = TRUE;
283 static gboolean disable_minor_collections = FALSE;
284 static gboolean disable_major_collections = FALSE;
285 static gboolean do_verify_nursery = FALSE;
286 static gboolean do_dump_nursery_content = FALSE;
287 static gboolean enable_nursery_canaries = FALSE;
289 #ifdef HEAVY_STATISTICS
290 guint64 stat_objects_alloced_degraded = 0;
291 guint64 stat_bytes_alloced_degraded = 0;
293 guint64 stat_copy_object_called_nursery = 0;
294 guint64 stat_objects_copied_nursery = 0;
295 guint64 stat_copy_object_called_major = 0;
296 guint64 stat_objects_copied_major = 0;
298 guint64 stat_scan_object_called_nursery = 0;
299 guint64 stat_scan_object_called_major = 0;
301 guint64 stat_slots_allocated_in_vain;
303 guint64 stat_nursery_copy_object_failed_from_space = 0;
304 guint64 stat_nursery_copy_object_failed_forwarded = 0;
305 guint64 stat_nursery_copy_object_failed_pinned = 0;
306 guint64 stat_nursery_copy_object_failed_to_space = 0;
308 static int stat_wbarrier_add_to_global_remset = 0;
309 static int stat_wbarrier_set_field = 0;
310 static int stat_wbarrier_set_arrayref = 0;
311 static int stat_wbarrier_arrayref_copy = 0;
312 static int stat_wbarrier_generic_store = 0;
313 static int stat_wbarrier_generic_store_atomic = 0;
314 static int stat_wbarrier_set_root = 0;
315 static int stat_wbarrier_value_copy = 0;
316 static int stat_wbarrier_object_copy = 0;
319 static guint64 stat_pinned_objects = 0;
321 static guint64 time_minor_pre_collection_fragment_clear = 0;
322 static guint64 time_minor_pinning = 0;
323 static guint64 time_minor_scan_remsets = 0;
324 static guint64 time_minor_scan_pinned = 0;
325 static guint64 time_minor_scan_roots = 0;
326 static guint64 time_minor_finish_gray_stack = 0;
327 static guint64 time_minor_fragment_creation = 0;
329 static guint64 time_major_pre_collection_fragment_clear = 0;
330 static guint64 time_major_pinning = 0;
331 static guint64 time_major_scan_pinned = 0;
332 static guint64 time_major_scan_roots = 0;
333 static guint64 time_major_scan_mod_union = 0;
334 static guint64 time_major_finish_gray_stack = 0;
335 static guint64 time_major_free_bigobjs = 0;
336 static guint64 time_major_los_sweep = 0;
337 static guint64 time_major_sweep = 0;
338 static guint64 time_major_fragment_creation = 0;
340 static guint64 time_max = 0;
342 static SGEN_TV_DECLARE (time_major_conc_collection_start);
343 static SGEN_TV_DECLARE (time_major_conc_collection_end);
345 static SGEN_TV_DECLARE (last_minor_collection_start_tv);
346 static SGEN_TV_DECLARE (last_minor_collection_end_tv);
348 int gc_debug_level = 0;
353 mono_gc_flush_info (void)
355 fflush (gc_debug_file);
359 #define TV_DECLARE SGEN_TV_DECLARE
360 #define TV_GETTIME SGEN_TV_GETTIME
361 #define TV_ELAPSED SGEN_TV_ELAPSED
363 SGEN_TV_DECLARE (sgen_init_timestamp);
365 NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
367 #define object_is_forwarded SGEN_OBJECT_IS_FORWARDED
368 #define object_is_pinned SGEN_OBJECT_IS_PINNED
369 #define pin_object SGEN_PIN_OBJECT
371 #define ptr_in_nursery sgen_ptr_in_nursery
373 #define LOAD_VTABLE SGEN_LOAD_VTABLE
376 safe_name (void* obj)
378 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
379 return vt->klass->name;
383 nursery_canaries_enabled (void)
385 return enable_nursery_canaries;
388 #define safe_object_get_size sgen_safe_object_get_size
391 sgen_safe_name (void* obj)
393 return safe_name (obj);
397 * ######################################################################
398 * ######## Global data.
399 * ######################################################################
401 LOCK_DECLARE (gc_mutex);
402 gboolean sgen_try_free_some_memory;
404 #define SCAN_START_SIZE SGEN_SCAN_START_SIZE
406 static mword pagesize = 4096;
407 size_t degraded_mode = 0;
409 static mword bytes_pinned_from_failed_allocation = 0;
411 GCMemSection *nursery_section = NULL;
412 static volatile mword lowest_heap_address = ~(mword)0;
413 static volatile mword highest_heap_address = 0;
415 LOCK_DECLARE (sgen_interruption_mutex);
417 typedef struct _FinalizeReadyEntry FinalizeReadyEntry;
418 struct _FinalizeReadyEntry {
419 FinalizeReadyEntry *next;
423 int current_collection_generation = -1;
424 volatile gboolean concurrent_collection_in_progress = FALSE;
426 /* objects that are ready to be finalized */
427 static FinalizeReadyEntry *fin_ready_list = NULL;
428 static FinalizeReadyEntry *critical_fin_list = NULL;
430 /* registered roots: the key to the hash is the root start address */
432 * Different kinds of roots are kept separate to speed up pin_from_roots () for example.
434 SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
435 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
436 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
437 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL)
439 static mword roots_size = 0; /* amount of memory in the root set */
441 #define GC_ROOT_NUM 32
443 int count; /* must be the first field */
444 void *objects [GC_ROOT_NUM];
445 int root_types [GC_ROOT_NUM];
446 uintptr_t extra_info [GC_ROOT_NUM];
450 notify_gc_roots (GCRootReport *report)
454 mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
459 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
461 if (report->count == GC_ROOT_NUM)
462 notify_gc_roots (report);
463 report->objects [report->count] = object;
464 report->root_types [report->count] = rtype;
465 report->extra_info [report->count++] = (uintptr_t)((MonoVTable*)LOAD_VTABLE (object))->klass;
468 MonoNativeTlsKey thread_info_key;
470 #ifdef HAVE_KW_THREAD
471 __thread SgenThreadInfo *sgen_thread_info;
472 __thread char *stack_end;
475 /* The size of a TLAB */
476 /* The bigger the value, the less often we have to go to the slow path to allocate a new
477 * one, but the more space is wasted by threads not allocating much memory.
479 * FIXME: Make this self-tuning for each thread.
481 guint32 tlab_size = (1024 * 4);
483 #define MAX_SMALL_OBJ_SIZE SGEN_MAX_SMALL_OBJ_SIZE
485 /* Functions supplied by the runtime to be called by the GC */
486 static MonoGCCallbacks gc_callbacks;
488 #define ALLOC_ALIGN SGEN_ALLOC_ALIGN
490 #define ALIGN_UP SGEN_ALIGN_UP
492 #define MOVED_OBJECTS_NUM 64
493 static void *moved_objects [MOVED_OBJECTS_NUM];
494 static int moved_objects_idx = 0;
496 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
497 MonoNativeThreadId main_gc_thread = NULL;
500 /*Object was pinned during the current collection*/
501 static mword objects_pinned;
504 * ######################################################################
505 * ######## Macros and function declarations.
506 * ######################################################################
509 typedef SgenGrayQueue GrayQueue;
511 /* forward declarations */
512 static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, ScanCopyContext ctx);
513 static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
514 static void scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx);
515 static void report_finalizer_roots (void);
516 static void report_registered_roots (void);
518 static void pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx);
519 static void finish_gray_stack (int generation, ScanCopyContext ctx);
521 void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise);
524 static void init_stats (void);
526 SgenMajorCollector major_collector;
527 SgenMinorCollector sgen_minor_collector;
528 /* FIXME: get rid of this */
529 static GrayQueue gray_queue;
531 static SgenRememberedSet remset;
533 /* The gray queue to use from the main collection thread. */
534 #define WORKERS_DISTRIBUTE_GRAY_QUEUE (&gray_queue)
537 * The gray queue a worker job must use. If we're not parallel or
538 * concurrent, we use the main gray queue.
540 static SgenGrayQueue*
541 sgen_workers_get_job_gray_queue (WorkerData *worker_data)
543 return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
547 gray_queue_redirect (SgenGrayQueue *queue)
549 gboolean wake = FALSE;
552 GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
555 sgen_section_gray_queue_enqueue (queue->alloc_prepare_data, section);
560 g_assert (concurrent_collection_in_progress);
561 sgen_workers_ensure_awake ();
566 gray_queue_enable_redirect (SgenGrayQueue *queue)
568 if (!concurrent_collection_in_progress)
571 sgen_gray_queue_set_alloc_prepare (queue, gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
572 gray_queue_redirect (queue);
576 sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags)
578 MonoVTable *array_fill_vtable = sgen_client_get_array_fill_vtable ();
580 while (start < end) {
584 if (!*(void**)start) {
585 start += sizeof (void*); /* should be ALLOC_ALIGN, really */
590 if (!(obj = SGEN_OBJECT_IS_FORWARDED (start)))
596 if ((MonoVTable*)SGEN_LOAD_VTABLE (obj) != array_fill_vtable) {
597 CHECK_CANARY_FOR_OBJECT (obj);
598 size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
599 callback (obj, size, data);
600 CANARIFY_SIZE (size);
602 size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
610 * sgen_add_to_global_remset:
612 * The global remset contains locations which point into newspace after
613 * a minor collection. This can happen if the objects they point to are pinned.
615 * LOCKING: If called from a parallel collector, the global remset
616 * lock must be held. For serial collectors that is not necessary.
619 sgen_add_to_global_remset (gpointer ptr, gpointer obj)
621 SGEN_ASSERT (5, sgen_ptr_in_nursery (obj), "Target pointer of global remset must be in the nursery");
623 HEAVY_STAT (++stat_wbarrier_add_to_global_remset);
625 if (!major_collector.is_concurrent) {
626 SGEN_ASSERT (5, current_collection_generation != -1, "Global remsets can only be added during collections");
628 if (current_collection_generation == -1)
629 SGEN_ASSERT (5, sgen_concurrent_collection_in_progress (), "Global remsets outside of collection pauses can only be added by the concurrent collector");
632 if (!object_is_pinned (obj))
633 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");
634 else if (sgen_cement_lookup_or_register (obj))
637 remset.record_pointer (ptr);
639 sgen_pin_stats_register_global_remset (obj);
641 SGEN_LOG (8, "Adding global remset for %p", ptr);
642 binary_protocol_global_remset (ptr, obj, (gpointer)SGEN_LOAD_VTABLE (obj));
646 if (G_UNLIKELY (MONO_GC_GLOBAL_REMSET_ADD_ENABLED ())) {
647 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
648 MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)obj, sgen_safe_object_get_size (obj),
649 vt->klass->name_space, vt->klass->name);
655 * sgen_drain_gray_stack:
657 * Scan objects in the gray stack until the stack is empty. This should be called
658 * frequently after each object is copied, to achieve better locality and cache
661 * max_objs is the maximum number of objects to scan, or -1 to scan until the stack is
665 sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx)
667 ScanObjectFunc scan_func = ctx.ops->scan_object;
668 GrayQueue *queue = ctx.queue;
670 if (current_collection_generation == GENERATION_OLD && major_collector.drain_gray_stack)
671 return major_collector.drain_gray_stack (ctx);
675 for (i = 0; i != max_objs; ++i) {
678 GRAY_OBJECT_DEQUEUE (queue, &obj, &desc);
681 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
682 scan_func (obj, desc, queue);
684 } while (max_objs < 0);
689 * Addresses in the pin queue are already sorted. This function finds
690 * the object header for each address and pins the object. The
691 * addresses must be inside the nursery section. The (start of the)
692 * address array is overwritten with the addresses of the actually
693 * pinned objects. Return the number of pinned objects.
696 pin_objects_from_nursery_pin_queue (gboolean do_scan_objects, ScanCopyContext ctx)
698 GCMemSection *section = nursery_section;
699 void **start = sgen_pinning_get_entry (section->pin_queue_first_entry);
700 void **end = sgen_pinning_get_entry (section->pin_queue_last_entry);
701 void *start_nursery = section->data;
702 void *end_nursery = section->next_data;
707 void *pinning_front = start_nursery;
709 void **definitely_pinned = start;
710 ScanObjectFunc scan_func = ctx.ops->scan_object;
711 SgenGrayQueue *queue = ctx.queue;
713 sgen_nursery_allocator_prepare_for_pinning ();
715 while (start < end) {
716 void *obj_to_pin = NULL;
717 size_t obj_to_pin_size = 0;
722 SGEN_ASSERT (0, addr >= start_nursery && addr < end_nursery, "Potential pinning address out of range");
723 SGEN_ASSERT (0, addr >= last, "Pin queue not sorted");
730 SGEN_LOG (5, "Considering pinning addr %p", addr);
731 /* We've already processed everything up to pinning_front. */
732 if (addr < pinning_front) {
738 * Find the closest scan start <= addr. We might search backward in the
739 * scan_starts array because entries might be NULL. In the worst case we
740 * start at start_nursery.
742 idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
743 SGEN_ASSERT (0, idx < section->num_scan_start, "Scan start index out of range");
744 search_start = (void*)section->scan_starts [idx];
745 if (!search_start || search_start > addr) {
748 search_start = section->scan_starts [idx];
749 if (search_start && search_start <= addr)
752 if (!search_start || search_start > addr)
753 search_start = start_nursery;
757 * If the pinning front is closer than the scan start we found, start
758 * searching at the front.
760 if (search_start < pinning_front)
761 search_start = pinning_front;
764 * Now addr should be in an object a short distance from search_start.
766 * search_start must point to zeroed mem or point to an object.
769 size_t obj_size, canarified_obj_size;
772 if (!*(void**)search_start) {
773 search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
774 /* The loop condition makes sure we don't overrun addr. */
778 canarified_obj_size = obj_size = ALIGN_UP (safe_object_get_size ((MonoObject*)search_start));
781 * Filler arrays are marked by an invalid sync word. We don't
782 * consider them for pinning. They are not delimited by canaries,
785 if (((MonoObject*)search_start)->synchronisation != GINT_TO_POINTER (-1)) {
786 CHECK_CANARY_FOR_OBJECT (search_start);
787 CANARIFY_SIZE (canarified_obj_size);
789 if (addr >= search_start && (char*)addr < (char*)search_start + obj_size) {
790 /* This is the object we're looking for. */
791 obj_to_pin = search_start;
792 obj_to_pin_size = canarified_obj_size;
797 /* Skip to the next object */
798 search_start = (void*)((char*)search_start + canarified_obj_size);
799 } while (search_start <= addr);
801 /* We've searched past the address we were looking for. */
803 pinning_front = search_start;
804 goto next_pin_queue_entry;
808 * We've found an object to pin. It might still be a dummy array, but we
809 * can advance the pinning front in any case.
811 pinning_front = (char*)obj_to_pin + obj_to_pin_size;
814 * If this is a dummy array marking the beginning of a nursery
815 * fragment, we don't pin it.
817 if (((MonoObject*)obj_to_pin)->synchronisation == GINT_TO_POINTER (-1))
818 goto next_pin_queue_entry;
821 * Finally - pin the object!
823 desc = sgen_obj_get_descriptor_safe (obj_to_pin);
824 if (do_scan_objects) {
825 scan_func (obj_to_pin, desc, queue);
827 SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
828 obj_to_pin, *(void**)obj_to_pin, safe_name (obj_to_pin), count);
829 binary_protocol_pin (obj_to_pin,
830 (gpointer)LOAD_VTABLE (obj_to_pin),
831 safe_object_get_size (obj_to_pin));
834 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
835 int gen = sgen_ptr_in_nursery (obj_to_pin) ? GENERATION_NURSERY : GENERATION_OLD;
836 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj_to_pin);
837 MONO_GC_OBJ_PINNED ((mword)obj_to_pin,
838 sgen_safe_object_get_size (obj_to_pin),
839 vt->klass->name_space, vt->klass->name, gen);
843 pin_object (obj_to_pin);
844 GRAY_OBJECT_ENQUEUE (queue, obj_to_pin, desc);
845 sgen_pin_stats_register_object (obj_to_pin, obj_to_pin_size);
846 definitely_pinned [count] = obj_to_pin;
850 next_pin_queue_entry:
854 //printf ("effective pinned: %d (at the end: %d)\n", count, (char*)end_nursery - (char*)last);
855 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
858 for (idx = 0; idx < count; ++idx)
859 add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
860 notify_gc_roots (&report);
862 stat_pinned_objects += count;
867 pin_objects_in_nursery (gboolean do_scan_objects, ScanCopyContext ctx)
871 if (nursery_section->pin_queue_first_entry == nursery_section->pin_queue_last_entry)
874 reduced_to = pin_objects_from_nursery_pin_queue (do_scan_objects, ctx);
875 nursery_section->pin_queue_last_entry = nursery_section->pin_queue_first_entry + reduced_to;
879 * This function is only ever called (via `collector_pin_object()` in `sgen-copy-object.h`)
880 * when we can't promote an object because we're out of memory.
883 sgen_pin_object (void *object, GrayQueue *queue)
886 * All pinned objects are assumed to have been staged, so we need to stage as well.
887 * Also, the count of staged objects shows that "late pinning" happened.
889 sgen_pin_stage_ptr (object);
891 SGEN_PIN_OBJECT (object);
892 binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
895 sgen_pin_stats_register_object (object, safe_object_get_size (object));
897 GRAY_OBJECT_ENQUEUE (queue, object, sgen_obj_get_descriptor_safe (object));
900 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
901 int gen = sgen_ptr_in_nursery (object) ? GENERATION_NURSERY : GENERATION_OLD;
902 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (object);
903 MONO_GC_OBJ_PINNED ((mword)object, sgen_safe_object_get_size (object), vt->klass->name_space, vt->klass->name, gen);
908 /* Sort the addresses in array in increasing order.
909 * Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
912 sgen_sort_addresses (void **array, size_t size)
917 for (i = 1; i < size; ++i) {
920 size_t parent = (child - 1) / 2;
922 if (array [parent] >= array [child])
925 tmp = array [parent];
926 array [parent] = array [child];
933 for (i = size - 1; i > 0; --i) {
936 array [i] = array [0];
942 while (root * 2 + 1 <= end) {
943 size_t child = root * 2 + 1;
945 if (child < end && array [child] < array [child + 1])
947 if (array [root] >= array [child])
951 array [root] = array [child];
960 * Scan the memory between start and end and queue values which could be pointers
961 * to the area between start_nursery and end_nursery for later consideration.
962 * Typically used for thread stacks.
965 conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
969 #ifdef VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE
970 VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
973 while (start < end) {
974 if (*start >= start_nursery && *start < end_nursery) {
976 * *start can point to the middle of an object
977 * note: should we handle pointing at the end of an object?
978 * pinning in C# code disallows pointing at the end of an object
979 * but there is some small chance that an optimizing C compiler
980 * may keep the only reference to an object by pointing
981 * at the end of it. We ignore this small chance for now.
982 * Pointers to the end of an object are indistinguishable
983 * from pointers to the start of the next object in memory
984 * so if we allow that we'd need to pin two objects...
985 * We queue the pointer in an array, the
986 * array will then be sorted and uniqued. This way
987 * we can coalesce several pinning pointers and it should
988 * be faster since we'd do a memory scan with increasing
989 * addresses. Note: we can align the address to the allocation
990 * alignment, so the unique process is more effective.
992 mword addr = (mword)*start;
993 addr &= ~(ALLOC_ALIGN - 1);
994 if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
995 SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
996 sgen_pin_stage_ptr ((void*)addr);
997 binary_protocol_pin_stage (start, (void*)addr);
1002 * FIXME: It seems we're registering objects from all over the heap
1003 * (at least from the nursery and the LOS), but we're only
1004 * registering pinned addresses in the nursery. What's up with
1007 * Also, why wouldn't we register addresses once the pinning queue
1008 * is sorted and uniqued?
1010 if (ptr_in_nursery ((void*)addr))
1011 sgen_pin_stats_register_address ((char*)addr, pin_type);
1016 SGEN_LOG (7, "found %d potential pinned heap pointers", count);
1020 * The first thing we do in a collection is to identify pinned objects.
1021 * This function considers all the areas of memory that need to be
1022 * conservatively scanned.
1025 pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx)
1029 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);
1030 /* objects pinned from the API are inside these roots */
1031 SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], start_root, root) {
1032 SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
1033 conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
1034 } SGEN_HASH_TABLE_FOREACH_END;
1035 /* now deal with the thread stacks
1036 * in the future we should be able to conservatively scan only:
1037 * *) the cpu registers
1038 * *) the unmanaged stack frames
1039 * *) the _last_ managed stack frame
1040 * *) pointers slots in managed frames
1042 scan_thread_data (start_nursery, end_nursery, FALSE, ctx);
1046 unpin_objects_from_queue (SgenGrayQueue *queue)
1051 GRAY_OBJECT_DEQUEUE (queue, &addr, &desc);
1054 g_assert (SGEN_OBJECT_IS_PINNED (addr));
1055 SGEN_UNPIN_OBJECT (addr);
1060 single_arg_user_copy_or_mark (void **obj, void *gc_data)
1062 ScanCopyContext *ctx = gc_data;
1063 ctx->ops->copy_or_mark_object (obj, ctx->queue);
1067 * The memory area from start_root to end_root contains pointers to objects.
1068 * Their position is precisely described by @desc (this means that the pointer
1069 * can be either NULL or the pointer to the start of an object).
1070 * This functions copies them to to_space updates them.
1072 * This function is not thread-safe!
1075 precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, mword desc, ScanCopyContext ctx)
1077 CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
1078 SgenGrayQueue *queue = ctx.queue;
1080 switch (desc & ROOT_DESC_TYPE_MASK) {
1081 case ROOT_DESC_BITMAP:
1082 desc >>= ROOT_DESC_TYPE_SHIFT;
1084 if ((desc & 1) && *start_root) {
1085 copy_func (start_root, queue);
1086 SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
1092 case ROOT_DESC_COMPLEX: {
1093 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1094 gsize bwords = (*bitmap_data) - 1;
1095 void **start_run = start_root;
1097 while (bwords-- > 0) {
1098 gsize bmap = *bitmap_data++;
1099 void **objptr = start_run;
1101 if ((bmap & 1) && *objptr) {
1102 copy_func (objptr, queue);
1103 SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
1108 start_run += GC_BITS_PER_WORD;
1112 case ROOT_DESC_USER: {
1113 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1114 marker (start_root, single_arg_user_copy_or_mark, &ctx);
1117 case ROOT_DESC_RUN_LEN:
1118 g_assert_not_reached ();
1120 g_assert_not_reached ();
1125 reset_heap_boundaries (void)
1127 lowest_heap_address = ~(mword)0;
1128 highest_heap_address = 0;
1132 sgen_update_heap_boundaries (mword low, mword high)
1137 old = lowest_heap_address;
1140 } while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
1143 old = highest_heap_address;
1146 } while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
1150 * Allocate and setup the data structures needed to be able to allocate objects
1151 * in the nursery. The nursery is stored in nursery_section.
1154 alloc_nursery (void)
1156 GCMemSection *section;
1161 if (nursery_section)
1163 SGEN_LOG (2, "Allocating nursery size: %zu", (size_t)sgen_nursery_size);
1164 /* later we will alloc a larger area for the nursery but only activate
1165 * what we need. The rest will be used as expansion if we have too many pinned
1166 * objects in the existing nursery.
1168 /* FIXME: handle OOM */
1169 section = sgen_alloc_internal (INTERNAL_MEM_SECTION);
1171 alloc_size = sgen_nursery_size;
1173 /* If there isn't enough space even for the nursery we should simply abort. */
1174 g_assert (sgen_memgov_try_alloc_space (alloc_size, SPACE_NURSERY));
1176 data = major_collector.alloc_heap (alloc_size, alloc_size, DEFAULT_NURSERY_BITS);
1177 sgen_update_heap_boundaries ((mword)data, (mword)(data + sgen_nursery_size));
1178 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 ());
1179 section->data = section->next_data = data;
1180 section->size = alloc_size;
1181 section->end_data = data + sgen_nursery_size;
1182 scan_starts = (alloc_size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
1183 section->scan_starts = sgen_alloc_internal_dynamic (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS, TRUE);
1184 section->num_scan_start = scan_starts;
1186 nursery_section = section;
1188 sgen_nursery_allocator_set_nursery_bounds (data, data + sgen_nursery_size);
1192 mono_gc_get_nursery (int *shift_bits, size_t *size)
1194 *size = sgen_nursery_size;
1195 *shift_bits = DEFAULT_NURSERY_BITS;
1196 return sgen_get_nursery_start ();
1200 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1202 SgenThreadInfo *info = mono_thread_info_current ();
1204 /* Could be called from sgen_thread_unregister () with a NULL info */
1207 info->stopped_domain = domain;
1212 mono_gc_precise_stack_mark_enabled (void)
1214 return !conservative_stack_mark;
1218 mono_gc_get_logfile (void)
1220 return gc_debug_file;
1224 report_finalizer_roots_list (FinalizeReadyEntry *list)
1226 GCRootReport report;
1227 FinalizeReadyEntry *fin;
1230 for (fin = list; fin; fin = fin->next) {
1233 add_profile_gc_root (&report, fin->object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1235 notify_gc_roots (&report);
1239 report_finalizer_roots (void)
1241 report_finalizer_roots_list (fin_ready_list);
1242 report_finalizer_roots_list (critical_fin_list);
1245 static GCRootReport *root_report;
1248 single_arg_report_root (void **obj, void *gc_data)
1251 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1255 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1257 switch (desc & ROOT_DESC_TYPE_MASK) {
1258 case ROOT_DESC_BITMAP:
1259 desc >>= ROOT_DESC_TYPE_SHIFT;
1261 if ((desc & 1) && *start_root) {
1262 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1268 case ROOT_DESC_COMPLEX: {
1269 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1270 gsize bwords = (*bitmap_data) - 1;
1271 void **start_run = start_root;
1273 while (bwords-- > 0) {
1274 gsize bmap = *bitmap_data++;
1275 void **objptr = start_run;
1277 if ((bmap & 1) && *objptr) {
1278 add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1283 start_run += GC_BITS_PER_WORD;
1287 case ROOT_DESC_USER: {
1288 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1289 root_report = report;
1290 marker (start_root, single_arg_report_root, NULL);
1293 case ROOT_DESC_RUN_LEN:
1294 g_assert_not_reached ();
1296 g_assert_not_reached ();
1301 report_registered_roots_by_type (int root_type)
1303 GCRootReport report;
1307 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1308 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1309 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1310 } SGEN_HASH_TABLE_FOREACH_END;
1311 notify_gc_roots (&report);
1315 report_registered_roots (void)
1317 report_registered_roots_by_type (ROOT_TYPE_NORMAL);
1318 report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
1322 scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx)
1324 CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
1325 SgenGrayQueue *queue = ctx.queue;
1326 FinalizeReadyEntry *fin;
1328 for (fin = list; fin; fin = fin->next) {
1331 SGEN_LOG (5, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object));
1332 copy_func (&fin->object, queue);
1337 generation_name (int generation)
1339 switch (generation) {
1340 case GENERATION_NURSERY: return "nursery";
1341 case GENERATION_OLD: return "old";
1342 default: g_assert_not_reached ();
1347 sgen_generation_name (int generation)
1349 return generation_name (generation);
1353 finish_gray_stack (int generation, ScanCopyContext ctx)
1357 int done_with_ephemerons, ephemeron_rounds = 0;
1358 char *start_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_start () : NULL;
1359 char *end_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_end () : (char*)-1;
1360 SgenGrayQueue *queue = ctx.queue;
1363 * We copied all the reachable objects. Now it's the time to copy
1364 * the objects that were not referenced by the roots, but by the copied objects.
1365 * we built a stack of objects pointed to by gray_start: they are
1366 * additional roots and we may add more items as we go.
1367 * We loop until gray_start == gray_objects which means no more objects have
1368 * been added. Note this is iterative: no recursion is involved.
1369 * We need to walk the LO list as well in search of marked big objects
1370 * (use a flag since this is needed only on major collections). We need to loop
1371 * here as well, so keep a counter of marked LO (increasing it in copy_object).
1372 * To achieve better cache locality and cache usage, we drain the gray stack
1373 * frequently, after each object is copied, and just finish the work here.
1375 sgen_drain_gray_stack (-1, ctx);
1377 SGEN_LOG (2, "%s generation done", generation_name (generation));
1380 Reset bridge data, we might have lingering data from a previous collection if this is a major
1381 collection trigged by minor overflow.
1383 We must reset the gathered bridges since their original block might be evacuated due to major
1384 fragmentation in the meanwhile and the bridge code should not have to deal with that.
1386 if (sgen_need_bridge_processing ())
1387 sgen_bridge_reset_data ();
1390 * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
1391 * before processing finalizable objects and non-tracking weak links to avoid finalizing/clearing
1392 * objects that are in fact reachable.
1394 done_with_ephemerons = 0;
1396 done_with_ephemerons = sgen_client_mark_ephemerons (ctx);
1397 sgen_drain_gray_stack (-1, ctx);
1399 } while (!done_with_ephemerons);
1401 sgen_mark_togglerefs (start_addr, end_addr, ctx);
1403 if (sgen_need_bridge_processing ()) {
1404 /*Make sure the gray stack is empty before we process bridge objects so we get liveness right*/
1405 sgen_drain_gray_stack (-1, ctx);
1406 sgen_collect_bridge_objects (generation, ctx);
1407 if (generation == GENERATION_OLD)
1408 sgen_collect_bridge_objects (GENERATION_NURSERY, ctx);
1411 Do the first bridge step here, as the collector liveness state will become useless after that.
1413 An important optimization is to only proccess the possibly dead part of the object graph and skip
1414 over all live objects as we transitively know everything they point must be alive too.
1416 The above invariant is completely wrong if we let the gray queue be drained and mark/copy everything.
1418 This has the unfortunate side effect of making overflow collections perform the first step twice, but
1419 given we now have heuristics that perform major GC in anticipation of minor overflows this should not
1422 sgen_bridge_processing_stw_step ();
1426 Make sure we drain the gray stack before processing disappearing links and finalizers.
1427 If we don't make sure it is empty we might wrongly see a live object as dead.
1429 sgen_drain_gray_stack (-1, ctx);
1432 We must clear weak links that don't track resurrection before processing object ready for
1433 finalization so they can be cleared before that.
1435 sgen_null_link_in_range (generation, TRUE, ctx);
1436 if (generation == GENERATION_OLD)
1437 sgen_null_link_in_range (GENERATION_NURSERY, TRUE, ctx);
1440 /* walk the finalization queue and move also the objects that need to be
1441 * finalized: use the finalized objects as new roots so the objects they depend
1442 * on are also not reclaimed. As with the roots above, only objects in the nursery
1443 * are marked/copied.
1445 sgen_finalize_in_range (generation, ctx);
1446 if (generation == GENERATION_OLD)
1447 sgen_finalize_in_range (GENERATION_NURSERY, ctx);
1448 /* drain the new stack that might have been created */
1449 SGEN_LOG (6, "Precise scan of gray area post fin");
1450 sgen_drain_gray_stack (-1, ctx);
1453 * This must be done again after processing finalizable objects since CWL slots are cleared only after the key is finalized.
1455 done_with_ephemerons = 0;
1457 done_with_ephemerons = sgen_client_mark_ephemerons (ctx);
1458 sgen_drain_gray_stack (-1, ctx);
1460 } while (!done_with_ephemerons);
1462 sgen_client_clear_unreachable_ephemerons (ctx);
1465 * We clear togglerefs only after all possible chances of revival are done.
1466 * This is semantically more inline with what users expect and it allows for
1467 * user finalizers to correctly interact with TR objects.
1469 sgen_clear_togglerefs (start_addr, end_addr, ctx);
1472 SGEN_LOG (2, "Finalize queue handling scan for %s generation: %d usecs %d ephemeron rounds", generation_name (generation), TV_ELAPSED (atv, btv), ephemeron_rounds);
1475 * handle disappearing links
1476 * Note we do this after checking the finalization queue because if an object
1477 * survives (at least long enough to be finalized) we don't clear the link.
1478 * This also deals with a possible issue with the monitor reclamation: with the Boehm
1479 * GC a finalized object my lose the monitor because it is cleared before the finalizer is
1482 g_assert (sgen_gray_object_queue_is_empty (queue));
1484 sgen_null_link_in_range (generation, FALSE, ctx);
1485 if (generation == GENERATION_OLD)
1486 sgen_null_link_in_range (GENERATION_NURSERY, FALSE, ctx);
1487 if (sgen_gray_object_queue_is_empty (queue))
1489 sgen_drain_gray_stack (-1, ctx);
1492 g_assert (sgen_gray_object_queue_is_empty (queue));
1494 sgen_gray_object_queue_trim_free_list (queue);
1498 sgen_check_section_scan_starts (GCMemSection *section)
1501 for (i = 0; i < section->num_scan_start; ++i) {
1502 if (section->scan_starts [i]) {
1503 mword size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
1504 g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
1510 check_scan_starts (void)
1512 if (!do_scan_starts_check)
1514 sgen_check_section_scan_starts (nursery_section);
1515 major_collector.check_scan_starts ();
1519 scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx)
1523 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1524 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1525 precisely_scan_objects_from (start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc, ctx);
1526 } SGEN_HASH_TABLE_FOREACH_END;
1530 sgen_register_moved_object (void *obj, void *destination)
1532 g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
1534 if (moved_objects_idx == MOVED_OBJECTS_NUM) {
1535 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
1536 moved_objects_idx = 0;
1538 moved_objects [moved_objects_idx++] = obj;
1539 moved_objects [moved_objects_idx++] = destination;
1545 static gboolean inited = FALSE;
1550 mono_counters_register ("Collection max time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME | MONO_COUNTER_MONOTONIC, &time_max);
1552 mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_pre_collection_fragment_clear);
1553 mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_pinning);
1554 mono_counters_register ("Minor scan remembered set", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_remsets);
1555 mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_pinned);
1556 mono_counters_register ("Minor scan roots", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_roots);
1557 mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_fragment_creation);
1559 mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_pre_collection_fragment_clear);
1560 mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_pinning);
1561 mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_pinned);
1562 mono_counters_register ("Major scan roots", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_roots);
1563 mono_counters_register ("Major scan mod union", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_mod_union);
1564 mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_finish_gray_stack);
1565 mono_counters_register ("Major free big objects", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_free_bigobjs);
1566 mono_counters_register ("Major LOS sweep", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_los_sweep);
1567 mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_sweep);
1568 mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_fragment_creation);
1570 mono_counters_register ("Number of pinned objects", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_pinned_objects);
1572 #ifdef HEAVY_STATISTICS
1573 mono_counters_register ("WBarrier remember pointer", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_add_to_global_remset);
1574 mono_counters_register ("WBarrier set field", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_field);
1575 mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_arrayref);
1576 mono_counters_register ("WBarrier arrayref copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_arrayref_copy);
1577 mono_counters_register ("WBarrier generic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store);
1578 mono_counters_register ("WBarrier generic atomic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store_atomic);
1579 mono_counters_register ("WBarrier set root", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_root);
1580 mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_value_copy);
1581 mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_object_copy);
1583 mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_alloced_degraded);
1584 mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_bytes_alloced_degraded);
1586 mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_copy_object_called_nursery);
1587 mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_copied_nursery);
1588 mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_copy_object_called_major);
1589 mono_counters_register ("# objects copied (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_copied_major);
1591 mono_counters_register ("# scan_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_scan_object_called_nursery);
1592 mono_counters_register ("# scan_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_scan_object_called_major);
1594 mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_slots_allocated_in_vain);
1596 mono_counters_register ("# nursery copy_object() failed from space", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_from_space);
1597 mono_counters_register ("# nursery copy_object() failed forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_forwarded);
1598 mono_counters_register ("# nursery copy_object() failed pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_pinned);
1599 mono_counters_register ("# nursery copy_object() failed to space", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_to_space);
1601 sgen_nursery_allocator_init_heavy_stats ();
1609 reset_pinned_from_failed_allocation (void)
1611 bytes_pinned_from_failed_allocation = 0;
1615 sgen_set_pinned_from_failed_allocation (mword objsize)
1617 bytes_pinned_from_failed_allocation += objsize;
1621 sgen_collection_is_concurrent (void)
1623 switch (current_collection_generation) {
1624 case GENERATION_NURSERY:
1626 case GENERATION_OLD:
1627 return concurrent_collection_in_progress;
1629 g_error ("Invalid current generation %d", current_collection_generation);
1634 sgen_concurrent_collection_in_progress (void)
1636 return concurrent_collection_in_progress;
1640 SgenThreadPoolJob job;
1641 SgenObjectOperations *ops;
1645 job_remembered_set_scan (void *worker_data_untyped, SgenThreadPoolJob *job)
1647 WorkerData *worker_data = worker_data_untyped;
1648 ScanJob *job_data = (ScanJob*)job;
1649 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1650 remset.scan_remsets (ctx);
1654 SgenThreadPoolJob job;
1655 SgenObjectOperations *ops;
1659 } ScanFromRegisteredRootsJob;
1662 job_scan_from_registered_roots (void *worker_data_untyped, SgenThreadPoolJob *job)
1664 WorkerData *worker_data = worker_data_untyped;
1665 ScanFromRegisteredRootsJob *job_data = (ScanFromRegisteredRootsJob*)job;
1666 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1668 scan_from_registered_roots (job_data->heap_start, job_data->heap_end, job_data->root_type, ctx);
1672 SgenThreadPoolJob job;
1673 SgenObjectOperations *ops;
1676 } ScanThreadDataJob;
1679 job_scan_thread_data (void *worker_data_untyped, SgenThreadPoolJob *job)
1681 WorkerData *worker_data = worker_data_untyped;
1682 ScanThreadDataJob *job_data = (ScanThreadDataJob*)job;
1683 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1685 scan_thread_data (job_data->heap_start, job_data->heap_end, TRUE, ctx);
1689 SgenThreadPoolJob job;
1690 SgenObjectOperations *ops;
1691 FinalizeReadyEntry *list;
1692 } ScanFinalizerEntriesJob;
1695 job_scan_finalizer_entries (void *worker_data_untyped, SgenThreadPoolJob *job)
1697 WorkerData *worker_data = worker_data_untyped;
1698 ScanFinalizerEntriesJob *job_data = (ScanFinalizerEntriesJob*)job;
1699 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1701 scan_finalizer_entries (job_data->list, ctx);
1705 job_scan_major_mod_union_card_table (void *worker_data_untyped, SgenThreadPoolJob *job)
1707 WorkerData *worker_data = worker_data_untyped;
1708 ScanJob *job_data = (ScanJob*)job;
1709 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1711 g_assert (concurrent_collection_in_progress);
1712 major_collector.scan_card_table (TRUE, ctx);
1716 job_scan_los_mod_union_card_table (void *worker_data_untyped, SgenThreadPoolJob *job)
1718 WorkerData *worker_data = worker_data_untyped;
1719 ScanJob *job_data = (ScanJob*)job;
1720 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1722 g_assert (concurrent_collection_in_progress);
1723 sgen_los_scan_card_table (TRUE, ctx);
1727 verify_scan_starts (char *start, char *end)
1731 for (i = 0; i < nursery_section->num_scan_start; ++i) {
1732 char *addr = nursery_section->scan_starts [i];
1733 if (addr > start && addr < end)
1734 SGEN_LOG (1, "NFC-BAD SCAN START [%zu] %p for obj [%p %p]", i, addr, start, end);
1739 verify_nursery (void)
1741 char *start, *end, *cur, *hole_start;
1743 if (!do_verify_nursery)
1746 if (nursery_canaries_enabled ())
1747 SGEN_LOG (1, "Checking nursery canaries...");
1749 /*This cleans up unused fragments */
1750 sgen_nursery_allocator_prepare_for_pinning ();
1752 hole_start = start = cur = sgen_get_nursery_start ();
1753 end = sgen_get_nursery_end ();
1758 if (!*(void**)cur) {
1759 cur += sizeof (void*);
1763 if (object_is_forwarded (cur))
1764 SGEN_LOG (1, "FORWARDED OBJ %p", cur);
1765 else if (object_is_pinned (cur))
1766 SGEN_LOG (1, "PINNED OBJ %p", cur);
1768 ss = safe_object_get_size ((MonoObject*)cur);
1769 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
1770 verify_scan_starts (cur, cur + size);
1771 if (do_dump_nursery_content) {
1772 if (cur > hole_start)
1773 SGEN_LOG (1, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start));
1774 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_client_get_array_fill_vtable ());
1776 if (nursery_canaries_enabled () && (MonoVTable*)SGEN_LOAD_VTABLE (cur) != sgen_client_get_array_fill_vtable ()) {
1777 CHECK_CANARY_FOR_OBJECT (cur);
1778 CANARIFY_SIZE (size);
1786 * Checks that no objects in the nursery are fowarded or pinned. This
1787 * is a precondition to restarting the mutator while doing a
1788 * concurrent collection. Note that we don't clear fragments because
1789 * we depend on that having happened earlier.
1792 check_nursery_is_clean (void)
1796 cur = sgen_get_nursery_start ();
1797 end = sgen_get_nursery_end ();
1802 if (!*(void**)cur) {
1803 cur += sizeof (void*);
1807 g_assert (!object_is_forwarded (cur));
1808 g_assert (!object_is_pinned (cur));
1810 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
1811 verify_scan_starts (cur, cur + size);
1818 init_gray_queue (void)
1820 if (sgen_collection_is_concurrent ())
1821 sgen_workers_init_distribute_gray_queue ();
1822 sgen_gray_object_queue_init (&gray_queue, NULL);
1826 enqueue_scan_from_roots_jobs (char *heap_start, char *heap_end, SgenObjectOperations *ops)
1828 ScanFromRegisteredRootsJob *scrrj;
1829 ScanThreadDataJob *stdj;
1830 ScanFinalizerEntriesJob *sfej;
1832 /* registered roots, this includes static fields */
1834 scrrj = (ScanFromRegisteredRootsJob*)sgen_thread_pool_job_alloc ("scan from registered roots normal", job_scan_from_registered_roots, sizeof (ScanFromRegisteredRootsJob));
1836 scrrj->heap_start = heap_start;
1837 scrrj->heap_end = heap_end;
1838 scrrj->root_type = ROOT_TYPE_NORMAL;
1839 sgen_workers_enqueue_job (&scrrj->job);
1841 scrrj = (ScanFromRegisteredRootsJob*)sgen_thread_pool_job_alloc ("scan from registered roots wbarrier", job_scan_from_registered_roots, sizeof (ScanFromRegisteredRootsJob));
1843 scrrj->heap_start = heap_start;
1844 scrrj->heap_end = heap_end;
1845 scrrj->root_type = ROOT_TYPE_WBARRIER;
1846 sgen_workers_enqueue_job (&scrrj->job);
1850 stdj = (ScanThreadDataJob*)sgen_thread_pool_job_alloc ("scan thread data", job_scan_thread_data, sizeof (ScanThreadDataJob));
1851 stdj->heap_start = heap_start;
1852 stdj->heap_end = heap_end;
1853 sgen_workers_enqueue_job (&stdj->job);
1855 /* Scan the list of objects ready for finalization. */
1857 sfej = (ScanFinalizerEntriesJob*)sgen_thread_pool_job_alloc ("scan finalizer entries", job_scan_finalizer_entries, sizeof (ScanFinalizerEntriesJob));
1858 sfej->list = fin_ready_list;
1860 sgen_workers_enqueue_job (&sfej->job);
1862 sfej = (ScanFinalizerEntriesJob*)sgen_thread_pool_job_alloc ("scan critical finalizer entries", job_scan_finalizer_entries, sizeof (ScanFinalizerEntriesJob));
1863 sfej->list = critical_fin_list;
1865 sgen_workers_enqueue_job (&sfej->job);
1869 * Perform a nursery collection.
1871 * Return whether any objects were late-pinned due to being out of memory.
1874 collect_nursery (SgenGrayQueue *unpin_queue, gboolean finish_up_concurrent_mark)
1876 gboolean needs_major;
1877 size_t max_garbage_amount;
1879 mword fragment_total;
1881 SgenObjectOperations *object_ops = &sgen_minor_collector.serial_ops;
1882 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, &gray_queue);
1886 if (disable_minor_collections)
1889 TV_GETTIME (last_minor_collection_start_tv);
1890 atv = last_minor_collection_start_tv;
1892 MONO_GC_BEGIN (GENERATION_NURSERY);
1893 binary_protocol_collection_begin (gc_stats.minor_gc_count, GENERATION_NURSERY);
1897 #ifndef DISABLE_PERFCOUNTERS
1898 mono_perfcounters->gc_collections0++;
1901 current_collection_generation = GENERATION_NURSERY;
1903 SGEN_ASSERT (0, !sgen_collection_is_concurrent (), "Why is the nursery collection concurrent?");
1905 reset_pinned_from_failed_allocation ();
1907 check_scan_starts ();
1909 sgen_nursery_alloc_prepare_for_minor ();
1913 nursery_next = sgen_nursery_alloc_get_upper_alloc_bound ();
1914 /* FIXME: optimize later to use the higher address where an object can be present */
1915 nursery_next = MAX (nursery_next, sgen_get_nursery_end ());
1917 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 ()));
1918 max_garbage_amount = nursery_next - sgen_get_nursery_start ();
1919 g_assert (nursery_section->size >= max_garbage_amount);
1921 /* world must be stopped already */
1923 time_minor_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
1925 sgen_client_pre_collection_checks ();
1927 nursery_section->next_data = nursery_next;
1929 major_collector.start_nursery_collection ();
1931 sgen_memgov_minor_collection_start ();
1935 gc_stats.minor_gc_count ++;
1937 if (whole_heap_check_before_collection) {
1938 sgen_clear_nursery_fragments ();
1939 sgen_check_whole_heap (finish_up_concurrent_mark);
1941 if (consistency_check_at_minor_collection)
1942 sgen_check_consistency ();
1944 MONO_GC_CHECKPOINT_1 (GENERATION_NURSERY);
1946 sgen_process_fin_stage_entries ();
1947 sgen_process_dislink_stage_entries ();
1949 MONO_GC_CHECKPOINT_2 (GENERATION_NURSERY);
1951 /* pin from pinned handles */
1952 sgen_init_pinning ();
1953 mono_profiler_gc_event (MONO_GC_EVENT_MARK_START, 0);
1954 pin_from_roots (sgen_get_nursery_start (), nursery_next, ctx);
1955 /* pin cemented objects */
1956 sgen_pin_cemented_objects ();
1957 /* identify pinned objects */
1958 sgen_optimize_pin_queue ();
1959 sgen_pinning_setup_section (nursery_section);
1961 pin_objects_in_nursery (FALSE, ctx);
1962 sgen_pinning_trim_queue_to_section (nursery_section);
1965 time_minor_pinning += TV_ELAPSED (btv, atv);
1966 SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (btv, atv));
1967 SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
1969 MONO_GC_CHECKPOINT_3 (GENERATION_NURSERY);
1972 * FIXME: When we finish a concurrent collection we do a nursery collection first,
1973 * as part of which we scan the card table. Then, later, we scan the mod union
1974 * cardtable. We should only have to do one.
1976 sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan remset", job_remembered_set_scan, sizeof (ScanJob));
1977 sj->ops = object_ops;
1978 sgen_workers_enqueue_job (&sj->job);
1980 /* we don't have complete write barrier yet, so we scan all the old generation sections */
1982 time_minor_scan_remsets += TV_ELAPSED (atv, btv);
1983 SGEN_LOG (2, "Old generation scan: %d usecs", TV_ELAPSED (atv, btv));
1985 MONO_GC_CHECKPOINT_4 (GENERATION_NURSERY);
1987 sgen_drain_gray_stack (-1, ctx);
1989 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
1990 report_registered_roots ();
1991 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
1992 report_finalizer_roots ();
1994 time_minor_scan_pinned += TV_ELAPSED (btv, atv);
1996 MONO_GC_CHECKPOINT_5 (GENERATION_NURSERY);
1998 enqueue_scan_from_roots_jobs (sgen_get_nursery_start (), nursery_next, object_ops);
2001 time_minor_scan_roots += TV_ELAPSED (atv, btv);
2003 MONO_GC_CHECKPOINT_6 (GENERATION_NURSERY);
2004 MONO_GC_CHECKPOINT_7 (GENERATION_NURSERY);
2005 MONO_GC_CHECKPOINT_8 (GENERATION_NURSERY);
2007 finish_gray_stack (GENERATION_NURSERY, ctx);
2009 time_minor_finish_gray_stack += TV_ELAPSED (btv, atv);
2010 mono_profiler_gc_event (MONO_GC_EVENT_MARK_END, 0);
2012 MONO_GC_CHECKPOINT_9 (GENERATION_NURSERY);
2014 if (objects_pinned) {
2015 sgen_optimize_pin_queue ();
2016 sgen_pinning_setup_section (nursery_section);
2019 /* walk the pin_queue, build up the fragment list of free memory, unmark
2020 * pinned objects as we go, memzero() the empty fragments so they are ready for the
2023 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_START, 0);
2024 fragment_total = sgen_build_nursery_fragments (nursery_section, unpin_queue);
2025 if (!fragment_total)
2028 /* Clear TLABs for all threads */
2029 sgen_clear_tlabs ();
2031 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_END, 0);
2033 time_minor_fragment_creation += TV_ELAPSED (atv, btv);
2034 SGEN_LOG (2, "Fragment creation: %d usecs, %lu bytes available", TV_ELAPSED (atv, btv), (unsigned long)fragment_total);
2036 if (consistency_check_at_minor_collection)
2037 sgen_check_major_refs ();
2039 major_collector.finish_nursery_collection ();
2041 TV_GETTIME (last_minor_collection_end_tv);
2042 gc_stats.minor_gc_time += TV_ELAPSED (last_minor_collection_start_tv, last_minor_collection_end_tv);
2044 sgen_debug_dump_heap ("minor", gc_stats.minor_gc_count - 1, NULL);
2046 /* prepare the pin queue for the next collection */
2047 sgen_finish_pinning ();
2048 if (fin_ready_list || critical_fin_list) {
2049 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2050 mono_gc_finalize_notify ();
2052 sgen_pin_stats_reset ();
2053 /* clear cemented hash */
2054 sgen_cement_clear_below_threshold ();
2056 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2058 remset.finish_minor_collection ();
2060 check_scan_starts ();
2062 binary_protocol_flush_buffers (FALSE);
2064 sgen_memgov_minor_collection_end ();
2066 /*objects are late pinned because of lack of memory, so a major is a good call*/
2067 needs_major = objects_pinned > 0;
2068 current_collection_generation = -1;
2071 MONO_GC_END (GENERATION_NURSERY);
2072 binary_protocol_collection_end (gc_stats.minor_gc_count - 1, GENERATION_NURSERY, 0, 0);
2074 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2075 sgen_check_nursery_objects_pinned (unpin_queue != NULL);
2081 scan_nursery_objects_callback (char *obj, size_t size, ScanCopyContext *ctx)
2084 * This is called on all objects in the nursery, including pinned ones, so we need
2085 * to use sgen_obj_get_descriptor_safe(), which masks out the vtable tag bits.
2087 ctx->ops->scan_object (obj, sgen_obj_get_descriptor_safe (obj), ctx->queue);
2091 scan_nursery_objects (ScanCopyContext ctx)
2093 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
2094 (IterateObjectCallbackFunc)scan_nursery_objects_callback, (void*)&ctx, FALSE);
2098 COPY_OR_MARK_FROM_ROOTS_SERIAL,
2099 COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT,
2100 COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT
2101 } CopyOrMarkFromRootsMode;
2104 major_copy_or_mark_from_roots (size_t *old_next_pin_slot, CopyOrMarkFromRootsMode mode, gboolean scan_whole_nursery, SgenObjectOperations *object_ops)
2109 /* FIXME: only use these values for the precise scan
2110 * note that to_space pointers should be excluded anyway...
2112 char *heap_start = NULL;
2113 char *heap_end = (char*)-1;
2114 gboolean profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2115 GCRootReport root_report = { 0 };
2116 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2117 gboolean concurrent = mode != COPY_OR_MARK_FROM_ROOTS_SERIAL;
2119 SGEN_ASSERT (0, !!concurrent == !!concurrent_collection_in_progress, "We've been called with the wrong mode.");
2121 if (scan_whole_nursery)
2122 SGEN_ASSERT (0, mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT, "Scanning whole nursery only makes sense when we're finishing a concurrent collection.");
2125 /*This cleans up unused fragments */
2126 sgen_nursery_allocator_prepare_for_pinning ();
2128 if (do_concurrent_checks)
2129 check_nursery_is_clean ();
2131 /* The concurrent collector doesn't touch the nursery. */
2132 sgen_nursery_alloc_prepare_for_major ();
2139 /* Pinning depends on this */
2140 sgen_clear_nursery_fragments ();
2142 if (whole_heap_check_before_collection)
2143 sgen_check_whole_heap (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT);
2146 time_major_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2148 if (!sgen_collection_is_concurrent ())
2149 nursery_section->next_data = sgen_get_nursery_end ();
2150 /* we should also coalesce scanning from sections close to each other
2151 * and deal with pointers outside of the sections later.
2156 sgen_client_pre_collection_checks ();
2159 /* Remsets are not useful for a major collection */
2160 remset.clear_cards ();
2163 sgen_process_fin_stage_entries ();
2164 sgen_process_dislink_stage_entries ();
2167 sgen_init_pinning ();
2168 SGEN_LOG (6, "Collecting pinned addresses");
2169 pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address, ctx);
2171 if (mode != COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
2172 if (major_collector.is_concurrent) {
2174 * The concurrent major collector cannot evict
2175 * yet, so we need to pin cemented objects to
2176 * not break some asserts.
2178 * FIXME: We could evict now!
2180 sgen_pin_cemented_objects ();
2184 sgen_optimize_pin_queue ();
2187 * pin_queue now contains all candidate pointers, sorted and
2188 * uniqued. We must do two passes now to figure out which
2189 * objects are pinned.
2191 * The first is to find within the pin_queue the area for each
2192 * section. This requires that the pin_queue be sorted. We
2193 * also process the LOS objects and pinned chunks here.
2195 * The second, destructive, pass is to reduce the section
2196 * areas to pointers to the actually pinned objects.
2198 SGEN_LOG (6, "Pinning from sections");
2199 /* first pass for the sections */
2200 sgen_find_section_pin_queue_start_end (nursery_section);
2201 /* identify possible pointers to the insize of large objects */
2202 SGEN_LOG (6, "Pinning from large objects");
2203 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
2205 if (sgen_find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + sgen_los_object_size (bigobj), &dummy, &dummy)) {
2206 binary_protocol_pin (bigobj->data, (gpointer)LOAD_VTABLE (bigobj->data), safe_object_get_size (((MonoObject*)(bigobj->data))));
2208 #ifdef ENABLE_DTRACE
2209 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
2210 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (bigobj->data);
2211 MONO_GC_OBJ_PINNED ((mword)bigobj->data, sgen_safe_object_get_size ((MonoObject*)bigobj->data), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
2215 if (sgen_los_object_is_pinned (bigobj->data)) {
2216 SGEN_ASSERT (0, mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT, "LOS objects can only be pinned here after concurrent marking.");
2219 sgen_los_pin_object (bigobj->data);
2220 if (SGEN_OBJECT_HAS_REFERENCES (bigobj->data))
2221 GRAY_OBJECT_ENQUEUE (WORKERS_DISTRIBUTE_GRAY_QUEUE, bigobj->data, sgen_obj_get_descriptor (bigobj->data));
2222 sgen_pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
2223 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));
2226 add_profile_gc_root (&root_report, bigobj->data, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2230 notify_gc_roots (&root_report);
2231 /* second pass for the sections */
2234 * Concurrent mark never follows references into the nursery. In the start and
2235 * finish pauses we must scan live nursery objects, though.
2237 * In the finish pause we do this conservatively by scanning all nursery objects.
2238 * Previously we would only scan pinned objects here. We assumed that all objects
2239 * that were pinned during the nursery collection immediately preceding this finish
2240 * mark would be pinned again here. Due to the way we get the stack end for the GC
2241 * thread, however, that's not necessarily the case: we scan part of the stack used
2242 * by the GC itself, which changes constantly, so pinning isn't entirely
2245 * The split nursery also complicates things because non-pinned objects can survive
2246 * in the nursery. That's why we need to do a full scan of the nursery for it, too.
2248 * In the future we shouldn't do a preceding nursery collection at all and instead
2249 * do the finish pause with promotion from the nursery.
2251 * A further complication arises when we have late-pinned objects from the preceding
2252 * nursery collection. Those are the result of being out of memory when trying to
2253 * evacuate objects. They won't be found from the roots, so we just scan the whole
2256 * Non-concurrent mark evacuates from the nursery, so it's
2257 * sufficient to just scan pinned nursery objects.
2259 if (scan_whole_nursery || mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT || (concurrent && sgen_minor_collector.is_split)) {
2260 scan_nursery_objects (ctx);
2262 pin_objects_in_nursery (concurrent, ctx);
2263 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2264 sgen_check_nursery_objects_pinned (mode != COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT);
2267 major_collector.pin_objects (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2268 if (old_next_pin_slot)
2269 *old_next_pin_slot = sgen_get_pinned_count ();
2272 time_major_pinning += TV_ELAPSED (atv, btv);
2273 SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (atv, btv));
2274 SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
2276 major_collector.init_to_space ();
2279 * The concurrent collector doesn't move objects, neither on
2280 * the major heap nor in the nursery, so we can mark even
2281 * before pinning has finished. For the non-concurrent
2282 * collector we start the workers after pinning.
2284 if (mode != COPY_OR_MARK_FROM_ROOTS_SERIAL) {
2285 SGEN_ASSERT (0, sgen_workers_all_done (), "Why are the workers not done when we start or finish a major collection?");
2286 sgen_workers_start_all_workers (object_ops);
2287 gray_queue_enable_redirect (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2290 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2291 main_gc_thread = mono_native_thread_self ();
2294 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2295 report_registered_roots ();
2297 time_major_scan_pinned += TV_ELAPSED (btv, atv);
2299 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2300 report_finalizer_roots ();
2303 * FIXME: is this the right context? It doesn't seem to contain a copy function
2304 * unless we're concurrent.
2306 enqueue_scan_from_roots_jobs (heap_start, heap_end, object_ops);
2309 time_major_scan_roots += TV_ELAPSED (atv, btv);
2311 if (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT) {
2314 /* Mod union card table */
2315 sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan mod union cardtable", job_scan_major_mod_union_card_table, sizeof (ScanJob));
2316 sj->ops = object_ops;
2317 sgen_workers_enqueue_job (&sj->job);
2319 sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan LOS mod union cardtable", job_scan_los_mod_union_card_table, sizeof (ScanJob));
2320 sj->ops = object_ops;
2321 sgen_workers_enqueue_job (&sj->job);
2324 time_major_scan_mod_union += TV_ELAPSED (btv, atv);
2329 major_finish_copy_or_mark (void)
2331 if (!concurrent_collection_in_progress)
2335 * Prepare the pin queue for the next collection. Since pinning runs on the worker
2336 * threads we must wait for the jobs to finish before we can reset it.
2338 sgen_workers_wait_for_jobs_finished ();
2339 sgen_finish_pinning ();
2341 sgen_pin_stats_reset ();
2343 if (do_concurrent_checks)
2344 check_nursery_is_clean ();
2348 major_start_collection (gboolean concurrent, size_t *old_next_pin_slot)
2350 SgenObjectOperations *object_ops;
2352 MONO_GC_BEGIN (GENERATION_OLD);
2353 binary_protocol_collection_begin (gc_stats.major_gc_count, GENERATION_OLD);
2355 current_collection_generation = GENERATION_OLD;
2356 #ifndef DISABLE_PERFCOUNTERS
2357 mono_perfcounters->gc_collections1++;
2360 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2362 sgen_cement_reset ();
2365 g_assert (major_collector.is_concurrent);
2366 concurrent_collection_in_progress = TRUE;
2368 object_ops = &major_collector.major_ops_concurrent_start;
2370 object_ops = &major_collector.major_ops_serial;
2373 reset_pinned_from_failed_allocation ();
2375 sgen_memgov_major_collection_start ();
2377 //count_ref_nonref_objs ();
2378 //consistency_check ();
2380 check_scan_starts ();
2383 SGEN_LOG (1, "Start major collection %d", gc_stats.major_gc_count);
2384 gc_stats.major_gc_count ++;
2386 if (major_collector.start_major_collection)
2387 major_collector.start_major_collection ();
2389 major_copy_or_mark_from_roots (old_next_pin_slot, concurrent ? COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT : COPY_OR_MARK_FROM_ROOTS_SERIAL, FALSE, object_ops);
2390 major_finish_copy_or_mark ();
2394 major_finish_collection (const char *reason, size_t old_next_pin_slot, gboolean forced, gboolean scan_whole_nursery)
2396 ScannedObjectCounts counts;
2397 SgenObjectOperations *object_ops;
2403 if (concurrent_collection_in_progress) {
2404 object_ops = &major_collector.major_ops_concurrent_finish;
2406 major_copy_or_mark_from_roots (NULL, COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT, scan_whole_nursery, object_ops);
2408 major_finish_copy_or_mark ();
2410 sgen_workers_join ();
2412 SGEN_ASSERT (0, sgen_gray_object_queue_is_empty (&gray_queue), "Why is the gray queue not empty after workers have finished working?");
2414 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2415 main_gc_thread = NULL;
2418 if (do_concurrent_checks)
2419 check_nursery_is_clean ();
2421 SGEN_ASSERT (0, !scan_whole_nursery, "scan_whole_nursery only applies to concurrent collections");
2422 object_ops = &major_collector.major_ops_serial;
2426 * The workers have stopped so we need to finish gray queue
2427 * work that might result from finalization in the main GC
2428 * thread. Redirection must therefore be turned off.
2430 sgen_gray_object_queue_disable_alloc_prepare (&gray_queue);
2431 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2433 /* all the objects in the heap */
2434 finish_gray_stack (GENERATION_OLD, CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, &gray_queue));
2436 time_major_finish_gray_stack += TV_ELAPSED (btv, atv);
2438 SGEN_ASSERT (0, sgen_workers_all_done (), "Can't have workers working after joining");
2440 if (objects_pinned) {
2441 g_assert (!concurrent_collection_in_progress);
2444 * This is slow, but we just OOM'd.
2446 * See comment at `sgen_pin_queue_clear_discarded_entries` for how the pin
2447 * queue is laid out at this point.
2449 sgen_pin_queue_clear_discarded_entries (nursery_section, old_next_pin_slot);
2451 * We need to reestablish all pinned nursery objects in the pin queue
2452 * because they're needed for fragment creation. Unpinning happens by
2453 * walking the whole queue, so it's not necessary to reestablish where major
2454 * heap block pins are - all we care is that they're still in there
2457 sgen_optimize_pin_queue ();
2458 sgen_find_section_pin_queue_start_end (nursery_section);
2462 reset_heap_boundaries ();
2463 sgen_update_heap_boundaries ((mword)sgen_get_nursery_start (), (mword)sgen_get_nursery_end ());
2465 if (!concurrent_collection_in_progress) {
2466 /* walk the pin_queue, build up the fragment list of free memory, unmark
2467 * pinned objects as we go, memzero() the empty fragments so they are ready for the
2470 if (!sgen_build_nursery_fragments (nursery_section, NULL))
2473 /* prepare the pin queue for the next collection */
2474 sgen_finish_pinning ();
2476 /* Clear TLABs for all threads */
2477 sgen_clear_tlabs ();
2479 sgen_pin_stats_reset ();
2482 sgen_cement_clear_below_threshold ();
2484 if (check_mark_bits_after_major_collection)
2485 sgen_check_heap_marked (concurrent_collection_in_progress);
2488 time_major_fragment_creation += TV_ELAPSED (atv, btv);
2490 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, !major_collector.sweeps_lazily);
2493 time_major_free_bigobjs += TV_ELAPSED (btv, atv);
2498 time_major_los_sweep += TV_ELAPSED (atv, btv);
2500 major_collector.sweep ();
2502 MONO_GC_SWEEP_END (GENERATION_OLD, !major_collector.sweeps_lazily);
2505 time_major_sweep += TV_ELAPSED (btv, atv);
2507 sgen_debug_dump_heap ("major", gc_stats.major_gc_count - 1, reason);
2509 if (fin_ready_list || critical_fin_list) {
2510 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2511 mono_gc_finalize_notify ();
2514 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2516 sgen_memgov_major_collection_end (forced);
2517 current_collection_generation = -1;
2519 memset (&counts, 0, sizeof (ScannedObjectCounts));
2520 major_collector.finish_major_collection (&counts);
2522 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2524 SGEN_ASSERT (0, sgen_workers_all_done (), "Can't have workers working after major collection has finished");
2525 if (concurrent_collection_in_progress)
2526 concurrent_collection_in_progress = FALSE;
2528 check_scan_starts ();
2530 binary_protocol_flush_buffers (FALSE);
2532 //consistency_check ();
2534 MONO_GC_END (GENERATION_OLD);
2535 binary_protocol_collection_end (gc_stats.major_gc_count - 1, GENERATION_OLD, counts.num_scanned_objects, counts.num_unique_scanned_objects);
2539 major_do_collection (const char *reason, gboolean forced)
2541 TV_DECLARE (time_start);
2542 TV_DECLARE (time_end);
2543 size_t old_next_pin_slot;
2545 if (disable_major_collections)
2548 if (major_collector.get_and_reset_num_major_objects_marked) {
2549 long long num_marked = major_collector.get_and_reset_num_major_objects_marked ();
2550 g_assert (!num_marked);
2553 /* world must be stopped already */
2554 TV_GETTIME (time_start);
2556 major_start_collection (FALSE, &old_next_pin_slot);
2557 major_finish_collection (reason, old_next_pin_slot, forced, FALSE);
2559 TV_GETTIME (time_end);
2560 gc_stats.major_gc_time += TV_ELAPSED (time_start, time_end);
2562 /* FIXME: also report this to the user, preferably in gc-end. */
2563 if (major_collector.get_and_reset_num_major_objects_marked)
2564 major_collector.get_and_reset_num_major_objects_marked ();
2566 return bytes_pinned_from_failed_allocation > 0;
2570 major_start_concurrent_collection (const char *reason)
2572 TV_DECLARE (time_start);
2573 TV_DECLARE (time_end);
2574 long long num_objects_marked;
2576 if (disable_major_collections)
2579 TV_GETTIME (time_start);
2580 SGEN_TV_GETTIME (time_major_conc_collection_start);
2582 num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
2583 g_assert (num_objects_marked == 0);
2585 MONO_GC_CONCURRENT_START_BEGIN (GENERATION_OLD);
2586 binary_protocol_concurrent_start ();
2588 // FIXME: store reason and pass it when finishing
2589 major_start_collection (TRUE, NULL);
2591 gray_queue_redirect (&gray_queue);
2593 num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
2594 MONO_GC_CONCURRENT_START_END (GENERATION_OLD, num_objects_marked);
2596 TV_GETTIME (time_end);
2597 gc_stats.major_gc_time += TV_ELAPSED (time_start, time_end);
2599 current_collection_generation = -1;
2603 * Returns whether the major collection has finished.
2606 major_should_finish_concurrent_collection (void)
2608 SGEN_ASSERT (0, sgen_gray_object_queue_is_empty (&gray_queue), "Why is the gray queue not empty before we have started doing anything?");
2609 return sgen_workers_all_done ();
2613 major_update_concurrent_collection (void)
2615 TV_DECLARE (total_start);
2616 TV_DECLARE (total_end);
2618 TV_GETTIME (total_start);
2620 MONO_GC_CONCURRENT_UPDATE_FINISH_BEGIN (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
2621 binary_protocol_concurrent_update ();
2623 major_collector.update_cardtable_mod_union ();
2624 sgen_los_update_cardtable_mod_union ();
2626 MONO_GC_CONCURRENT_UPDATE_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
2628 TV_GETTIME (total_end);
2629 gc_stats.major_gc_time += TV_ELAPSED (total_start, total_end);
2633 major_finish_concurrent_collection (gboolean forced)
2635 TV_DECLARE (total_start);
2636 TV_DECLARE (total_end);
2637 gboolean late_pinned;
2638 SgenGrayQueue unpin_queue;
2639 memset (&unpin_queue, 0, sizeof (unpin_queue));
2641 TV_GETTIME (total_start);
2643 MONO_GC_CONCURRENT_UPDATE_FINISH_BEGIN (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
2644 binary_protocol_concurrent_finish ();
2647 * The major collector can add global remsets which are processed in the finishing
2648 * nursery collection, below. That implies that the workers must have finished
2649 * marking before the nursery collection is allowed to run, otherwise we might miss
2652 sgen_workers_wait ();
2654 SGEN_TV_GETTIME (time_major_conc_collection_end);
2655 gc_stats.major_gc_time_concurrent += SGEN_TV_ELAPSED (time_major_conc_collection_start, time_major_conc_collection_end);
2657 major_collector.update_cardtable_mod_union ();
2658 sgen_los_update_cardtable_mod_union ();
2660 late_pinned = collect_nursery (&unpin_queue, TRUE);
2662 if (mod_union_consistency_check)
2663 sgen_check_mod_union_consistency ();
2665 current_collection_generation = GENERATION_OLD;
2666 major_finish_collection ("finishing", -1, forced, late_pinned);
2668 if (whole_heap_check_before_collection)
2669 sgen_check_whole_heap (FALSE);
2671 unpin_objects_from_queue (&unpin_queue);
2672 sgen_gray_object_queue_deinit (&unpin_queue);
2674 MONO_GC_CONCURRENT_FINISH_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
2676 TV_GETTIME (total_end);
2677 gc_stats.major_gc_time += TV_ELAPSED (total_start, total_end) - TV_ELAPSED (last_minor_collection_start_tv, last_minor_collection_end_tv);
2679 current_collection_generation = -1;
2683 * Ensure an allocation request for @size will succeed by freeing enough memory.
2685 * LOCKING: The GC lock MUST be held.
2688 sgen_ensure_free_space (size_t size)
2690 int generation_to_collect = -1;
2691 const char *reason = NULL;
2693 if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
2694 if (sgen_need_major_collection (size)) {
2695 reason = "LOS overflow";
2696 generation_to_collect = GENERATION_OLD;
2699 if (degraded_mode) {
2700 if (sgen_need_major_collection (size)) {
2701 reason = "Degraded mode overflow";
2702 generation_to_collect = GENERATION_OLD;
2704 } else if (sgen_need_major_collection (size)) {
2705 reason = "Minor allowance";
2706 generation_to_collect = GENERATION_OLD;
2708 generation_to_collect = GENERATION_NURSERY;
2709 reason = "Nursery full";
2713 if (generation_to_collect == -1) {
2714 if (concurrent_collection_in_progress && sgen_workers_all_done ()) {
2715 generation_to_collect = GENERATION_OLD;
2716 reason = "Finish concurrent collection";
2720 if (generation_to_collect == -1)
2722 sgen_perform_collection (size, generation_to_collect, reason, FALSE);
2726 * LOCKING: Assumes the GC lock is held.
2729 sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish)
2731 TV_DECLARE (gc_start);
2732 TV_DECLARE (gc_end);
2733 TV_DECLARE (gc_total_start);
2734 TV_DECLARE (gc_total_end);
2735 GGTimingInfo infos [2];
2736 int overflow_generation_to_collect = -1;
2737 int oldest_generation_collected = generation_to_collect;
2738 const char *overflow_reason = NULL;
2740 MONO_GC_REQUESTED (generation_to_collect, requested_size, wait_to_finish ? 1 : 0);
2742 binary_protocol_collection_force (generation_to_collect);
2744 SGEN_ASSERT (0, generation_to_collect == GENERATION_NURSERY || generation_to_collect == GENERATION_OLD, "What generation is this?");
2746 mono_profiler_gc_event (MONO_GC_EVENT_START, generation_to_collect);
2748 TV_GETTIME (gc_start);
2750 sgen_stop_world (generation_to_collect);
2752 TV_GETTIME (gc_total_start);
2754 if (concurrent_collection_in_progress) {
2756 * We update the concurrent collection. If it finished, we're done. If
2757 * not, and we've been asked to do a nursery collection, we do that.
2759 gboolean finish = major_should_finish_concurrent_collection () || (wait_to_finish && generation_to_collect == GENERATION_OLD);
2762 major_finish_concurrent_collection (wait_to_finish);
2763 oldest_generation_collected = GENERATION_OLD;
2765 sgen_workers_signal_start_nursery_collection_and_wait ();
2767 major_update_concurrent_collection ();
2768 if (generation_to_collect == GENERATION_NURSERY)
2769 collect_nursery (NULL, FALSE);
2771 sgen_workers_signal_finish_nursery_collection ();
2778 * If we've been asked to do a major collection, and the major collector wants to
2779 * run synchronously (to evacuate), we set the flag to do that.
2781 if (generation_to_collect == GENERATION_OLD &&
2782 allow_synchronous_major &&
2783 major_collector.want_synchronous_collection &&
2784 *major_collector.want_synchronous_collection) {
2785 wait_to_finish = TRUE;
2788 SGEN_ASSERT (0, !concurrent_collection_in_progress, "Why did this not get handled above?");
2791 * There's no concurrent collection in progress. Collect the generation we're asked
2792 * to collect. If the major collector is concurrent and we're not forced to wait,
2793 * start a concurrent collection.
2795 // FIXME: extract overflow reason
2796 if (generation_to_collect == GENERATION_NURSERY) {
2797 if (collect_nursery (NULL, FALSE)) {
2798 overflow_generation_to_collect = GENERATION_OLD;
2799 overflow_reason = "Minor overflow";
2802 if (major_collector.is_concurrent && !wait_to_finish) {
2803 collect_nursery (NULL, FALSE);
2804 major_start_concurrent_collection (reason);
2805 // FIXME: set infos[0] properly
2809 if (major_do_collection (reason, wait_to_finish)) {
2810 overflow_generation_to_collect = GENERATION_NURSERY;
2811 overflow_reason = "Excessive pinning";
2815 TV_GETTIME (gc_end);
2817 memset (infos, 0, sizeof (infos));
2818 infos [0].generation = generation_to_collect;
2819 infos [0].reason = reason;
2820 infos [0].is_overflow = FALSE;
2821 infos [1].generation = -1;
2822 infos [0].total_time = SGEN_TV_ELAPSED (gc_start, gc_end);
2824 SGEN_ASSERT (0, !concurrent_collection_in_progress, "Why did this not get handled above?");
2826 if (overflow_generation_to_collect != -1) {
2828 * We need to do an overflow collection, either because we ran out of memory
2829 * or the nursery is fully pinned.
2832 mono_profiler_gc_event (MONO_GC_EVENT_START, overflow_generation_to_collect);
2833 infos [1].generation = overflow_generation_to_collect;
2834 infos [1].reason = overflow_reason;
2835 infos [1].is_overflow = TRUE;
2836 infos [1].total_time = gc_end;
2838 if (overflow_generation_to_collect == GENERATION_NURSERY)
2839 collect_nursery (NULL, FALSE);
2841 major_do_collection (overflow_reason, wait_to_finish);
2843 TV_GETTIME (gc_end);
2844 infos [1].total_time = SGEN_TV_ELAPSED (infos [1].total_time, gc_end);
2846 /* keep events symmetric */
2847 mono_profiler_gc_event (MONO_GC_EVENT_END, overflow_generation_to_collect);
2849 oldest_generation_collected = MAX (oldest_generation_collected, overflow_generation_to_collect);
2852 SGEN_LOG (2, "Heap size: %lu, LOS size: %lu", (unsigned long)mono_gc_get_heap_size (), (unsigned long)los_memory_usage);
2854 /* this also sets the proper pointers for the next allocation */
2855 if (generation_to_collect == GENERATION_NURSERY && !sgen_can_alloc_size (requested_size)) {
2856 /* TypeBuilder and MonoMethod are killing mcs with fragmentation */
2857 SGEN_LOG (1, "nursery collection didn't find enough room for %zd alloc (%zd pinned)", requested_size, sgen_get_pinned_count ());
2858 sgen_dump_pin_queue ();
2863 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2865 TV_GETTIME (gc_total_end);
2866 time_max = MAX (time_max, TV_ELAPSED (gc_total_start, gc_total_end));
2868 sgen_restart_world (oldest_generation_collected, infos);
2870 mono_profiler_gc_event (MONO_GC_EVENT_END, generation_to_collect);
2874 * ######################################################################
2875 * ######## Memory allocation from the OS
2876 * ######################################################################
2877 * This section of code deals with getting memory from the OS and
2878 * allocating memory for GC-internal data structures.
2879 * Internal memory can be handled with a freelist for small objects.
2885 G_GNUC_UNUSED static void
2886 report_internal_mem_usage (void)
2888 printf ("Internal memory usage:\n");
2889 sgen_report_internal_mem_usage ();
2890 printf ("Pinned memory usage:\n");
2891 major_collector.report_pinned_memory_usage ();
2895 * ######################################################################
2896 * ######## Finalization support
2897 * ######################################################################
2901 * If the object has been forwarded it means it's still referenced from a root.
2902 * If it is pinned it's still alive as well.
2903 * A LOS object is only alive if we have pinned it.
2904 * Return TRUE if @obj is ready to be finalized.
2906 static inline gboolean
2907 sgen_is_object_alive (void *object)
2909 if (ptr_in_nursery (object))
2910 return sgen_nursery_is_object_alive (object);
2912 return sgen_major_is_object_alive (object);
2916 * This function returns true if @object is either alive and belongs to the
2917 * current collection - major collections are full heap, so old gen objects
2918 * are never alive during a minor collection.
2921 sgen_is_object_alive_and_on_current_collection (char *object)
2923 if (ptr_in_nursery (object))
2924 return sgen_nursery_is_object_alive (object);
2926 if (current_collection_generation == GENERATION_NURSERY)
2929 return sgen_major_is_object_alive (object);
2934 sgen_gc_is_object_ready_for_finalization (void *object)
2936 return !sgen_is_object_alive (object);
2940 sgen_queue_finalization_entry (MonoObject *obj)
2942 FinalizeReadyEntry *entry = sgen_alloc_internal (INTERNAL_MEM_FINALIZE_READY_ENTRY);
2943 gboolean critical = sgen_client_object_has_critical_finalizer (obj);
2944 entry->object = obj;
2946 entry->next = critical_fin_list;
2947 critical_fin_list = entry;
2949 entry->next = fin_ready_list;
2950 fin_ready_list = entry;
2953 sgen_client_object_queued_for_finalization (obj);
2955 #ifdef ENABLE_DTRACE
2956 if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
2957 int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
2958 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
2959 MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
2960 vt->klass->name_space, vt->klass->name, gen, critical);
2966 sgen_object_is_live (void *obj)
2968 return sgen_is_object_alive_and_on_current_collection (obj);
2972 mono_gc_invoke_finalizers (void)
2974 FinalizeReadyEntry *entry = NULL;
2975 gboolean entry_is_critical = FALSE;
2978 /* FIXME: batch to reduce lock contention */
2979 while (fin_ready_list || critical_fin_list) {
2983 FinalizeReadyEntry **list = entry_is_critical ? &critical_fin_list : &fin_ready_list;
2985 /* We have finalized entry in the last
2986 interation, now we need to remove it from
2989 *list = entry->next;
2991 FinalizeReadyEntry *e = *list;
2992 while (e->next != entry)
2994 e->next = entry->next;
2996 sgen_free_internal (entry, INTERNAL_MEM_FINALIZE_READY_ENTRY);
3000 /* Now look for the first non-null entry. */
3001 for (entry = fin_ready_list; entry && !entry->object; entry = entry->next)
3004 entry_is_critical = FALSE;
3006 entry_is_critical = TRUE;
3007 for (entry = critical_fin_list; entry && !entry->object; entry = entry->next)
3012 g_assert (entry->object);
3013 num_ready_finalizers--;
3014 obj = entry->object;
3015 entry->object = NULL;
3016 SGEN_LOG (7, "Finalizing object %p (%s)", obj, safe_name (obj));
3024 g_assert (entry->object == NULL);
3026 /* the object is on the stack so it is pinned */
3027 /*g_print ("Calling finalizer for object: %p (%s)\n", entry->object, safe_name (entry->object));*/
3028 mono_gc_run_finalize (obj, NULL);
3035 mono_gc_pending_finalizers (void)
3037 return fin_ready_list || critical_fin_list;
3041 * ######################################################################
3042 * ######## registered roots support
3043 * ######################################################################
3047 * We do not coalesce roots.
3050 mono_gc_register_root_inner (char *start, size_t size, void *descr, int root_type)
3052 RootRecord new_root;
3055 for (i = 0; i < ROOT_TYPE_NUM; ++i) {
3056 RootRecord *root = sgen_hash_table_lookup (&roots_hash [i], start);
3057 /* we allow changing the size and the descriptor (for thread statics etc) */
3059 size_t old_size = root->end_root - start;
3060 root->end_root = start + size;
3061 g_assert (((root->root_desc != 0) && (descr != NULL)) ||
3062 ((root->root_desc == 0) && (descr == NULL)));
3063 root->root_desc = (mword)descr;
3065 roots_size -= old_size;
3071 new_root.end_root = start + size;
3072 new_root.root_desc = (mword)descr;
3074 sgen_hash_table_replace (&roots_hash [root_type], start, &new_root, NULL);
3077 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);
3084 mono_gc_register_root (char *start, size_t size, void *descr)
3086 return mono_gc_register_root_inner (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED);
3090 mono_gc_register_root_wbarrier (char *start, size_t size, void *descr)
3092 return mono_gc_register_root_inner (start, size, descr, ROOT_TYPE_WBARRIER);
3096 mono_gc_deregister_root (char* addr)
3102 for (root_type = 0; root_type < ROOT_TYPE_NUM; ++root_type) {
3103 if (sgen_hash_table_remove (&roots_hash [root_type], addr, &root))
3104 roots_size -= (root.end_root - addr);
3110 * ######################################################################
3111 * ######## Thread handling (stop/start code)
3112 * ######################################################################
3115 unsigned int sgen_global_stop_count = 0;
3118 sgen_get_current_collection_generation (void)
3120 return current_collection_generation;
3124 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
3126 gc_callbacks = *callbacks;
3130 mono_gc_get_gc_callbacks ()
3132 return &gc_callbacks;
3135 /* Variables holding start/end nursery so it won't have to be passed at every call */
3136 static void *scan_area_arg_start, *scan_area_arg_end;
3139 mono_gc_conservatively_scan_area (void *start, void *end)
3141 conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
3145 mono_gc_scan_object (void *obj, void *gc_data)
3147 ScanCopyContext *ctx = gc_data;
3148 ctx->ops->copy_or_mark_object (&obj, ctx->queue);
3153 * Mark from thread stacks and registers.
3156 scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, ScanCopyContext ctx)
3158 SgenThreadInfo *info;
3160 scan_area_arg_start = start_nursery;
3161 scan_area_arg_end = end_nursery;
3163 FOREACH_THREAD (info) {
3165 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);
3168 if (info->gc_disabled) {
3169 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);
3172 if (!mono_thread_info_is_live (info)) {
3173 SGEN_LOG (3, "Skipping non-running thread %p, range: %p-%p, size: %td (state %x)", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, info->info.thread_state);
3176 g_assert (info->suspend_done);
3177 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 ());
3178 if (gc_callbacks.thread_mark_func && !conservative_stack_mark) {
3179 gc_callbacks.thread_mark_func (info->runtime_data, info->stack_start, info->stack_end, precise, &ctx);
3180 } else if (!precise) {
3181 if (!conservative_stack_mark) {
3182 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
3183 conservative_stack_mark = TRUE;
3185 conservatively_pin_objects_from (info->stack_start, info->stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
3190 conservatively_pin_objects_from ((void**)&info->ctx, (void**)&info->ctx + ARCH_NUM_REGS,
3191 start_nursery, end_nursery, PIN_TYPE_STACK);
3193 conservatively_pin_objects_from ((void**)&info->regs, (void**)&info->regs + ARCH_NUM_REGS,
3194 start_nursery, end_nursery, PIN_TYPE_STACK);
3197 } END_FOREACH_THREAD
3201 sgen_thread_register (SgenThreadInfo* info, void *addr)
3204 guint8 *staddr = NULL;
3206 #ifndef HAVE_KW_THREAD
3207 info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
3209 g_assert (!mono_native_tls_get_value (thread_info_key));
3210 mono_native_tls_set_value (thread_info_key, info);
3212 sgen_thread_info = info;
3215 #ifdef SGEN_POSIX_STW
3216 info->stop_count = -1;
3220 info->stack_start = NULL;
3221 info->stopped_ip = NULL;
3222 info->stopped_domain = NULL;
3224 memset (&info->ctx, 0, sizeof (MonoContext));
3226 memset (&info->regs, 0, sizeof (info->regs));
3229 sgen_init_tlab_info (info);
3231 binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
3233 /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
3234 mono_thread_info_get_stack_bounds (&staddr, &stsize);
3237 info->stack_start_limit = staddr;
3239 info->stack_end = staddr + stsize;
3241 gsize stack_bottom = (gsize)addr;
3242 stack_bottom += 4095;
3243 stack_bottom &= ~4095;
3244 info->stack_end = (char*)stack_bottom;
3247 #ifdef HAVE_KW_THREAD
3248 stack_end = info->stack_end;
3251 SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->stack_end);
3253 if (gc_callbacks.thread_attach_func)
3254 info->runtime_data = gc_callbacks.thread_attach_func ();
3259 sgen_thread_detach (SgenThreadInfo *p)
3261 /* If a delegate is passed to native code and invoked on a thread we dont
3262 * know about, the jit will register it with mono_jit_thread_attach, but
3263 * we have no way of knowing when that thread goes away. SGen has a TSD
3264 * so we assume that if the domain is still registered, we can detach
3267 if (mono_domain_get ())
3268 mono_thread_detach_internal (mono_thread_internal_current ());
3272 sgen_thread_unregister (SgenThreadInfo *p)
3274 MonoNativeThreadId tid;
3276 tid = mono_thread_info_get_tid (p);
3277 binary_protocol_thread_unregister ((gpointer)tid);
3278 SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
3280 #ifndef HAVE_KW_THREAD
3281 mono_native_tls_set_value (thread_info_key, NULL);
3283 sgen_thread_info = NULL;
3286 if (p->info.runtime_thread)
3287 mono_threads_add_joinable_thread ((gpointer)tid);
3289 if (gc_callbacks.thread_detach_func) {
3290 gc_callbacks.thread_detach_func (p->runtime_data);
3291 p->runtime_data = NULL;
3297 sgen_thread_attach (SgenThreadInfo *info)
3300 /*this is odd, can we get attached before the gc is inited?*/
3304 if (gc_callbacks.thread_attach_func && !info->runtime_data)
3305 info->runtime_data = gc_callbacks.thread_attach_func ();
3308 mono_gc_register_thread (void *baseptr)
3310 return mono_thread_info_attach (baseptr) != NULL;
3314 * mono_gc_set_stack_end:
3316 * Set the end of the current threads stack to STACK_END. The stack space between
3317 * STACK_END and the real end of the threads stack will not be scanned during collections.
3320 mono_gc_set_stack_end (void *stack_end)
3322 SgenThreadInfo *info;
3325 info = mono_thread_info_current ();
3327 g_assert (stack_end < info->stack_end);
3328 info->stack_end = stack_end;
3333 #if USE_PTHREAD_INTERCEPT
3337 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
3339 return pthread_create (new_thread, attr, start_routine, arg);
3343 mono_gc_pthread_join (pthread_t thread, void **retval)
3345 return pthread_join (thread, retval);
3349 mono_gc_pthread_detach (pthread_t thread)
3351 return pthread_detach (thread);
3355 mono_gc_pthread_exit (void *retval)
3357 mono_thread_info_detach ();
3358 pthread_exit (retval);
3359 g_assert_not_reached ();
3362 #endif /* USE_PTHREAD_INTERCEPT */
3365 * ######################################################################
3366 * ######## Write barriers
3367 * ######################################################################
3371 * Note: the write barriers first do the needed GC work and then do the actual store:
3372 * this way the value is visible to the conservative GC scan after the write barrier
3373 * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
3374 * the conservative scan, otherwise by the remembered set scan.
3377 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
3379 HEAVY_STAT (++stat_wbarrier_set_field);
3380 if (ptr_in_nursery (field_ptr)) {
3381 *(void**)field_ptr = value;
3384 SGEN_LOG (8, "Adding remset at %p", field_ptr);
3386 binary_protocol_wbarrier (field_ptr, value, value->vtable);
3388 remset.wbarrier_set_field (obj, field_ptr, value);
3392 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
3394 HEAVY_STAT (++stat_wbarrier_arrayref_copy);
3395 /*This check can be done without taking a lock since dest_ptr array is pinned*/
3396 if (ptr_in_nursery (dest_ptr) || count <= 0) {
3397 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
3401 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
3402 if (binary_protocol_is_heavy_enabled ()) {
3404 for (i = 0; i < count; ++i) {
3405 gpointer dest = (gpointer*)dest_ptr + i;
3406 gpointer obj = *((gpointer*)src_ptr + i);
3408 binary_protocol_wbarrier (dest, obj, (gpointer)LOAD_VTABLE (obj));
3413 remset.wbarrier_arrayref_copy (dest_ptr, src_ptr, count);
3417 mono_gc_wbarrier_generic_nostore (gpointer ptr)
3421 HEAVY_STAT (++stat_wbarrier_generic_store);
3423 sgen_client_wbarrier_generic_nostore_check (ptr);
3425 obj = *(gpointer*)ptr;
3427 binary_protocol_wbarrier (ptr, obj, (gpointer)LOAD_VTABLE (obj));
3430 * We need to record old->old pointer locations for the
3431 * concurrent collector.
3433 if (!ptr_in_nursery (obj) && !concurrent_collection_in_progress) {
3434 SGEN_LOG (8, "Skipping remset at %p", ptr);
3438 SGEN_LOG (8, "Adding remset at %p", ptr);
3440 remset.wbarrier_generic_nostore (ptr);
3444 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
3446 SGEN_LOG (8, "Wbarrier store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
3447 SGEN_UPDATE_REFERENCE_ALLOW_NULL (ptr, value);
3448 if (ptr_in_nursery (value))
3449 mono_gc_wbarrier_generic_nostore (ptr);
3450 sgen_dummy_use (value);
3453 /* Same as mono_gc_wbarrier_generic_store () but performs the store
3454 * as an atomic operation with release semantics.
3457 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, MonoObject *value)
3459 HEAVY_STAT (++stat_wbarrier_generic_store_atomic);
3461 SGEN_LOG (8, "Wbarrier atomic store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
3463 InterlockedWritePointer (ptr, value);
3465 if (ptr_in_nursery (value))
3466 mono_gc_wbarrier_generic_nostore (ptr);
3468 sgen_dummy_use (value);
3471 void mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
3473 mword *dest = _dest;
3478 mono_gc_wbarrier_generic_store (dest, (MonoObject*)*src);
3480 SGEN_UPDATE_REFERENCE_ALLOW_NULL (dest, *src);
3483 size -= SIZEOF_VOID_P;
3489 * ######################################################################
3490 * ######## Other mono public interface functions.
3491 * ######################################################################
3494 #define REFS_SIZE 128
3497 MonoGCReferences callback;
3501 MonoObject *refs [REFS_SIZE];
3502 uintptr_t offsets [REFS_SIZE];
3506 #define HANDLE_PTR(ptr,obj) do { \
3508 if (hwi->count == REFS_SIZE) { \
3509 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data); \
3513 hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start; \
3514 hwi->refs [hwi->count++] = *(ptr); \
3519 collect_references (HeapWalkInfo *hwi, char *start, size_t size)
3521 mword desc = sgen_obj_get_descriptor (start);
3523 #include "sgen-scan-object.h"
3527 walk_references (char *start, size_t size, void *data)
3529 HeapWalkInfo *hwi = data;
3532 collect_references (hwi, start, size);
3533 if (hwi->count || !hwi->called)
3534 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
3538 * mono_gc_walk_heap:
3539 * @flags: flags for future use
3540 * @callback: a function pointer called for each object in the heap
3541 * @data: a user data pointer that is passed to callback
3543 * This function can be used to iterate over all the live objects in the heap:
3544 * for each object, @callback is invoked, providing info about the object's
3545 * location in memory, its class, its size and the objects it references.
3546 * For each referenced object it's offset from the object address is
3547 * reported in the offsets array.
3548 * The object references may be buffered, so the callback may be invoked
3549 * multiple times for the same object: in all but the first call, the size
3550 * argument will be zero.
3551 * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
3552 * profiler event handler.
3554 * Returns: a non-zero value if the GC doesn't support heap walking
3557 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
3562 hwi.callback = callback;
3565 sgen_clear_nursery_fragments ();
3566 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE);
3568 major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
3569 sgen_los_iterate_objects (walk_references, &hwi);
3575 mono_gc_collect (int generation)
3580 sgen_perform_collection (0, generation, "user request", TRUE);
3585 mono_gc_max_generation (void)
3591 mono_gc_collection_count (int generation)
3593 if (generation == 0)
3594 return gc_stats.minor_gc_count;
3595 return gc_stats.major_gc_count;
3599 mono_gc_get_used_size (void)
3603 tot = los_memory_usage;
3604 tot += nursery_section->next_data - nursery_section->data;
3605 tot += major_collector.get_used_size ();
3606 /* FIXME: account for pinned objects */
3612 mono_gc_get_los_limit (void)
3614 return MAX_SMALL_OBJ_SIZE;
3618 mono_gc_user_markers_supported (void)
3624 mono_object_is_alive (MonoObject* o)
3630 mono_gc_get_generation (MonoObject *obj)
3632 if (ptr_in_nursery (obj))
3638 mono_gc_enable_events (void)
3643 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
3645 sgen_register_disappearing_link (obj, link_addr, track, FALSE);
3649 mono_gc_weak_link_remove (void **link_addr, gboolean track)
3651 sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
3655 mono_gc_weak_link_get (void **link_addr)
3657 void * volatile *link_addr_volatile;
3661 link_addr_volatile = link_addr;
3662 ptr = (void*)*link_addr_volatile;
3664 * At this point we have a hidden pointer. If the GC runs
3665 * here, it will not recognize the hidden pointer as a
3666 * reference, and if the object behind it is not referenced
3667 * elsewhere, it will be freed. Once the world is restarted
3668 * we reveal the pointer, giving us a pointer to a freed
3669 * object. To make sure we don't return it, we load the
3670 * hidden pointer again. If it's still the same, we can be
3671 * sure the object reference is valid.
3674 obj = (MonoObject*) REVEAL_POINTER (ptr);
3678 mono_memory_barrier ();
3681 * During the second bridge processing step the world is
3682 * running again. That step processes all weak links once
3683 * more to null those that refer to dead objects. Before that
3684 * is completed, those links must not be followed, so we
3685 * conservatively wait for bridge processing when any weak
3686 * link is dereferenced.
3688 if (G_UNLIKELY (bridge_processing_in_progress))
3689 mono_gc_wait_for_bridge_processing ();
3691 if ((void*)*link_addr_volatile != ptr)
3698 mono_gc_set_allow_synchronous_major (gboolean flag)
3700 if (!major_collector.is_concurrent)
3703 allow_synchronous_major = flag;
3708 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
3712 result = func (data);
3713 UNLOCK_INTERRUPTION;
3718 mono_gc_is_gc_thread (void)
3722 result = mono_thread_info_current () != NULL;
3728 is_critical_method (MonoMethod *method)
3730 return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
3734 sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...)
3738 va_start (ap, description_format);
3740 fprintf (stderr, "Warning: In environment variable `%s': ", env_var);
3741 vfprintf (stderr, description_format, ap);
3743 fprintf (stderr, " - %s", fallback);
3744 fprintf (stderr, "\n");
3750 parse_double_in_interval (const char *env_var, const char *opt_name, const char *opt, double min, double max, double *result)
3753 double val = strtod (opt, &endptr);
3754 if (endptr == opt) {
3755 sgen_env_var_error (env_var, "Using default value.", "`%s` must be a number.", opt_name);
3758 else if (val < min || val > max) {
3759 sgen_env_var_error (env_var, "Using default value.", "`%s` must be between %.2f - %.2f.", opt_name, min, max);
3767 thread_in_critical_region (SgenThreadInfo *info)
3769 return info->in_critical_region;
3773 mono_gc_base_init (void)
3775 MonoThreadInfoCallbacks cb;
3778 char *major_collector_opt = NULL;
3779 char *minor_collector_opt = NULL;
3780 size_t max_heap = 0;
3781 size_t soft_limit = 0;
3784 gboolean debug_print_allowance = FALSE;
3785 double allowance_ratio = 0, save_target = 0;
3786 gboolean cement_enabled = TRUE;
3788 mono_counters_init ();
3791 result = InterlockedCompareExchange (&gc_initialized, -1, 0);
3794 /* already inited */
3797 /* being inited by another thread */
3801 /* we will init it */
3804 g_assert_not_reached ();
3806 } while (result != 0);
3808 SGEN_TV_GETTIME (sgen_init_timestamp);
3810 LOCK_INIT (gc_mutex);
3812 pagesize = mono_pagesize ();
3813 gc_debug_file = stderr;
3815 cb.thread_register = sgen_thread_register;
3816 cb.thread_detach = sgen_thread_detach;
3817 cb.thread_unregister = sgen_thread_unregister;
3818 cb.thread_attach = sgen_thread_attach;
3819 cb.mono_method_is_critical = (gpointer)is_critical_method;
3820 cb.mono_thread_in_critical_region = thread_in_critical_region;
3822 cb.thread_exit = mono_gc_pthread_exit;
3823 cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
3826 mono_threads_init (&cb, sizeof (SgenThreadInfo));
3828 LOCK_INIT (sgen_interruption_mutex);
3830 if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
3831 opts = g_strsplit (env, ",", -1);
3832 for (ptr = opts; *ptr; ++ptr) {
3834 if (g_str_has_prefix (opt, "major=")) {
3835 opt = strchr (opt, '=') + 1;
3836 major_collector_opt = g_strdup (opt);
3837 } else if (g_str_has_prefix (opt, "minor=")) {
3838 opt = strchr (opt, '=') + 1;
3839 minor_collector_opt = g_strdup (opt);
3847 sgen_init_internal_allocator ();
3848 sgen_init_nursery_allocator ();
3849 sgen_init_fin_weak_hash ();
3851 sgen_init_hash_table ();
3852 sgen_init_descriptors ();
3853 sgen_init_gray_queues ();
3854 sgen_init_allocator ();
3856 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_SECTION, SGEN_SIZEOF_GC_MEM_SECTION);
3857 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_FINALIZE_READY_ENTRY, sizeof (FinalizeReadyEntry));
3858 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_GRAY_QUEUE, sizeof (GrayQueueSection));
3860 sgen_client_init ();
3862 #ifndef HAVE_KW_THREAD
3863 mono_native_tls_alloc (&thread_info_key, NULL);
3864 #if defined(__APPLE__) || defined (HOST_WIN32)
3866 * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
3867 * where the two are the same.
3869 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, thread_info_key);
3873 int tls_offset = -1;
3874 MONO_THREAD_VAR_OFFSET (sgen_thread_info, tls_offset);
3875 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, tls_offset);
3880 * This needs to happen before any internal allocations because
3881 * it inits the small id which is required for hazard pointer
3886 mono_thread_info_attach (&dummy);
3888 if (!minor_collector_opt) {
3889 sgen_simple_nursery_init (&sgen_minor_collector);
3891 if (!strcmp (minor_collector_opt, "simple")) {
3893 sgen_simple_nursery_init (&sgen_minor_collector);
3894 } else if (!strcmp (minor_collector_opt, "split")) {
3895 sgen_split_nursery_init (&sgen_minor_collector);
3897 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `simple` instead.", "Unknown minor collector `%s'.", minor_collector_opt);
3898 goto use_simple_nursery;
3902 if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep")) {
3903 use_marksweep_major:
3904 sgen_marksweep_init (&major_collector);
3905 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-conc")) {
3906 sgen_marksweep_conc_init (&major_collector);
3908 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `marksweep` instead.", "Unknown major collector `%s'.", major_collector_opt);
3909 goto use_marksweep_major;
3912 ///* Keep this the default for now */
3913 /* Precise marking is broken on all supported targets. Disable until fixed. */
3914 conservative_stack_mark = TRUE;
3916 sgen_nursery_size = DEFAULT_NURSERY_SIZE;
3918 if (major_collector.is_concurrent)
3919 cement_enabled = FALSE;
3922 gboolean usage_printed = FALSE;
3924 for (ptr = opts; *ptr; ++ptr) {
3926 if (!strcmp (opt, ""))
3928 if (g_str_has_prefix (opt, "major="))
3930 if (g_str_has_prefix (opt, "minor="))
3932 if (g_str_has_prefix (opt, "max-heap-size=")) {
3933 size_t max_heap_candidate = 0;
3934 opt = strchr (opt, '=') + 1;
3935 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap_candidate)) {
3936 max_heap = (max_heap_candidate + mono_pagesize () - 1) & ~(size_t)(mono_pagesize () - 1);
3937 if (max_heap != max_heap_candidate)
3938 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Rounding up.", "`max-heap-size` size must be a multiple of %d.", mono_pagesize ());
3940 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`max-heap-size` must be an integer.");
3944 if (g_str_has_prefix (opt, "soft-heap-limit=")) {
3945 opt = strchr (opt, '=') + 1;
3946 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &soft_limit)) {
3947 if (soft_limit <= 0) {
3948 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be positive.");
3952 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be an integer.");
3956 if (g_str_has_prefix (opt, "stack-mark=")) {
3957 opt = strchr (opt, '=') + 1;
3958 if (!strcmp (opt, "precise")) {
3959 conservative_stack_mark = FALSE;
3960 } else if (!strcmp (opt, "conservative")) {
3961 conservative_stack_mark = TRUE;
3963 sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
3964 "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
3968 if (g_str_has_prefix (opt, "bridge-implementation=")) {
3969 opt = strchr (opt, '=') + 1;
3970 sgen_set_bridge_implementation (opt);
3973 if (g_str_has_prefix (opt, "toggleref-test")) {
3974 sgen_register_test_toggleref_callback ();
3979 if (g_str_has_prefix (opt, "nursery-size=")) {
3981 opt = strchr (opt, '=') + 1;
3982 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &val)) {
3983 if ((val & (val - 1))) {
3984 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be a power of two.");
3988 if (val < SGEN_MAX_NURSERY_WASTE) {
3989 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.",
3990 "`nursery-size` must be at least %d bytes.", SGEN_MAX_NURSERY_WASTE);
3994 sgen_nursery_size = val;
3995 sgen_nursery_bits = 0;
3996 while (ONE_P << (++ sgen_nursery_bits) != sgen_nursery_size)
3999 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be an integer.");
4005 if (g_str_has_prefix (opt, "save-target-ratio=")) {
4007 opt = strchr (opt, '=') + 1;
4008 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "save-target-ratio", opt,
4009 SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO, &val)) {
4014 if (g_str_has_prefix (opt, "default-allowance-ratio=")) {
4016 opt = strchr (opt, '=') + 1;
4017 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "default-allowance-ratio", opt,
4018 SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, &val)) {
4019 allowance_ratio = val;
4023 if (g_str_has_prefix (opt, "allow-synchronous-major=")) {
4024 if (!major_collector.is_concurrent) {
4025 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`allow-synchronous-major` is only valid for the concurrent major collector.");
4029 opt = strchr (opt, '=') + 1;
4031 if (!strcmp (opt, "yes")) {
4032 allow_synchronous_major = TRUE;
4033 } else if (!strcmp (opt, "no")) {
4034 allow_synchronous_major = FALSE;
4036 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`allow-synchronous-major` must be either `yes' or `no'.");
4041 if (!strcmp (opt, "cementing")) {
4042 cement_enabled = TRUE;
4045 if (!strcmp (opt, "no-cementing")) {
4046 cement_enabled = FALSE;
4050 if (major_collector.handle_gc_param && major_collector.handle_gc_param (opt))
4053 if (sgen_minor_collector.handle_gc_param && sgen_minor_collector.handle_gc_param (opt))
4056 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Unknown option `%s`.", opt);
4061 fprintf (stderr, "\n%s must be a comma-delimited list of one or more of the following:\n", MONO_GC_PARAMS_NAME);
4062 fprintf (stderr, " max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4063 fprintf (stderr, " soft-heap-limit=n (where N is an integer, possibly with a k, m or a g suffix)\n");
4064 fprintf (stderr, " nursery-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4065 fprintf (stderr, " major=COLLECTOR (where COLLECTOR is `marksweep', `marksweep-conc', `marksweep-par')\n");
4066 fprintf (stderr, " minor=COLLECTOR (where COLLECTOR is `simple' or `split')\n");
4067 fprintf (stderr, " wbarrier=WBARRIER (where WBARRIER is `remset' or `cardtable')\n");
4068 fprintf (stderr, " stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
4069 fprintf (stderr, " [no-]cementing\n");
4070 if (major_collector.is_concurrent)
4071 fprintf (stderr, " allow-synchronous-major=FLAG (where FLAG is `yes' or `no')\n");
4072 if (major_collector.print_gc_param_usage)
4073 major_collector.print_gc_param_usage ();
4074 if (sgen_minor_collector.print_gc_param_usage)
4075 sgen_minor_collector.print_gc_param_usage ();
4076 fprintf (stderr, " Experimental options:\n");
4077 fprintf (stderr, " save-target-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
4078 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);
4079 fprintf (stderr, "\n");
4081 usage_printed = TRUE;
4086 if (major_collector_opt)
4087 g_free (major_collector_opt);
4089 if (minor_collector_opt)
4090 g_free (minor_collector_opt);
4094 if (major_collector.is_concurrent && cement_enabled) {
4095 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`cementing` is not supported on concurrent major collectors.");
4096 cement_enabled = FALSE;
4099 sgen_cement_init (cement_enabled);
4101 if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
4102 gboolean usage_printed = FALSE;
4104 opts = g_strsplit (env, ",", -1);
4105 for (ptr = opts; ptr && *ptr; ptr ++) {
4107 if (!strcmp (opt, ""))
4109 if (opt [0] >= '0' && opt [0] <= '9') {
4110 gc_debug_level = atoi (opt);
4115 char *rf = g_strdup_printf ("%s.%d", opt, mono_process_current_pid ());
4116 gc_debug_file = fopen (rf, "wb");
4118 gc_debug_file = stderr;
4121 } else if (!strcmp (opt, "print-allowance")) {
4122 debug_print_allowance = TRUE;
4123 } else if (!strcmp (opt, "print-pinning")) {
4124 sgen_pin_stats_enable ();
4125 } else if (!strcmp (opt, "verify-before-allocs")) {
4126 verify_before_allocs = 1;
4127 has_per_allocation_action = TRUE;
4128 } else if (g_str_has_prefix (opt, "verify-before-allocs=")) {
4129 char *arg = strchr (opt, '=') + 1;
4130 verify_before_allocs = atoi (arg);
4131 has_per_allocation_action = TRUE;
4132 } else if (!strcmp (opt, "collect-before-allocs")) {
4133 collect_before_allocs = 1;
4134 has_per_allocation_action = TRUE;
4135 } else if (g_str_has_prefix (opt, "collect-before-allocs=")) {
4136 char *arg = strchr (opt, '=') + 1;
4137 has_per_allocation_action = TRUE;
4138 collect_before_allocs = atoi (arg);
4139 } else if (!strcmp (opt, "verify-before-collections")) {
4140 whole_heap_check_before_collection = TRUE;
4141 } else if (!strcmp (opt, "check-at-minor-collections")) {
4142 consistency_check_at_minor_collection = TRUE;
4143 nursery_clear_policy = CLEAR_AT_GC;
4144 } else if (!strcmp (opt, "mod-union-consistency-check")) {
4145 if (!major_collector.is_concurrent) {
4146 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`mod-union-consistency-check` only works with concurrent major collector.");
4149 mod_union_consistency_check = TRUE;
4150 } else if (!strcmp (opt, "check-mark-bits")) {
4151 check_mark_bits_after_major_collection = TRUE;
4152 } else if (!strcmp (opt, "check-nursery-pinned")) {
4153 check_nursery_objects_pinned = TRUE;
4154 } else if (!strcmp (opt, "clear-at-gc")) {
4155 nursery_clear_policy = CLEAR_AT_GC;
4156 } else if (!strcmp (opt, "clear-nursery-at-gc")) {
4157 nursery_clear_policy = CLEAR_AT_GC;
4158 } else if (!strcmp (opt, "clear-at-tlab-creation")) {
4159 nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
4160 } else if (!strcmp (opt, "debug-clear-at-tlab-creation")) {
4161 nursery_clear_policy = CLEAR_AT_TLAB_CREATION_DEBUG;
4162 } else if (!strcmp (opt, "check-scan-starts")) {
4163 do_scan_starts_check = TRUE;
4164 } else if (!strcmp (opt, "verify-nursery-at-minor-gc")) {
4165 do_verify_nursery = TRUE;
4166 } else if (!strcmp (opt, "check-concurrent")) {
4167 if (!major_collector.is_concurrent) {
4168 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`check-concurrent` only works with concurrent major collectors.");
4171 do_concurrent_checks = TRUE;
4172 } else if (!strcmp (opt, "dump-nursery-at-minor-gc")) {
4173 do_dump_nursery_content = TRUE;
4174 } else if (!strcmp (opt, "no-managed-allocator")) {
4175 sgen_set_use_managed_allocator (FALSE);
4176 } else if (!strcmp (opt, "disable-minor")) {
4177 disable_minor_collections = TRUE;
4178 } else if (!strcmp (opt, "disable-major")) {
4179 disable_major_collections = TRUE;
4180 } else if (g_str_has_prefix (opt, "heap-dump=")) {
4181 char *filename = strchr (opt, '=') + 1;
4182 nursery_clear_policy = CLEAR_AT_GC;
4183 sgen_debug_enable_heap_dump (filename);
4184 } else if (g_str_has_prefix (opt, "binary-protocol=")) {
4185 char *filename = strchr (opt, '=') + 1;
4186 char *colon = strrchr (filename, ':');
4189 if (!mono_gc_parse_environment_string_extract_number (colon + 1, &limit)) {
4190 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring limit.", "Binary protocol file size limit must be an integer.");
4195 binary_protocol_init (filename, (long long)limit);
4196 } else if (!strcmp (opt, "nursery-canaries")) {
4197 do_verify_nursery = TRUE;
4198 sgen_set_use_managed_allocator (FALSE);
4199 enable_nursery_canaries = TRUE;
4200 } else if (!strcmp (opt, "do-not-finalize")) {
4201 do_not_finalize = TRUE;
4202 } else if (!strcmp (opt, "log-finalizers")) {
4203 log_finalizers = TRUE;
4204 } else if (!sgen_client_handle_gc_debug (opt) && !sgen_bridge_handle_gc_debug (opt)) {
4205 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "Unknown option `%s`.", opt);
4210 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);
4211 fprintf (stderr, "Valid <option>s are:\n");
4212 fprintf (stderr, " collect-before-allocs[=<n>]\n");
4213 fprintf (stderr, " verify-before-allocs[=<n>]\n");
4214 fprintf (stderr, " check-at-minor-collections\n");
4215 fprintf (stderr, " check-mark-bits\n");
4216 fprintf (stderr, " check-nursery-pinned\n");
4217 fprintf (stderr, " verify-before-collections\n");
4218 fprintf (stderr, " verify-nursery-at-minor-gc\n");
4219 fprintf (stderr, " dump-nursery-at-minor-gc\n");
4220 fprintf (stderr, " disable-minor\n");
4221 fprintf (stderr, " disable-major\n");
4222 fprintf (stderr, " check-concurrent\n");
4223 fprintf (stderr, " clear-[nursery-]at-gc\n");
4224 fprintf (stderr, " clear-at-tlab-creation\n");
4225 fprintf (stderr, " debug-clear-at-tlab-creation\n");
4226 fprintf (stderr, " check-scan-starts\n");
4227 fprintf (stderr, " no-managed-allocator\n");
4228 fprintf (stderr, " print-allowance\n");
4229 fprintf (stderr, " print-pinning\n");
4230 fprintf (stderr, " heap-dump=<filename>\n");
4231 fprintf (stderr, " binary-protocol=<filename>[:<file-size-limit>]\n");
4232 fprintf (stderr, " nursery-canaries\n");
4233 fprintf (stderr, " do-not-finalize\n");
4234 fprintf (stderr, " log-finalizers\n");
4235 sgen_client_print_gc_debug_usage ();
4236 sgen_bridge_print_gc_debug_usage ();
4237 fprintf (stderr, "\n");
4239 usage_printed = TRUE;
4245 if (check_mark_bits_after_major_collection)
4246 nursery_clear_policy = CLEAR_AT_GC;
4248 if (major_collector.post_param_init)
4249 major_collector.post_param_init (&major_collector);
4251 if (major_collector.needs_thread_pool)
4252 sgen_workers_init (1);
4254 sgen_memgov_init (max_heap, soft_limit, debug_print_allowance, allowance_ratio, save_target);
4256 memset (&remset, 0, sizeof (remset));
4258 sgen_card_table_init (&remset);
4264 mono_gc_get_gc_name (void)
4269 static MonoMethod *write_barrier_conc_method;
4270 static MonoMethod *write_barrier_noconc_method;
4273 sgen_is_critical_method (MonoMethod *method)
4275 return (method == write_barrier_conc_method || method == write_barrier_noconc_method || sgen_is_managed_allocator (method));
4279 sgen_has_critical_method (void)
4281 return write_barrier_conc_method || write_barrier_noconc_method || sgen_has_managed_allocator ();
4287 emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels, gboolean is_concurrent)
4289 int shifted_nursery_start = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4291 memset (nursery_check_return_labels, 0, sizeof (int) * 2);
4292 // if (ptr_in_nursery (ptr)) return;
4294 * Masking out the bits might be faster, but we would have to use 64 bit
4295 * immediates, which might be slower.
4297 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4298 mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_START);
4299 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
4300 mono_mb_emit_byte (mb, CEE_SHR_UN);
4301 mono_mb_emit_stloc (mb, shifted_nursery_start);
4303 mono_mb_emit_ldarg (mb, 0);
4304 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
4305 mono_mb_emit_byte (mb, CEE_SHR_UN);
4306 mono_mb_emit_ldloc (mb, shifted_nursery_start);
4307 nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
4309 if (!is_concurrent) {
4310 // if (!ptr_in_nursery (*ptr)) return;
4311 mono_mb_emit_ldarg (mb, 0);
4312 mono_mb_emit_byte (mb, CEE_LDIND_I);
4313 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
4314 mono_mb_emit_byte (mb, CEE_SHR_UN);
4315 mono_mb_emit_ldloc (mb, shifted_nursery_start);
4316 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
4322 mono_gc_get_specific_write_barrier (gboolean is_concurrent)
4325 MonoMethodBuilder *mb;
4326 MonoMethodSignature *sig;
4327 MonoMethod **write_barrier_method_addr;
4328 #ifdef MANAGED_WBARRIER
4329 int i, nursery_check_labels [2];
4331 #ifdef HAVE_KW_THREAD
4332 int stack_end_offset = -1;
4334 MONO_THREAD_VAR_OFFSET (stack_end, stack_end_offset);
4335 g_assert (stack_end_offset != -1);
4339 // FIXME: Maybe create a separate version for ctors (the branch would be
4340 // correctly predicted more times)
4342 write_barrier_method_addr = &write_barrier_conc_method;
4344 write_barrier_method_addr = &write_barrier_noconc_method;
4346 if (*write_barrier_method_addr)
4347 return *write_barrier_method_addr;
4349 /* Create the IL version of mono_gc_barrier_generic_store () */
4350 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4351 sig->ret = &mono_defaults.void_class->byval_arg;
4352 sig->params [0] = &mono_defaults.int_class->byval_arg;
4355 mb = mono_mb_new (mono_defaults.object_class, "wbarrier_conc", MONO_WRAPPER_WRITE_BARRIER);
4357 mb = mono_mb_new (mono_defaults.object_class, "wbarrier_noconc", MONO_WRAPPER_WRITE_BARRIER);
4360 #ifdef MANAGED_WBARRIER
4361 emit_nursery_check (mb, nursery_check_labels, is_concurrent);
4363 addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
4367 LDC_PTR sgen_cardtable
4369 address >> CARD_BITS
4373 if (SGEN_HAVE_OVERLAPPING_CARDS) {
4374 LDC_PTR card_table_mask
4381 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4382 mono_mb_emit_byte (mb, CEE_MONO_LDPTR_CARD_TABLE);
4383 mono_mb_emit_ldarg (mb, 0);
4384 mono_mb_emit_icon (mb, CARD_BITS);
4385 mono_mb_emit_byte (mb, CEE_SHR_UN);
4386 mono_mb_emit_byte (mb, CEE_CONV_I);
4387 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
4388 #if SIZEOF_VOID_P == 8
4389 mono_mb_emit_icon8 (mb, CARD_MASK);
4391 mono_mb_emit_icon (mb, CARD_MASK);
4393 mono_mb_emit_byte (mb, CEE_CONV_I);
4394 mono_mb_emit_byte (mb, CEE_AND);
4396 mono_mb_emit_byte (mb, CEE_ADD);
4397 mono_mb_emit_icon (mb, 1);
4398 mono_mb_emit_byte (mb, CEE_STIND_I1);
4401 for (i = 0; i < 2; ++i) {
4402 if (nursery_check_labels [i])
4403 mono_mb_patch_branch (mb, nursery_check_labels [i]);
4405 mono_mb_emit_byte (mb, CEE_RET);
4407 mono_mb_emit_ldarg (mb, 0);
4408 mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
4409 mono_mb_emit_byte (mb, CEE_RET);
4412 res = mono_mb_create_method (mb, sig, 16);
4416 if (*write_barrier_method_addr) {
4417 /* Already created */
4418 mono_free_method (res);
4420 /* double-checked locking */
4421 mono_memory_barrier ();
4422 *write_barrier_method_addr = res;
4426 return *write_barrier_method_addr;
4430 mono_gc_get_write_barrier (void)
4432 return mono_gc_get_specific_write_barrier (major_collector.is_concurrent);
4436 mono_gc_get_description (void)
4438 return g_strdup ("sgen");
4442 mono_gc_set_desktop_mode (void)
4447 mono_gc_is_moving (void)
4453 mono_gc_is_disabled (void)
4459 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
4466 sgen_get_nursery_clear_policy (void)
4468 return nursery_clear_policy;
4478 sgen_gc_unlock (void)
4480 gboolean try_free = sgen_try_free_some_memory;
4481 sgen_try_free_some_memory = FALSE;
4482 mono_mutex_unlock (&gc_mutex);
4483 MONO_GC_UNLOCKED ();
4485 mono_thread_hazardous_try_free_some ();
4489 sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
4491 major_collector.iterate_live_block_ranges (callback);
4495 sgen_get_major_collector (void)
4497 return &major_collector;
4500 void mono_gc_set_skip_thread (gboolean skip)
4502 SgenThreadInfo *info = mono_thread_info_current ();
4505 info->gc_disabled = skip;
4510 sgen_get_remset (void)
4516 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
4523 sgen_check_whole_heap_stw (void)
4525 sgen_stop_world (0);
4526 sgen_clear_nursery_fragments ();
4527 sgen_check_whole_heap (FALSE);
4528 sgen_restart_world (0, NULL);
4532 sgen_gc_event_moves (void)
4534 if (moved_objects_idx) {
4535 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
4536 moved_objects_idx = 0;
4541 sgen_timestamp (void)
4543 SGEN_TV_DECLARE (timestamp);
4544 SGEN_TV_GETTIME (timestamp);
4545 return SGEN_TV_ELAPSED (sgen_init_timestamp, timestamp);
4548 #endif /* HAVE_SGEN_GC */