2 * sgen-gc.c: Simple generational GC.
4 * Copyright 2001-2003 Ximian, Inc
5 * Copyright 2003-2010 Novell, Inc.
6 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
7 * Copyright (C) 2012 Xamarin Inc
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11 #ifndef __MONO_SGENGC_H__
12 #define __MONO_SGENGC_H__
19 typedef struct _SgenThreadInfo SgenThreadInfo;
20 #undef THREAD_INFO_TYPE
21 #define THREAD_INFO_TYPE SgenThreadInfo
29 #include "mono/utils/mono-compiler.h"
30 #include "mono/utils/atomic.h"
31 #include "mono/utils/mono-os-mutex.h"
32 #include "mono/utils/mono-coop-mutex.h"
33 #include "mono/sgen/sgen-conf.h"
34 #include "mono/sgen/sgen-hash-table.h"
35 #include "mono/sgen/sgen-protocol.h"
36 #include "mono/sgen/gc-internal-agnostic.h"
38 /* The method used to clear the nursery */
39 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
40 * Clearing at TLAB creation is much faster, but more complex and it might expose hard
45 CLEAR_AT_TLAB_CREATION,
46 CLEAR_AT_TLAB_CREATION_DEBUG
49 NurseryClearPolicy sgen_get_nursery_clear_policy (void);
51 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
52 #define SGEN_POSIX_STW 1
56 * The nursery section uses this struct.
58 typedef struct _GCMemSection GCMemSection;
59 struct _GCMemSection {
62 /* pointer where more data could be allocated if it fits */
66 * scan starts is an array of pointers to objects equally spaced in the allocation area
67 * They let use quickly find pinned objects from pinning pointers.
70 /* in major collections indexes in the pin_queue for objects that pin this section */
71 size_t pin_queue_first_entry;
72 size_t pin_queue_last_entry;
73 size_t num_scan_start;
77 * Recursion is not allowed for the thread lock.
79 #define LOCK_DECLARE(name) mono_mutex_t name
80 /* if changing LOCK_INIT to something that isn't idempotent, look at
81 its use in mono_gc_base_init in sgen-gc.c */
82 #define LOCK_INIT(name) mono_os_mutex_init (&(name))
83 #define LOCK_GC do { sgen_gc_lock (); } while (0)
84 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
86 extern MonoCoopMutex sgen_interruption_mutex;
88 #define LOCK_INTERRUPTION mono_coop_mutex_lock (&sgen_interruption_mutex)
89 #define UNLOCK_INTERRUPTION mono_coop_mutex_unlock (&sgen_interruption_mutex)
91 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
92 #define SGEN_CAS InterlockedCompareExchange
93 #define SGEN_CAS_PTR InterlockedCompareExchangePointer
94 #define SGEN_ATOMIC_ADD(x,i) do { \
98 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
100 #define SGEN_ATOMIC_ADD_P(x,i) do { \
104 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
107 #ifdef HEAVY_STATISTICS
108 extern guint64 stat_objects_alloced_degraded;
109 extern guint64 stat_bytes_alloced_degraded;
110 extern guint64 stat_copy_object_called_major;
111 extern guint64 stat_objects_copied_major;
114 #define SGEN_ASSERT(level, a, ...) do { \
115 if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) { \
116 g_error (__VA_ARGS__); \
120 # define LOG_TIMESTAMP \
125 localtime_r(&t, &tod); \
126 strftime(logTime, sizeof(logTime), "%Y-%m-%d %H:%M:%S", &tod); \
129 # define LOG_TIMESTAMP \
134 tod = localtime(&t); \
135 strftime(logTime, sizeof(logTime), "%F %T", tod); \
139 #define SGEN_LOG(level, format, ...) do { \
140 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
143 mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__); \
146 #define SGEN_COND_LOG(level, cond, format, ...) do { \
147 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
151 mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__); \
155 extern int gc_debug_level;
156 extern FILE* gc_debug_file;
158 extern int current_collection_generation;
160 extern unsigned int sgen_global_stop_count;
162 #define SGEN_ALIGN_UP_TO(val,align) (((val) + (align - 1)) & ~(align - 1))
163 #define SGEN_ALIGN_DOWN_TO(val,align) ((val) & ~(align - 1))
165 #define SGEN_ALLOC_ALIGN 8
166 #define SGEN_ALLOC_ALIGN_BITS 3
168 /* s must be non-negative */
169 #define SGEN_CAN_ALIGN_UP(s) ((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
170 #define SGEN_ALIGN_UP(s) SGEN_ALIGN_UP_TO(s, SGEN_ALLOC_ALIGN)
171 #define SGEN_ALIGN_DOWN(s) SGEN_ALIGN_DOWN_TO(s, SGEN_ALLOC_ALIGN)
173 #if SIZEOF_VOID_P == 4
180 sgen_aligned_addr_hash (gconstpointer ptr)
182 return GPOINTER_TO_UINT (ptr) >> 3;
185 #define SGEN_PTR_IN_NURSERY(p,bits,start,end) (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
189 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
190 #define DEFAULT_NURSERY_SIZE (sgen_nursery_size)
191 extern size_t sgen_nursery_size;
192 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
193 #define DEFAULT_NURSERY_BITS (sgen_nursery_bits)
194 extern int sgen_nursery_bits;
198 #define DEFAULT_NURSERY_SIZE (4*1024*1024)
199 #define DEFAULT_NURSERY_BITS 22
203 extern char *sgen_nursery_start;
204 extern char *sgen_nursery_end;
206 static inline MONO_ALWAYS_INLINE gboolean
207 sgen_ptr_in_nursery (void *p)
209 return SGEN_PTR_IN_NURSERY ((p), DEFAULT_NURSERY_BITS, sgen_nursery_start, sgen_nursery_end);
212 static inline MONO_ALWAYS_INLINE char*
213 sgen_get_nursery_start (void)
215 return sgen_nursery_start;
218 static inline MONO_ALWAYS_INLINE char*
219 sgen_get_nursery_end (void)
221 return sgen_nursery_end;
225 * We use the lowest three bits in the vtable pointer of objects to tag whether they're
226 * forwarded, pinned, and/or cemented. These are the valid states:
229 * |------------------+------+
231 * | forwarded | 001 |
233 * | pinned, cemented | 110 |
235 * We store them in the vtable slot because the bits are used in the sync block for other
236 * purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
237 * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
238 * would be an invalid combination for the monitor and hash code).
241 #include "sgen-tagged-pointer.h"
243 #define SGEN_VTABLE_BITS_MASK SGEN_TAGGED_POINTER_MASK
245 #define SGEN_POINTER_IS_TAGGED_FORWARDED(p) SGEN_POINTER_IS_TAGGED_1((p))
246 #define SGEN_POINTER_TAG_FORWARDED(p) SGEN_POINTER_TAG_1((p))
248 #define SGEN_POINTER_IS_TAGGED_PINNED(p) SGEN_POINTER_IS_TAGGED_2((p))
249 #define SGEN_POINTER_TAG_PINNED(p) SGEN_POINTER_TAG_2((p))
251 #define SGEN_POINTER_IS_TAGGED_CEMENTED(p) SGEN_POINTER_IS_TAGGED_4((p))
252 #define SGEN_POINTER_TAG_CEMENTED(p) SGEN_POINTER_TAG_4((p))
254 #define SGEN_POINTER_UNTAG_VTABLE(p) SGEN_POINTER_UNTAG_ALL((p))
256 /* returns NULL if not forwarded, or the forwarded address */
257 #define SGEN_VTABLE_IS_FORWARDED(vtable) ((GCVTable *)(SGEN_POINTER_IS_TAGGED_FORWARDED ((vtable)) ? SGEN_POINTER_UNTAG_VTABLE ((vtable)) : NULL))
258 #define SGEN_OBJECT_IS_FORWARDED(obj) ((GCObject *)SGEN_VTABLE_IS_FORWARDED (((mword*)(obj))[0]))
260 #define SGEN_VTABLE_IS_PINNED(vtable) SGEN_POINTER_IS_TAGGED_PINNED ((vtable))
261 #define SGEN_OBJECT_IS_PINNED(obj) (SGEN_VTABLE_IS_PINNED (((mword*)(obj))[0]))
263 #define SGEN_OBJECT_IS_CEMENTED(obj) (SGEN_POINTER_IS_TAGGED_CEMENTED (((mword*)(obj))[0]))
265 /* set the forwarded address fw_addr for object obj */
266 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do { \
267 *(void**)(obj) = SGEN_POINTER_TAG_FORWARDED ((fw_addr)); \
269 #define SGEN_PIN_OBJECT(obj) do { \
270 *(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
272 #define SGEN_CEMENT_OBJECT(obj) do { \
273 *(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
275 /* Unpins and uncements */
276 #define SGEN_UNPIN_OBJECT(obj) do { \
277 *(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
281 * Since we set bits in the vtable, use the macro to load it from the pointer to
282 * an object that is potentially pinned.
284 #define SGEN_LOAD_VTABLE(obj) ((GCVTable)(SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((GCObject *)(obj)))))
287 List of what each bit on of the vtable gc bits means.
290 // When the Java bridge has determined an object is "bridged", it uses these two bits to cache that information.
291 SGEN_GC_BIT_BRIDGE_OBJECT = 1,
292 SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT = 2,
293 SGEN_GC_BIT_FINALIZER_AWARE = 4,
296 void sgen_gc_init (void);
298 void sgen_os_init (void);
300 void sgen_update_heap_boundaries (mword low, mword high);
302 void sgen_check_section_scan_starts (GCMemSection *section);
304 void sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type);
306 gboolean sgen_gc_initialized (void);
308 /* Keep in sync with description_for_type() in sgen-internal.c! */
310 INTERNAL_MEM_PIN_QUEUE,
311 INTERNAL_MEM_FRAGMENT,
312 INTERNAL_MEM_SECTION,
313 INTERNAL_MEM_SCAN_STARTS,
314 INTERNAL_MEM_FIN_TABLE,
315 INTERNAL_MEM_FINALIZE_ENTRY,
316 INTERNAL_MEM_FINALIZE_READY,
317 INTERNAL_MEM_DISLINK_TABLE,
318 INTERNAL_MEM_DISLINK,
319 INTERNAL_MEM_ROOTS_TABLE,
320 INTERNAL_MEM_ROOT_RECORD,
321 INTERNAL_MEM_STATISTICS,
322 INTERNAL_MEM_STAT_PINNED_CLASS,
323 INTERNAL_MEM_STAT_REMSET_CLASS,
324 INTERNAL_MEM_GRAY_QUEUE,
325 INTERNAL_MEM_MS_TABLES,
326 INTERNAL_MEM_MS_BLOCK_INFO,
327 INTERNAL_MEM_MS_BLOCK_INFO_SORT,
328 INTERNAL_MEM_WORKER_DATA,
329 INTERNAL_MEM_THREAD_POOL_JOB,
330 INTERNAL_MEM_BRIDGE_DATA,
331 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE,
332 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY,
333 INTERNAL_MEM_BRIDGE_HASH_TABLE,
334 INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
335 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
336 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
337 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE,
338 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY,
339 INTERNAL_MEM_TARJAN_OBJ_BUCKET,
340 INTERNAL_MEM_BRIDGE_DEBUG,
341 INTERNAL_MEM_TOGGLEREF_DATA,
342 INTERNAL_MEM_CARDTABLE_MOD_UNION,
343 INTERNAL_MEM_BINARY_PROTOCOL,
344 INTERNAL_MEM_TEMPORARY,
345 INTERNAL_MEM_LOG_ENTRY,
346 INTERNAL_MEM_COMPLEX_DESCRIPTORS,
347 INTERNAL_MEM_FIRST_CLIENT
356 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
357 #define BINARY_PROTOCOL_ARG(x) ,x
359 #define BINARY_PROTOCOL_ARG(x)
362 void sgen_init_internal_allocator (void);
364 #define SGEN_DEFINE_OBJECT_VTABLE
365 #ifdef SGEN_CLIENT_HEADER
366 #include SGEN_CLIENT_HEADER
368 #include "metadata/sgen-client-mono.h"
370 #undef SGEN_DEFINE_OBJECT_VTABLE
372 #include "mono/sgen/sgen-descriptor.h"
373 #include "mono/sgen/sgen-gray.h"
375 /* the runtime can register areas of memory as roots: we keep two lists of roots,
376 * a pinned root set for conservatively scanned roots and a normal one for
377 * precisely scanned roots (currently implemented as a single list).
379 typedef struct _RootRecord RootRecord;
382 SgenDescriptor root_desc;
388 ROOT_TYPE_NORMAL = 0, /* "normal" roots */
389 ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
390 ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
394 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
396 int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, int source, const char *msg);
397 void sgen_deregister_root (char* addr);
399 typedef void (*IterateObjectCallbackFunc) (GCObject*, size_t, void*);
401 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags, gboolean fail_on_canaries);
403 /* eventually share with MonoThread? */
405 * This structure extends the MonoThreadInfo structure.
407 struct _SgenThreadInfo {
408 SgenClientThreadInfo client_info;
416 gboolean sgen_is_worker_thread (MonoNativeThreadId thread);
418 typedef void (*CopyOrMarkObjectFunc) (GCObject**, SgenGrayQueue*);
419 typedef void (*ScanObjectFunc) (GCObject *obj, SgenDescriptor desc, SgenGrayQueue*);
420 typedef void (*ScanVTypeFunc) (GCObject *full_object, char *start, SgenDescriptor desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
421 typedef void (*ScanPtrFieldFunc) (GCObject *obj, GCObject **ptr, SgenGrayQueue* queue);
422 typedef gboolean (*DrainGrayStackFunc) (SgenGrayQueue *queue);
425 CopyOrMarkObjectFunc copy_or_mark_object;
426 ScanObjectFunc scan_object;
427 ScanVTypeFunc scan_vtype;
428 ScanPtrFieldFunc scan_ptr_field;
429 /* Drain stack optimized for the above functions */
430 DrainGrayStackFunc drain_gray_stack;
431 /*FIXME add allocation function? */
432 } SgenObjectOperations;
436 SgenObjectOperations *ops;
437 SgenGrayQueue *queue;
440 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
442 void sgen_report_internal_mem_usage (void);
443 void sgen_dump_internal_mem_usage (FILE *heap_dump_file);
444 void sgen_dump_section (GCMemSection *section, const char *type);
445 void sgen_dump_occupied (char *start, char *end, char *section_start);
447 void sgen_register_fixed_internal_mem_type (int type, size_t size);
449 void* sgen_alloc_internal (int type);
450 void sgen_free_internal (void *addr, int type);
452 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure);
453 void sgen_free_internal_dynamic (void *addr, size_t size, int type);
455 void sgen_pin_stats_enable (void);
456 void sgen_pin_stats_register_object (GCObject *obj, int generation);
457 void sgen_pin_stats_register_global_remset (GCObject *obj);
458 void sgen_pin_stats_report (void);
460 void sgen_sort_addresses (void **array, size_t size);
461 void sgen_add_to_global_remset (gpointer ptr, GCObject *obj);
463 int sgen_get_current_collection_generation (void);
464 gboolean sgen_collection_is_concurrent (void);
465 gboolean sgen_concurrent_collection_in_progress (void);
467 typedef struct _SgenFragment SgenFragment;
469 struct _SgenFragment {
471 char *fragment_start;
472 char *fragment_next; /* the current soft limit for allocation */
474 SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
478 SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
479 SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
480 } SgenFragmentAllocator;
482 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end);
483 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator);
484 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size);
485 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size);
486 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
487 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
488 SgenFragment* sgen_fragment_allocator_alloc (void);
489 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator);
490 void sgen_clear_range (char *start, char *end);
494 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
495 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
496 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
498 Experimental results on how much space we waste with a 4Mb nursery:
500 Note that the wastage applies to the half nursery, or 2Mb:
502 Test 1 (compiling corlib):
507 #define SGEN_TO_SPACE_GRANULE_BITS 9
508 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
510 extern char *sgen_space_bitmap;
511 extern size_t sgen_space_bitmap_size;
513 static inline gboolean
514 sgen_nursery_is_to_space (void *object)
516 size_t idx = ((char*)object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
517 size_t byte = idx >> 3;
518 size_t bit = idx & 0x7;
520 SGEN_ASSERT (4, sgen_ptr_in_nursery (object), "object %p is not in nursery [%p - %p]", object, sgen_get_nursery_start (), sgen_get_nursery_end ());
521 SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %zd out of range (%zd)", byte, sgen_space_bitmap_size);
523 return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
526 static inline gboolean
527 sgen_nursery_is_from_space (void *object)
529 return !sgen_nursery_is_to_space (object);
532 static inline gboolean
533 sgen_nursery_is_object_alive (GCObject *obj)
535 /* FIXME put this asserts under a non default level */
536 g_assert (sgen_ptr_in_nursery (obj));
538 if (sgen_nursery_is_to_space (obj))
541 if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
550 GCObject* (*alloc_for_promotion) (GCVTable vtable, GCObject *obj, size_t objsize, gboolean has_references);
552 SgenObjectOperations serial_ops;
553 SgenObjectOperations serial_ops_with_concurrent_major;
555 void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
556 void (*clear_fragments) (void);
557 SgenFragment* (*build_fragments_get_exclude_head) (void);
558 void (*build_fragments_release_exclude_head) (void);
559 void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
560 void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
562 gboolean (*handle_gc_param) (const char *opt); /* Optional */
563 void (*print_gc_param_usage) (void); /* Optional */
564 } SgenMinorCollector;
566 extern SgenMinorCollector sgen_minor_collector;
568 void sgen_simple_nursery_init (SgenMinorCollector *collector);
569 void sgen_split_nursery_init (SgenMinorCollector *collector);
571 /* Updating references */
573 #ifdef SGEN_CHECK_UPDATE_REFERENCE
574 gboolean sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread);
577 sgen_update_reference (GCObject **p, GCObject *o, gboolean allow_null)
580 SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
581 SGEN_ASSERT (0, !sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
585 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), TRUE)
586 #define SGEN_UPDATE_REFERENCE(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), FALSE)
588 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) (*(GCObject**)(p) = (GCObject*)(o))
589 #define SGEN_UPDATE_REFERENCE(p,o) SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
592 /* Major collector */
594 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
595 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
596 void sgen_major_collector_iterate_block_ranges (sgen_cardtable_block_callback callback);
599 ITERATE_OBJECTS_SWEEP = 1,
600 ITERATE_OBJECTS_NON_PINNED = 2,
601 ITERATE_OBJECTS_PINNED = 4,
602 ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
603 ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
604 ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
605 } IterateObjectsFlags;
609 size_t num_scanned_objects;
610 size_t num_unique_scanned_objects;
611 } ScannedObjectCounts;
614 CARDTABLE_SCAN_GLOBAL = 0,
615 CARDTABLE_SCAN_MOD_UNION = 1,
616 CARDTABLE_SCAN_MOD_UNION_PRECLEAN = CARDTABLE_SCAN_MOD_UNION | 2,
619 typedef struct _SgenMajorCollector SgenMajorCollector;
620 struct _SgenMajorCollector {
622 gboolean is_concurrent;
623 gboolean needs_thread_pool;
624 gboolean supports_cardtable;
625 gboolean sweeps_lazily;
627 void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
628 gboolean (*is_object_live) (GCObject *obj);
629 GCObject* (*alloc_small_pinned_obj) (GCVTable vtable, size_t size, gboolean has_references);
630 GCObject* (*alloc_degraded) (GCVTable vtable, size_t size);
632 SgenObjectOperations major_ops_serial;
633 SgenObjectOperations major_ops_concurrent_start;
634 SgenObjectOperations major_ops_concurrent_finish;
636 GCObject* (*alloc_object) (GCVTable vtable, size_t size, gboolean has_references);
637 void (*free_pinned_object) (GCObject *obj, size_t size);
640 * This is used for domain unloading, heap walking from the logging profiler, and
641 * debugging. Can assume the world is stopped.
643 void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
645 void (*free_non_pinned_object) (GCObject *obj, size_t size);
646 void (*pin_objects) (SgenGrayQueue *queue);
647 void (*pin_major_object) (GCObject *obj, SgenGrayQueue *queue);
648 void (*scan_card_table) (CardTableScanType scan_type, ScanCopyContext ctx);
649 void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
650 void (*iterate_block_ranges) (sgen_cardtable_block_callback callback);
651 void (*update_cardtable_mod_union) (void);
652 void (*init_to_space) (void);
653 void (*sweep) (void);
654 gboolean (*have_swept) (void);
655 void (*finish_sweeping) (void);
656 void (*free_swept_blocks) (size_t allowance);
657 void (*check_scan_starts) (void);
658 void (*dump_heap) (FILE *heap_dump_file);
659 gint64 (*get_used_size) (void);
660 void (*start_nursery_collection) (void);
661 void (*finish_nursery_collection) (void);
662 void (*start_major_collection) (void);
663 void (*finish_major_collection) (ScannedObjectCounts *counts);
664 gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
665 gboolean (*ptr_is_from_pinned_alloc) (char *ptr);
666 void (*report_pinned_memory_usage) (void);
667 size_t (*get_num_major_sections) (void);
668 size_t (*get_bytes_survived_last_sweep) (void);
669 gboolean (*handle_gc_param) (const char *opt);
670 void (*print_gc_param_usage) (void);
671 void (*post_param_init) (SgenMajorCollector *collector);
672 gboolean (*is_valid_object) (char *ptr);
673 GCVTable (*describe_pointer) (char *pointer);
674 guint8* (*get_cardtable_mod_union_for_reference) (char *object);
675 long long (*get_and_reset_num_major_objects_marked) (void);
676 void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
679 extern SgenMajorCollector major_collector;
681 void sgen_marksweep_init (SgenMajorCollector *collector);
682 void sgen_marksweep_fixed_init (SgenMajorCollector *collector);
683 void sgen_marksweep_par_init (SgenMajorCollector *collector);
684 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector);
685 void sgen_marksweep_conc_init (SgenMajorCollector *collector);
686 SgenMajorCollector* sgen_get_major_collector (void);
689 typedef struct _SgenRememberedSet {
690 void (*wbarrier_set_field) (GCObject *obj, gpointer field_ptr, GCObject* value);
691 void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
692 void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, size_t element_size);
693 void (*wbarrier_object_copy) (GCObject* obj, GCObject *src);
694 void (*wbarrier_generic_nostore) (gpointer ptr);
695 void (*record_pointer) (gpointer ptr);
697 void (*scan_remsets) (ScanCopyContext ctx);
699 void (*clear_cards) (void);
701 void (*finish_minor_collection) (void);
702 gboolean (*find_address) (char *addr);
703 gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
706 SgenRememberedSet *sgen_get_remset (void);
709 * These must be kept in sync with object.h. They're here for using SGen independently of
712 void mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count);
713 void mono_gc_wbarrier_generic_nostore (gpointer ptr);
714 void mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value);
715 void mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value);
717 void sgen_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap);
719 static inline SgenDescriptor
720 sgen_obj_get_descriptor (GCObject *obj)
722 GCVTable vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
723 SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable), "Object can't be tagged");
724 return sgen_vtable_get_descriptor (vtable);
727 static inline SgenDescriptor
728 sgen_obj_get_descriptor_safe (GCObject *obj)
730 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
731 return sgen_vtable_get_descriptor (vtable);
734 static mword sgen_client_par_object_get_size (GCVTable vtable, GCObject* o);
735 static mword sgen_client_slow_object_get_size (GCVTable vtable, GCObject* o);
738 sgen_safe_object_get_size (GCObject *obj)
742 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
745 return sgen_client_par_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
748 static inline gboolean
749 sgen_safe_object_is_small (GCObject *obj, int type)
751 if (type <= DESC_TYPE_MAX_SMALL_OBJ)
753 return SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject*)obj)) <= SGEN_MAX_SMALL_OBJ_SIZE;
757 * This variant guarantees to return the exact size of the object
758 * before alignment. Needed for canary support.
761 sgen_safe_object_get_size_unaligned (GCObject *obj)
765 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
766 obj = (GCObject*)forwarded;
769 return sgen_client_slow_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
772 #ifdef SGEN_CLIENT_HEADER
773 #include SGEN_CLIENT_HEADER
775 #include "metadata/sgen-client-mono.h"
778 gboolean sgen_object_is_live (GCObject *obj);
780 void sgen_init_fin_weak_hash (void);
782 /* FIXME: move the toggleref stuff out of here */
783 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx);
784 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx);
786 void sgen_process_togglerefs (void);
787 void sgen_register_test_toggleref_callback (void);
789 void sgen_mark_bridge_object (GCObject *obj);
790 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx);
792 typedef gboolean (*SgenObjectPredicateFunc) (GCObject *obj, void *user_data);
794 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track);
796 gboolean sgen_gc_is_object_ready_for_finalization (GCObject *object);
797 void sgen_gc_lock (void);
798 void sgen_gc_unlock (void);
800 void sgen_queue_finalization_entry (GCObject *obj);
801 const char* sgen_generation_name (int generation);
803 void sgen_finalize_in_range (int generation, ScanCopyContext ctx);
804 void sgen_null_link_in_range (int generation, ScanCopyContext ctx, gboolean track);
805 void sgen_process_fin_stage_entries (void);
806 gboolean sgen_have_pending_finalizers (void);
807 void sgen_object_register_for_finalization (GCObject *obj, void *user_data);
809 void sgen_finalize_if (SgenObjectPredicateFunc predicate, void *user_data);
810 void sgen_remove_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, int generation);
811 void sgen_set_suspend_finalizers (void);
813 void sgen_register_disappearing_link (GCObject *obj, void **link, gboolean track, gboolean in_gc);
815 GCObject* sgen_weak_link_get (void **link_addr);
817 gboolean sgen_drain_gray_stack (ScanCopyContext ctx);
825 void sgen_pin_object (GCObject *object, SgenGrayQueue *queue);
826 void sgen_set_pinned_from_failed_allocation (mword objsize);
828 void sgen_ensure_free_space (size_t size, int generation);
829 void sgen_gc_collect (int generation);
830 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish, gboolean stw);
832 int sgen_gc_collection_count (int generation);
833 /* FIXME: what exactly does this return? */
834 size_t sgen_gc_get_used_size (void);
835 size_t sgen_gc_get_total_heap_allocation (void);
839 void sgen_stop_world (int generation);
840 void sgen_restart_world (int generation);
841 gboolean sgen_is_world_stopped (void);
843 gboolean sgen_set_allow_synchronous_major (gboolean flag);
847 typedef struct _LOSObject LOSObject;
850 mword size; /* this is the object size, lowest bit used for pin/mark */
851 guint8 * volatile cardtable_mod_union; /* only used by the concurrent collector */
852 #if SIZEOF_VOID_P < 8
853 mword dummy; /* to align object to sizeof (double) */
855 GCObject data [MONO_ZERO_LEN_ARRAY];
858 extern LOSObject *los_object_list;
859 extern mword los_memory_usage;
860 extern mword los_memory_usage_total;
862 void sgen_los_free_object (LOSObject *obj);
863 void* sgen_los_alloc_large_inner (GCVTable vtable, size_t size);
864 void sgen_los_sweep (void);
865 gboolean sgen_ptr_is_in_los (char *ptr, char **start);
866 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data);
867 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
868 void sgen_los_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx);
869 void sgen_los_update_cardtable_mod_union (void);
870 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards);
871 gboolean sgen_los_is_valid_object (char *object);
872 gboolean mono_sgen_los_describe_pointer (char *ptr);
873 LOSObject* sgen_los_header_for_object (GCObject *data);
874 mword sgen_los_object_size (LOSObject *obj);
875 void sgen_los_pin_object (GCObject *obj);
876 gboolean sgen_los_object_is_pinned (GCObject *obj);
877 void sgen_los_mark_mod_union_card (GCObject *mono_obj, void **ptr);
880 /* nursery allocator */
882 void sgen_clear_nursery_fragments (void);
883 void sgen_nursery_allocator_prepare_for_pinning (void);
884 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end);
885 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue);
886 void sgen_init_nursery_allocator (void);
887 void sgen_nursery_allocator_init_heavy_stats (void);
888 void sgen_init_allocator (void);
889 char* sgen_nursery_alloc_get_upper_alloc_bound (void);
890 void* sgen_nursery_alloc (size_t size);
891 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size);
892 gboolean sgen_can_alloc_size (size_t size);
893 void sgen_nursery_retire_region (void *address, ptrdiff_t size);
895 void sgen_nursery_alloc_prepare_for_minor (void);
896 void sgen_nursery_alloc_prepare_for_major (void);
898 GCObject* sgen_alloc_for_promotion (GCObject *obj, size_t objsize, gboolean has_references);
900 GCObject* sgen_alloc_obj_nolock (GCVTable vtable, size_t size);
901 GCObject* sgen_try_alloc_obj_nolock (GCVTable vtable, size_t size);
905 void* sgen_thread_register (SgenThreadInfo* info, void *addr);
906 void sgen_thread_unregister (SgenThreadInfo *p);
908 /* Finalization/ephemeron support */
910 static inline gboolean
911 sgen_major_is_object_alive (GCObject *object)
915 /* Oldgen objects can be pinned and forwarded too */
916 if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
920 * FIXME: major_collector.is_object_live() also calculates the
921 * size. Avoid the double calculation.
923 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (object));
924 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
925 return sgen_los_object_is_pinned (object);
927 return major_collector.is_object_live (object);
931 * This function returns true if @object is either alive or it belongs to the old gen
932 * and we're currently doing a minor collection.
935 sgen_is_object_alive_for_current_gen (GCObject *object)
937 if (sgen_ptr_in_nursery (object))
938 return sgen_nursery_is_object_alive (object);
940 if (current_collection_generation == GENERATION_NURSERY)
943 return sgen_major_is_object_alive (object);
946 int sgen_gc_invoke_finalizers (void);
950 void sgen_init_gchandles (void);
952 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track);
954 typedef gpointer (*SgenGCHandleIterateCallback) (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user);
956 void sgen_gchandle_iterate (GCHandleType handle_type, int max_generation, SgenGCHandleIterateCallback callback, gpointer user);
957 void sgen_gchandle_set_target (guint32 gchandle, GCObject *obj);
958 void sgen_mark_normal_gc_handles (void *addr, SgenUserMarkFunc mark_func, void *gc_data);
959 gpointer sgen_gchandle_get_metadata (guint32 gchandle);
963 extern GCMemSection *nursery_section;
964 extern guint32 collect_before_allocs;
965 extern guint32 verify_before_allocs;
966 extern gboolean has_per_allocation_action;
967 extern size_t degraded_mode;
968 extern int default_nursery_size;
969 extern guint32 tlab_size;
970 extern NurseryClearPolicy nursery_clear_policy;
971 extern gboolean sgen_try_free_some_memory;
972 extern mword total_promoted_size;
973 extern mword total_allocated_major;
974 extern volatile gboolean sgen_suspend_finalizers;
975 extern MonoCoopMutex gc_mutex;
977 /* Nursery helpers. */
980 sgen_set_nursery_scan_start (char *p)
982 size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
983 char *old = nursery_section->scan_starts [idx];
985 nursery_section->scan_starts [idx] = p;
989 /* Object Allocation */
999 void sgen_clear_tlabs (void);
1001 GCObject* sgen_alloc_obj (GCVTable vtable, size_t size);
1002 GCObject* sgen_alloc_obj_pinned (GCVTable vtable, size_t size);
1003 GCObject* sgen_alloc_obj_mature (GCVTable vtable, size_t size);
1007 void sgen_check_remset_consistency (void);
1008 void sgen_check_mod_union_consistency (void);
1009 void sgen_check_major_refs (void);
1010 void sgen_check_whole_heap (gboolean allow_missing_pinning);
1011 void sgen_check_whole_heap_stw (void);
1012 void sgen_check_objref (char *obj);
1013 void sgen_check_heap_marked (gboolean nursery_must_be_pinned);
1014 void sgen_check_nursery_objects_pinned (gboolean pinned);
1015 void sgen_check_for_xdomain_refs (void);
1016 GCObject* sgen_find_object_for_ptr (char *ptr);
1018 void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise);
1020 void sgen_debug_enable_heap_dump (const char *filename);
1021 void sgen_debug_dump_heap (const char *type, int num, const char *reason);
1023 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content);
1024 void sgen_debug_check_nursery_is_clean (void);
1026 /* Environment variable parsing */
1028 #define MONO_GC_PARAMS_NAME "MONO_GC_PARAMS"
1029 #define MONO_GC_DEBUG_NAME "MONO_GC_DEBUG"
1031 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...);
1035 void sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*));
1036 gint64 sgen_timestamp (void);
1039 * Canary (guard word) support
1041 * - CANARY_SIZE must be multiple of word size in bytes
1042 * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1045 gboolean nursery_canaries_enabled (void);
1047 #define CANARY_SIZE 8
1048 #define CANARY_STRING "koupepia"
1050 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) { \
1051 size = size + CANARY_SIZE; \
1054 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) { \
1055 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE); \
1058 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1060 #define CHECK_CANARY_FOR_OBJECT(addr,fail) if (nursery_canaries_enabled ()) { \
1061 char* canary_ptr = (char*) (addr) + sgen_safe_object_get_size_unaligned ((GCObject *) (addr)); \
1062 if (!CANARY_VALID(canary_ptr)) { \
1063 char canary_copy[CANARY_SIZE +1]; \
1064 strncpy (canary_copy, canary_ptr, CANARY_SIZE); \
1065 canary_copy[CANARY_SIZE] = 0; \
1067 g_error ("CORRUPT CANARY:\naddr->%p\ntype->%s\nexcepted->'%s'\nfound->'%s'\n", (char*) addr, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), CANARY_STRING, canary_copy); \
1069 g_warning ("CORRUPT CANARY:\naddr->%p\ntype->%s\nexcepted->'%s'\nfound->'%s'\n", (char*) addr, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), CANARY_STRING, canary_copy); \
1073 * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1076 sgen_dummy_use (gpointer v)
1078 #if defined(__GNUC__)
1079 __asm__ volatile ("" : "=r"(v) : "r"(v));
1080 #elif defined(_MSC_VER)
1081 static volatile gpointer ptr;
1084 #error "Implement sgen_dummy_use for your compiler"
1088 #endif /* HAVE_SGEN_GC */
1090 #endif /* __MONO_SGENGC_H__ */