update rx (mobile builds).
[mono-project.git] / mono / metadata / sgen-gc.c
blob07fc95c3794b38a6e0b83f5f2547ad5a60ea7b41
1 /*
2 * sgen-gc.c: Simple generational GC.
4 * Author:
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:
37 * 64 KB pinned space
38 * 64 KB internal space
39 * size of nursery
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
44 * forwarding ptr)
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
58 * copying GC.
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
76 * TODO:
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.
104 (See next item)
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
134 free...)
136 *) memzero the major fragments after restarting the world and optionally a smaller
137 chunk at a time
139 *) investigate having fragment zeroing threads
141 *) separate locks for finalization and other minor stuff to reduce
142 lock contention
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.
167 #include "config.h"
168 #ifdef HAVE_SGEN_GC
170 #ifdef __MACH__
171 #undef _XOPEN_SOURCE
172 #define _XOPEN_SOURCE
173 #define _DARWIN_C_SOURCE
174 #endif
176 #ifdef HAVE_UNISTD_H
177 #include <unistd.h>
178 #endif
179 #ifdef HAVE_PTHREAD_H
180 #include <pthread.h>
181 #endif
182 #ifdef HAVE_SEMAPHORE_H
183 #include <semaphore.h>
184 #endif
185 #include <stdio.h>
186 #include <string.h>
187 #include <signal.h>
188 #include <errno.h>
189 #include <assert.h>
191 #include "metadata/sgen-gc.h"
192 #include "metadata/metadata-internals.h"
193 #include "metadata/class-internals.h"
194 #include "metadata/gc-internal.h"
195 #include "metadata/object-internals.h"
196 #include "metadata/threads.h"
197 #include "metadata/sgen-cardtable.h"
198 #include "metadata/sgen-ssb.h"
199 #include "metadata/sgen-protocol.h"
200 #include "metadata/sgen-archdep.h"
201 #include "metadata/sgen-bridge.h"
202 #include "metadata/sgen-memory-governor.h"
203 #include "metadata/sgen-hash-table.h"
204 #include "metadata/mono-gc.h"
205 #include "metadata/method-builder.h"
206 #include "metadata/profiler-private.h"
207 #include "metadata/monitor.h"
208 #include "metadata/threadpool-internals.h"
209 #include "metadata/mempool-internals.h"
210 #include "metadata/marshal.h"
211 #include "metadata/runtime.h"
212 #include "metadata/sgen-cardtable.h"
213 #include "metadata/sgen-pinning.h"
214 #include "metadata/sgen-workers.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"
229 #endif
231 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
232 a = i,
234 enum {
235 #include "mono/cil/opcode.def"
236 CEE_LAST
239 #undef OPDEF
241 #undef pthread_create
242 #undef pthread_join
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, check whether mark bits are consistent after major collections */
264 static gboolean check_mark_bits_after_major_collection = FALSE;
265 /* If set, check that all nursery objects are pinned/not pinned, depending on context */
266 static gboolean check_nursery_objects_pinned = FALSE;
267 /* If set, do a few checks when the concurrent collector is used */
268 static gboolean do_concurrent_checks = FALSE;
269 /* If set, check that there are no references to the domain left at domain unload */
270 static gboolean xdomain_checks = FALSE;
271 /* If not null, dump the heap after each collection into this file */
272 static FILE *heap_dump_file = NULL;
273 /* If set, mark stacks conservatively, even if precise marking is possible */
274 static gboolean conservative_stack_mark = FALSE;
275 /* If set, do a plausibility check on the scan_starts before and after
276 each collection */
277 static gboolean do_scan_starts_check = FALSE;
278 static gboolean nursery_collection_is_parallel = FALSE;
279 static gboolean disable_minor_collections = FALSE;
280 static gboolean disable_major_collections = FALSE;
281 gboolean do_pin_stats = FALSE;
282 static gboolean do_verify_nursery = FALSE;
283 static gboolean do_dump_nursery_content = FALSE;
285 #ifdef HEAVY_STATISTICS
286 long long stat_objects_alloced_degraded = 0;
287 long long stat_bytes_alloced_degraded = 0;
289 long long stat_copy_object_called_nursery = 0;
290 long long stat_objects_copied_nursery = 0;
291 long long stat_copy_object_called_major = 0;
292 long long stat_objects_copied_major = 0;
294 long long stat_scan_object_called_nursery = 0;
295 long long stat_scan_object_called_major = 0;
297 long long stat_slots_allocated_in_vain;
299 long long stat_nursery_copy_object_failed_from_space = 0;
300 long long stat_nursery_copy_object_failed_forwarded = 0;
301 long long stat_nursery_copy_object_failed_pinned = 0;
302 long long stat_nursery_copy_object_failed_to_space = 0;
304 static int stat_wbarrier_set_field = 0;
305 static int stat_wbarrier_set_arrayref = 0;
306 static int stat_wbarrier_arrayref_copy = 0;
307 static int stat_wbarrier_generic_store = 0;
308 static int stat_wbarrier_set_root = 0;
309 static int stat_wbarrier_value_copy = 0;
310 static int stat_wbarrier_object_copy = 0;
311 #endif
313 int stat_minor_gcs = 0;
314 int stat_major_gcs = 0;
316 static long long stat_pinned_objects = 0;
318 static long long time_minor_pre_collection_fragment_clear = 0;
319 static long long time_minor_pinning = 0;
320 static long long time_minor_scan_remsets = 0;
321 static long long time_minor_scan_pinned = 0;
322 static long long time_minor_scan_registered_roots = 0;
323 static long long time_minor_scan_thread_data = 0;
324 static long long time_minor_finish_gray_stack = 0;
325 static long long time_minor_fragment_creation = 0;
327 static long long time_major_pre_collection_fragment_clear = 0;
328 static long long time_major_pinning = 0;
329 static long long time_major_scan_pinned = 0;
330 static long long time_major_scan_registered_roots = 0;
331 static long long time_major_scan_thread_data = 0;
332 static long long time_major_scan_alloc_pinned = 0;
333 static long long time_major_scan_finalized = 0;
334 static long long time_major_scan_big_objects = 0;
335 static long long time_major_finish_gray_stack = 0;
336 static long long time_major_free_bigobjs = 0;
337 static long long time_major_los_sweep = 0;
338 static long long time_major_sweep = 0;
339 static long long time_major_fragment_creation = 0;
341 int gc_debug_level = 0;
342 FILE* gc_debug_file;
345 void
346 mono_gc_flush_info (void)
348 fflush (gc_debug_file);
352 #define TV_DECLARE SGEN_TV_DECLARE
353 #define TV_GETTIME SGEN_TV_GETTIME
354 #define TV_ELAPSED SGEN_TV_ELAPSED
355 #define TV_ELAPSED_MS SGEN_TV_ELAPSED_MS
357 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
359 NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
361 #define object_is_forwarded SGEN_OBJECT_IS_FORWARDED
362 #define object_is_pinned SGEN_OBJECT_IS_PINNED
363 #define pin_object SGEN_PIN_OBJECT
364 #define unpin_object SGEN_UNPIN_OBJECT
366 #define ptr_in_nursery sgen_ptr_in_nursery
368 #define LOAD_VTABLE SGEN_LOAD_VTABLE
370 static const char*
371 safe_name (void* obj)
373 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
374 return vt->klass->name;
377 #define safe_object_get_size sgen_safe_object_get_size
379 const char*
380 sgen_safe_name (void* obj)
382 return safe_name (obj);
386 * ######################################################################
387 * ######## Global data.
388 * ######################################################################
390 LOCK_DECLARE (gc_mutex);
391 static int gc_disabled = 0;
393 static gboolean use_cardtable;
395 #define SCAN_START_SIZE SGEN_SCAN_START_SIZE
397 static mword pagesize = 4096;
398 int degraded_mode = 0;
400 static mword bytes_pinned_from_failed_allocation = 0;
402 GCMemSection *nursery_section = NULL;
403 static mword lowest_heap_address = ~(mword)0;
404 static mword highest_heap_address = 0;
406 LOCK_DECLARE (sgen_interruption_mutex);
407 static LOCK_DECLARE (pin_queue_mutex);
409 #define LOCK_PIN_QUEUE mono_mutex_lock (&pin_queue_mutex)
410 #define UNLOCK_PIN_QUEUE mono_mutex_unlock (&pin_queue_mutex)
412 typedef struct _FinalizeReadyEntry FinalizeReadyEntry;
413 struct _FinalizeReadyEntry {
414 FinalizeReadyEntry *next;
415 void *object;
418 typedef struct _EphemeronLinkNode EphemeronLinkNode;
420 struct _EphemeronLinkNode {
421 EphemeronLinkNode *next;
422 char *array;
425 typedef struct {
426 void *key;
427 void *value;
428 } Ephemeron;
430 int current_collection_generation = -1;
431 volatile gboolean concurrent_collection_in_progress = FALSE;
433 /* objects that are ready to be finalized */
434 static FinalizeReadyEntry *fin_ready_list = NULL;
435 static FinalizeReadyEntry *critical_fin_list = NULL;
437 static EphemeronLinkNode *ephemeron_list;
439 /* registered roots: the key to the hash is the root start address */
441 * Different kinds of roots are kept separate to speed up pin_from_roots () for example.
443 SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
444 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
445 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
446 SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL)
448 static mword roots_size = 0; /* amount of memory in the root set */
450 #define GC_ROOT_NUM 32
451 typedef struct {
452 int count; /* must be the first field */
453 void *objects [GC_ROOT_NUM];
454 int root_types [GC_ROOT_NUM];
455 uintptr_t extra_info [GC_ROOT_NUM];
456 } GCRootReport;
458 static void
459 notify_gc_roots (GCRootReport *report)
461 if (!report->count)
462 return;
463 mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
464 report->count = 0;
467 static void
468 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
470 if (report->count == GC_ROOT_NUM)
471 notify_gc_roots (report);
472 report->objects [report->count] = object;
473 report->root_types [report->count] = rtype;
474 report->extra_info [report->count++] = (uintptr_t)((MonoVTable*)LOAD_VTABLE (object))->klass;
477 MonoNativeTlsKey thread_info_key;
479 #ifdef HAVE_KW_THREAD
480 __thread SgenThreadInfo *sgen_thread_info;
481 __thread gpointer *store_remset_buffer;
482 __thread long store_remset_buffer_index;
483 __thread char *stack_end;
484 __thread long *store_remset_buffer_index_addr;
485 #endif
487 /* The size of a TLAB */
488 /* The bigger the value, the less often we have to go to the slow path to allocate a new
489 * one, but the more space is wasted by threads not allocating much memory.
490 * FIXME: Tune this.
491 * FIXME: Make this self-tuning for each thread.
493 guint32 tlab_size = (1024 * 4);
495 #define MAX_SMALL_OBJ_SIZE SGEN_MAX_SMALL_OBJ_SIZE
497 /* Functions supplied by the runtime to be called by the GC */
498 static MonoGCCallbacks gc_callbacks;
500 #define ALLOC_ALIGN SGEN_ALLOC_ALIGN
501 #define ALLOC_ALIGN_BITS SGEN_ALLOC_ALIGN_BITS
503 #define ALIGN_UP SGEN_ALIGN_UP
505 #define MOVED_OBJECTS_NUM 64
506 static void *moved_objects [MOVED_OBJECTS_NUM];
507 static int moved_objects_idx = 0;
509 /* Vtable of the objects used to fill out nursery fragments before a collection */
510 static MonoVTable *array_fill_vtable;
512 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
513 MonoNativeThreadId main_gc_thread = NULL;
514 #endif
516 /*Object was pinned during the current collection*/
517 static mword objects_pinned;
520 * ######################################################################
521 * ######## Macros and function declarations.
522 * ######################################################################
525 inline static void*
526 align_pointer (void *ptr)
528 mword p = (mword)ptr;
529 p += sizeof (gpointer) - 1;
530 p &= ~ (sizeof (gpointer) - 1);
531 return (void*)p;
534 typedef SgenGrayQueue GrayQueue;
536 /* forward declarations */
537 static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue);
538 static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
539 static void scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx);
540 static void report_finalizer_roots (void);
541 static void report_registered_roots (void);
543 static void pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue);
544 static int pin_objects_from_addresses (GCMemSection *section, void **start, void **end, void *start_nursery, void *end_nursery, ScanCopyContext ctx);
545 static void finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *queue);
547 void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise);
550 static void init_stats (void);
552 static int mark_ephemerons_in_range (ScanCopyContext ctx);
553 static void clear_unreachable_ephemerons (ScanCopyContext ctx);
554 static void null_ephemerons_for_domain (MonoDomain *domain);
556 SgenObjectOperations current_object_ops;
557 SgenMajorCollector major_collector;
558 SgenMinorCollector sgen_minor_collector;
559 static GrayQueue gray_queue;
560 static GrayQueue remember_major_objects_gray_queue;
562 static SgenRemeberedSet remset;
564 /* The gray queue to use from the main collection thread. */
565 #define WORKERS_DISTRIBUTE_GRAY_QUEUE (&gray_queue)
568 * The gray queue a worker job must use. If we're not parallel or
569 * concurrent, we use the main gray queue.
571 static SgenGrayQueue*
572 sgen_workers_get_job_gray_queue (WorkerData *worker_data)
574 return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
577 static gboolean have_non_collection_major_object_remembers = FALSE;
579 gboolean
580 sgen_remember_major_object_for_concurrent_mark (char *obj)
582 if (!major_collector.is_concurrent)
583 return FALSE;
585 g_assert (current_collection_generation == GENERATION_NURSERY || current_collection_generation == -1);
587 if (!concurrent_collection_in_progress)
588 return FALSE;
590 GRAY_OBJECT_ENQUEUE (&remember_major_objects_gray_queue, obj);
592 if (current_collection_generation != GENERATION_NURSERY) {
594 * This happens when the mutator allocates large or
595 * pinned objects or when allocating in degraded
596 * mode.
598 have_non_collection_major_object_remembers = TRUE;
601 return TRUE;
604 static void
605 gray_queue_redirect (SgenGrayQueue *queue)
607 gboolean wake = FALSE;
610 for (;;) {
611 GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
612 if (!section)
613 break;
614 sgen_section_gray_queue_enqueue (queue->alloc_prepare_data, section);
615 wake = TRUE;
618 if (wake) {
619 g_assert (concurrent_collection_in_progress ||
620 (current_collection_generation == GENERATION_OLD && major_collector.is_parallel));
621 if (sgen_workers_have_started ()) {
622 sgen_workers_wake_up_all ();
623 } else {
624 if (concurrent_collection_in_progress)
625 g_assert (current_collection_generation == -1);
630 static void
631 redirect_major_object_remembers (void)
633 gray_queue_redirect (&remember_major_objects_gray_queue);
634 have_non_collection_major_object_remembers = FALSE;
637 static gboolean
638 is_xdomain_ref_allowed (gpointer *ptr, char *obj, MonoDomain *domain)
640 MonoObject *o = (MonoObject*)(obj);
641 MonoObject *ref = (MonoObject*)*(ptr);
642 int offset = (char*)(ptr) - (char*)o;
644 if (o->vtable->klass == mono_defaults.thread_class && offset == G_STRUCT_OFFSET (MonoThread, internal_thread))
645 return TRUE;
646 if (o->vtable->klass == mono_defaults.internal_thread_class && offset == G_STRUCT_OFFSET (MonoInternalThread, current_appcontext))
647 return TRUE;
648 if (mono_class_has_parent_fast (o->vtable->klass, mono_defaults.real_proxy_class) &&
649 offset == G_STRUCT_OFFSET (MonoRealProxy, unwrapped_server))
650 return TRUE;
651 /* Thread.cached_culture_info */
652 if (!strcmp (ref->vtable->klass->name_space, "System.Globalization") &&
653 !strcmp (ref->vtable->klass->name, "CultureInfo") &&
654 !strcmp(o->vtable->klass->name_space, "System") &&
655 !strcmp(o->vtable->klass->name, "Object[]"))
656 return TRUE;
658 * at System.IO.MemoryStream.InternalConstructor (byte[],int,int,bool,bool) [0x0004d] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.IO/MemoryStream.cs:121
659 * at System.IO.MemoryStream..ctor (byte[]) [0x00017] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.IO/MemoryStream.cs:81
660 * at (wrapper remoting-invoke-with-check) System.IO.MemoryStream..ctor (byte[]) <IL 0x00020, 0xffffffff>
661 * at System.Runtime.Remoting.Messaging.CADMethodCallMessage.GetArguments () [0x0000d] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Messaging/CADMessages.cs:327
662 * at System.Runtime.Remoting.Messaging.MethodCall..ctor (System.Runtime.Remoting.Messaging.CADMethodCallMessage) [0x00017] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Messaging/MethodCall.cs:87
663 * at System.AppDomain.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage,byte[]&,System.Runtime.Remoting.Messaging.CADMethodReturnMessage&) [0x00018] in /home/schani/Work/novell/trunk/mcs/class/corlib/System/AppDomain.cs:1213
664 * at (wrapper remoting-invoke-with-check) System.AppDomain.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage,byte[]&,System.Runtime.Remoting.Messaging.CADMethodReturnMessage&) <IL 0x0003d, 0xffffffff>
665 * at System.Runtime.Remoting.Channels.CrossAppDomainSink.ProcessMessageInDomain (byte[],System.Runtime.Remoting.Messaging.CADMethodCallMessage) [0x00008] in /home/schani/Work/novell/trunk/mcs/class/corlib/System.Runtime.Remoting.Channels/CrossAppDomainChannel.cs:198
666 * at (wrapper runtime-invoke) object.runtime_invoke_CrossAppDomainSink/ProcessMessageRes_object_object (object,intptr,intptr,intptr) <IL 0x0004c, 0xffffffff>
668 if (!strcmp (ref->vtable->klass->name_space, "System") &&
669 !strcmp (ref->vtable->klass->name, "Byte[]") &&
670 !strcmp (o->vtable->klass->name_space, "System.IO") &&
671 !strcmp (o->vtable->klass->name, "MemoryStream"))
672 return TRUE;
673 /* append_job() in threadpool.c */
674 if (!strcmp (ref->vtable->klass->name_space, "System.Runtime.Remoting.Messaging") &&
675 !strcmp (ref->vtable->klass->name, "AsyncResult") &&
676 !strcmp (o->vtable->klass->name_space, "System") &&
677 !strcmp (o->vtable->klass->name, "Object[]") &&
678 mono_thread_pool_is_queue_array ((MonoArray*) o))
679 return TRUE;
680 return FALSE;
683 static void
684 check_reference_for_xdomain (gpointer *ptr, char *obj, MonoDomain *domain)
686 MonoObject *o = (MonoObject*)(obj);
687 MonoObject *ref = (MonoObject*)*(ptr);
688 int offset = (char*)(ptr) - (char*)o;
689 MonoClass *class;
690 MonoClassField *field;
691 char *str;
693 if (!ref || ref->vtable->domain == domain)
694 return;
695 if (is_xdomain_ref_allowed (ptr, obj, domain))
696 return;
698 field = NULL;
699 for (class = o->vtable->klass; class; class = class->parent) {
700 int i;
702 for (i = 0; i < class->field.count; ++i) {
703 if (class->fields[i].offset == offset) {
704 field = &class->fields[i];
705 break;
708 if (field)
709 break;
712 if (ref->vtable->klass == mono_defaults.string_class)
713 str = mono_string_to_utf8 ((MonoString*)ref);
714 else
715 str = NULL;
716 g_print ("xdomain reference in %p (%s.%s) at offset %d (%s) to %p (%s.%s) (%s) - pointed to by:\n",
717 o, o->vtable->klass->name_space, o->vtable->klass->name,
718 offset, field ? field->name : "",
719 ref, ref->vtable->klass->name_space, ref->vtable->klass->name, str ? str : "");
720 mono_gc_scan_for_specific_ref (o, TRUE);
721 if (str)
722 g_free (str);
725 #undef HANDLE_PTR
726 #define HANDLE_PTR(ptr,obj) check_reference_for_xdomain ((ptr), (obj), domain)
728 static void
729 scan_object_for_xdomain_refs (char *start, mword size, void *data)
731 MonoDomain *domain = ((MonoObject*)start)->vtable->domain;
733 #include "sgen-scan-object.h"
736 static gboolean scan_object_for_specific_ref_precise = TRUE;
738 #undef HANDLE_PTR
739 #define HANDLE_PTR(ptr,obj) do { \
740 if ((MonoObject*)*(ptr) == key) { \
741 g_print ("found ref to %p in object %p (%s) at offset %td\n", \
742 key, (obj), safe_name ((obj)), ((char*)(ptr) - (char*)(obj))); \
744 } while (0)
746 static void
747 scan_object_for_specific_ref (char *start, MonoObject *key)
749 char *forwarded;
751 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (start)))
752 start = forwarded;
754 if (scan_object_for_specific_ref_precise) {
755 #include "sgen-scan-object.h"
756 } else {
757 mword *words = (mword*)start;
758 size_t size = safe_object_get_size ((MonoObject*)start);
759 int i;
760 for (i = 0; i < size / sizeof (mword); ++i) {
761 if (words [i] == (mword)key) {
762 g_print ("found possible ref to %p in object %p (%s) at offset %td\n",
763 key, start, safe_name (start), i * sizeof (mword));
769 void
770 sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags)
772 while (start < end) {
773 size_t size;
774 char *obj;
776 if (!*(void**)start) {
777 start += sizeof (void*); /* should be ALLOC_ALIGN, really */
778 continue;
781 if (allow_flags) {
782 if (!(obj = SGEN_OBJECT_IS_FORWARDED (start)))
783 obj = start;
784 } else {
785 obj = start;
788 size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
790 if ((MonoVTable*)SGEN_LOAD_VTABLE (obj) != array_fill_vtable)
791 callback (obj, size, data);
793 start += size;
797 static void
798 scan_object_for_specific_ref_callback (char *obj, size_t size, MonoObject *key)
800 scan_object_for_specific_ref (obj, key);
803 static void
804 check_root_obj_specific_ref (RootRecord *root, MonoObject *key, MonoObject *obj)
806 if (key != obj)
807 return;
808 g_print ("found ref to %p in root record %p\n", key, root);
811 static MonoObject *check_key = NULL;
812 static RootRecord *check_root = NULL;
814 static void
815 check_root_obj_specific_ref_from_marker (void **obj)
817 check_root_obj_specific_ref (check_root, check_key, *obj);
820 static void
821 scan_roots_for_specific_ref (MonoObject *key, int root_type)
823 void **start_root;
824 RootRecord *root;
825 check_key = key;
827 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
828 mword desc = root->root_desc;
830 check_root = root;
832 switch (desc & ROOT_DESC_TYPE_MASK) {
833 case ROOT_DESC_BITMAP:
834 desc >>= ROOT_DESC_TYPE_SHIFT;
835 while (desc) {
836 if (desc & 1)
837 check_root_obj_specific_ref (root, key, *start_root);
838 desc >>= 1;
839 start_root++;
841 return;
842 case ROOT_DESC_COMPLEX: {
843 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
844 int bwords = (*bitmap_data) - 1;
845 void **start_run = start_root;
846 bitmap_data++;
847 while (bwords-- > 0) {
848 gsize bmap = *bitmap_data++;
849 void **objptr = start_run;
850 while (bmap) {
851 if (bmap & 1)
852 check_root_obj_specific_ref (root, key, *objptr);
853 bmap >>= 1;
854 ++objptr;
856 start_run += GC_BITS_PER_WORD;
858 break;
860 case ROOT_DESC_USER: {
861 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
862 marker (start_root, check_root_obj_specific_ref_from_marker);
863 break;
865 case ROOT_DESC_RUN_LEN:
866 g_assert_not_reached ();
867 default:
868 g_assert_not_reached ();
870 } SGEN_HASH_TABLE_FOREACH_END;
872 check_key = NULL;
873 check_root = NULL;
876 void
877 mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise)
879 void **ptr;
880 RootRecord *root;
882 scan_object_for_specific_ref_precise = precise;
884 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
885 (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key, TRUE);
887 major_collector.iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
889 sgen_los_iterate_objects ((IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
891 scan_roots_for_specific_ref (key, ROOT_TYPE_NORMAL);
892 scan_roots_for_specific_ref (key, ROOT_TYPE_WBARRIER);
894 SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], ptr, root) {
895 while (ptr < (void**)root->end_root) {
896 check_root_obj_specific_ref (root, *ptr, key);
897 ++ptr;
899 } SGEN_HASH_TABLE_FOREACH_END;
902 static gboolean
903 need_remove_object_for_domain (char *start, MonoDomain *domain)
905 if (mono_object_domain (start) == domain) {
906 SGEN_LOG (4, "Need to cleanup object %p", start);
907 binary_protocol_cleanup (start, (gpointer)LOAD_VTABLE (start), safe_object_get_size ((MonoObject*)start));
908 return TRUE;
910 return FALSE;
913 static void
914 process_object_for_domain_clearing (char *start, MonoDomain *domain)
916 GCVTable *vt = (GCVTable*)LOAD_VTABLE (start);
917 if (vt->klass == mono_defaults.internal_thread_class)
918 g_assert (mono_object_domain (start) == mono_get_root_domain ());
919 /* The object could be a proxy for an object in the domain
920 we're deleting. */
921 if (mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
922 MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
924 /* The server could already have been zeroed out, so
925 we need to check for that, too. */
926 if (server && (!LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
927 SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
928 ((MonoRealProxy*)start)->unwrapped_server = NULL;
933 static MonoDomain *check_domain = NULL;
935 static void
936 check_obj_not_in_domain (void **o)
938 g_assert (((MonoObject*)(*o))->vtable->domain != check_domain);
941 static void
942 scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type)
944 void **start_root;
945 RootRecord *root;
946 check_domain = domain;
947 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
948 mword desc = root->root_desc;
950 /* The MonoDomain struct is allowed to hold
951 references to objects in its own domain. */
952 if (start_root == (void**)domain)
953 continue;
955 switch (desc & ROOT_DESC_TYPE_MASK) {
956 case ROOT_DESC_BITMAP:
957 desc >>= ROOT_DESC_TYPE_SHIFT;
958 while (desc) {
959 if ((desc & 1) && *start_root)
960 check_obj_not_in_domain (*start_root);
961 desc >>= 1;
962 start_root++;
964 break;
965 case ROOT_DESC_COMPLEX: {
966 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
967 int bwords = (*bitmap_data) - 1;
968 void **start_run = start_root;
969 bitmap_data++;
970 while (bwords-- > 0) {
971 gsize bmap = *bitmap_data++;
972 void **objptr = start_run;
973 while (bmap) {
974 if ((bmap & 1) && *objptr)
975 check_obj_not_in_domain (*objptr);
976 bmap >>= 1;
977 ++objptr;
979 start_run += GC_BITS_PER_WORD;
981 break;
983 case ROOT_DESC_USER: {
984 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
985 marker (start_root, check_obj_not_in_domain);
986 break;
988 case ROOT_DESC_RUN_LEN:
989 g_assert_not_reached ();
990 default:
991 g_assert_not_reached ();
993 } SGEN_HASH_TABLE_FOREACH_END;
995 check_domain = NULL;
998 static void
999 check_for_xdomain_refs (void)
1001 LOSObject *bigobj;
1003 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
1004 (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL, FALSE);
1006 major_collector.iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)scan_object_for_xdomain_refs, NULL);
1008 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
1009 scan_object_for_xdomain_refs (bigobj->data, sgen_los_object_size (bigobj), NULL);
1012 static gboolean
1013 clear_domain_process_object (char *obj, MonoDomain *domain)
1015 gboolean remove;
1017 process_object_for_domain_clearing (obj, domain);
1018 remove = need_remove_object_for_domain (obj, domain);
1020 if (remove && ((MonoObject*)obj)->synchronisation) {
1021 void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)obj);
1022 if (dislink)
1023 sgen_register_disappearing_link (NULL, dislink, FALSE, TRUE);
1026 return remove;
1029 static void
1030 clear_domain_process_minor_object_callback (char *obj, size_t size, MonoDomain *domain)
1032 if (clear_domain_process_object (obj, domain))
1033 memset (obj, 0, size);
1036 static void
1037 clear_domain_process_major_object_callback (char *obj, size_t size, MonoDomain *domain)
1039 clear_domain_process_object (obj, domain);
1042 static void
1043 clear_domain_free_major_non_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
1045 if (need_remove_object_for_domain (obj, domain))
1046 major_collector.free_non_pinned_object (obj, size);
1049 static void
1050 clear_domain_free_major_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
1052 if (need_remove_object_for_domain (obj, domain))
1053 major_collector.free_pinned_object (obj, size);
1057 * When appdomains are unloaded we can easily remove objects that have finalizers,
1058 * but all the others could still be present in random places on the heap.
1059 * We need a sweep to get rid of them even though it's going to be costly
1060 * with big heaps.
1061 * The reason we need to remove them is because we access the vtable and class
1062 * structures to know the object size and the reference bitmap: once the domain is
1063 * unloaded the point to random memory.
1065 void
1066 mono_gc_clear_domain (MonoDomain * domain)
1068 LOSObject *bigobj, *prev;
1069 int i;
1071 LOCK_GC;
1073 sgen_process_fin_stage_entries ();
1074 sgen_process_dislink_stage_entries ();
1076 sgen_clear_nursery_fragments ();
1078 if (xdomain_checks && domain != mono_get_root_domain ()) {
1079 scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
1080 scan_for_registered_roots_in_domain (domain, ROOT_TYPE_WBARRIER);
1081 check_for_xdomain_refs ();
1084 /*Ephemerons and dislinks must be processed before LOS since they might end up pointing
1085 to memory returned to the OS.*/
1086 null_ephemerons_for_domain (domain);
1088 for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
1089 sgen_null_links_for_domain (domain, i);
1091 for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
1092 sgen_remove_finalizers_for_domain (domain, i);
1094 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
1095 (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain, FALSE);
1097 /* We need two passes over major and large objects because
1098 freeing such objects might give their memory back to the OS
1099 (in the case of large objects) or obliterate its vtable
1100 (pinned objects with major-copying or pinned and non-pinned
1101 objects with major-mark&sweep), but we might need to
1102 dereference a pointer from an object to another object if
1103 the first object is a proxy. */
1104 major_collector.iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
1105 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
1106 clear_domain_process_object (bigobj->data, domain);
1108 prev = NULL;
1109 for (bigobj = los_object_list; bigobj;) {
1110 if (need_remove_object_for_domain (bigobj->data, domain)) {
1111 LOSObject *to_free = bigobj;
1112 if (prev)
1113 prev->next = bigobj->next;
1114 else
1115 los_object_list = bigobj->next;
1116 bigobj = bigobj->next;
1117 SGEN_LOG (4, "Freeing large object %p", bigobj->data);
1118 sgen_los_free_object (to_free);
1119 continue;
1121 prev = bigobj;
1122 bigobj = bigobj->next;
1124 major_collector.iterate_objects (TRUE, FALSE, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
1125 major_collector.iterate_objects (FALSE, TRUE, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
1127 if (G_UNLIKELY (do_pin_stats)) {
1128 if (domain == mono_get_root_domain ())
1129 sgen_pin_stats_print_class_stats ();
1132 UNLOCK_GC;
1136 * sgen_add_to_global_remset:
1138 * The global remset contains locations which point into newspace after
1139 * a minor collection. This can happen if the objects they point to are pinned.
1141 * LOCKING: If called from a parallel collector, the global remset
1142 * lock must be held. For serial collectors that is not necessary.
1144 void
1145 sgen_add_to_global_remset (gpointer ptr, gpointer obj)
1147 remset.record_pointer (ptr);
1149 #ifdef ENABLE_DTRACE
1150 if (G_UNLIKELY (MONO_GC_GLOBAL_REMSET_ADD_ENABLED ())) {
1151 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
1152 MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)obj, sgen_safe_object_get_size (obj),
1153 vt->klass->name_space, vt->klass->name);
1155 #endif
1159 * sgen_drain_gray_stack:
1161 * Scan objects in the gray stack until the stack is empty. This should be called
1162 * frequently after each object is copied, to achieve better locality and cache
1163 * usage.
1165 gboolean
1166 sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx)
1168 char *obj;
1169 ScanObjectFunc scan_func = ctx.scan_func;
1170 GrayQueue *queue = ctx.queue;
1172 if (max_objs == -1) {
1173 for (;;) {
1174 GRAY_OBJECT_DEQUEUE (queue, obj);
1175 if (!obj)
1176 return TRUE;
1177 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
1178 scan_func (obj, queue);
1180 } else {
1181 int i;
1183 do {
1184 for (i = 0; i != max_objs; ++i) {
1185 GRAY_OBJECT_DEQUEUE (queue, obj);
1186 if (!obj)
1187 return TRUE;
1188 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
1189 scan_func (obj, queue);
1191 } while (max_objs < 0);
1192 return FALSE;
1197 * Addresses from start to end are already sorted. This function finds
1198 * the object header for each address and pins the object. The
1199 * addresses must be inside the passed section. The (start of the)
1200 * address array is overwritten with the addresses of the actually
1201 * pinned objects. Return the number of pinned objects.
1203 static int
1204 pin_objects_from_addresses (GCMemSection *section, void **start, void **end, void *start_nursery, void *end_nursery, ScanCopyContext ctx)
1206 void *last = NULL;
1207 int count = 0;
1208 void *search_start;
1209 void *last_obj = NULL;
1210 size_t last_obj_size = 0;
1211 void *addr;
1212 int idx;
1213 void **definitely_pinned = start;
1214 ScanObjectFunc scan_func = ctx.scan_func;
1215 SgenGrayQueue *queue = ctx.queue;
1217 sgen_nursery_allocator_prepare_for_pinning ();
1219 while (start < end) {
1220 addr = *start;
1221 /* the range check should be reduntant */
1222 if (addr != last && addr >= start_nursery && addr < end_nursery) {
1223 SGEN_LOG (5, "Considering pinning addr %p", addr);
1224 /* multiple pointers to the same object */
1225 if (addr >= last_obj && (char*)addr < (char*)last_obj + last_obj_size) {
1226 start++;
1227 continue;
1229 idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
1230 g_assert (idx < section->num_scan_start);
1231 search_start = (void*)section->scan_starts [idx];
1232 if (!search_start || search_start > addr) {
1233 while (idx) {
1234 --idx;
1235 search_start = section->scan_starts [idx];
1236 if (search_start && search_start <= addr)
1237 break;
1239 if (!search_start || search_start > addr)
1240 search_start = start_nursery;
1242 if (search_start < last_obj)
1243 search_start = (char*)last_obj + last_obj_size;
1244 /* now addr should be in an object a short distance from search_start
1245 * Note that search_start must point to zeroed mem or point to an object.
1248 do {
1249 if (!*(void**)search_start) {
1250 /* Consistency check */
1252 for (frag = nursery_fragments; frag; frag = frag->next) {
1253 if (search_start >= frag->fragment_start && search_start < frag->fragment_end)
1254 g_assert_not_reached ();
1258 search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
1259 continue;
1261 last_obj = search_start;
1262 last_obj_size = ALIGN_UP (safe_object_get_size ((MonoObject*)search_start));
1264 if (((MonoObject*)last_obj)->synchronisation == GINT_TO_POINTER (-1)) {
1265 /* Marks the beginning of a nursery fragment, skip */
1266 } else {
1267 SGEN_LOG (8, "Pinned try match %p (%s), size %zd", last_obj, safe_name (last_obj), last_obj_size);
1268 if (addr >= search_start && (char*)addr < (char*)last_obj + last_obj_size) {
1269 if (scan_func) {
1270 scan_func (search_start, queue);
1271 } else {
1272 SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
1273 search_start, *(void**)search_start, safe_name (search_start), count);
1274 binary_protocol_pin (search_start,
1275 (gpointer)LOAD_VTABLE (search_start),
1276 safe_object_get_size (search_start));
1278 #ifdef ENABLE_DTRACE
1279 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1280 int gen = sgen_ptr_in_nursery (search_start) ? GENERATION_NURSERY : GENERATION_OLD;
1281 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (search_start);
1282 MONO_GC_OBJ_PINNED ((mword)search_start,
1283 sgen_safe_object_get_size (search_start),
1284 vt->klass->name_space, vt->klass->name, gen);
1286 #endif
1288 pin_object (search_start);
1289 GRAY_OBJECT_ENQUEUE (queue, search_start);
1290 if (G_UNLIKELY (do_pin_stats))
1291 sgen_pin_stats_register_object (search_start, last_obj_size);
1292 definitely_pinned [count] = search_start;
1293 count++;
1295 break;
1298 /* skip to the next object */
1299 search_start = (void*)((char*)search_start + last_obj_size);
1300 } while (search_start <= addr);
1301 /* we either pinned the correct object or we ignored the addr because
1302 * it points to unused zeroed memory.
1304 last = addr;
1306 start++;
1308 //printf ("effective pinned: %d (at the end: %d)\n", count, (char*)end_nursery - (char*)last);
1309 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
1310 GCRootReport report;
1311 report.count = 0;
1312 for (idx = 0; idx < count; ++idx)
1313 add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
1314 notify_gc_roots (&report);
1316 stat_pinned_objects += count;
1317 return count;
1320 void
1321 sgen_pin_objects_in_section (GCMemSection *section, ScanCopyContext ctx)
1323 int num_entries = section->pin_queue_num_entries;
1324 if (num_entries) {
1325 void **start = section->pin_queue_start;
1326 int reduced_to;
1327 reduced_to = pin_objects_from_addresses (section, start, start + num_entries,
1328 section->data, section->next_data, ctx);
1329 section->pin_queue_num_entries = reduced_to;
1330 if (!reduced_to)
1331 section->pin_queue_start = NULL;
1336 void
1337 sgen_pin_object (void *object, GrayQueue *queue)
1339 g_assert (!concurrent_collection_in_progress);
1341 if (sgen_collection_is_parallel ()) {
1342 LOCK_PIN_QUEUE;
1343 /*object arrives pinned*/
1344 sgen_pin_stage_ptr (object);
1345 ++objects_pinned ;
1346 UNLOCK_PIN_QUEUE;
1347 } else {
1348 SGEN_PIN_OBJECT (object);
1349 sgen_pin_stage_ptr (object);
1350 ++objects_pinned;
1351 if (G_UNLIKELY (do_pin_stats))
1352 sgen_pin_stats_register_object (object, safe_object_get_size (object));
1354 GRAY_OBJECT_ENQUEUE (queue, object);
1355 binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
1357 #ifdef ENABLE_DTRACE
1358 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1359 int gen = sgen_ptr_in_nursery (object) ? GENERATION_NURSERY : GENERATION_OLD;
1360 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (object);
1361 MONO_GC_OBJ_PINNED ((mword)object, sgen_safe_object_get_size (object), vt->klass->name_space, vt->klass->name, gen);
1363 #endif
1366 void
1367 sgen_parallel_pin_or_update (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue)
1369 for (;;) {
1370 mword vtable_word;
1371 gboolean major_pinned = FALSE;
1373 if (sgen_ptr_in_nursery (obj)) {
1374 if (SGEN_CAS_PTR (obj, (void*)((mword)vt | SGEN_PINNED_BIT), vt) == vt) {
1375 sgen_pin_object (obj, queue);
1376 break;
1378 } else {
1379 major_collector.pin_major_object (obj, queue);
1380 major_pinned = TRUE;
1383 vtable_word = *(mword*)obj;
1384 /*someone else forwarded it, update the pointer and bail out*/
1385 if (vtable_word & SGEN_FORWARDED_BIT) {
1386 *ptr = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1387 break;
1390 /*someone pinned it, nothing to do.*/
1391 if (vtable_word & SGEN_PINNED_BIT || major_pinned)
1392 break;
1396 /* Sort the addresses in array in increasing order.
1397 * Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
1399 void
1400 sgen_sort_addresses (void **array, int size)
1402 int i;
1403 void *tmp;
1405 for (i = 1; i < size; ++i) {
1406 int child = i;
1407 while (child > 0) {
1408 int parent = (child - 1) / 2;
1410 if (array [parent] >= array [child])
1411 break;
1413 tmp = array [parent];
1414 array [parent] = array [child];
1415 array [child] = tmp;
1417 child = parent;
1421 for (i = size - 1; i > 0; --i) {
1422 int end, root;
1423 tmp = array [i];
1424 array [i] = array [0];
1425 array [0] = tmp;
1427 end = i - 1;
1428 root = 0;
1430 while (root * 2 + 1 <= end) {
1431 int child = root * 2 + 1;
1433 if (child < end && array [child] < array [child + 1])
1434 ++child;
1435 if (array [root] >= array [child])
1436 break;
1438 tmp = array [root];
1439 array [root] = array [child];
1440 array [child] = tmp;
1442 root = child;
1448 * Scan the memory between start and end and queue values which could be pointers
1449 * to the area between start_nursery and end_nursery for later consideration.
1450 * Typically used for thread stacks.
1452 static void
1453 conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
1455 int count = 0;
1457 #ifdef VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE
1458 VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
1459 #endif
1461 while (start < end) {
1462 if (*start >= start_nursery && *start < end_nursery) {
1464 * *start can point to the middle of an object
1465 * note: should we handle pointing at the end of an object?
1466 * pinning in C# code disallows pointing at the end of an object
1467 * but there is some small chance that an optimizing C compiler
1468 * may keep the only reference to an object by pointing
1469 * at the end of it. We ignore this small chance for now.
1470 * Pointers to the end of an object are indistinguishable
1471 * from pointers to the start of the next object in memory
1472 * so if we allow that we'd need to pin two objects...
1473 * We queue the pointer in an array, the
1474 * array will then be sorted and uniqued. This way
1475 * we can coalesce several pinning pointers and it should
1476 * be faster since we'd do a memory scan with increasing
1477 * addresses. Note: we can align the address to the allocation
1478 * alignment, so the unique process is more effective.
1480 mword addr = (mword)*start;
1481 addr &= ~(ALLOC_ALIGN - 1);
1482 if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
1483 SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
1484 sgen_pin_stage_ptr ((void*)addr);
1485 count++;
1487 if (G_UNLIKELY (do_pin_stats)) {
1488 if (ptr_in_nursery ((void*)addr))
1489 sgen_pin_stats_register_address ((char*)addr, pin_type);
1492 start++;
1494 if (count)
1495 SGEN_LOG (7, "found %d potential pinned heap pointers", count);
1499 * The first thing we do in a collection is to identify pinned objects.
1500 * This function considers all the areas of memory that need to be
1501 * conservatively scanned.
1503 static void
1504 pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue)
1506 void **start_root;
1507 RootRecord *root;
1508 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);
1509 /* objects pinned from the API are inside these roots */
1510 SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], start_root, root) {
1511 SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
1512 conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
1513 } SGEN_HASH_TABLE_FOREACH_END;
1514 /* now deal with the thread stacks
1515 * in the future we should be able to conservatively scan only:
1516 * *) the cpu registers
1517 * *) the unmanaged stack frames
1518 * *) the _last_ managed stack frame
1519 * *) pointers slots in managed frames
1521 scan_thread_data (start_nursery, end_nursery, FALSE, queue);
1524 static void
1525 unpin_objects_from_queue (SgenGrayQueue *queue)
1527 for (;;) {
1528 char *addr;
1529 GRAY_OBJECT_DEQUEUE (queue, addr);
1530 if (!addr)
1531 break;
1532 g_assert (SGEN_OBJECT_IS_PINNED (addr));
1533 SGEN_UNPIN_OBJECT (addr);
1537 typedef struct {
1538 CopyOrMarkObjectFunc func;
1539 GrayQueue *queue;
1540 } UserCopyOrMarkData;
1542 static MonoNativeTlsKey user_copy_or_mark_key;
1544 static void
1545 init_user_copy_or_mark_key (void)
1547 mono_native_tls_alloc (&user_copy_or_mark_key, NULL);
1550 static void
1551 set_user_copy_or_mark_data (UserCopyOrMarkData *data)
1553 mono_native_tls_set_value (user_copy_or_mark_key, data);
1556 static void
1557 single_arg_user_copy_or_mark (void **obj)
1559 UserCopyOrMarkData *data = mono_native_tls_get_value (user_copy_or_mark_key);
1561 data->func (obj, data->queue);
1565 * The memory area from start_root to end_root contains pointers to objects.
1566 * Their position is precisely described by @desc (this means that the pointer
1567 * can be either NULL or the pointer to the start of an object).
1568 * This functions copies them to to_space updates them.
1570 * This function is not thread-safe!
1572 static void
1573 precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, mword desc, ScanCopyContext ctx)
1575 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1576 SgenGrayQueue *queue = ctx.queue;
1578 switch (desc & ROOT_DESC_TYPE_MASK) {
1579 case ROOT_DESC_BITMAP:
1580 desc >>= ROOT_DESC_TYPE_SHIFT;
1581 while (desc) {
1582 if ((desc & 1) && *start_root) {
1583 copy_func (start_root, queue);
1584 SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
1585 sgen_drain_gray_stack (-1, ctx);
1587 desc >>= 1;
1588 start_root++;
1590 return;
1591 case ROOT_DESC_COMPLEX: {
1592 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1593 int bwords = (*bitmap_data) - 1;
1594 void **start_run = start_root;
1595 bitmap_data++;
1596 while (bwords-- > 0) {
1597 gsize bmap = *bitmap_data++;
1598 void **objptr = start_run;
1599 while (bmap) {
1600 if ((bmap & 1) && *objptr) {
1601 copy_func (objptr, queue);
1602 SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
1603 sgen_drain_gray_stack (-1, ctx);
1605 bmap >>= 1;
1606 ++objptr;
1608 start_run += GC_BITS_PER_WORD;
1610 break;
1612 case ROOT_DESC_USER: {
1613 UserCopyOrMarkData data = { copy_func, queue };
1614 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1615 set_user_copy_or_mark_data (&data);
1616 marker (start_root, single_arg_user_copy_or_mark);
1617 set_user_copy_or_mark_data (NULL);
1618 break;
1620 case ROOT_DESC_RUN_LEN:
1621 g_assert_not_reached ();
1622 default:
1623 g_assert_not_reached ();
1627 static void
1628 reset_heap_boundaries (void)
1630 lowest_heap_address = ~(mword)0;
1631 highest_heap_address = 0;
1634 void
1635 sgen_update_heap_boundaries (mword low, mword high)
1637 mword old;
1639 do {
1640 old = lowest_heap_address;
1641 if (low >= old)
1642 break;
1643 } while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
1645 do {
1646 old = highest_heap_address;
1647 if (high <= old)
1648 break;
1649 } while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
1653 * Allocate and setup the data structures needed to be able to allocate objects
1654 * in the nursery. The nursery is stored in nursery_section.
1656 static void
1657 alloc_nursery (void)
1659 GCMemSection *section;
1660 char *data;
1661 int scan_starts;
1662 int alloc_size;
1664 if (nursery_section)
1665 return;
1666 SGEN_LOG (2, "Allocating nursery size: %lu", (unsigned long)sgen_nursery_size);
1667 /* later we will alloc a larger area for the nursery but only activate
1668 * what we need. The rest will be used as expansion if we have too many pinned
1669 * objects in the existing nursery.
1671 /* FIXME: handle OOM */
1672 section = sgen_alloc_internal (INTERNAL_MEM_SECTION);
1674 alloc_size = sgen_nursery_size;
1676 /* If there isn't enough space even for the nursery we should simply abort. */
1677 g_assert (sgen_memgov_try_alloc_space (alloc_size, SPACE_NURSERY));
1679 #ifdef SGEN_ALIGN_NURSERY
1680 data = major_collector.alloc_heap (alloc_size, alloc_size, DEFAULT_NURSERY_BITS);
1681 #else
1682 data = major_collector.alloc_heap (alloc_size, 0, DEFAULT_NURSERY_BITS);
1683 #endif
1684 sgen_update_heap_boundaries ((mword)data, (mword)(data + sgen_nursery_size));
1685 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 ());
1686 section->data = section->next_data = data;
1687 section->size = alloc_size;
1688 section->end_data = data + sgen_nursery_size;
1689 scan_starts = (alloc_size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
1690 section->scan_starts = sgen_alloc_internal_dynamic (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS, TRUE);
1691 section->num_scan_start = scan_starts;
1693 nursery_section = section;
1695 sgen_nursery_allocator_set_nursery_bounds (data, data + sgen_nursery_size);
1698 void*
1699 mono_gc_get_nursery (int *shift_bits, size_t *size)
1701 *size = sgen_nursery_size;
1702 #ifdef SGEN_ALIGN_NURSERY
1703 *shift_bits = DEFAULT_NURSERY_BITS;
1704 #else
1705 *shift_bits = -1;
1706 #endif
1707 return sgen_get_nursery_start ();
1710 void
1711 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1713 SgenThreadInfo *info = mono_thread_info_current ();
1715 /* Could be called from sgen_thread_unregister () with a NULL info */
1716 if (domain) {
1717 g_assert (info);
1718 info->stopped_domain = domain;
1722 gboolean
1723 mono_gc_precise_stack_mark_enabled (void)
1725 return !conservative_stack_mark;
1728 FILE *
1729 mono_gc_get_logfile (void)
1731 return gc_debug_file;
1734 static void
1735 report_finalizer_roots_list (FinalizeReadyEntry *list)
1737 GCRootReport report;
1738 FinalizeReadyEntry *fin;
1740 report.count = 0;
1741 for (fin = list; fin; fin = fin->next) {
1742 if (!fin->object)
1743 continue;
1744 add_profile_gc_root (&report, fin->object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1746 notify_gc_roots (&report);
1749 static void
1750 report_finalizer_roots (void)
1752 report_finalizer_roots_list (fin_ready_list);
1753 report_finalizer_roots_list (critical_fin_list);
1756 static GCRootReport *root_report;
1758 static void
1759 single_arg_report_root (void **obj)
1761 if (*obj)
1762 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1765 static void
1766 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1768 switch (desc & ROOT_DESC_TYPE_MASK) {
1769 case ROOT_DESC_BITMAP:
1770 desc >>= ROOT_DESC_TYPE_SHIFT;
1771 while (desc) {
1772 if ((desc & 1) && *start_root) {
1773 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1775 desc >>= 1;
1776 start_root++;
1778 return;
1779 case ROOT_DESC_COMPLEX: {
1780 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1781 int bwords = (*bitmap_data) - 1;
1782 void **start_run = start_root;
1783 bitmap_data++;
1784 while (bwords-- > 0) {
1785 gsize bmap = *bitmap_data++;
1786 void **objptr = start_run;
1787 while (bmap) {
1788 if ((bmap & 1) && *objptr) {
1789 add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1791 bmap >>= 1;
1792 ++objptr;
1794 start_run += GC_BITS_PER_WORD;
1796 break;
1798 case ROOT_DESC_USER: {
1799 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1800 root_report = report;
1801 marker (start_root, single_arg_report_root);
1802 break;
1804 case ROOT_DESC_RUN_LEN:
1805 g_assert_not_reached ();
1806 default:
1807 g_assert_not_reached ();
1811 static void
1812 report_registered_roots_by_type (int root_type)
1814 GCRootReport report;
1815 void **start_root;
1816 RootRecord *root;
1817 report.count = 0;
1818 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1819 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1820 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1821 } SGEN_HASH_TABLE_FOREACH_END;
1822 notify_gc_roots (&report);
1825 static void
1826 report_registered_roots (void)
1828 report_registered_roots_by_type (ROOT_TYPE_NORMAL);
1829 report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
1832 static void
1833 scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx)
1835 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1836 SgenGrayQueue *queue = ctx.queue;
1837 FinalizeReadyEntry *fin;
1839 for (fin = list; fin; fin = fin->next) {
1840 if (!fin->object)
1841 continue;
1842 SGEN_LOG (5, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object));
1843 copy_func (&fin->object, queue);
1847 static const char*
1848 generation_name (int generation)
1850 switch (generation) {
1851 case GENERATION_NURSERY: return "nursery";
1852 case GENERATION_OLD: return "old";
1853 default: g_assert_not_reached ();
1857 const char*
1858 sgen_generation_name (int generation)
1860 return generation_name (generation);
1863 SgenObjectOperations *
1864 sgen_get_current_object_ops (void){
1865 return &current_object_ops;
1869 static void
1870 finish_gray_stack (char *start_addr, char *end_addr, int generation, GrayQueue *queue)
1872 TV_DECLARE (atv);
1873 TV_DECLARE (btv);
1874 int done_with_ephemerons, ephemeron_rounds = 0;
1875 CopyOrMarkObjectFunc copy_func = current_object_ops.copy_or_mark_object;
1876 ScanObjectFunc scan_func = current_object_ops.scan_object;
1877 ScanCopyContext ctx = { scan_func, copy_func, queue };
1880 * We copied all the reachable objects. Now it's the time to copy
1881 * the objects that were not referenced by the roots, but by the copied objects.
1882 * we built a stack of objects pointed to by gray_start: they are
1883 * additional roots and we may add more items as we go.
1884 * We loop until gray_start == gray_objects which means no more objects have
1885 * been added. Note this is iterative: no recursion is involved.
1886 * We need to walk the LO list as well in search of marked big objects
1887 * (use a flag since this is needed only on major collections). We need to loop
1888 * here as well, so keep a counter of marked LO (increasing it in copy_object).
1889 * To achieve better cache locality and cache usage, we drain the gray stack
1890 * frequently, after each object is copied, and just finish the work here.
1892 sgen_drain_gray_stack (-1, ctx);
1893 TV_GETTIME (atv);
1894 SGEN_LOG (2, "%s generation done", generation_name (generation));
1897 Reset bridge data, we might have lingering data from a previous collection if this is a major
1898 collection trigged by minor overflow.
1900 We must reset the gathered bridges since their original block might be evacuated due to major
1901 fragmentation in the meanwhile and the bridge code should not have to deal with that.
1903 sgen_bridge_reset_data ();
1906 * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
1907 * before processing finalizable objects and non-tracking weak links to avoid finalizing/clearing
1908 * objects that are in fact reachable.
1910 done_with_ephemerons = 0;
1911 do {
1912 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1913 sgen_drain_gray_stack (-1, ctx);
1914 ++ephemeron_rounds;
1915 } while (!done_with_ephemerons);
1917 sgen_scan_togglerefs (start_addr, end_addr, ctx);
1918 if (generation == GENERATION_OLD)
1919 sgen_scan_togglerefs (sgen_get_nursery_start (), sgen_get_nursery_end (), ctx);
1921 if (sgen_need_bridge_processing ()) {
1922 sgen_collect_bridge_objects (generation, ctx);
1923 if (generation == GENERATION_OLD)
1924 sgen_collect_bridge_objects (GENERATION_NURSERY, ctx);
1928 Make sure we drain the gray stack before processing disappearing links and finalizers.
1929 If we don't make sure it is empty we might wrongly see a live object as dead.
1931 sgen_drain_gray_stack (-1, ctx);
1934 We must clear weak links that don't track resurrection before processing object ready for
1935 finalization so they can be cleared before that.
1937 sgen_null_link_in_range (generation, TRUE, ctx);
1938 if (generation == GENERATION_OLD)
1939 sgen_null_link_in_range (GENERATION_NURSERY, TRUE, ctx);
1942 /* walk the finalization queue and move also the objects that need to be
1943 * finalized: use the finalized objects as new roots so the objects they depend
1944 * on are also not reclaimed. As with the roots above, only objects in the nursery
1945 * are marked/copied.
1947 sgen_finalize_in_range (generation, ctx);
1948 if (generation == GENERATION_OLD)
1949 sgen_finalize_in_range (GENERATION_NURSERY, ctx);
1950 /* drain the new stack that might have been created */
1951 SGEN_LOG (6, "Precise scan of gray area post fin");
1952 sgen_drain_gray_stack (-1, ctx);
1955 * This must be done again after processing finalizable objects since CWL slots are cleared only after the key is finalized.
1957 done_with_ephemerons = 0;
1958 do {
1959 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1960 sgen_drain_gray_stack (-1, ctx);
1961 ++ephemeron_rounds;
1962 } while (!done_with_ephemerons);
1965 * Clear ephemeron pairs with unreachable keys.
1966 * We pass the copy func so we can figure out if an array was promoted or not.
1968 clear_unreachable_ephemerons (ctx);
1970 TV_GETTIME (btv);
1971 SGEN_LOG (2, "Finalize queue handling scan for %s generation: %d usecs %d ephemeron rounds", generation_name (generation), TV_ELAPSED (atv, btv), ephemeron_rounds);
1974 * handle disappearing links
1975 * Note we do this after checking the finalization queue because if an object
1976 * survives (at least long enough to be finalized) we don't clear the link.
1977 * This also deals with a possible issue with the monitor reclamation: with the Boehm
1978 * GC a finalized object my lose the monitor because it is cleared before the finalizer is
1979 * called.
1981 g_assert (sgen_gray_object_queue_is_empty (queue));
1982 for (;;) {
1983 sgen_null_link_in_range (generation, FALSE, ctx);
1984 if (generation == GENERATION_OLD)
1985 sgen_null_link_in_range (GENERATION_NURSERY, FALSE, ctx);
1986 if (sgen_gray_object_queue_is_empty (queue))
1987 break;
1988 sgen_drain_gray_stack (-1, ctx);
1991 g_assert (sgen_gray_object_queue_is_empty (queue));
1994 void
1995 sgen_check_section_scan_starts (GCMemSection *section)
1997 int i;
1998 for (i = 0; i < section->num_scan_start; ++i) {
1999 if (section->scan_starts [i]) {
2000 guint size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
2001 g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
2006 static void
2007 check_scan_starts (void)
2009 if (!do_scan_starts_check)
2010 return;
2011 sgen_check_section_scan_starts (nursery_section);
2012 major_collector.check_scan_starts ();
2015 static void
2016 scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx)
2018 void **start_root;
2019 RootRecord *root;
2020 SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
2021 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
2022 precisely_scan_objects_from (start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc, ctx);
2023 } SGEN_HASH_TABLE_FOREACH_END;
2026 void
2027 sgen_dump_occupied (char *start, char *end, char *section_start)
2029 fprintf (heap_dump_file, "<occupied offset=\"%td\" size=\"%td\"/>\n", start - section_start, end - start);
2032 void
2033 sgen_dump_section (GCMemSection *section, const char *type)
2035 char *start = section->data;
2036 char *end = section->data + section->size;
2037 char *occ_start = NULL;
2038 GCVTable *vt;
2039 char *old_start = NULL; /* just for debugging */
2041 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%lu\">\n", type, (unsigned long)section->size);
2043 while (start < end) {
2044 guint size;
2045 MonoClass *class;
2047 if (!*(void**)start) {
2048 if (occ_start) {
2049 sgen_dump_occupied (occ_start, start, section->data);
2050 occ_start = NULL;
2052 start += sizeof (void*); /* should be ALLOC_ALIGN, really */
2053 continue;
2055 g_assert (start < section->next_data);
2057 if (!occ_start)
2058 occ_start = start;
2060 vt = (GCVTable*)LOAD_VTABLE (start);
2061 class = vt->klass;
2063 size = ALIGN_UP (safe_object_get_size ((MonoObject*) start));
2066 fprintf (heap_dump_file, "<object offset=\"%d\" class=\"%s.%s\" size=\"%d\"/>\n",
2067 start - section->data,
2068 vt->klass->name_space, vt->klass->name,
2069 size);
2072 old_start = start;
2073 start += size;
2075 if (occ_start)
2076 sgen_dump_occupied (occ_start, start, section->data);
2078 fprintf (heap_dump_file, "</section>\n");
2081 static void
2082 dump_object (MonoObject *obj, gboolean dump_location)
2084 static char class_name [1024];
2086 MonoClass *class = mono_object_class (obj);
2087 int i, j;
2090 * Python's XML parser is too stupid to parse angle brackets
2091 * in strings, so we just ignore them;
2093 i = j = 0;
2094 while (class->name [i] && j < sizeof (class_name) - 1) {
2095 if (!strchr ("<>\"", class->name [i]))
2096 class_name [j++] = class->name [i];
2097 ++i;
2099 g_assert (j < sizeof (class_name));
2100 class_name [j] = 0;
2102 fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%d\"",
2103 class->name_space, class_name,
2104 safe_object_get_size (obj));
2105 if (dump_location) {
2106 const char *location;
2107 if (ptr_in_nursery (obj))
2108 location = "nursery";
2109 else if (safe_object_get_size (obj) <= MAX_SMALL_OBJ_SIZE)
2110 location = "major";
2111 else
2112 location = "LOS";
2113 fprintf (heap_dump_file, " location=\"%s\"", location);
2115 fprintf (heap_dump_file, "/>\n");
2118 static void
2119 dump_heap (const char *type, int num, const char *reason)
2121 ObjectList *list;
2122 LOSObject *bigobj;
2124 fprintf (heap_dump_file, "<collection type=\"%s\" num=\"%d\"", type, num);
2125 if (reason)
2126 fprintf (heap_dump_file, " reason=\"%s\"", reason);
2127 fprintf (heap_dump_file, ">\n");
2128 fprintf (heap_dump_file, "<other-mem-usage type=\"mempools\" size=\"%ld\"/>\n", mono_mempool_get_bytes_allocated ());
2129 sgen_dump_internal_mem_usage (heap_dump_file);
2130 fprintf (heap_dump_file, "<pinned type=\"stack\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_STACK));
2131 /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */
2132 fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_OTHER));
2134 fprintf (heap_dump_file, "<pinned-objects>\n");
2135 for (list = sgen_pin_stats_get_object_list (); list; list = list->next)
2136 dump_object (list->obj, TRUE);
2137 fprintf (heap_dump_file, "</pinned-objects>\n");
2139 sgen_dump_section (nursery_section, "nursery");
2141 major_collector.dump_heap (heap_dump_file);
2143 fprintf (heap_dump_file, "<los>\n");
2144 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
2145 dump_object ((MonoObject*)bigobj->data, FALSE);
2146 fprintf (heap_dump_file, "</los>\n");
2148 fprintf (heap_dump_file, "</collection>\n");
2151 void
2152 sgen_register_moved_object (void *obj, void *destination)
2154 g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
2156 /* FIXME: handle this for parallel collector */
2157 g_assert (!sgen_collection_is_parallel ());
2159 if (moved_objects_idx == MOVED_OBJECTS_NUM) {
2160 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
2161 moved_objects_idx = 0;
2163 moved_objects [moved_objects_idx++] = obj;
2164 moved_objects [moved_objects_idx++] = destination;
2167 static void
2168 init_stats (void)
2170 static gboolean inited = FALSE;
2172 if (inited)
2173 return;
2175 mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_pre_collection_fragment_clear);
2176 mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_pinning);
2177 mono_counters_register ("Minor scan remembered set", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_scan_remsets);
2178 mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_scan_pinned);
2179 mono_counters_register ("Minor scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_scan_registered_roots);
2180 mono_counters_register ("Minor scan thread data", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_scan_thread_data);
2181 mono_counters_register ("Minor finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_finish_gray_stack);
2182 mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_minor_fragment_creation);
2184 mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_pre_collection_fragment_clear);
2185 mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_pinning);
2186 mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_pinned);
2187 mono_counters_register ("Major scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_registered_roots);
2188 mono_counters_register ("Major scan thread data", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_thread_data);
2189 mono_counters_register ("Major scan alloc_pinned", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_alloc_pinned);
2190 mono_counters_register ("Major scan finalized", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_finalized);
2191 mono_counters_register ("Major scan big objects", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_scan_big_objects);
2192 mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_finish_gray_stack);
2193 mono_counters_register ("Major free big objects", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_free_bigobjs);
2194 mono_counters_register ("Major LOS sweep", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_los_sweep);
2195 mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_sweep);
2196 mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_TIME_INTERVAL, &time_major_fragment_creation);
2198 mono_counters_register ("Number of pinned objects", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_pinned_objects);
2200 #ifdef HEAVY_STATISTICS
2201 mono_counters_register ("WBarrier set field", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_field);
2202 mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_arrayref);
2203 mono_counters_register ("WBarrier arrayref copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_arrayref_copy);
2204 mono_counters_register ("WBarrier generic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store);
2205 mono_counters_register ("WBarrier set root", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_root);
2206 mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_value_copy);
2207 mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_object_copy);
2209 mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced_degraded);
2210 mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_degraded);
2212 mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_nursery);
2213 mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_nursery);
2214 mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_major);
2215 mono_counters_register ("# objects copied (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_major);
2217 mono_counters_register ("# scan_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_nursery);
2218 mono_counters_register ("# scan_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_major);
2220 mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
2222 mono_counters_register ("# nursery copy_object() failed from space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_from_space);
2223 mono_counters_register ("# nursery copy_object() failed forwarded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_forwarded);
2224 mono_counters_register ("# nursery copy_object() failed pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_pinned);
2225 mono_counters_register ("# nursery copy_object() failed to space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_to_space);
2227 sgen_nursery_allocator_init_heavy_stats ();
2228 sgen_alloc_init_heavy_stats ();
2229 #endif
2231 inited = TRUE;
2235 static void
2236 reset_pinned_from_failed_allocation (void)
2238 bytes_pinned_from_failed_allocation = 0;
2241 void
2242 sgen_set_pinned_from_failed_allocation (mword objsize)
2244 bytes_pinned_from_failed_allocation += objsize;
2247 gboolean
2248 sgen_collection_is_parallel (void)
2250 switch (current_collection_generation) {
2251 case GENERATION_NURSERY:
2252 return nursery_collection_is_parallel;
2253 case GENERATION_OLD:
2254 return major_collector.is_parallel;
2255 default:
2256 g_error ("Invalid current generation %d", current_collection_generation);
2260 gboolean
2261 sgen_collection_is_concurrent (void)
2263 switch (current_collection_generation) {
2264 case GENERATION_NURSERY:
2265 return FALSE;
2266 case GENERATION_OLD:
2267 return major_collector.is_concurrent;
2268 default:
2269 g_error ("Invalid current generation %d", current_collection_generation);
2273 gboolean
2274 sgen_concurrent_collection_in_progress (void)
2276 return concurrent_collection_in_progress;
2279 typedef struct
2281 char *heap_start;
2282 char *heap_end;
2283 } FinishRememberedSetScanJobData;
2285 static void
2286 job_finish_remembered_set_scan (WorkerData *worker_data, void *job_data_untyped)
2288 FinishRememberedSetScanJobData *job_data = job_data_untyped;
2290 remset.finish_scan_remsets (job_data->heap_start, job_data->heap_end, sgen_workers_get_job_gray_queue (worker_data));
2291 sgen_free_internal_dynamic (job_data, sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2294 typedef struct
2296 CopyOrMarkObjectFunc copy_or_mark_func;
2297 ScanObjectFunc scan_func;
2298 char *heap_start;
2299 char *heap_end;
2300 int root_type;
2301 } ScanFromRegisteredRootsJobData;
2303 static void
2304 job_scan_from_registered_roots (WorkerData *worker_data, void *job_data_untyped)
2306 ScanFromRegisteredRootsJobData *job_data = job_data_untyped;
2307 ScanCopyContext ctx = { job_data->scan_func, job_data->copy_or_mark_func,
2308 sgen_workers_get_job_gray_queue (worker_data) };
2310 scan_from_registered_roots (job_data->heap_start, job_data->heap_end, job_data->root_type, ctx);
2311 sgen_free_internal_dynamic (job_data, sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2314 typedef struct
2316 char *heap_start;
2317 char *heap_end;
2318 } ScanThreadDataJobData;
2320 static void
2321 job_scan_thread_data (WorkerData *worker_data, void *job_data_untyped)
2323 ScanThreadDataJobData *job_data = job_data_untyped;
2325 scan_thread_data (job_data->heap_start, job_data->heap_end, TRUE,
2326 sgen_workers_get_job_gray_queue (worker_data));
2327 sgen_free_internal_dynamic (job_data, sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2330 typedef struct
2332 FinalizeReadyEntry *list;
2333 } ScanFinalizerEntriesJobData;
2335 static void
2336 job_scan_finalizer_entries (WorkerData *worker_data, void *job_data_untyped)
2338 ScanFinalizerEntriesJobData *job_data = job_data_untyped;
2339 ScanCopyContext ctx = { NULL, current_object_ops.copy_or_mark_object, sgen_workers_get_job_gray_queue (worker_data) };
2341 scan_finalizer_entries (job_data->list, ctx);
2342 sgen_free_internal_dynamic (job_data, sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2345 static void
2346 job_scan_major_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2348 g_assert (concurrent_collection_in_progress);
2349 major_collector.scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2352 static void
2353 job_scan_los_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2355 g_assert (concurrent_collection_in_progress);
2356 sgen_los_scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2359 static void
2360 verify_scan_starts (char *start, char *end)
2362 int i;
2364 for (i = 0; i < nursery_section->num_scan_start; ++i) {
2365 char *addr = nursery_section->scan_starts [i];
2366 if (addr > start && addr < end)
2367 SGEN_LOG (1, "NFC-BAD SCAN START [%d] %p for obj [%p %p]", i, addr, start, end);
2371 static void
2372 verify_nursery (void)
2374 char *start, *end, *cur, *hole_start;
2376 if (!do_verify_nursery)
2377 return;
2379 /*This cleans up unused fragments */
2380 sgen_nursery_allocator_prepare_for_pinning ();
2382 hole_start = start = cur = sgen_get_nursery_start ();
2383 end = sgen_get_nursery_end ();
2385 while (cur < end) {
2386 size_t ss, size;
2388 if (!*(void**)cur) {
2389 cur += sizeof (void*);
2390 continue;
2393 if (object_is_forwarded (cur))
2394 SGEN_LOG (1, "FORWARDED OBJ %p", cur);
2395 else if (object_is_pinned (cur))
2396 SGEN_LOG (1, "PINNED OBJ %p", cur);
2398 ss = safe_object_get_size ((MonoObject*)cur);
2399 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2400 verify_scan_starts (cur, cur + size);
2401 if (do_dump_nursery_content) {
2402 if (cur > hole_start)
2403 SGEN_LOG (1, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start));
2404 SGEN_LOG (1, "OBJ [%p %p %d %d %s %d]", cur, cur + size, (int)size, (int)ss, sgen_safe_name ((MonoObject*)cur), (gpointer)LOAD_VTABLE (cur) == sgen_get_array_fill_vtable ());
2406 cur += size;
2407 hole_start = cur;
2412 * Checks that no objects in the nursery are fowarded or pinned. This
2413 * is a precondition to restarting the mutator while doing a
2414 * concurrent collection. Note that we don't clear fragments because
2415 * we depend on that having happened earlier.
2417 static void
2418 check_nursery_is_clean (void)
2420 char *start, *end, *cur;
2422 start = cur = sgen_get_nursery_start ();
2423 end = sgen_get_nursery_end ();
2425 while (cur < end) {
2426 size_t ss, size;
2428 if (!*(void**)cur) {
2429 cur += sizeof (void*);
2430 continue;
2433 g_assert (!object_is_forwarded (cur));
2434 g_assert (!object_is_pinned (cur));
2436 ss = safe_object_get_size ((MonoObject*)cur);
2437 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2438 verify_scan_starts (cur, cur + size);
2440 cur += size;
2444 static void
2445 init_gray_queue (void)
2447 if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ()) {
2448 sgen_workers_init_distribute_gray_queue ();
2449 sgen_gray_object_queue_init_with_alloc_prepare (&gray_queue, NULL,
2450 gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
2451 } else {
2452 sgen_gray_object_queue_init (&gray_queue, NULL);
2455 if (major_collector.is_concurrent) {
2456 sgen_gray_object_queue_init_with_alloc_prepare (&remember_major_objects_gray_queue, NULL,
2457 gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
2458 } else {
2459 sgen_gray_object_queue_init_invalid (&remember_major_objects_gray_queue);
2464 * Collect objects in the nursery. Returns whether to trigger a major
2465 * collection.
2467 static gboolean
2468 collect_nursery (SgenGrayQueue *unpin_queue)
2470 gboolean needs_major;
2471 size_t max_garbage_amount;
2472 char *nursery_next;
2473 FinishRememberedSetScanJobData *frssjd;
2474 ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2475 ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2476 ScanThreadDataJobData *stdjd;
2477 mword fragment_total;
2478 ScanCopyContext ctx;
2479 TV_DECLARE (all_atv);
2480 TV_DECLARE (all_btv);
2481 TV_DECLARE (atv);
2482 TV_DECLARE (btv);
2484 if (disable_minor_collections)
2485 return TRUE;
2487 MONO_GC_BEGIN (GENERATION_NURSERY);
2488 binary_protocol_collection_begin (stat_minor_gcs, GENERATION_NURSERY);
2490 verify_nursery ();
2492 #ifndef DISABLE_PERFCOUNTERS
2493 mono_perfcounters->gc_collections0++;
2494 #endif
2496 current_collection_generation = GENERATION_NURSERY;
2497 if (sgen_collection_is_parallel ())
2498 current_object_ops = sgen_minor_collector.parallel_ops;
2499 else
2500 current_object_ops = sgen_minor_collector.serial_ops;
2502 reset_pinned_from_failed_allocation ();
2504 check_scan_starts ();
2506 sgen_nursery_alloc_prepare_for_minor ();
2508 degraded_mode = 0;
2509 objects_pinned = 0;
2510 nursery_next = sgen_nursery_alloc_get_upper_alloc_bound ();
2511 /* FIXME: optimize later to use the higher address where an object can be present */
2512 nursery_next = MAX (nursery_next, sgen_get_nursery_end ());
2514 SGEN_LOG (1, "Start nursery collection %d %p-%p, size: %d", stat_minor_gcs, sgen_get_nursery_start (), nursery_next, (int)(nursery_next - sgen_get_nursery_start ()));
2515 max_garbage_amount = nursery_next - sgen_get_nursery_start ();
2516 g_assert (nursery_section->size >= max_garbage_amount);
2518 /* world must be stopped already */
2519 TV_GETTIME (all_atv);
2520 atv = all_atv;
2522 TV_GETTIME (btv);
2523 time_minor_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2525 if (xdomain_checks) {
2526 sgen_clear_nursery_fragments ();
2527 check_for_xdomain_refs ();
2530 nursery_section->next_data = nursery_next;
2532 major_collector.start_nursery_collection ();
2534 sgen_memgov_minor_collection_start ();
2536 init_gray_queue ();
2538 stat_minor_gcs++;
2539 gc_stats.minor_gc_count ++;
2541 if (remset.prepare_for_minor_collection)
2542 remset.prepare_for_minor_collection ();
2544 MONO_GC_CHECKPOINT_1 (GENERATION_NURSERY);
2546 sgen_process_fin_stage_entries ();
2547 sgen_process_dislink_stage_entries ();
2549 MONO_GC_CHECKPOINT_2 (GENERATION_NURSERY);
2551 /* pin from pinned handles */
2552 sgen_init_pinning ();
2553 mono_profiler_gc_event (MONO_GC_EVENT_MARK_START, 0);
2554 pin_from_roots (sgen_get_nursery_start (), nursery_next, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2555 /* identify pinned objects */
2556 sgen_optimize_pin_queue (0);
2557 sgen_pinning_setup_section (nursery_section);
2558 ctx.scan_func = NULL;
2559 ctx.copy_func = NULL;
2560 ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2561 sgen_pin_objects_in_section (nursery_section, ctx);
2562 sgen_pinning_trim_queue_to_section (nursery_section);
2564 TV_GETTIME (atv);
2565 time_minor_pinning += TV_ELAPSED (btv, atv);
2566 SGEN_LOG (2, "Finding pinned pointers: %d in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (btv, atv));
2567 SGEN_LOG (4, "Start scan with %d pinned objects", sgen_get_pinned_count ());
2569 MONO_GC_CHECKPOINT_3 (GENERATION_NURSERY);
2571 if (whole_heap_check_before_collection) {
2572 sgen_clear_nursery_fragments ();
2573 sgen_check_whole_heap ();
2575 if (consistency_check_at_minor_collection)
2576 sgen_check_consistency ();
2578 sgen_workers_start_all_workers ();
2581 * Perform the sequential part of remembered set scanning.
2582 * This usually involves scanning global information that might later be produced by evacuation.
2584 if (remset.begin_scan_remsets)
2585 remset.begin_scan_remsets (sgen_get_nursery_start (), nursery_next, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2587 sgen_workers_start_marking ();
2589 frssjd = sgen_alloc_internal_dynamic (sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2590 frssjd->heap_start = sgen_get_nursery_start ();
2591 frssjd->heap_end = nursery_next;
2592 sgen_workers_enqueue_job (job_finish_remembered_set_scan, frssjd);
2594 /* we don't have complete write barrier yet, so we scan all the old generation sections */
2595 TV_GETTIME (btv);
2596 time_minor_scan_remsets += TV_ELAPSED (atv, btv);
2597 SGEN_LOG (2, "Old generation scan: %d usecs", TV_ELAPSED (atv, btv));
2599 MONO_GC_CHECKPOINT_4 (GENERATION_NURSERY);
2601 if (!sgen_collection_is_parallel ()) {
2602 ctx.scan_func = current_object_ops.scan_object;
2603 ctx.copy_func = NULL;
2604 ctx.queue = &gray_queue;
2605 sgen_drain_gray_stack (-1, ctx);
2608 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2609 report_registered_roots ();
2610 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2611 report_finalizer_roots ();
2612 TV_GETTIME (atv);
2613 time_minor_scan_pinned += TV_ELAPSED (btv, atv);
2615 MONO_GC_CHECKPOINT_5 (GENERATION_NURSERY);
2617 /* registered roots, this includes static fields */
2618 scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2619 scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2620 scrrjd_normal->scan_func = current_object_ops.scan_object;
2621 scrrjd_normal->heap_start = sgen_get_nursery_start ();
2622 scrrjd_normal->heap_end = nursery_next;
2623 scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2624 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2626 scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2627 scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2628 scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2629 scrrjd_wbarrier->heap_start = sgen_get_nursery_start ();
2630 scrrjd_wbarrier->heap_end = nursery_next;
2631 scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2632 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2634 TV_GETTIME (btv);
2635 time_minor_scan_registered_roots += TV_ELAPSED (atv, btv);
2637 MONO_GC_CHECKPOINT_6 (GENERATION_NURSERY);
2639 /* thread data */
2640 stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2641 stdjd->heap_start = sgen_get_nursery_start ();
2642 stdjd->heap_end = nursery_next;
2643 sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2645 TV_GETTIME (atv);
2646 time_minor_scan_thread_data += TV_ELAPSED (btv, atv);
2647 btv = atv;
2649 MONO_GC_CHECKPOINT_7 (GENERATION_NURSERY);
2651 g_assert (!sgen_collection_is_parallel () && !sgen_collection_is_concurrent ());
2653 if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ())
2654 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2656 /* Scan the list of objects ready for finalization. If */
2657 sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2658 sfejd_fin_ready->list = fin_ready_list;
2659 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2661 sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2662 sfejd_critical_fin->list = critical_fin_list;
2663 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2665 MONO_GC_CHECKPOINT_8 (GENERATION_NURSERY);
2667 finish_gray_stack (sgen_get_nursery_start (), nursery_next, GENERATION_NURSERY, &gray_queue);
2668 TV_GETTIME (atv);
2669 time_minor_finish_gray_stack += TV_ELAPSED (btv, atv);
2670 mono_profiler_gc_event (MONO_GC_EVENT_MARK_END, 0);
2672 MONO_GC_CHECKPOINT_9 (GENERATION_NURSERY);
2675 * The (single-threaded) finalization code might have done
2676 * some copying/marking so we can only reset the GC thread's
2677 * worker data here instead of earlier when we joined the
2678 * workers.
2680 sgen_workers_reset_data ();
2682 if (objects_pinned) {
2683 sgen_optimize_pin_queue (0);
2684 sgen_pinning_setup_section (nursery_section);
2687 /* walk the pin_queue, build up the fragment list of free memory, unmark
2688 * pinned objects as we go, memzero() the empty fragments so they are ready for the
2689 * next allocations.
2691 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_START, 0);
2692 fragment_total = sgen_build_nursery_fragments (nursery_section,
2693 nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries,
2694 unpin_queue);
2695 if (!fragment_total)
2696 degraded_mode = 1;
2698 /* Clear TLABs for all threads */
2699 sgen_clear_tlabs ();
2701 mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_END, 0);
2702 TV_GETTIME (btv);
2703 time_minor_fragment_creation += TV_ELAPSED (atv, btv);
2704 SGEN_LOG (2, "Fragment creation: %d usecs, %lu bytes available", TV_ELAPSED (atv, btv), (unsigned long)fragment_total);
2706 if (consistency_check_at_minor_collection)
2707 sgen_check_major_refs ();
2709 major_collector.finish_nursery_collection ();
2711 TV_GETTIME (all_btv);
2712 gc_stats.minor_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
2714 if (heap_dump_file)
2715 dump_heap ("minor", stat_minor_gcs - 1, NULL);
2717 /* prepare the pin queue for the next collection */
2718 sgen_finish_pinning ();
2719 if (fin_ready_list || critical_fin_list) {
2720 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2721 mono_gc_finalize_notify ();
2723 sgen_pin_stats_reset ();
2725 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2727 if (remset.finish_minor_collection)
2728 remset.finish_minor_collection ();
2730 check_scan_starts ();
2732 binary_protocol_flush_buffers (FALSE);
2734 sgen_memgov_minor_collection_end ();
2736 /*objects are late pinned because of lack of memory, so a major is a good call*/
2737 needs_major = objects_pinned > 0;
2738 current_collection_generation = -1;
2739 objects_pinned = 0;
2741 MONO_GC_END (GENERATION_NURSERY);
2742 binary_protocol_collection_end (stat_minor_gcs - 1, GENERATION_NURSERY);
2744 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2745 sgen_check_nursery_objects_pinned (unpin_queue != NULL);
2747 return needs_major;
2750 static void
2751 scan_nursery_objects_callback (char *obj, size_t size, ScanCopyContext *ctx)
2753 ctx->scan_func (obj, ctx->queue);
2756 static void
2757 scan_nursery_objects (ScanCopyContext ctx)
2759 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
2760 (IterateObjectCallbackFunc)scan_nursery_objects_callback, (void*)&ctx, FALSE);
2763 static void
2764 major_copy_or_mark_from_roots (int *old_next_pin_slot, gboolean finish_up_concurrent_mark, gboolean scan_mod_union)
2766 LOSObject *bigobj;
2767 TV_DECLARE (atv);
2768 TV_DECLARE (btv);
2769 /* FIXME: only use these values for the precise scan
2770 * note that to_space pointers should be excluded anyway...
2772 char *heap_start = NULL;
2773 char *heap_end = (char*)-1;
2774 gboolean profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2775 GCRootReport root_report = { 0 };
2776 ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2777 ScanThreadDataJobData *stdjd;
2778 ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2779 ScanCopyContext ctx;
2781 if (major_collector.is_concurrent) {
2782 /*This cleans up unused fragments */
2783 sgen_nursery_allocator_prepare_for_pinning ();
2785 if (do_concurrent_checks)
2786 check_nursery_is_clean ();
2787 } else {
2788 /* The concurrent collector doesn't touch the nursery. */
2789 sgen_nursery_alloc_prepare_for_major ();
2792 init_gray_queue ();
2794 TV_GETTIME (atv);
2796 /* Pinning depends on this */
2797 sgen_clear_nursery_fragments ();
2799 if (whole_heap_check_before_collection)
2800 sgen_check_whole_heap ();
2802 TV_GETTIME (btv);
2803 time_major_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2805 if (!sgen_collection_is_concurrent ())
2806 nursery_section->next_data = sgen_get_nursery_end ();
2807 /* we should also coalesce scanning from sections close to each other
2808 * and deal with pointers outside of the sections later.
2811 objects_pinned = 0;
2812 *major_collector.have_swept = FALSE;
2814 if (xdomain_checks) {
2815 sgen_clear_nursery_fragments ();
2816 check_for_xdomain_refs ();
2819 if (!major_collector.is_concurrent) {
2820 /* Remsets are not useful for a major collection */
2821 remset.prepare_for_major_collection ();
2824 sgen_process_fin_stage_entries ();
2825 sgen_process_dislink_stage_entries ();
2827 TV_GETTIME (atv);
2828 sgen_init_pinning ();
2829 SGEN_LOG (6, "Collecting pinned addresses");
2830 pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2831 sgen_optimize_pin_queue (0);
2834 * The concurrent collector doesn't move objects, neither on
2835 * the major heap nor in the nursery, so we can mark even
2836 * before pinning has finished. For the non-concurrent
2837 * collector we start the workers after pinning.
2839 if (major_collector.is_concurrent) {
2840 sgen_workers_start_all_workers ();
2841 sgen_workers_start_marking ();
2845 * pin_queue now contains all candidate pointers, sorted and
2846 * uniqued. We must do two passes now to figure out which
2847 * objects are pinned.
2849 * The first is to find within the pin_queue the area for each
2850 * section. This requires that the pin_queue be sorted. We
2851 * also process the LOS objects and pinned chunks here.
2853 * The second, destructive, pass is to reduce the section
2854 * areas to pointers to the actually pinned objects.
2856 SGEN_LOG (6, "Pinning from sections");
2857 /* first pass for the sections */
2858 sgen_find_section_pin_queue_start_end (nursery_section);
2859 major_collector.find_pin_queue_start_ends (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2860 /* identify possible pointers to the insize of large objects */
2861 SGEN_LOG (6, "Pinning from large objects");
2862 for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
2863 int dummy;
2864 if (sgen_find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + sgen_los_object_size (bigobj), &dummy)) {
2865 binary_protocol_pin (bigobj->data, (gpointer)LOAD_VTABLE (bigobj->data), safe_object_get_size (((MonoObject*)(bigobj->data))));
2867 #ifdef ENABLE_DTRACE
2868 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
2869 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (bigobj->data);
2870 MONO_GC_OBJ_PINNED ((mword)bigobj->data, sgen_safe_object_get_size ((MonoObject*)bigobj->data), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
2872 #endif
2874 if (sgen_los_object_is_pinned (bigobj->data)) {
2875 g_assert (finish_up_concurrent_mark);
2876 continue;
2878 sgen_los_pin_object (bigobj->data);
2879 /* FIXME: only enqueue if object has references */
2880 GRAY_OBJECT_ENQUEUE (WORKERS_DISTRIBUTE_GRAY_QUEUE, bigobj->data);
2881 if (G_UNLIKELY (do_pin_stats))
2882 sgen_pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
2883 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));
2885 if (profile_roots)
2886 add_profile_gc_root (&root_report, bigobj->data, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2889 if (profile_roots)
2890 notify_gc_roots (&root_report);
2891 /* second pass for the sections */
2892 ctx.scan_func = concurrent_collection_in_progress ? current_object_ops.scan_object : NULL;
2893 ctx.copy_func = NULL;
2894 ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2896 if (major_collector.is_concurrent && sgen_minor_collector.is_split) {
2898 * With the split nursery, not all remaining nursery
2899 * objects are pinned: those in to-space are not. We
2900 * need to scan all nursery objects, though, so we
2901 * have to do it by iterating over the whole nursery.
2903 scan_nursery_objects (ctx);
2904 } else {
2905 sgen_pin_objects_in_section (nursery_section, ctx);
2906 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2907 sgen_check_nursery_objects_pinned (!concurrent_collection_in_progress || finish_up_concurrent_mark);
2910 major_collector.pin_objects (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2911 if (old_next_pin_slot)
2912 *old_next_pin_slot = sgen_get_pinned_count ();
2914 TV_GETTIME (btv);
2915 time_major_pinning += TV_ELAPSED (atv, btv);
2916 SGEN_LOG (2, "Finding pinned pointers: %d in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (atv, btv));
2917 SGEN_LOG (4, "Start scan with %d pinned objects", sgen_get_pinned_count ());
2919 major_collector.init_to_space ();
2921 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2922 main_gc_thread = mono_native_thread_self ();
2923 #endif
2925 if (!major_collector.is_concurrent) {
2926 sgen_workers_start_all_workers ();
2927 sgen_workers_start_marking ();
2930 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2931 report_registered_roots ();
2932 TV_GETTIME (atv);
2933 time_major_scan_pinned += TV_ELAPSED (btv, atv);
2935 /* registered roots, this includes static fields */
2936 scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2937 scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2938 scrrjd_normal->scan_func = current_object_ops.scan_object;
2939 scrrjd_normal->heap_start = heap_start;
2940 scrrjd_normal->heap_end = heap_end;
2941 scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2942 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2944 scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2945 scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2946 scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2947 scrrjd_wbarrier->heap_start = heap_start;
2948 scrrjd_wbarrier->heap_end = heap_end;
2949 scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2950 sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2952 TV_GETTIME (btv);
2953 time_major_scan_registered_roots += TV_ELAPSED (atv, btv);
2955 /* Threads */
2956 stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2957 stdjd->heap_start = heap_start;
2958 stdjd->heap_end = heap_end;
2959 sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2961 TV_GETTIME (atv);
2962 time_major_scan_thread_data += TV_ELAPSED (btv, atv);
2964 TV_GETTIME (btv);
2965 time_major_scan_alloc_pinned += TV_ELAPSED (atv, btv);
2967 if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2968 report_finalizer_roots ();
2970 /* scan the list of objects ready for finalization */
2971 sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2972 sfejd_fin_ready->list = fin_ready_list;
2973 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2975 sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2976 sfejd_critical_fin->list = critical_fin_list;
2977 sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2979 if (scan_mod_union) {
2980 g_assert (finish_up_concurrent_mark);
2982 /* Mod union card table */
2983 sgen_workers_enqueue_job (job_scan_major_mod_union_cardtable, NULL);
2984 sgen_workers_enqueue_job (job_scan_los_mod_union_cardtable, NULL);
2987 TV_GETTIME (atv);
2988 time_major_scan_finalized += TV_ELAPSED (btv, atv);
2989 SGEN_LOG (2, "Root scan: %d usecs", TV_ELAPSED (btv, atv));
2991 TV_GETTIME (btv);
2992 time_major_scan_big_objects += TV_ELAPSED (atv, btv);
2994 if (major_collector.is_concurrent) {
2995 /* prepare the pin queue for the next collection */
2996 sgen_finish_pinning ();
2998 sgen_pin_stats_reset ();
3000 if (do_concurrent_checks)
3001 check_nursery_is_clean ();
3005 static void
3006 major_start_collection (int *old_next_pin_slot)
3008 MONO_GC_BEGIN (GENERATION_OLD);
3009 binary_protocol_collection_begin (stat_major_gcs, GENERATION_OLD);
3011 current_collection_generation = GENERATION_OLD;
3012 #ifndef DISABLE_PERFCOUNTERS
3013 mono_perfcounters->gc_collections1++;
3014 #endif
3016 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
3018 if (major_collector.is_concurrent)
3019 concurrent_collection_in_progress = TRUE;
3021 current_object_ops = major_collector.major_ops;
3023 reset_pinned_from_failed_allocation ();
3025 sgen_memgov_major_collection_start ();
3027 //count_ref_nonref_objs ();
3028 //consistency_check ();
3030 check_scan_starts ();
3032 degraded_mode = 0;
3033 SGEN_LOG (1, "Start major collection %d", stat_major_gcs);
3034 stat_major_gcs++;
3035 gc_stats.major_gc_count ++;
3037 if (major_collector.start_major_collection)
3038 major_collector.start_major_collection ();
3040 major_copy_or_mark_from_roots (old_next_pin_slot, FALSE, FALSE);
3043 static void
3044 wait_for_workers_to_finish (void)
3046 g_assert (sgen_gray_object_queue_is_empty (&remember_major_objects_gray_queue));
3048 if (major_collector.is_parallel || major_collector.is_concurrent) {
3049 gray_queue_redirect (&gray_queue);
3050 sgen_workers_join ();
3053 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3055 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
3056 main_gc_thread = NULL;
3057 #endif
3060 static void
3061 major_finish_collection (const char *reason, int old_next_pin_slot, gboolean scan_mod_union)
3063 LOSObject *bigobj, *prevbo;
3064 TV_DECLARE (atv);
3065 TV_DECLARE (btv);
3066 char *heap_start = NULL;
3067 char *heap_end = (char*)-1;
3069 TV_GETTIME (btv);
3071 if (major_collector.is_concurrent || major_collector.is_parallel)
3072 wait_for_workers_to_finish ();
3074 current_object_ops = major_collector.major_ops;
3076 if (major_collector.is_concurrent) {
3077 major_copy_or_mark_from_roots (NULL, TRUE, scan_mod_union);
3078 wait_for_workers_to_finish ();
3080 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3082 if (do_concurrent_checks)
3083 check_nursery_is_clean ();
3087 * The workers have stopped so we need to finish gray queue
3088 * work that might result from finalization in the main GC
3089 * thread. Redirection must therefore be turned off.
3091 sgen_gray_object_queue_disable_alloc_prepare (&gray_queue);
3092 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
3094 /* all the objects in the heap */
3095 finish_gray_stack (heap_start, heap_end, GENERATION_OLD, &gray_queue);
3096 TV_GETTIME (atv);
3097 time_major_finish_gray_stack += TV_ELAPSED (btv, atv);
3100 * The (single-threaded) finalization code might have done
3101 * some copying/marking so we can only reset the GC thread's
3102 * worker data here instead of earlier when we joined the
3103 * workers.
3105 sgen_workers_reset_data ();
3107 if (objects_pinned) {
3108 g_assert (!major_collector.is_concurrent);
3110 /*This is slow, but we just OOM'd*/
3111 sgen_pin_queue_clear_discarded_entries (nursery_section, old_next_pin_slot);
3112 sgen_optimize_pin_queue (0);
3113 sgen_find_section_pin_queue_start_end (nursery_section);
3114 objects_pinned = 0;
3117 reset_heap_boundaries ();
3118 sgen_update_heap_boundaries ((mword)sgen_get_nursery_start (), (mword)sgen_get_nursery_end ());
3120 if (check_mark_bits_after_major_collection)
3121 sgen_check_major_heap_marked ();
3123 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, !major_collector.sweeps_lazily);
3125 /* sweep the big objects list */
3126 prevbo = NULL;
3127 for (bigobj = los_object_list; bigobj;) {
3128 g_assert (!object_is_pinned (bigobj->data));
3129 if (sgen_los_object_is_pinned (bigobj->data)) {
3130 sgen_los_unpin_object (bigobj->data);
3131 sgen_update_heap_boundaries ((mword)bigobj->data, (mword)bigobj->data + sgen_los_object_size (bigobj));
3132 } else {
3133 LOSObject *to_free;
3134 /* not referenced anywhere, so we can free it */
3135 if (prevbo)
3136 prevbo->next = bigobj->next;
3137 else
3138 los_object_list = bigobj->next;
3139 to_free = bigobj;
3140 bigobj = bigobj->next;
3141 sgen_los_free_object (to_free);
3142 continue;
3144 prevbo = bigobj;
3145 bigobj = bigobj->next;
3148 TV_GETTIME (btv);
3149 time_major_free_bigobjs += TV_ELAPSED (atv, btv);
3151 sgen_los_sweep ();
3153 TV_GETTIME (atv);
3154 time_major_los_sweep += TV_ELAPSED (btv, atv);
3156 major_collector.sweep ();
3158 MONO_GC_SWEEP_END (GENERATION_OLD, !major_collector.sweeps_lazily);
3160 TV_GETTIME (btv);
3161 time_major_sweep += TV_ELAPSED (atv, btv);
3163 if (!major_collector.is_concurrent) {
3164 /* walk the pin_queue, build up the fragment list of free memory, unmark
3165 * pinned objects as we go, memzero() the empty fragments so they are ready for the
3166 * next allocations.
3168 if (!sgen_build_nursery_fragments (nursery_section, nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries, NULL))
3169 degraded_mode = 1;
3171 /* prepare the pin queue for the next collection */
3172 sgen_finish_pinning ();
3174 /* Clear TLABs for all threads */
3175 sgen_clear_tlabs ();
3177 sgen_pin_stats_reset ();
3180 TV_GETTIME (atv);
3181 time_major_fragment_creation += TV_ELAPSED (btv, atv);
3183 if (heap_dump_file)
3184 dump_heap ("major", stat_major_gcs - 1, reason);
3186 if (fin_ready_list || critical_fin_list) {
3187 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
3188 mono_gc_finalize_notify ();
3191 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3193 sgen_memgov_major_collection_end ();
3194 current_collection_generation = -1;
3196 major_collector.finish_major_collection ();
3198 g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
3200 if (major_collector.is_concurrent)
3201 concurrent_collection_in_progress = FALSE;
3203 check_scan_starts ();
3205 binary_protocol_flush_buffers (FALSE);
3207 //consistency_check ();
3209 MONO_GC_END (GENERATION_OLD);
3210 binary_protocol_collection_end (stat_major_gcs - 1, GENERATION_OLD);
3213 static gboolean
3214 major_do_collection (const char *reason)
3216 TV_DECLARE (all_atv);
3217 TV_DECLARE (all_btv);
3218 int old_next_pin_slot;
3220 if (major_collector.get_and_reset_num_major_objects_marked) {
3221 long long num_marked = major_collector.get_and_reset_num_major_objects_marked ();
3222 g_assert (!num_marked);
3225 /* world must be stopped already */
3226 TV_GETTIME (all_atv);
3228 major_start_collection (&old_next_pin_slot);
3229 major_finish_collection (reason, old_next_pin_slot, FALSE);
3231 TV_GETTIME (all_btv);
3232 gc_stats.major_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
3234 /* FIXME: also report this to the user, preferably in gc-end. */
3235 if (major_collector.get_and_reset_num_major_objects_marked)
3236 major_collector.get_and_reset_num_major_objects_marked ();
3238 return bytes_pinned_from_failed_allocation > 0;
3241 static gboolean major_do_collection (const char *reason);
3243 static void
3244 major_start_concurrent_collection (const char *reason)
3246 long long num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3248 g_assert (num_objects_marked == 0);
3250 MONO_GC_CONCURRENT_START_BEGIN (GENERATION_OLD);
3252 // FIXME: store reason and pass it when finishing
3253 major_start_collection (NULL);
3255 gray_queue_redirect (&gray_queue);
3256 sgen_workers_wait_for_jobs ();
3258 num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3259 MONO_GC_CONCURRENT_START_END (GENERATION_OLD, num_objects_marked);
3261 current_collection_generation = -1;
3264 static gboolean
3265 major_update_or_finish_concurrent_collection (gboolean force_finish)
3267 SgenGrayQueue unpin_queue;
3268 memset (&unpin_queue, 0, sizeof (unpin_queue));
3270 MONO_GC_CONCURRENT_UPDATE_FINISH_BEGIN (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3272 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3273 if (!have_non_collection_major_object_remembers)
3274 g_assert (sgen_gray_object_queue_is_empty (&remember_major_objects_gray_queue));
3276 major_collector.update_cardtable_mod_union ();
3277 sgen_los_update_cardtable_mod_union ();
3279 if (!force_finish && !sgen_workers_all_done ()) {
3280 MONO_GC_CONCURRENT_UPDATE_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3281 return FALSE;
3284 collect_nursery (&unpin_queue);
3285 redirect_major_object_remembers ();
3287 current_collection_generation = GENERATION_OLD;
3288 major_finish_collection ("finishing", -1, TRUE);
3290 unpin_objects_from_queue (&unpin_queue);
3291 sgen_gray_object_queue_deinit (&unpin_queue);
3293 MONO_GC_CONCURRENT_FINISH_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3295 current_collection_generation = -1;
3297 if (whole_heap_check_before_collection)
3298 sgen_check_whole_heap ();
3300 return TRUE;
3304 * Ensure an allocation request for @size will succeed by freeing enough memory.
3306 * LOCKING: The GC lock MUST be held.
3308 void
3309 sgen_ensure_free_space (size_t size)
3311 int generation_to_collect = -1;
3312 const char *reason = NULL;
3315 if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
3316 if (sgen_need_major_collection (size)) {
3317 reason = "LOS overflow";
3318 generation_to_collect = GENERATION_OLD;
3320 } else {
3321 if (degraded_mode) {
3322 if (sgen_need_major_collection (size)) {
3323 reason = "Degraded mode overflow";
3324 generation_to_collect = GENERATION_OLD;
3326 } else if (sgen_need_major_collection (size)) {
3327 reason = "Minor allowance";
3328 generation_to_collect = GENERATION_OLD;
3329 } else {
3330 generation_to_collect = GENERATION_NURSERY;
3331 reason = "Nursery full";
3335 if (generation_to_collect == -1) {
3336 if (concurrent_collection_in_progress && sgen_workers_all_done ()) {
3337 generation_to_collect = GENERATION_OLD;
3338 reason = "Finish concurrent collection";
3342 if (generation_to_collect == -1)
3343 return;
3344 sgen_perform_collection (size, generation_to_collect, reason, FALSE);
3347 void
3348 sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish)
3350 TV_DECLARE (gc_end);
3351 GGTimingInfo infos [2];
3352 int overflow_generation_to_collect = -1;
3353 int oldest_generation_collected = generation_to_collect;
3354 const char *overflow_reason = NULL;
3356 MONO_GC_REQUESTED (generation_to_collect, requested_size, wait_to_finish ? 1 : 0);
3358 g_assert (generation_to_collect == GENERATION_NURSERY || generation_to_collect == GENERATION_OLD);
3360 if (have_non_collection_major_object_remembers) {
3361 g_assert (concurrent_collection_in_progress);
3362 redirect_major_object_remembers ();
3365 memset (infos, 0, sizeof (infos));
3366 mono_profiler_gc_event (MONO_GC_EVENT_START, generation_to_collect);
3368 infos [0].generation = generation_to_collect;
3369 infos [0].reason = reason;
3370 infos [0].is_overflow = FALSE;
3371 TV_GETTIME (infos [0].total_time);
3372 infos [1].generation = -1;
3374 sgen_stop_world (generation_to_collect);
3376 if (concurrent_collection_in_progress) {
3377 if (major_update_or_finish_concurrent_collection (wait_to_finish && generation_to_collect == GENERATION_OLD)) {
3378 oldest_generation_collected = GENERATION_OLD;
3379 goto done;
3381 if (generation_to_collect == GENERATION_OLD)
3382 goto done;
3385 //FIXME extract overflow reason
3386 if (generation_to_collect == GENERATION_NURSERY) {
3387 if (collect_nursery (NULL)) {
3388 overflow_generation_to_collect = GENERATION_OLD;
3389 overflow_reason = "Minor overflow";
3391 if (concurrent_collection_in_progress) {
3392 redirect_major_object_remembers ();
3393 sgen_workers_wake_up_all ();
3395 } else {
3396 SgenGrayQueue unpin_queue;
3397 SgenGrayQueue *unpin_queue_ptr;
3398 memset (&unpin_queue, 0, sizeof (unpin_queue));
3400 if (major_collector.is_concurrent && wait_to_finish)
3401 unpin_queue_ptr = &unpin_queue;
3402 else
3403 unpin_queue_ptr = NULL;
3405 if (major_collector.is_concurrent) {
3406 g_assert (!concurrent_collection_in_progress);
3407 collect_nursery (unpin_queue_ptr);
3410 if (major_collector.is_concurrent && !wait_to_finish) {
3411 major_start_concurrent_collection (reason);
3412 // FIXME: set infos[0] properly
3413 goto done;
3414 } else {
3415 if (major_do_collection (reason)) {
3416 overflow_generation_to_collect = GENERATION_NURSERY;
3417 overflow_reason = "Excessive pinning";
3421 if (unpin_queue_ptr) {
3422 unpin_objects_from_queue (unpin_queue_ptr);
3423 sgen_gray_object_queue_deinit (unpin_queue_ptr);
3427 TV_GETTIME (gc_end);
3428 infos [0].total_time = SGEN_TV_ELAPSED (infos [0].total_time, gc_end);
3431 if (!major_collector.is_concurrent && overflow_generation_to_collect != -1) {
3432 mono_profiler_gc_event (MONO_GC_EVENT_START, overflow_generation_to_collect);
3433 infos [1].generation = overflow_generation_to_collect;
3434 infos [1].reason = overflow_reason;
3435 infos [1].is_overflow = TRUE;
3436 infos [1].total_time = gc_end;
3438 if (overflow_generation_to_collect == GENERATION_NURSERY)
3439 collect_nursery (NULL);
3440 else
3441 major_do_collection (overflow_reason);
3443 TV_GETTIME (gc_end);
3444 infos [1].total_time = SGEN_TV_ELAPSED (infos [1].total_time, gc_end);
3446 /* keep events symmetric */
3447 mono_profiler_gc_event (MONO_GC_EVENT_END, overflow_generation_to_collect);
3449 oldest_generation_collected = MAX (oldest_generation_collected, overflow_generation_to_collect);
3452 SGEN_LOG (2, "Heap size: %lu, LOS size: %lu", (unsigned long)mono_gc_get_heap_size (), (unsigned long)los_memory_usage);
3454 /* this also sets the proper pointers for the next allocation */
3455 if (generation_to_collect == GENERATION_NURSERY && !sgen_can_alloc_size (requested_size)) {
3456 /* TypeBuilder and MonoMethod are killing mcs with fragmentation */
3457 SGEN_LOG (1, "nursery collection didn't find enough room for %zd alloc (%d pinned)", requested_size, sgen_get_pinned_count ());
3458 sgen_dump_pin_queue ();
3459 degraded_mode = 1;
3462 done:
3463 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3464 g_assert (sgen_gray_object_queue_is_empty (&remember_major_objects_gray_queue));
3466 sgen_restart_world (oldest_generation_collected, infos);
3468 mono_profiler_gc_event (MONO_GC_EVENT_END, generation_to_collect);
3472 * ######################################################################
3473 * ######## Memory allocation from the OS
3474 * ######################################################################
3475 * This section of code deals with getting memory from the OS and
3476 * allocating memory for GC-internal data structures.
3477 * Internal memory can be handled with a freelist for small objects.
3481 * Debug reporting.
3483 G_GNUC_UNUSED static void
3484 report_internal_mem_usage (void)
3486 printf ("Internal memory usage:\n");
3487 sgen_report_internal_mem_usage ();
3488 printf ("Pinned memory usage:\n");
3489 major_collector.report_pinned_memory_usage ();
3493 * ######################################################################
3494 * ######## Finalization support
3495 * ######################################################################
3498 static inline gboolean
3499 sgen_major_is_object_alive (void *object)
3501 mword objsize;
3503 /* Oldgen objects can be pinned and forwarded too */
3504 if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
3505 return TRUE;
3508 * FIXME: major_collector.is_object_live() also calculates the
3509 * size. Avoid the double calculation.
3511 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)object));
3512 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
3513 return sgen_los_object_is_pinned (object);
3515 return major_collector.is_object_live (object);
3519 * If the object has been forwarded it means it's still referenced from a root.
3520 * If it is pinned it's still alive as well.
3521 * A LOS object is only alive if we have pinned it.
3522 * Return TRUE if @obj is ready to be finalized.
3524 static inline gboolean
3525 sgen_is_object_alive (void *object)
3527 if (ptr_in_nursery (object))
3528 return sgen_nursery_is_object_alive (object);
3530 return sgen_major_is_object_alive (object);
3534 * This function returns true if @object is either alive or it belongs to the old gen
3535 * and we're currently doing a minor collection.
3537 static inline int
3538 sgen_is_object_alive_for_current_gen (char *object)
3540 if (ptr_in_nursery (object))
3541 return sgen_nursery_is_object_alive (object);
3543 if (current_collection_generation == GENERATION_NURSERY)
3544 return TRUE;
3546 return sgen_major_is_object_alive (object);
3550 * This function returns true if @object is either alive and belongs to the
3551 * current collection - major collections are full heap, so old gen objects
3552 * are never alive during a minor collection.
3554 static inline int
3555 sgen_is_object_alive_and_on_current_collection (char *object)
3557 if (ptr_in_nursery (object))
3558 return sgen_nursery_is_object_alive (object);
3560 if (current_collection_generation == GENERATION_NURSERY)
3561 return FALSE;
3563 return sgen_major_is_object_alive (object);
3567 gboolean
3568 sgen_gc_is_object_ready_for_finalization (void *object)
3570 return !sgen_is_object_alive (object);
3573 static gboolean
3574 has_critical_finalizer (MonoObject *obj)
3576 MonoClass *class;
3578 if (!mono_defaults.critical_finalizer_object)
3579 return FALSE;
3581 class = ((MonoVTable*)LOAD_VTABLE (obj))->klass;
3583 return mono_class_has_parent_fast (class, mono_defaults.critical_finalizer_object);
3586 void
3587 sgen_queue_finalization_entry (MonoObject *obj)
3589 FinalizeReadyEntry *entry = sgen_alloc_internal (INTERNAL_MEM_FINALIZE_READY_ENTRY);
3590 gboolean critical = has_critical_finalizer (obj);
3591 entry->object = obj;
3592 if (critical) {
3593 entry->next = critical_fin_list;
3594 critical_fin_list = entry;
3595 } else {
3596 entry->next = fin_ready_list;
3597 fin_ready_list = entry;
3600 #ifdef ENABLE_DTRACE
3601 if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
3602 int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
3603 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
3604 MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
3605 vt->klass->name_space, vt->klass->name, gen, critical);
3607 #endif
3610 gboolean
3611 sgen_object_is_live (void *obj)
3613 return sgen_is_object_alive_and_on_current_collection (obj);
3616 /* LOCKING: requires that the GC lock is held */
3617 static void
3618 null_ephemerons_for_domain (MonoDomain *domain)
3620 EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3622 while (current) {
3623 MonoObject *object = (MonoObject*)current->array;
3625 if (object && !object->vtable) {
3626 EphemeronLinkNode *tmp = current;
3628 if (prev)
3629 prev->next = current->next;
3630 else
3631 ephemeron_list = current->next;
3633 current = current->next;
3634 sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3635 } else {
3636 prev = current;
3637 current = current->next;
3642 /* LOCKING: requires that the GC lock is held */
3643 static void
3644 clear_unreachable_ephemerons (ScanCopyContext ctx)
3646 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3647 GrayQueue *queue = ctx.queue;
3648 EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3649 MonoArray *array;
3650 Ephemeron *cur, *array_end;
3651 char *tombstone;
3653 while (current) {
3654 char *object = current->array;
3656 if (!sgen_is_object_alive_for_current_gen (object)) {
3657 EphemeronLinkNode *tmp = current;
3659 SGEN_LOG (5, "Dead Ephemeron array at %p", object);
3661 if (prev)
3662 prev->next = current->next;
3663 else
3664 ephemeron_list = current->next;
3666 current = current->next;
3667 sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3669 continue;
3672 copy_func ((void**)&object, queue);
3673 current->array = object;
3675 SGEN_LOG (5, "Clearing unreachable entries for ephemeron array at %p", object);
3677 array = (MonoArray*)object;
3678 cur = mono_array_addr (array, Ephemeron, 0);
3679 array_end = cur + mono_array_length_fast (array);
3680 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3682 for (; cur < array_end; ++cur) {
3683 char *key = (char*)cur->key;
3685 if (!key || key == tombstone)
3686 continue;
3688 SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3689 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3690 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3692 if (!sgen_is_object_alive_for_current_gen (key)) {
3693 cur->key = tombstone;
3694 cur->value = NULL;
3695 continue;
3698 prev = current;
3699 current = current->next;
3704 LOCKING: requires that the GC lock is held
3706 Limitations: We scan all ephemerons on every collection since the current design doesn't allow for a simple nursery/mature split.
3708 static int
3709 mark_ephemerons_in_range (ScanCopyContext ctx)
3711 CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3712 GrayQueue *queue = ctx.queue;
3713 int nothing_marked = 1;
3714 EphemeronLinkNode *current = ephemeron_list;
3715 MonoArray *array;
3716 Ephemeron *cur, *array_end;
3717 char *tombstone;
3719 for (current = ephemeron_list; current; current = current->next) {
3720 char *object = current->array;
3721 SGEN_LOG (5, "Ephemeron array at %p", object);
3723 /*It has to be alive*/
3724 if (!sgen_is_object_alive_for_current_gen (object)) {
3725 SGEN_LOG (5, "\tnot reachable");
3726 continue;
3729 copy_func ((void**)&object, queue);
3731 array = (MonoArray*)object;
3732 cur = mono_array_addr (array, Ephemeron, 0);
3733 array_end = cur + mono_array_length_fast (array);
3734 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3736 for (; cur < array_end; ++cur) {
3737 char *key = cur->key;
3739 if (!key || key == tombstone)
3740 continue;
3742 SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3743 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3744 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3746 if (sgen_is_object_alive_for_current_gen (key)) {
3747 char *value = cur->value;
3749 copy_func ((void**)&cur->key, queue);
3750 if (value) {
3751 if (!sgen_is_object_alive_for_current_gen (value))
3752 nothing_marked = 0;
3753 copy_func ((void**)&cur->value, queue);
3759 SGEN_LOG (5, "Ephemeron run finished. Is it done %d", nothing_marked);
3760 return nothing_marked;
3764 mono_gc_invoke_finalizers (void)
3766 FinalizeReadyEntry *entry = NULL;
3767 gboolean entry_is_critical = FALSE;
3768 int count = 0;
3769 void *obj;
3770 /* FIXME: batch to reduce lock contention */
3771 while (fin_ready_list || critical_fin_list) {
3772 LOCK_GC;
3774 if (entry) {
3775 FinalizeReadyEntry **list = entry_is_critical ? &critical_fin_list : &fin_ready_list;
3777 /* We have finalized entry in the last
3778 interation, now we need to remove it from
3779 the list. */
3780 if (*list == entry)
3781 *list = entry->next;
3782 else {
3783 FinalizeReadyEntry *e = *list;
3784 while (e->next != entry)
3785 e = e->next;
3786 e->next = entry->next;
3788 sgen_free_internal (entry, INTERNAL_MEM_FINALIZE_READY_ENTRY);
3789 entry = NULL;
3792 /* Now look for the first non-null entry. */
3793 for (entry = fin_ready_list; entry && !entry->object; entry = entry->next)
3795 if (entry) {
3796 entry_is_critical = FALSE;
3797 } else {
3798 entry_is_critical = TRUE;
3799 for (entry = critical_fin_list; entry && !entry->object; entry = entry->next)
3803 if (entry) {
3804 g_assert (entry->object);
3805 num_ready_finalizers--;
3806 obj = entry->object;
3807 entry->object = NULL;
3808 SGEN_LOG (7, "Finalizing object %p (%s)", obj, safe_name (obj));
3811 UNLOCK_GC;
3813 if (!entry)
3814 break;
3816 g_assert (entry->object == NULL);
3817 count++;
3818 /* the object is on the stack so it is pinned */
3819 /*g_print ("Calling finalizer for object: %p (%s)\n", entry->object, safe_name (entry->object));*/
3820 mono_gc_run_finalize (obj, NULL);
3822 g_assert (!entry);
3823 return count;
3826 gboolean
3827 mono_gc_pending_finalizers (void)
3829 return fin_ready_list || critical_fin_list;
3833 * ######################################################################
3834 * ######## registered roots support
3835 * ######################################################################
3839 * We do not coalesce roots.
3841 static int
3842 mono_gc_register_root_inner (char *start, size_t size, void *descr, int root_type)
3844 RootRecord new_root;
3845 int i;
3846 LOCK_GC;
3847 for (i = 0; i < ROOT_TYPE_NUM; ++i) {
3848 RootRecord *root = sgen_hash_table_lookup (&roots_hash [i], start);
3849 /* we allow changing the size and the descriptor (for thread statics etc) */
3850 if (root) {
3851 size_t old_size = root->end_root - start;
3852 root->end_root = start + size;
3853 g_assert (((root->root_desc != 0) && (descr != NULL)) ||
3854 ((root->root_desc == 0) && (descr == NULL)));
3855 root->root_desc = (mword)descr;
3856 roots_size += size;
3857 roots_size -= old_size;
3858 UNLOCK_GC;
3859 return TRUE;
3863 new_root.end_root = start + size;
3864 new_root.root_desc = (mword)descr;
3866 sgen_hash_table_replace (&roots_hash [root_type], start, &new_root, NULL);
3867 roots_size += size;
3869 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);
3871 UNLOCK_GC;
3872 return TRUE;
3876 mono_gc_register_root (char *start, size_t size, void *descr)
3878 return mono_gc_register_root_inner (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED);
3882 mono_gc_register_root_wbarrier (char *start, size_t size, void *descr)
3884 return mono_gc_register_root_inner (start, size, descr, ROOT_TYPE_WBARRIER);
3887 void
3888 mono_gc_deregister_root (char* addr)
3890 int root_type;
3891 RootRecord root;
3893 LOCK_GC;
3894 for (root_type = 0; root_type < ROOT_TYPE_NUM; ++root_type) {
3895 if (sgen_hash_table_remove (&roots_hash [root_type], addr, &root))
3896 roots_size -= (root.end_root - addr);
3898 UNLOCK_GC;
3902 * ######################################################################
3903 * ######## Thread handling (stop/start code)
3904 * ######################################################################
3907 unsigned int sgen_global_stop_count = 0;
3909 void
3910 sgen_fill_thread_info_for_suspend (SgenThreadInfo *info)
3912 if (remset.fill_thread_info_for_suspend)
3913 remset.fill_thread_info_for_suspend (info);
3917 sgen_get_current_collection_generation (void)
3919 return current_collection_generation;
3922 void
3923 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
3925 gc_callbacks = *callbacks;
3928 MonoGCCallbacks *
3929 mono_gc_get_gc_callbacks ()
3931 return &gc_callbacks;
3934 /* Variables holding start/end nursery so it won't have to be passed at every call */
3935 static void *scan_area_arg_start, *scan_area_arg_end;
3937 void
3938 mono_gc_conservatively_scan_area (void *start, void *end)
3940 conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
3943 void*
3944 mono_gc_scan_object (void *obj)
3946 UserCopyOrMarkData *data = mono_native_tls_get_value (user_copy_or_mark_key);
3947 current_object_ops.copy_or_mark_object (&obj, data->queue);
3948 return obj;
3952 * Mark from thread stacks and registers.
3954 static void
3955 scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue)
3957 SgenThreadInfo *info;
3959 scan_area_arg_start = start_nursery;
3960 scan_area_arg_end = end_nursery;
3962 FOREACH_THREAD (info) {
3963 if (info->skip) {
3964 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);
3965 continue;
3967 if (info->gc_disabled) {
3968 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);
3969 continue;
3972 if (!info->joined_stw) {
3973 SGEN_LOG (3, "Skipping thread not seen in STW %p, range: %p-%p, size: %td", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start);
3974 continue;
3977 SGEN_LOG (3, "Scanning thread %p, range: %p-%p, size: %td, pinned=%d", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, sgen_get_pinned_count ());
3978 if (!info->thread_is_dying) {
3979 if (gc_callbacks.thread_mark_func && !conservative_stack_mark) {
3980 UserCopyOrMarkData data = { NULL, queue };
3981 set_user_copy_or_mark_data (&data);
3982 gc_callbacks.thread_mark_func (info->runtime_data, info->stack_start, info->stack_end, precise);
3983 set_user_copy_or_mark_data (NULL);
3984 } else if (!precise) {
3985 if (!conservative_stack_mark) {
3986 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
3987 conservative_stack_mark = TRUE;
3989 conservatively_pin_objects_from (info->stack_start, info->stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
3993 if (!info->thread_is_dying && !precise) {
3994 #ifdef USE_MONO_CTX
3995 conservatively_pin_objects_from ((void**)&info->ctx, (void**)&info->ctx + ARCH_NUM_REGS,
3996 start_nursery, end_nursery, PIN_TYPE_STACK);
3997 #else
3998 conservatively_pin_objects_from (&info->regs, &info->regs + ARCH_NUM_REGS,
3999 start_nursery, end_nursery, PIN_TYPE_STACK);
4000 #endif
4002 } END_FOREACH_THREAD
4005 static gboolean
4006 ptr_on_stack (void *ptr)
4008 gpointer stack_start = &stack_start;
4009 SgenThreadInfo *info = mono_thread_info_current ();
4011 if (ptr >= stack_start && ptr < (gpointer)info->stack_end)
4012 return TRUE;
4013 return FALSE;
4016 static void*
4017 sgen_thread_register (SgenThreadInfo* info, void *addr)
4019 #ifndef HAVE_KW_THREAD
4020 SgenThreadInfo *__thread_info__ = info;
4021 #endif
4023 LOCK_GC;
4024 #ifndef HAVE_KW_THREAD
4025 info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
4027 g_assert (!mono_native_tls_get_value (thread_info_key));
4028 mono_native_tls_set_value (thread_info_key, info);
4029 #else
4030 sgen_thread_info = info;
4031 #endif
4033 #if !defined(__MACH__)
4034 info->stop_count = -1;
4035 info->signal = 0;
4036 #endif
4037 info->skip = 0;
4038 info->joined_stw = FALSE;
4039 info->doing_handshake = FALSE;
4040 info->thread_is_dying = FALSE;
4041 info->stack_start = NULL;
4042 info->store_remset_buffer_addr = &STORE_REMSET_BUFFER;
4043 info->store_remset_buffer_index_addr = &STORE_REMSET_BUFFER_INDEX;
4044 info->stopped_ip = NULL;
4045 info->stopped_domain = NULL;
4046 #ifdef USE_MONO_CTX
4047 memset (&info->ctx, 0, sizeof (MonoContext));
4048 #else
4049 memset (&info->regs, 0, sizeof (info->regs));
4050 #endif
4052 sgen_init_tlab_info (info);
4054 binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
4056 #ifdef HAVE_KW_THREAD
4057 store_remset_buffer_index_addr = &store_remset_buffer_index;
4058 #endif
4060 /* try to get it with attributes first */
4061 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
4063 size_t size;
4064 void *sstart;
4065 pthread_attr_t attr;
4066 pthread_getattr_np (pthread_self (), &attr);
4067 pthread_attr_getstack (&attr, &sstart, &size);
4068 info->stack_start_limit = sstart;
4069 info->stack_end = (char*)sstart + size;
4070 pthread_attr_destroy (&attr);
4072 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
4073 info->stack_end = (char*)pthread_get_stackaddr_np (pthread_self ());
4074 info->stack_start_limit = (char*)info->stack_end - pthread_get_stacksize_np (pthread_self ());
4075 #else
4077 /* FIXME: we assume the stack grows down */
4078 gsize stack_bottom = (gsize)addr;
4079 stack_bottom += 4095;
4080 stack_bottom &= ~4095;
4081 info->stack_end = (char*)stack_bottom;
4083 #endif
4085 #ifdef HAVE_KW_THREAD
4086 stack_end = info->stack_end;
4087 #endif
4089 if (remset.register_thread)
4090 remset.register_thread (info);
4092 SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->stack_end);
4094 if (gc_callbacks.thread_attach_func)
4095 info->runtime_data = gc_callbacks.thread_attach_func ();
4097 UNLOCK_GC;
4098 return info;
4101 static void
4102 sgen_wbarrier_cleanup_thread (SgenThreadInfo *p)
4104 if (remset.cleanup_thread)
4105 remset.cleanup_thread (p);
4108 static void
4109 sgen_thread_unregister (SgenThreadInfo *p)
4111 /* If a delegate is passed to native code and invoked on a thread we dont
4112 * know about, the jit will register it with mono_jit_thread_attach, but
4113 * we have no way of knowing when that thread goes away. SGen has a TSD
4114 * so we assume that if the domain is still registered, we can detach
4115 * the thread
4117 if (mono_domain_get ())
4118 mono_thread_detach (mono_thread_current ());
4120 p->thread_is_dying = TRUE;
4123 There is a race condition between a thread finishing executing and been removed
4124 from the GC thread set.
4125 This happens on posix systems when TLS data is been cleaned-up, libpthread will
4126 set the thread_info slot to NULL before calling the cleanup function. This
4127 opens a window in which the thread is registered but has a NULL TLS.
4129 The suspend signal handler needs TLS data to know where to store thread state
4130 data or otherwise it will simply ignore the thread.
4132 This solution works because the thread doing STW will wait until all threads been
4133 suspended handshake back, so there is no race between the doing_hankshake test
4134 and the suspend_thread call.
4136 This is not required on systems that do synchronous STW as those can deal with
4137 the above race at suspend time.
4139 FIXME: I believe we could avoid this by using mono_thread_info_lookup when
4140 mono_thread_info_current returns NULL. Or fix mono_thread_info_lookup to do so.
4142 #if (defined(__MACH__) && MONO_MACH_ARCH_SUPPORTED) || !defined(HAVE_PTHREAD_KILL)
4143 LOCK_GC;
4144 #else
4145 while (!TRYLOCK_GC) {
4146 if (!sgen_park_current_thread_if_doing_handshake (p))
4147 g_usleep (50);
4149 MONO_GC_LOCKED ();
4150 #endif
4152 binary_protocol_thread_unregister ((gpointer)mono_thread_info_get_tid (p));
4153 SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)mono_thread_info_get_tid (p));
4155 if (gc_callbacks.thread_detach_func) {
4156 gc_callbacks.thread_detach_func (p->runtime_data);
4157 p->runtime_data = NULL;
4159 sgen_wbarrier_cleanup_thread (p);
4161 mono_threads_unregister_current_thread (p);
4162 UNLOCK_GC;
4166 static void
4167 sgen_thread_attach (SgenThreadInfo *info)
4169 LOCK_GC;
4170 /*this is odd, can we get attached before the gc is inited?*/
4171 init_stats ();
4172 UNLOCK_GC;
4174 if (gc_callbacks.thread_attach_func && !info->runtime_data)
4175 info->runtime_data = gc_callbacks.thread_attach_func ();
4177 gboolean
4178 mono_gc_register_thread (void *baseptr)
4180 return mono_thread_info_attach (baseptr) != NULL;
4184 * mono_gc_set_stack_end:
4186 * Set the end of the current threads stack to STACK_END. The stack space between
4187 * STACK_END and the real end of the threads stack will not be scanned during collections.
4189 void
4190 mono_gc_set_stack_end (void *stack_end)
4192 SgenThreadInfo *info;
4194 LOCK_GC;
4195 info = mono_thread_info_current ();
4196 if (info) {
4197 g_assert (stack_end < info->stack_end);
4198 info->stack_end = stack_end;
4200 UNLOCK_GC;
4203 #if USE_PTHREAD_INTERCEPT
4207 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
4209 return pthread_create (new_thread, attr, start_routine, arg);
4213 mono_gc_pthread_join (pthread_t thread, void **retval)
4215 return pthread_join (thread, retval);
4219 mono_gc_pthread_detach (pthread_t thread)
4221 return pthread_detach (thread);
4224 void
4225 mono_gc_pthread_exit (void *retval)
4227 pthread_exit (retval);
4230 #endif /* USE_PTHREAD_INTERCEPT */
4233 * ######################################################################
4234 * ######## Write barriers
4235 * ######################################################################
4239 * Note: the write barriers first do the needed GC work and then do the actual store:
4240 * this way the value is visible to the conservative GC scan after the write barrier
4241 * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
4242 * the conservative scan, otherwise by the remembered set scan.
4244 void
4245 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
4247 HEAVY_STAT (++stat_wbarrier_set_field);
4248 if (ptr_in_nursery (field_ptr)) {
4249 *(void**)field_ptr = value;
4250 return;
4252 SGEN_LOG (8, "Adding remset at %p", field_ptr);
4253 if (value)
4254 binary_protocol_wbarrier (field_ptr, value, value->vtable);
4256 remset.wbarrier_set_field (obj, field_ptr, value);
4259 void
4260 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
4262 HEAVY_STAT (++stat_wbarrier_set_arrayref);
4263 if (ptr_in_nursery (slot_ptr)) {
4264 *(void**)slot_ptr = value;
4265 return;
4267 SGEN_LOG (8, "Adding remset at %p", slot_ptr);
4268 if (value)
4269 binary_protocol_wbarrier (slot_ptr, value, value->vtable);
4271 remset.wbarrier_set_arrayref (arr, slot_ptr, value);
4274 void
4275 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
4277 HEAVY_STAT (++stat_wbarrier_arrayref_copy);
4278 /*This check can be done without taking a lock since dest_ptr array is pinned*/
4279 if (ptr_in_nursery (dest_ptr) || count <= 0) {
4280 mono_gc_memmove (dest_ptr, src_ptr, count * sizeof (gpointer));
4281 return;
4284 #ifdef SGEN_BINARY_PROTOCOL
4286 int i;
4287 for (i = 0; i < count; ++i) {
4288 gpointer dest = (gpointer*)dest_ptr + i;
4289 gpointer obj = *((gpointer*)src_ptr + i);
4290 if (obj)
4291 binary_protocol_wbarrier (dest, obj, (gpointer)LOAD_VTABLE (obj));
4294 #endif
4296 remset.wbarrier_arrayref_copy (dest_ptr, src_ptr, count);
4299 static char *found_obj;
4301 static void
4302 find_object_for_ptr_callback (char *obj, size_t size, void *user_data)
4304 char *ptr = user_data;
4306 if (ptr >= obj && ptr < obj + size) {
4307 g_assert (!found_obj);
4308 found_obj = obj;
4312 /* for use in the debugger */
4313 char* find_object_for_ptr (char *ptr);
4314 char*
4315 find_object_for_ptr (char *ptr)
4317 if (ptr >= nursery_section->data && ptr < nursery_section->end_data) {
4318 found_obj = NULL;
4319 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
4320 find_object_for_ptr_callback, ptr, TRUE);
4321 if (found_obj)
4322 return found_obj;
4325 found_obj = NULL;
4326 sgen_los_iterate_objects (find_object_for_ptr_callback, ptr);
4327 if (found_obj)
4328 return found_obj;
4331 * Very inefficient, but this is debugging code, supposed to
4332 * be called from gdb, so we don't care.
4334 found_obj = NULL;
4335 major_collector.iterate_objects (TRUE, TRUE, find_object_for_ptr_callback, ptr);
4336 return found_obj;
4339 void
4340 mono_gc_wbarrier_generic_nostore (gpointer ptr)
4342 gpointer obj;
4344 HEAVY_STAT (++stat_wbarrier_generic_store);
4346 #ifdef XDOMAIN_CHECKS_IN_WBARRIER
4347 /* FIXME: ptr_in_heap must be called with the GC lock held */
4348 if (xdomain_checks && *(MonoObject**)ptr && ptr_in_heap (ptr)) {
4349 char *start = find_object_for_ptr (ptr);
4350 MonoObject *value = *(MonoObject**)ptr;
4351 LOCK_GC;
4352 g_assert (start);
4353 if (start) {
4354 MonoObject *obj = (MonoObject*)start;
4355 if (obj->vtable->domain != value->vtable->domain)
4356 g_assert (is_xdomain_ref_allowed (ptr, start, obj->vtable->domain));
4358 UNLOCK_GC;
4360 #endif
4362 obj = *(gpointer*)ptr;
4363 if (obj)
4364 binary_protocol_wbarrier (ptr, obj, (gpointer)LOAD_VTABLE (obj));
4366 if (ptr_in_nursery (ptr) || ptr_on_stack (ptr)) {
4367 SGEN_LOG (8, "Skipping remset at %p", ptr);
4368 return;
4372 * We need to record old->old pointer locations for the
4373 * concurrent collector.
4375 if (!ptr_in_nursery (obj) && !concurrent_collection_in_progress) {
4376 SGEN_LOG (8, "Skipping remset at %p", ptr);
4377 return;
4380 SGEN_LOG (8, "Adding remset at %p", ptr);
4382 remset.wbarrier_generic_nostore (ptr);
4385 void
4386 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
4388 SGEN_LOG (8, "Wbarrier store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
4389 *(void**)ptr = value;
4390 if (ptr_in_nursery (value))
4391 mono_gc_wbarrier_generic_nostore (ptr);
4392 sgen_dummy_use (value);
4395 void mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
4397 mword *dest = _dest;
4398 mword *src = _src;
4400 while (size) {
4401 if (bitmap & 0x1)
4402 mono_gc_wbarrier_generic_store (dest, (MonoObject*)*src);
4403 else
4404 *dest = *src;
4405 ++src;
4406 ++dest;
4407 size -= SIZEOF_VOID_P;
4408 bitmap >>= 1;
4412 #ifdef SGEN_BINARY_PROTOCOL
4413 #undef HANDLE_PTR
4414 #define HANDLE_PTR(ptr,obj) do { \
4415 gpointer o = *(gpointer*)(ptr); \
4416 if ((o)) { \
4417 gpointer d = ((char*)dest) + ((char*)(ptr) - (char*)(obj)); \
4418 binary_protocol_wbarrier (d, o, (gpointer) LOAD_VTABLE (o)); \
4420 } while (0)
4422 static void
4423 scan_object_for_binary_protocol_copy_wbarrier (gpointer dest, char *start, mword desc)
4425 #define SCAN_OBJECT_NOVTABLE
4426 #include "sgen-scan-object.h"
4428 #endif
4430 void
4431 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
4433 HEAVY_STAT (++stat_wbarrier_value_copy);
4434 g_assert (klass->valuetype);
4436 SGEN_LOG (8, "Adding value remset at %p, count %d, descr %p for class %s (%p)", dest, count, klass->gc_descr, klass->name, klass);
4438 if (ptr_in_nursery (dest) || ptr_on_stack (dest) || !SGEN_CLASS_HAS_REFERENCES (klass)) {
4439 size_t element_size = mono_class_value_size (klass, NULL);
4440 size_t size = count * element_size;
4441 mono_gc_memmove (dest, src, size);
4442 return;
4445 #ifdef SGEN_BINARY_PROTOCOL
4447 size_t element_size = mono_class_value_size (klass, NULL);
4448 int i;
4449 for (i = 0; i < count; ++i) {
4450 scan_object_for_binary_protocol_copy_wbarrier ((char*)dest + i * element_size,
4451 (char*)src + i * element_size - sizeof (MonoObject),
4452 (mword) klass->gc_descr);
4455 #endif
4457 remset.wbarrier_value_copy (dest, src, count, klass);
4461 * mono_gc_wbarrier_object_copy:
4463 * Write barrier to call when obj is the result of a clone or copy of an object.
4465 void
4466 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
4468 int size;
4470 HEAVY_STAT (++stat_wbarrier_object_copy);
4472 if (ptr_in_nursery (obj) || ptr_on_stack (obj)) {
4473 size = mono_object_class (obj)->instance_size;
4474 mono_gc_memmove ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
4475 size - sizeof (MonoObject));
4476 return;
4479 #ifdef SGEN_BINARY_PROTOCOL
4480 scan_object_for_binary_protocol_copy_wbarrier (obj, (char*)src, (mword) src->vtable->gc_descr);
4481 #endif
4483 remset.wbarrier_object_copy (obj, src);
4488 * ######################################################################
4489 * ######## Other mono public interface functions.
4490 * ######################################################################
4493 #define REFS_SIZE 128
4494 typedef struct {
4495 void *data;
4496 MonoGCReferences callback;
4497 int flags;
4498 int count;
4499 int called;
4500 MonoObject *refs [REFS_SIZE];
4501 uintptr_t offsets [REFS_SIZE];
4502 } HeapWalkInfo;
4504 #undef HANDLE_PTR
4505 #define HANDLE_PTR(ptr,obj) do { \
4506 if (*(ptr)) { \
4507 if (hwi->count == REFS_SIZE) { \
4508 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data); \
4509 hwi->count = 0; \
4510 hwi->called = 1; \
4512 hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start; \
4513 hwi->refs [hwi->count++] = *(ptr); \
4515 } while (0)
4517 static void
4518 collect_references (HeapWalkInfo *hwi, char *start, size_t size)
4520 #include "sgen-scan-object.h"
4523 static void
4524 walk_references (char *start, size_t size, void *data)
4526 HeapWalkInfo *hwi = data;
4527 hwi->called = 0;
4528 hwi->count = 0;
4529 collect_references (hwi, start, size);
4530 if (hwi->count || !hwi->called)
4531 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
4535 * mono_gc_walk_heap:
4536 * @flags: flags for future use
4537 * @callback: a function pointer called for each object in the heap
4538 * @data: a user data pointer that is passed to callback
4540 * This function can be used to iterate over all the live objects in the heap:
4541 * for each object, @callback is invoked, providing info about the object's
4542 * location in memory, its class, its size and the objects it references.
4543 * For each referenced object it's offset from the object address is
4544 * reported in the offsets array.
4545 * The object references may be buffered, so the callback may be invoked
4546 * multiple times for the same object: in all but the first call, the size
4547 * argument will be zero.
4548 * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
4549 * profiler event handler.
4551 * Returns: a non-zero value if the GC doesn't support heap walking
4554 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
4556 HeapWalkInfo hwi;
4558 hwi.flags = flags;
4559 hwi.callback = callback;
4560 hwi.data = data;
4562 sgen_clear_nursery_fragments ();
4563 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE);
4565 major_collector.iterate_objects (TRUE, TRUE, walk_references, &hwi);
4566 sgen_los_iterate_objects (walk_references, &hwi);
4568 return 0;
4571 void
4572 mono_gc_collect (int generation)
4574 LOCK_GC;
4575 if (generation > 1)
4576 generation = 1;
4577 sgen_perform_collection (0, generation, "user request", TRUE);
4578 UNLOCK_GC;
4582 mono_gc_max_generation (void)
4584 return 1;
4588 mono_gc_collection_count (int generation)
4590 if (generation == 0)
4591 return stat_minor_gcs;
4592 return stat_major_gcs;
4595 int64_t
4596 mono_gc_get_used_size (void)
4598 gint64 tot = 0;
4599 LOCK_GC;
4600 tot = los_memory_usage;
4601 tot += nursery_section->next_data - nursery_section->data;
4602 tot += major_collector.get_used_size ();
4603 /* FIXME: account for pinned objects */
4604 UNLOCK_GC;
4605 return tot;
4608 void
4609 mono_gc_disable (void)
4611 LOCK_GC;
4612 gc_disabled++;
4613 UNLOCK_GC;
4616 void
4617 mono_gc_enable (void)
4619 LOCK_GC;
4620 gc_disabled--;
4621 UNLOCK_GC;
4625 mono_gc_get_los_limit (void)
4627 return MAX_SMALL_OBJ_SIZE;
4630 gboolean
4631 mono_gc_user_markers_supported (void)
4633 return TRUE;
4636 gboolean
4637 mono_object_is_alive (MonoObject* o)
4639 return TRUE;
4643 mono_gc_get_generation (MonoObject *obj)
4645 if (ptr_in_nursery (obj))
4646 return 0;
4647 return 1;
4650 void
4651 mono_gc_enable_events (void)
4655 void
4656 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
4658 sgen_register_disappearing_link (obj, link_addr, track, FALSE);
4661 void
4662 mono_gc_weak_link_remove (void **link_addr, gboolean track)
4664 sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
4667 MonoObject*
4668 mono_gc_weak_link_get (void **link_addr)
4671 * We must only load *link_addr once because it might change
4672 * under our feet, and REVEAL_POINTER (NULL) results in an
4673 * invalid reference.
4675 void *ptr = *link_addr;
4676 if (!ptr)
4677 return NULL;
4680 * During the second bridge processing step the world is
4681 * running again. That step processes all weak links once
4682 * more to null those that refer to dead objects. Before that
4683 * is completed, those links must not be followed, so we
4684 * conservatively wait for bridge processing when any weak
4685 * link is dereferenced.
4687 if (G_UNLIKELY (bridge_processing_in_progress))
4688 mono_gc_wait_for_bridge_processing ();
4690 return (MonoObject*) REVEAL_POINTER (ptr);
4693 gboolean
4694 mono_gc_ephemeron_array_add (MonoObject *obj)
4696 EphemeronLinkNode *node;
4698 LOCK_GC;
4700 node = sgen_alloc_internal (INTERNAL_MEM_EPHEMERON_LINK);
4701 if (!node) {
4702 UNLOCK_GC;
4703 return FALSE;
4705 node->array = (char*)obj;
4706 node->next = ephemeron_list;
4707 ephemeron_list = node;
4709 SGEN_LOG (5, "Registered ephemeron array %p", obj);
4711 UNLOCK_GC;
4712 return TRUE;
4715 void*
4716 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
4718 void *result;
4719 LOCK_INTERRUPTION;
4720 result = func (data);
4721 UNLOCK_INTERRUPTION;
4722 return result;
4725 gboolean
4726 mono_gc_is_gc_thread (void)
4728 gboolean result;
4729 LOCK_GC;
4730 result = mono_thread_info_current () != NULL;
4731 UNLOCK_GC;
4732 return result;
4735 static gboolean
4736 is_critical_method (MonoMethod *method)
4738 return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
4741 void
4742 mono_gc_base_init (void)
4744 MonoThreadInfoCallbacks cb;
4745 char *env;
4746 char **opts, **ptr;
4747 char *major_collector_opt = NULL;
4748 char *minor_collector_opt = NULL;
4749 glong max_heap = 0;
4750 glong soft_limit = 0;
4751 int num_workers;
4752 int result;
4753 int dummy;
4754 gboolean debug_print_allowance = FALSE;
4755 double allowance_ratio = 0, save_target = 0;
4756 gboolean have_split_nursery = FALSE;
4758 do {
4759 result = InterlockedCompareExchange (&gc_initialized, -1, 0);
4760 switch (result) {
4761 case 1:
4762 /* already inited */
4763 return;
4764 case -1:
4765 /* being inited by another thread */
4766 g_usleep (1000);
4767 break;
4768 case 0:
4769 /* we will init it */
4770 break;
4771 default:
4772 g_assert_not_reached ();
4774 } while (result != 0);
4776 LOCK_INIT (gc_mutex);
4778 pagesize = mono_pagesize ();
4779 gc_debug_file = stderr;
4781 cb.thread_register = sgen_thread_register;
4782 cb.thread_unregister = sgen_thread_unregister;
4783 cb.thread_attach = sgen_thread_attach;
4784 cb.mono_method_is_critical = (gpointer)is_critical_method;
4785 #ifndef HOST_WIN32
4786 cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
4787 #endif
4789 mono_threads_init (&cb, sizeof (SgenThreadInfo));
4791 LOCK_INIT (sgen_interruption_mutex);
4792 LOCK_INIT (pin_queue_mutex);
4794 init_user_copy_or_mark_key ();
4796 if ((env = getenv ("MONO_GC_PARAMS"))) {
4797 opts = g_strsplit (env, ",", -1);
4798 for (ptr = opts; *ptr; ++ptr) {
4799 char *opt = *ptr;
4800 if (g_str_has_prefix (opt, "major=")) {
4801 opt = strchr (opt, '=') + 1;
4802 major_collector_opt = g_strdup (opt);
4803 } else if (g_str_has_prefix (opt, "minor=")) {
4804 opt = strchr (opt, '=') + 1;
4805 minor_collector_opt = g_strdup (opt);
4808 } else {
4809 opts = NULL;
4812 init_stats ();
4813 sgen_init_internal_allocator ();
4814 sgen_init_nursery_allocator ();
4816 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_SECTION, SGEN_SIZEOF_GC_MEM_SECTION);
4817 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_FINALIZE_READY_ENTRY, sizeof (FinalizeReadyEntry));
4818 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_GRAY_QUEUE, sizeof (GrayQueueSection));
4819 g_assert (sizeof (GenericStoreRememberedSet) == sizeof (gpointer) * STORE_REMSET_BUFFER_SIZE);
4820 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_STORE_REMSET, sizeof (GenericStoreRememberedSet));
4821 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
4823 #ifndef HAVE_KW_THREAD
4824 mono_native_tls_alloc (&thread_info_key, NULL);
4825 #endif
4828 * This needs to happen before any internal allocations because
4829 * it inits the small id which is required for hazard pointer
4830 * operations.
4832 sgen_os_init ();
4834 mono_thread_info_attach (&dummy);
4836 if (!minor_collector_opt) {
4837 sgen_simple_nursery_init (&sgen_minor_collector);
4838 } else {
4839 if (!strcmp (minor_collector_opt, "simple")) {
4840 sgen_simple_nursery_init (&sgen_minor_collector);
4841 } else if (!strcmp (minor_collector_opt, "split")) {
4842 sgen_split_nursery_init (&sgen_minor_collector);
4843 have_split_nursery = TRUE;
4844 } else {
4845 fprintf (stderr, "Unknown minor collector `%s'.\n", minor_collector_opt);
4846 exit (1);
4850 if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep")) {
4851 sgen_marksweep_init (&major_collector);
4852 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed")) {
4853 sgen_marksweep_fixed_init (&major_collector);
4854 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-par")) {
4855 sgen_marksweep_par_init (&major_collector);
4856 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed-par")) {
4857 sgen_marksweep_fixed_par_init (&major_collector);
4858 } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-conc")) {
4859 sgen_marksweep_conc_init (&major_collector);
4860 } else {
4861 fprintf (stderr, "Unknown major collector `%s'.\n", major_collector_opt);
4862 exit (1);
4865 #ifdef SGEN_HAVE_CARDTABLE
4866 use_cardtable = major_collector.supports_cardtable;
4867 #else
4868 use_cardtable = FALSE;
4869 #endif
4871 num_workers = mono_cpu_count ();
4872 g_assert (num_workers > 0);
4873 if (num_workers > 16)
4874 num_workers = 16;
4876 ///* Keep this the default for now */
4877 /* Precise marking is broken on all supported targets. Disable until fixed. */
4878 conservative_stack_mark = TRUE;
4880 sgen_nursery_size = DEFAULT_NURSERY_SIZE;
4882 if (opts) {
4883 for (ptr = opts; *ptr; ++ptr) {
4884 char *opt = *ptr;
4885 if (g_str_has_prefix (opt, "major="))
4886 continue;
4887 if (g_str_has_prefix (opt, "minor="))
4888 continue;
4889 if (g_str_has_prefix (opt, "wbarrier=")) {
4890 opt = strchr (opt, '=') + 1;
4891 if (strcmp (opt, "remset") == 0) {
4892 if (major_collector.is_concurrent) {
4893 fprintf (stderr, "The concurrent collector does not support the SSB write barrier.\n");
4894 exit (1);
4896 use_cardtable = FALSE;
4897 } else if (strcmp (opt, "cardtable") == 0) {
4898 if (!use_cardtable) {
4899 if (major_collector.supports_cardtable)
4900 fprintf (stderr, "The cardtable write barrier is not supported on this platform.\n");
4901 else
4902 fprintf (stderr, "The major collector does not support the cardtable write barrier.\n");
4903 exit (1);
4905 } else {
4906 fprintf (stderr, "wbarrier must either be `remset' or `cardtable'.");
4907 exit (1);
4909 continue;
4911 if (g_str_has_prefix (opt, "max-heap-size=")) {
4912 opt = strchr (opt, '=') + 1;
4913 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap)) {
4914 if ((max_heap & (mono_pagesize () - 1))) {
4915 fprintf (stderr, "max-heap-size size must be a multiple of %d.\n", mono_pagesize ());
4916 exit (1);
4918 } else {
4919 fprintf (stderr, "max-heap-size must be an integer.\n");
4920 exit (1);
4922 continue;
4924 if (g_str_has_prefix (opt, "soft-heap-limit=")) {
4925 opt = strchr (opt, '=') + 1;
4926 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &soft_limit)) {
4927 if (soft_limit <= 0) {
4928 fprintf (stderr, "soft-heap-limit must be positive.\n");
4929 exit (1);
4931 } else {
4932 fprintf (stderr, "soft-heap-limit must be an integer.\n");
4933 exit (1);
4935 continue;
4937 if (g_str_has_prefix (opt, "workers=")) {
4938 long val;
4939 char *endptr;
4940 if (!major_collector.is_parallel) {
4941 fprintf (stderr, "The workers= option can only be used for parallel collectors.");
4942 exit (1);
4944 opt = strchr (opt, '=') + 1;
4945 val = strtol (opt, &endptr, 10);
4946 if (!*opt || *endptr) {
4947 fprintf (stderr, "Cannot parse the workers= option value.");
4948 exit (1);
4950 if (val <= 0 || val > 16) {
4951 fprintf (stderr, "The number of workers must be in the range 1 to 16.");
4952 exit (1);
4954 num_workers = (int)val;
4955 continue;
4957 if (g_str_has_prefix (opt, "stack-mark=")) {
4958 opt = strchr (opt, '=') + 1;
4959 if (!strcmp (opt, "precise")) {
4960 conservative_stack_mark = FALSE;
4961 } else if (!strcmp (opt, "conservative")) {
4962 conservative_stack_mark = TRUE;
4963 } else {
4964 fprintf (stderr, "Invalid value '%s' for stack-mark= option, possible values are: 'precise', 'conservative'.\n", opt);
4965 exit (1);
4967 continue;
4969 if (g_str_has_prefix (opt, "bridge=")) {
4970 opt = strchr (opt, '=') + 1;
4971 sgen_register_test_bridge_callbacks (g_strdup (opt));
4972 continue;
4974 #ifdef USER_CONFIG
4975 if (g_str_has_prefix (opt, "nursery-size=")) {
4976 long val;
4977 opt = strchr (opt, '=') + 1;
4978 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &val)) {
4979 sgen_nursery_size = val;
4980 #ifdef SGEN_ALIGN_NURSERY
4981 if ((val & (val - 1))) {
4982 fprintf (stderr, "The nursery size must be a power of two.\n");
4983 exit (1);
4986 if (val < SGEN_MAX_NURSERY_WASTE) {
4987 fprintf (stderr, "The nursery size must be at least %d bytes.\n", SGEN_MAX_NURSERY_WASTE);
4988 exit (1);
4991 sgen_nursery_bits = 0;
4992 while (1 << (++ sgen_nursery_bits) != sgen_nursery_size)
4994 #endif
4995 } else {
4996 fprintf (stderr, "nursery-size must be an integer.\n");
4997 exit (1);
4999 continue;
5001 #endif
5002 if (g_str_has_prefix (opt, "save-target-ratio=")) {
5003 char *endptr;
5004 opt = strchr (opt, '=') + 1;
5005 save_target = strtod (opt, &endptr);
5006 if (endptr == opt) {
5007 fprintf (stderr, "save-target-ratio must be a number.");
5008 exit (1);
5010 if (save_target < SGEN_MIN_SAVE_TARGET_RATIO || save_target > SGEN_MAX_SAVE_TARGET_RATIO) {
5011 fprintf (stderr, "save-target-ratio must be between %.2f - %.2f.", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
5012 exit (1);
5014 continue;
5016 if (g_str_has_prefix (opt, "default-allowance-ratio=")) {
5017 char *endptr;
5018 opt = strchr (opt, '=') + 1;
5020 allowance_ratio = strtod (opt, &endptr);
5021 if (endptr == opt) {
5022 fprintf (stderr, "save-target-ratio must be a number.");
5023 exit (1);
5025 if (allowance_ratio < SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO || allowance_ratio > SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO) {
5026 fprintf (stderr, "default-allowance-ratio must be between %.2f - %.2f.", SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO);
5027 exit (1);
5029 continue;
5032 if (major_collector.handle_gc_param && major_collector.handle_gc_param (opt))
5033 continue;
5035 if (sgen_minor_collector.handle_gc_param && sgen_minor_collector.handle_gc_param (opt))
5036 continue;
5038 fprintf (stderr, "MONO_GC_PARAMS must be a comma-delimited list of one or more of the following:\n");
5039 fprintf (stderr, " max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
5040 fprintf (stderr, " soft-heap-limit=n (where N is an integer, possibly with a k, m or a g suffix)\n");
5041 fprintf (stderr, " nursery-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
5042 fprintf (stderr, " major=COLLECTOR (where COLLECTOR is `marksweep', `marksweep-par', 'marksweep-fixed' or 'marksweep-fixed-par')\n");
5043 fprintf (stderr, " minor=COLLECTOR (where COLLECTOR is `simple' or `split')\n");
5044 fprintf (stderr, " wbarrier=WBARRIER (where WBARRIER is `remset' or `cardtable')\n");
5045 fprintf (stderr, " stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
5046 if (major_collector.print_gc_param_usage)
5047 major_collector.print_gc_param_usage ();
5048 if (sgen_minor_collector.print_gc_param_usage)
5049 sgen_minor_collector.print_gc_param_usage ();
5050 fprintf (stderr, " Experimental options:\n");
5051 fprintf (stderr, " save-target-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
5052 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);
5053 exit (1);
5055 g_strfreev (opts);
5058 if (major_collector.is_parallel)
5059 sgen_workers_init (num_workers);
5060 else if (major_collector.is_concurrent)
5061 sgen_workers_init (1);
5063 if (major_collector_opt)
5064 g_free (major_collector_opt);
5066 if (minor_collector_opt)
5067 g_free (minor_collector_opt);
5069 alloc_nursery ();
5071 if ((env = getenv ("MONO_GC_DEBUG"))) {
5072 opts = g_strsplit (env, ",", -1);
5073 for (ptr = opts; ptr && *ptr; ptr ++) {
5074 char *opt = *ptr;
5075 if (opt [0] >= '0' && opt [0] <= '9') {
5076 gc_debug_level = atoi (opt);
5077 opt++;
5078 if (opt [0] == ':')
5079 opt++;
5080 if (opt [0]) {
5081 #ifdef HOST_WIN32
5082 char *rf = g_strdup_printf ("%s.%d", opt, GetCurrentProcessId ());
5083 #else
5084 char *rf = g_strdup_printf ("%s.%d", opt, getpid ());
5085 #endif
5086 gc_debug_file = fopen (rf, "wb");
5087 if (!gc_debug_file)
5088 gc_debug_file = stderr;
5089 g_free (rf);
5091 } else if (!strcmp (opt, "print-allowance")) {
5092 debug_print_allowance = TRUE;
5093 } else if (!strcmp (opt, "print-pinning")) {
5094 do_pin_stats = TRUE;
5095 } else if (!strcmp (opt, "verify-before-allocs")) {
5096 verify_before_allocs = 1;
5097 has_per_allocation_action = TRUE;
5098 } else if (g_str_has_prefix (opt, "verify-before-allocs=")) {
5099 char *arg = strchr (opt, '=') + 1;
5100 verify_before_allocs = atoi (arg);
5101 has_per_allocation_action = TRUE;
5102 } else if (!strcmp (opt, "collect-before-allocs")) {
5103 collect_before_allocs = 1;
5104 has_per_allocation_action = TRUE;
5105 } else if (g_str_has_prefix (opt, "collect-before-allocs=")) {
5106 char *arg = strchr (opt, '=') + 1;
5107 has_per_allocation_action = TRUE;
5108 collect_before_allocs = atoi (arg);
5109 } else if (!strcmp (opt, "verify-before-collections")) {
5110 whole_heap_check_before_collection = TRUE;
5111 } else if (!strcmp (opt, "check-at-minor-collections")) {
5112 consistency_check_at_minor_collection = TRUE;
5113 nursery_clear_policy = CLEAR_AT_GC;
5114 } else if (!strcmp (opt, "check-mark-bits")) {
5115 check_mark_bits_after_major_collection = TRUE;
5116 } else if (!strcmp (opt, "check-nursery-pinned")) {
5117 check_nursery_objects_pinned = TRUE;
5118 } else if (!strcmp (opt, "xdomain-checks")) {
5119 xdomain_checks = TRUE;
5120 } else if (!strcmp (opt, "clear-at-gc")) {
5121 nursery_clear_policy = CLEAR_AT_GC;
5122 } else if (!strcmp (opt, "clear-nursery-at-gc")) {
5123 nursery_clear_policy = CLEAR_AT_GC;
5124 } else if (!strcmp (opt, "check-scan-starts")) {
5125 do_scan_starts_check = TRUE;
5126 } else if (!strcmp (opt, "verify-nursery-at-minor-gc")) {
5127 do_verify_nursery = TRUE;
5128 } else if (!strcmp (opt, "check-concurrent")) {
5129 if (!major_collector.is_concurrent) {
5130 fprintf (stderr, "Error: check-concurrent only world with concurrent major collectors.\n");
5131 exit (1);
5133 do_concurrent_checks = TRUE;
5134 } else if (!strcmp (opt, "dump-nursery-at-minor-gc")) {
5135 do_dump_nursery_content = TRUE;
5136 } else if (!strcmp (opt, "no-managed-allocator")) {
5137 sgen_set_use_managed_allocator (FALSE);
5138 } else if (!strcmp (opt, "disable-minor")) {
5139 disable_minor_collections = TRUE;
5140 } else if (!strcmp (opt, "disable-major")) {
5141 disable_major_collections = TRUE;
5142 } else if (g_str_has_prefix (opt, "heap-dump=")) {
5143 char *filename = strchr (opt, '=') + 1;
5144 nursery_clear_policy = CLEAR_AT_GC;
5145 heap_dump_file = fopen (filename, "w");
5146 if (heap_dump_file) {
5147 fprintf (heap_dump_file, "<sgen-dump>\n");
5148 do_pin_stats = TRUE;
5150 #ifdef SGEN_BINARY_PROTOCOL
5151 } else if (g_str_has_prefix (opt, "binary-protocol=")) {
5152 char *filename = strchr (opt, '=') + 1;
5153 binary_protocol_init (filename);
5154 if (use_cardtable)
5155 fprintf (stderr, "Warning: Cardtable write barriers will not be binary-protocolled.\n");
5156 #endif
5157 } else {
5158 fprintf (stderr, "Invalid format for the MONO_GC_DEBUG env variable: '%s'\n", env);
5159 fprintf (stderr, "The format is: MONO_GC_DEBUG=[l[:filename]|<option>]+ where l is a debug level 0-9.\n");
5160 fprintf (stderr, "Valid options are:\n");
5161 fprintf (stderr, " collect-before-allocs[=<n>]\n");
5162 fprintf (stderr, " verify-before-allocs[=<n>]\n");
5163 fprintf (stderr, " check-at-minor-collections\n");
5164 fprintf (stderr, " check-mark-bits\n");
5165 fprintf (stderr, " check-nursery-pinned\n");
5166 fprintf (stderr, " verify-before-collections\n");
5167 fprintf (stderr, " verify-nursery-at-minor-gc\n");
5168 fprintf (stderr, " dump-nursery-at-minor-gc\n");
5169 fprintf (stderr, " disable-minor\n");
5170 fprintf (stderr, " disable-major\n");
5171 fprintf (stderr, " xdomain-checks\n");
5172 fprintf (stderr, " check-concurrent\n");
5173 fprintf (stderr, " clear-at-gc\n");
5174 fprintf (stderr, " clear-nursery-at-gc\n");
5175 fprintf (stderr, " check-scan-starts\n");
5176 fprintf (stderr, " no-managed-allocator\n");
5177 fprintf (stderr, " print-allowance\n");
5178 fprintf (stderr, " print-pinning\n");
5179 fprintf (stderr, " heap-dump=<filename>\n");
5180 #ifdef SGEN_BINARY_PROTOCOL
5181 fprintf (stderr, " binary-protocol=<filename>\n");
5182 #endif
5183 exit (1);
5186 g_strfreev (opts);
5189 if (major_collector.is_parallel) {
5190 if (heap_dump_file) {
5191 fprintf (stderr, "Error: Cannot do heap dump with the parallel collector.\n");
5192 exit (1);
5194 if (do_pin_stats) {
5195 fprintf (stderr, "Error: Cannot gather pinning statistics with the parallel collector.\n");
5196 exit (1);
5200 if (major_collector.post_param_init)
5201 major_collector.post_param_init (&major_collector);
5203 sgen_memgov_init (max_heap, soft_limit, debug_print_allowance, allowance_ratio, save_target);
5205 memset (&remset, 0, sizeof (remset));
5207 #ifdef SGEN_HAVE_CARDTABLE
5208 if (use_cardtable)
5209 sgen_card_table_init (&remset);
5210 else
5211 #endif
5212 sgen_ssb_init (&remset);
5214 if (remset.register_thread)
5215 remset.register_thread (mono_thread_info_current ());
5217 gc_initialized = 1;
5220 const char *
5221 mono_gc_get_gc_name (void)
5223 return "sgen";
5226 static MonoMethod *write_barrier_method;
5228 gboolean
5229 sgen_is_critical_method (MonoMethod *method)
5231 return (method == write_barrier_method || sgen_is_managed_allocator (method));
5234 gboolean
5235 sgen_has_critical_method (void)
5237 return write_barrier_method || sgen_has_managed_allocator ();
5240 static void
5241 emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels)
5243 memset (nursery_check_return_labels, 0, sizeof (int) * 3);
5244 #ifdef SGEN_ALIGN_NURSERY
5245 // if (ptr_in_nursery (ptr)) return;
5247 * Masking out the bits might be faster, but we would have to use 64 bit
5248 * immediates, which might be slower.
5250 mono_mb_emit_ldarg (mb, 0);
5251 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5252 mono_mb_emit_byte (mb, CEE_SHR_UN);
5253 mono_mb_emit_icon (mb, (mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS);
5254 nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
5256 if (!major_collector.is_concurrent) {
5257 // if (!ptr_in_nursery (*ptr)) return;
5258 mono_mb_emit_ldarg (mb, 0);
5259 mono_mb_emit_byte (mb, CEE_LDIND_I);
5260 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5261 mono_mb_emit_byte (mb, CEE_SHR_UN);
5262 mono_mb_emit_icon (mb, (mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS);
5263 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
5265 #else
5266 int label_continue1, label_continue2;
5267 int dereferenced_var;
5269 // if (ptr < (sgen_get_nursery_start ())) goto continue;
5270 mono_mb_emit_ldarg (mb, 0);
5271 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5272 label_continue_1 = mono_mb_emit_branch (mb, CEE_BLT);
5274 // if (ptr >= sgen_get_nursery_end ())) goto continue;
5275 mono_mb_emit_ldarg (mb, 0);
5276 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5277 label_continue_2 = mono_mb_emit_branch (mb, CEE_BGE);
5279 // Otherwise return
5280 nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BR);
5282 // continue:
5283 mono_mb_patch_branch (mb, label_continue_1);
5284 mono_mb_patch_branch (mb, label_continue_2);
5286 // Dereference and store in local var
5287 dereferenced_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5288 mono_mb_emit_ldarg (mb, 0);
5289 mono_mb_emit_byte (mb, CEE_LDIND_I);
5290 mono_mb_emit_stloc (mb, dereferenced_var);
5292 if (!major_collector.is_concurrent) {
5293 // if (*ptr < sgen_get_nursery_start ()) return;
5294 mono_mb_emit_ldloc (mb, dereferenced_var);
5295 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5296 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BLT);
5298 // if (*ptr >= sgen_get_nursery_end ()) return;
5299 mono_mb_emit_ldloc (mb, dereferenced_var);
5300 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5301 nursery_check_return_labels [2] = mono_mb_emit_branch (mb, CEE_BGE);
5303 #endif
5306 MonoMethod*
5307 mono_gc_get_write_barrier (void)
5309 MonoMethod *res;
5310 MonoMethodBuilder *mb;
5311 MonoMethodSignature *sig;
5312 #ifdef MANAGED_WBARRIER
5313 int i, nursery_check_labels [3];
5314 int label_no_wb_3, label_no_wb_4, label_need_wb, label_slow_path;
5315 int buffer_var, buffer_index_var, dummy_var;
5317 #ifdef HAVE_KW_THREAD
5318 int stack_end_offset = -1, store_remset_buffer_offset = -1;
5319 int store_remset_buffer_index_offset = -1, store_remset_buffer_index_addr_offset = -1;
5321 MONO_THREAD_VAR_OFFSET (stack_end, stack_end_offset);
5322 g_assert (stack_end_offset != -1);
5323 MONO_THREAD_VAR_OFFSET (store_remset_buffer, store_remset_buffer_offset);
5324 g_assert (store_remset_buffer_offset != -1);
5325 MONO_THREAD_VAR_OFFSET (store_remset_buffer_index, store_remset_buffer_index_offset);
5326 g_assert (store_remset_buffer_index_offset != -1);
5327 MONO_THREAD_VAR_OFFSET (store_remset_buffer_index_addr, store_remset_buffer_index_addr_offset);
5328 g_assert (store_remset_buffer_index_addr_offset != -1);
5329 #endif
5330 #endif
5332 // FIXME: Maybe create a separate version for ctors (the branch would be
5333 // correctly predicted more times)
5334 if (write_barrier_method)
5335 return write_barrier_method;
5337 /* Create the IL version of mono_gc_barrier_generic_store () */
5338 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5339 sig->ret = &mono_defaults.void_class->byval_arg;
5340 sig->params [0] = &mono_defaults.int_class->byval_arg;
5342 mb = mono_mb_new (mono_defaults.object_class, "wbarrier", MONO_WRAPPER_WRITE_BARRIER);
5344 #ifdef MANAGED_WBARRIER
5345 if (use_cardtable) {
5346 emit_nursery_check (mb, nursery_check_labels);
5348 addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
5349 *addr = 1;
5351 sgen_cardtable:
5352 LDC_PTR sgen_cardtable
5354 address >> CARD_BITS
5355 LDARG_0
5356 LDC_I4 CARD_BITS
5357 SHR_UN
5358 if (SGEN_HAVE_OVERLAPPING_CARDS) {
5359 LDC_PTR card_table_mask
5363 ldc_i4_1
5364 stind_i1
5366 mono_mb_emit_ptr (mb, sgen_cardtable);
5367 mono_mb_emit_ldarg (mb, 0);
5368 mono_mb_emit_icon (mb, CARD_BITS);
5369 mono_mb_emit_byte (mb, CEE_SHR_UN);
5370 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
5371 mono_mb_emit_ptr (mb, (gpointer)CARD_MASK);
5372 mono_mb_emit_byte (mb, CEE_AND);
5373 #endif
5374 mono_mb_emit_byte (mb, CEE_ADD);
5375 mono_mb_emit_icon (mb, 1);
5376 mono_mb_emit_byte (mb, CEE_STIND_I1);
5378 // return;
5379 for (i = 0; i < 3; ++i) {
5380 if (nursery_check_labels [i])
5381 mono_mb_patch_branch (mb, nursery_check_labels [i]);
5383 mono_mb_emit_byte (mb, CEE_RET);
5384 } else if (mono_runtime_has_tls_get ()) {
5385 emit_nursery_check (mb, nursery_check_labels);
5387 // if (ptr >= stack_end) goto need_wb;
5388 mono_mb_emit_ldarg (mb, 0);
5389 EMIT_TLS_ACCESS (mb, stack_end, stack_end_offset);
5390 label_need_wb = mono_mb_emit_branch (mb, CEE_BGE_UN);
5392 // if (ptr >= stack_start) return;
5393 dummy_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5394 mono_mb_emit_ldarg (mb, 0);
5395 mono_mb_emit_ldloc_addr (mb, dummy_var);
5396 label_no_wb_3 = mono_mb_emit_branch (mb, CEE_BGE_UN);
5398 // need_wb:
5399 mono_mb_patch_branch (mb, label_need_wb);
5401 // buffer = STORE_REMSET_BUFFER;
5402 buffer_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5403 EMIT_TLS_ACCESS (mb, store_remset_buffer, store_remset_buffer_offset);
5404 mono_mb_emit_stloc (mb, buffer_var);
5406 // buffer_index = STORE_REMSET_BUFFER_INDEX;
5407 buffer_index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5408 EMIT_TLS_ACCESS (mb, store_remset_buffer_index, store_remset_buffer_index_offset);
5409 mono_mb_emit_stloc (mb, buffer_index_var);
5411 // if (buffer [buffer_index] == ptr) return;
5412 mono_mb_emit_ldloc (mb, buffer_var);
5413 mono_mb_emit_ldloc (mb, buffer_index_var);
5414 g_assert (sizeof (gpointer) == 4 || sizeof (gpointer) == 8);
5415 mono_mb_emit_icon (mb, sizeof (gpointer) == 4 ? 2 : 3);
5416 mono_mb_emit_byte (mb, CEE_SHL);
5417 mono_mb_emit_byte (mb, CEE_ADD);
5418 mono_mb_emit_byte (mb, CEE_LDIND_I);
5419 mono_mb_emit_ldarg (mb, 0);
5420 label_no_wb_4 = mono_mb_emit_branch (mb, CEE_BEQ);
5422 // ++buffer_index;
5423 mono_mb_emit_ldloc (mb, buffer_index_var);
5424 mono_mb_emit_icon (mb, 1);
5425 mono_mb_emit_byte (mb, CEE_ADD);
5426 mono_mb_emit_stloc (mb, buffer_index_var);
5428 // if (buffer_index >= STORE_REMSET_BUFFER_SIZE) goto slow_path;
5429 mono_mb_emit_ldloc (mb, buffer_index_var);
5430 mono_mb_emit_icon (mb, STORE_REMSET_BUFFER_SIZE);
5431 label_slow_path = mono_mb_emit_branch (mb, CEE_BGE);
5433 // buffer [buffer_index] = ptr;
5434 mono_mb_emit_ldloc (mb, buffer_var);
5435 mono_mb_emit_ldloc (mb, buffer_index_var);
5436 g_assert (sizeof (gpointer) == 4 || sizeof (gpointer) == 8);
5437 mono_mb_emit_icon (mb, sizeof (gpointer) == 4 ? 2 : 3);
5438 mono_mb_emit_byte (mb, CEE_SHL);
5439 mono_mb_emit_byte (mb, CEE_ADD);
5440 mono_mb_emit_ldarg (mb, 0);
5441 mono_mb_emit_byte (mb, CEE_STIND_I);
5443 // STORE_REMSET_BUFFER_INDEX = buffer_index;
5444 EMIT_TLS_ACCESS (mb, store_remset_buffer_index_addr, store_remset_buffer_index_addr_offset);
5445 mono_mb_emit_ldloc (mb, buffer_index_var);
5446 mono_mb_emit_byte (mb, CEE_STIND_I);
5448 // return;
5449 for (i = 0; i < 3; ++i) {
5450 if (nursery_check_labels [i])
5451 mono_mb_patch_branch (mb, nursery_check_labels [i]);
5453 mono_mb_patch_branch (mb, label_no_wb_3);
5454 mono_mb_patch_branch (mb, label_no_wb_4);
5455 mono_mb_emit_byte (mb, CEE_RET);
5457 // slow path
5458 mono_mb_patch_branch (mb, label_slow_path);
5460 mono_mb_emit_ldarg (mb, 0);
5461 mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
5462 mono_mb_emit_byte (mb, CEE_RET);
5463 } else
5464 #endif
5466 mono_mb_emit_ldarg (mb, 0);
5467 mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
5468 mono_mb_emit_byte (mb, CEE_RET);
5471 res = mono_mb_create_method (mb, sig, 16);
5472 mono_mb_free (mb);
5474 mono_loader_lock ();
5475 if (write_barrier_method) {
5476 /* Already created */
5477 mono_free_method (res);
5478 } else {
5479 /* double-checked locking */
5480 mono_memory_barrier ();
5481 write_barrier_method = res;
5483 mono_loader_unlock ();
5485 return write_barrier_method;
5488 char*
5489 mono_gc_get_description (void)
5491 return g_strdup ("sgen");
5494 void
5495 mono_gc_set_desktop_mode (void)
5499 gboolean
5500 mono_gc_is_moving (void)
5502 return TRUE;
5505 gboolean
5506 mono_gc_is_disabled (void)
5508 return FALSE;
5511 #ifdef HOST_WIN32
5512 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
5514 return TRUE;
5516 #endif
5518 NurseryClearPolicy
5519 sgen_get_nursery_clear_policy (void)
5521 return nursery_clear_policy;
5524 MonoVTable*
5525 sgen_get_array_fill_vtable (void)
5527 if (!array_fill_vtable) {
5528 static MonoClass klass;
5529 static MonoVTable vtable;
5530 gsize bmap;
5532 MonoDomain *domain = mono_get_root_domain ();
5533 g_assert (domain);
5535 klass.element_class = mono_defaults.byte_class;
5536 klass.rank = 1;
5537 klass.instance_size = sizeof (MonoArray);
5538 klass.sizes.element_size = 1;
5539 klass.name = "array_filler_type";
5541 vtable.klass = &klass;
5542 bmap = 0;
5543 vtable.gc_descr = mono_gc_make_descr_for_array (TRUE, &bmap, 0, 1);
5544 vtable.rank = 1;
5546 array_fill_vtable = &vtable;
5548 return array_fill_vtable;
5551 void
5552 sgen_gc_lock (void)
5554 LOCK_GC;
5557 void
5558 sgen_gc_unlock (void)
5560 UNLOCK_GC;
5563 void
5564 sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
5566 major_collector.iterate_live_block_ranges (callback);
5569 void
5570 sgen_major_collector_scan_card_table (SgenGrayQueue *queue)
5572 major_collector.scan_card_table (FALSE, queue);
5575 SgenMajorCollector*
5576 sgen_get_major_collector (void)
5578 return &major_collector;
5581 void mono_gc_set_skip_thread (gboolean skip)
5583 SgenThreadInfo *info = mono_thread_info_current ();
5585 LOCK_GC;
5586 info->gc_disabled = skip;
5587 UNLOCK_GC;
5590 SgenRemeberedSet*
5591 sgen_get_remset (void)
5593 return &remset;
5596 guint
5597 mono_gc_get_vtable_bits (MonoClass *class)
5599 if (sgen_need_bridge_processing () && sgen_is_bridge_class (class))
5600 return SGEN_GC_BIT_BRIDGE_OBJECT;
5601 return 0;
5604 void
5605 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
5607 // FIXME:
5611 void
5612 sgen_check_whole_heap_stw (void)
5614 sgen_stop_world (0);
5615 sgen_clear_nursery_fragments ();
5616 sgen_check_whole_heap ();
5617 sgen_restart_world (0, NULL);
5620 void
5621 sgen_gc_event_moves (void)
5623 if (moved_objects_idx) {
5624 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
5625 moved_objects_idx = 0;
5629 #endif /* HAVE_SGEN_GC */