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 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License 2.0 as published by the Free Software Foundation;
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License 2.0 along with this library; if not, write to the Free
20 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #ifndef __MONO_SGENGC_H__
23 #define __MONO_SGENGC_H__
30 typedef struct _SgenThreadInfo SgenThreadInfo;
31 #undef THREAD_INFO_TYPE
32 #define THREAD_INFO_TYPE SgenThreadInfo
40 #include "mono/utils/mono-compiler.h"
41 #include "mono/utils/atomic.h"
42 #include "mono/utils/mono-os-mutex.h"
43 #include "mono/utils/mono-coop-mutex.h"
44 #include "mono/sgen/sgen-conf.h"
45 #include "mono/sgen/sgen-hash-table.h"
46 #include "mono/sgen/sgen-protocol.h"
47 #include "mono/sgen/gc-internal-agnostic.h"
49 /* The method used to clear the nursery */
50 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
51 * Clearing at TLAB creation is much faster, but more complex and it might expose hard
56 CLEAR_AT_TLAB_CREATION,
57 CLEAR_AT_TLAB_CREATION_DEBUG
60 NurseryClearPolicy sgen_get_nursery_clear_policy (void);
62 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
63 #define SGEN_POSIX_STW 1
67 * The nursery section uses this struct.
69 typedef struct _GCMemSection GCMemSection;
70 struct _GCMemSection {
73 /* pointer where more data could be allocated if it fits */
77 * scan starts is an array of pointers to objects equally spaced in the allocation area
78 * They let use quickly find pinned objects from pinning pointers.
81 /* in major collections indexes in the pin_queue for objects that pin this section */
82 size_t pin_queue_first_entry;
83 size_t pin_queue_last_entry;
84 size_t num_scan_start;
88 * Recursion is not allowed for the thread lock.
90 #define LOCK_DECLARE(name) mono_mutex_t name
91 /* if changing LOCK_INIT to something that isn't idempotent, look at
92 its use in mono_gc_base_init in sgen-gc.c */
93 #define LOCK_INIT(name) mono_os_mutex_init (&(name))
94 #define LOCK_GC do { sgen_gc_lock (); } while (0)
95 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
97 extern MonoCoopMutex sgen_interruption_mutex;
99 #define LOCK_INTERRUPTION mono_coop_mutex_lock (&sgen_interruption_mutex)
100 #define UNLOCK_INTERRUPTION mono_coop_mutex_unlock (&sgen_interruption_mutex)
102 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
103 #define SGEN_CAS InterlockedCompareExchange
104 #define SGEN_CAS_PTR InterlockedCompareExchangePointer
105 #define SGEN_ATOMIC_ADD(x,i) do { \
109 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
111 #define SGEN_ATOMIC_ADD_P(x,i) do { \
115 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
118 #ifdef HEAVY_STATISTICS
119 extern guint64 stat_objects_alloced_degraded;
120 extern guint64 stat_bytes_alloced_degraded;
121 extern guint64 stat_copy_object_called_major;
122 extern guint64 stat_objects_copied_major;
125 #define SGEN_ASSERT(level, a, ...) do { \
126 if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) { \
127 g_error (__VA_ARGS__); \
131 #define SGEN_LOG(level, format, ...) do { \
132 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
133 mono_gc_printf (gc_debug_file, format "\n", ##__VA_ARGS__); \
136 #define SGEN_COND_LOG(level, cond, format, ...) do { \
137 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
139 mono_gc_printf (gc_debug_file, format "\n", ##__VA_ARGS__); \
142 extern int gc_debug_level;
143 extern FILE* gc_debug_file;
145 extern int current_collection_generation;
147 extern unsigned int sgen_global_stop_count;
149 #define SGEN_ALIGN_UP_TO(val,align) (((val) + (align - 1)) & ~(align - 1))
150 #define SGEN_ALIGN_DOWN_TO(val,align) ((val) & ~(align - 1))
152 #define SGEN_ALLOC_ALIGN 8
153 #define SGEN_ALLOC_ALIGN_BITS 3
155 /* s must be non-negative */
156 #define SGEN_CAN_ALIGN_UP(s) ((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
157 #define SGEN_ALIGN_UP(s) SGEN_ALIGN_UP_TO(s, SGEN_ALLOC_ALIGN)
158 #define SGEN_ALIGN_DOWN(s) SGEN_ALIGN_DOWN_TO(s, SGEN_ALLOC_ALIGN)
160 #if SIZEOF_VOID_P == 4
167 sgen_aligned_addr_hash (gconstpointer ptr)
169 return GPOINTER_TO_UINT (ptr) >> 3;
172 #define SGEN_PTR_IN_NURSERY(p,bits,start,end) (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
176 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
177 #define DEFAULT_NURSERY_SIZE (sgen_nursery_size)
178 extern size_t sgen_nursery_size;
179 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
180 #define DEFAULT_NURSERY_BITS (sgen_nursery_bits)
181 extern int sgen_nursery_bits;
185 #define DEFAULT_NURSERY_SIZE (4*1024*1024)
186 #define DEFAULT_NURSERY_BITS 22
190 extern char *sgen_nursery_start;
191 extern char *sgen_nursery_end;
193 static inline MONO_ALWAYS_INLINE gboolean
194 sgen_ptr_in_nursery (void *p)
196 return SGEN_PTR_IN_NURSERY ((p), DEFAULT_NURSERY_BITS, sgen_nursery_start, sgen_nursery_end);
199 static inline MONO_ALWAYS_INLINE char*
200 sgen_get_nursery_start (void)
202 return sgen_nursery_start;
205 static inline MONO_ALWAYS_INLINE char*
206 sgen_get_nursery_end (void)
208 return sgen_nursery_end;
212 * We use the lowest three bits in the vtable pointer of objects to tag whether they're
213 * forwarded, pinned, and/or cemented. These are the valid states:
216 * |------------------+------+
218 * | forwarded | 001 |
220 * | pinned, cemented | 110 |
222 * We store them in the vtable slot because the bits are used in the sync block for other
223 * purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
224 * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
225 * would be an invalid combination for the monitor and hash code).
228 #include "sgen-tagged-pointer.h"
230 #define SGEN_VTABLE_BITS_MASK SGEN_TAGGED_POINTER_MASK
232 #define SGEN_POINTER_IS_TAGGED_FORWARDED(p) SGEN_POINTER_IS_TAGGED_1((p))
233 #define SGEN_POINTER_TAG_FORWARDED(p) SGEN_POINTER_TAG_1((p))
235 #define SGEN_POINTER_IS_TAGGED_PINNED(p) SGEN_POINTER_IS_TAGGED_2((p))
236 #define SGEN_POINTER_TAG_PINNED(p) SGEN_POINTER_TAG_2((p))
238 #define SGEN_POINTER_IS_TAGGED_CEMENTED(p) SGEN_POINTER_IS_TAGGED_4((p))
239 #define SGEN_POINTER_TAG_CEMENTED(p) SGEN_POINTER_TAG_4((p))
241 #define SGEN_POINTER_UNTAG_VTABLE(p) SGEN_POINTER_UNTAG_ALL((p))
243 /* returns NULL if not forwarded, or the forwarded address */
244 #define SGEN_VTABLE_IS_FORWARDED(vtable) ((GCVTable *)(SGEN_POINTER_IS_TAGGED_FORWARDED ((vtable)) ? SGEN_POINTER_UNTAG_VTABLE ((vtable)) : NULL))
245 #define SGEN_OBJECT_IS_FORWARDED(obj) ((GCObject *)SGEN_VTABLE_IS_FORWARDED (((mword*)(obj))[0]))
247 #define SGEN_VTABLE_IS_PINNED(vtable) SGEN_POINTER_IS_TAGGED_PINNED ((vtable))
248 #define SGEN_OBJECT_IS_PINNED(obj) (SGEN_VTABLE_IS_PINNED (((mword*)(obj))[0]))
250 #define SGEN_OBJECT_IS_CEMENTED(obj) (SGEN_POINTER_IS_TAGGED_CEMENTED (((mword*)(obj))[0]))
252 /* set the forwarded address fw_addr for object obj */
253 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do { \
254 *(void**)(obj) = SGEN_POINTER_TAG_FORWARDED ((fw_addr)); \
256 #define SGEN_PIN_OBJECT(obj) do { \
257 *(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
259 #define SGEN_CEMENT_OBJECT(obj) do { \
260 *(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
262 /* Unpins and uncements */
263 #define SGEN_UNPIN_OBJECT(obj) do { \
264 *(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
268 * Since we set bits in the vtable, use the macro to load it from the pointer to
269 * an object that is potentially pinned.
271 #define SGEN_LOAD_VTABLE(obj) ((GCVTable)(SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((GCObject *)(obj)))))
274 List of what each bit on of the vtable gc bits means.
277 SGEN_GC_BIT_BRIDGE_OBJECT = 1,
278 SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT = 2,
279 SGEN_GC_BIT_FINALIZER_AWARE = 4,
282 void sgen_gc_init (void);
284 void sgen_os_init (void);
286 void sgen_update_heap_boundaries (mword low, mword high);
288 void sgen_check_section_scan_starts (GCMemSection *section);
290 void sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type);
292 /* Keep in sync with description_for_type() in sgen-internal.c! */
294 INTERNAL_MEM_PIN_QUEUE,
295 INTERNAL_MEM_FRAGMENT,
296 INTERNAL_MEM_SECTION,
297 INTERNAL_MEM_SCAN_STARTS,
298 INTERNAL_MEM_FIN_TABLE,
299 INTERNAL_MEM_FINALIZE_ENTRY,
300 INTERNAL_MEM_FINALIZE_READY,
301 INTERNAL_MEM_DISLINK_TABLE,
302 INTERNAL_MEM_DISLINK,
303 INTERNAL_MEM_ROOTS_TABLE,
304 INTERNAL_MEM_ROOT_RECORD,
305 INTERNAL_MEM_STATISTICS,
306 INTERNAL_MEM_STAT_PINNED_CLASS,
307 INTERNAL_MEM_STAT_REMSET_CLASS,
308 INTERNAL_MEM_GRAY_QUEUE,
309 INTERNAL_MEM_MS_TABLES,
310 INTERNAL_MEM_MS_BLOCK_INFO,
311 INTERNAL_MEM_MS_BLOCK_INFO_SORT,
312 INTERNAL_MEM_WORKER_DATA,
313 INTERNAL_MEM_THREAD_POOL_JOB,
314 INTERNAL_MEM_BRIDGE_DATA,
315 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE,
316 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY,
317 INTERNAL_MEM_BRIDGE_HASH_TABLE,
318 INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
319 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
320 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
321 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE,
322 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY,
323 INTERNAL_MEM_TARJAN_OBJ_BUCKET,
324 INTERNAL_MEM_BRIDGE_DEBUG,
325 INTERNAL_MEM_TOGGLEREF_DATA,
326 INTERNAL_MEM_CARDTABLE_MOD_UNION,
327 INTERNAL_MEM_BINARY_PROTOCOL,
328 INTERNAL_MEM_TEMPORARY,
329 INTERNAL_MEM_FIRST_CLIENT
338 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
339 #define BINARY_PROTOCOL_ARG(x) ,x
341 #define BINARY_PROTOCOL_ARG(x)
344 void sgen_init_internal_allocator (void);
346 #define SGEN_DEFINE_OBJECT_VTABLE
347 #ifdef SGEN_CLIENT_HEADER
348 #include SGEN_CLIENT_HEADER
350 #include "metadata/sgen-client-mono.h"
352 #undef SGEN_DEFINE_OBJECT_VTABLE
354 #include "mono/sgen/sgen-descriptor.h"
355 #include "mono/sgen/sgen-gray.h"
357 /* the runtime can register areas of memory as roots: we keep two lists of roots,
358 * a pinned root set for conservatively scanned roots and a normal one for
359 * precisely scanned roots (currently implemented as a single list).
361 typedef struct _RootRecord RootRecord;
364 SgenDescriptor root_desc;
370 ROOT_TYPE_NORMAL = 0, /* "normal" roots */
371 ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
372 ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
376 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
378 int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, int source, const char *msg);
379 void sgen_deregister_root (char* addr);
381 typedef void (*IterateObjectCallbackFunc) (GCObject*, size_t, void*);
383 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags, gboolean fail_on_canaries);
385 /* eventually share with MonoThread? */
387 * This structure extends the MonoThreadInfo structure.
389 struct _SgenThreadInfo {
390 SgenClientThreadInfo client_info;
392 char **tlab_next_addr;
393 char **tlab_start_addr;
394 char **tlab_temp_end_addr;
395 char **tlab_real_end_addr;
397 #ifndef HAVE_KW_THREAD
405 gboolean sgen_is_worker_thread (MonoNativeThreadId thread);
407 typedef void (*CopyOrMarkObjectFunc) (GCObject**, SgenGrayQueue*);
408 typedef void (*ScanObjectFunc) (GCObject *obj, SgenDescriptor desc, SgenGrayQueue*);
409 typedef void (*ScanVTypeFunc) (GCObject *full_object, char *start, SgenDescriptor desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
410 typedef gboolean (*DrainGrayStackFunc) (SgenGrayQueue *queue);
413 CopyOrMarkObjectFunc copy_or_mark_object;
414 ScanObjectFunc scan_object;
415 ScanVTypeFunc scan_vtype;
416 /* Drain stack optimized for the above functions */
417 DrainGrayStackFunc drain_gray_stack;
418 /*FIXME add allocation function? */
419 } SgenObjectOperations;
423 SgenObjectOperations *ops;
424 SgenGrayQueue *queue;
427 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
429 void sgen_report_internal_mem_usage (void);
430 void sgen_dump_internal_mem_usage (FILE *heap_dump_file);
431 void sgen_dump_section (GCMemSection *section, const char *type);
432 void sgen_dump_occupied (char *start, char *end, char *section_start);
434 void sgen_register_fixed_internal_mem_type (int type, size_t size);
436 void* sgen_alloc_internal (int type);
437 void sgen_free_internal (void *addr, int type);
439 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure);
440 void sgen_free_internal_dynamic (void *addr, size_t size, int type);
442 void sgen_pin_stats_enable (void);
443 void sgen_pin_stats_register_object (GCObject *obj, size_t size);
444 void sgen_pin_stats_register_global_remset (GCObject *obj);
445 void sgen_pin_stats_print_class_stats (void);
447 void sgen_sort_addresses (void **array, size_t size);
448 void sgen_add_to_global_remset (gpointer ptr, GCObject *obj);
450 int sgen_get_current_collection_generation (void);
451 gboolean sgen_collection_is_concurrent (void);
452 gboolean sgen_concurrent_collection_in_progress (void);
454 typedef struct _SgenFragment SgenFragment;
456 struct _SgenFragment {
458 char *fragment_start;
459 char *fragment_next; /* the current soft limit for allocation */
461 SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
465 SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
466 SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
467 } SgenFragmentAllocator;
469 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end);
470 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator);
471 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size);
472 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size);
473 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
474 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
475 SgenFragment* sgen_fragment_allocator_alloc (void);
476 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator);
477 void sgen_clear_range (char *start, char *end);
481 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
482 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
483 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
485 Experimental results on how much space we waste with a 4Mb nursery:
487 Note that the wastage applies to the half nursery, or 2Mb:
489 Test 1 (compiling corlib):
494 #define SGEN_TO_SPACE_GRANULE_BITS 9
495 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
497 extern char *sgen_space_bitmap;
498 extern size_t sgen_space_bitmap_size;
500 static inline gboolean
501 sgen_nursery_is_to_space (void *object)
503 size_t idx = ((char*)object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
504 size_t byte = idx >> 3;
505 size_t bit = idx & 0x7;
507 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 ());
508 SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %zd out of range (%zd)", byte, sgen_space_bitmap_size);
510 return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
513 static inline gboolean
514 sgen_nursery_is_from_space (void *object)
516 return !sgen_nursery_is_to_space (object);
519 static inline gboolean
520 sgen_nursery_is_object_alive (GCObject *obj)
522 /* FIXME put this asserts under a non default level */
523 g_assert (sgen_ptr_in_nursery (obj));
525 if (sgen_nursery_is_to_space (obj))
528 if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
537 GCObject* (*alloc_for_promotion) (GCVTable vtable, GCObject *obj, size_t objsize, gboolean has_references);
539 SgenObjectOperations serial_ops;
541 void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
542 void (*clear_fragments) (void);
543 SgenFragment* (*build_fragments_get_exclude_head) (void);
544 void (*build_fragments_release_exclude_head) (void);
545 void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
546 void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
548 gboolean (*handle_gc_param) (const char *opt); /* Optional */
549 void (*print_gc_param_usage) (void); /* Optional */
550 } SgenMinorCollector;
552 extern SgenMinorCollector sgen_minor_collector;
554 void sgen_simple_nursery_init (SgenMinorCollector *collector);
555 void sgen_split_nursery_init (SgenMinorCollector *collector);
557 /* Updating references */
559 #ifdef SGEN_CHECK_UPDATE_REFERENCE
560 gboolean sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread) MONO_INTERNAL;
562 sgen_update_reference (GCObject **p, GCObject *o, gboolean allow_null)
565 SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
566 SGEN_ASSERT (0, !sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
570 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), TRUE)
571 #define SGEN_UPDATE_REFERENCE(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), FALSE)
573 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) (*(GCObject**)(p) = (GCObject*)(o))
574 #define SGEN_UPDATE_REFERENCE(p,o) SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
577 /* Major collector */
579 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
580 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
583 ITERATE_OBJECTS_SWEEP = 1,
584 ITERATE_OBJECTS_NON_PINNED = 2,
585 ITERATE_OBJECTS_PINNED = 4,
586 ITERATE_OBJECTS_ALL = ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED,
587 ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
588 ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
589 ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
590 } IterateObjectsFlags;
594 size_t num_scanned_objects;
595 size_t num_unique_scanned_objects;
596 } ScannedObjectCounts;
598 typedef struct _SgenMajorCollector SgenMajorCollector;
599 struct _SgenMajorCollector {
601 gboolean is_concurrent;
602 gboolean needs_thread_pool;
603 gboolean supports_cardtable;
604 gboolean sweeps_lazily;
606 void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
607 gboolean (*is_object_live) (GCObject *obj);
608 GCObject* (*alloc_small_pinned_obj) (GCVTable vtable, size_t size, gboolean has_references);
609 GCObject* (*alloc_degraded) (GCVTable vtable, size_t size);
611 SgenObjectOperations major_ops_serial;
612 SgenObjectOperations major_ops_concurrent_start;
613 SgenObjectOperations major_ops_concurrent_finish;
615 GCObject* (*alloc_object) (GCVTable vtable, size_t size, gboolean has_references);
616 void (*free_pinned_object) (GCObject *obj, size_t size);
619 * This is used for domain unloading, heap walking from the logging profiler, and
620 * debugging. Can assume the world is stopped.
622 void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
624 void (*free_non_pinned_object) (GCObject *obj, size_t size);
625 void (*pin_objects) (SgenGrayQueue *queue);
626 void (*pin_major_object) (GCObject *obj, SgenGrayQueue *queue);
627 void (*scan_card_table) (gboolean mod_union, ScanCopyContext ctx);
628 void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
629 void (*update_cardtable_mod_union) (void);
630 void (*init_to_space) (void);
631 void (*sweep) (void);
632 gboolean (*have_swept) (void);
633 void (*finish_sweeping) (void);
634 void (*free_swept_blocks) (size_t allowance);
635 void (*check_scan_starts) (void);
636 void (*dump_heap) (FILE *heap_dump_file);
637 gint64 (*get_used_size) (void);
638 void (*start_nursery_collection) (void);
639 void (*finish_nursery_collection) (void);
640 void (*start_major_collection) (void);
641 void (*finish_major_collection) (ScannedObjectCounts *counts);
642 gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
643 gboolean (*ptr_is_from_pinned_alloc) (char *ptr);
644 void (*report_pinned_memory_usage) (void);
645 size_t (*get_num_major_sections) (void);
646 size_t (*get_bytes_survived_last_sweep) (void);
647 gboolean (*handle_gc_param) (const char *opt);
648 void (*print_gc_param_usage) (void);
649 void (*post_param_init) (SgenMajorCollector *collector);
650 gboolean (*is_valid_object) (char *ptr);
651 GCVTable (*describe_pointer) (char *pointer);
652 guint8* (*get_cardtable_mod_union_for_reference) (char *object);
653 long long (*get_and_reset_num_major_objects_marked) (void);
654 void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
657 extern SgenMajorCollector major_collector;
659 void sgen_marksweep_init (SgenMajorCollector *collector);
660 void sgen_marksweep_fixed_init (SgenMajorCollector *collector);
661 void sgen_marksweep_par_init (SgenMajorCollector *collector);
662 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector);
663 void sgen_marksweep_conc_init (SgenMajorCollector *collector);
664 SgenMajorCollector* sgen_get_major_collector (void);
667 typedef struct _SgenRememberedSet {
668 void (*wbarrier_set_field) (GCObject *obj, gpointer field_ptr, GCObject* value);
669 void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
670 void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, size_t element_size);
671 void (*wbarrier_object_copy) (GCObject* obj, GCObject *src);
672 void (*wbarrier_generic_nostore) (gpointer ptr);
673 void (*record_pointer) (gpointer ptr);
675 void (*scan_remsets) (ScanCopyContext ctx);
677 void (*clear_cards) (void);
679 void (*finish_minor_collection) (void);
680 gboolean (*find_address) (char *addr);
681 gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
684 SgenRememberedSet *sgen_get_remset (void);
687 * These must be kept in sync with object.h. They're here for using SGen independently of
690 void mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count);
691 void mono_gc_wbarrier_generic_nostore (gpointer ptr);
692 void mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value);
693 void mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value);
695 void sgen_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap);
697 static inline SgenDescriptor
698 sgen_obj_get_descriptor (GCObject *obj)
700 GCVTable vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
701 SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable), "Object can't be tagged");
702 return sgen_vtable_get_descriptor (vtable);
705 static inline SgenDescriptor
706 sgen_obj_get_descriptor_safe (GCObject *obj)
708 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
709 return sgen_vtable_get_descriptor (vtable);
712 static mword sgen_client_par_object_get_size (GCVTable vtable, GCObject* o);
713 static mword sgen_client_slow_object_get_size (GCVTable vtable, GCObject* o);
716 sgen_safe_object_get_size (GCObject *obj)
720 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
723 return sgen_client_par_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
726 static inline gboolean
727 sgen_safe_object_is_small (GCObject *obj, int type)
729 if (type <= DESC_TYPE_MAX_SMALL_OBJ)
731 return SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject*)obj)) <= SGEN_MAX_SMALL_OBJ_SIZE;
735 * This variant guarantees to return the exact size of the object
736 * before alignment. Needed for canary support.
739 sgen_safe_object_get_size_unaligned (GCObject *obj)
743 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
744 obj = (GCObject*)forwarded;
747 return sgen_client_slow_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
750 #ifdef SGEN_CLIENT_HEADER
751 #include SGEN_CLIENT_HEADER
753 #include "metadata/sgen-client-mono.h"
756 gboolean sgen_object_is_live (GCObject *obj);
758 void sgen_init_fin_weak_hash (void);
760 /* FIXME: move the toggleref stuff out of here */
761 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx);
762 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx);
764 void sgen_process_togglerefs (void);
765 void sgen_register_test_toggleref_callback (void);
767 void sgen_mark_bridge_object (GCObject *obj);
768 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx);
770 typedef gboolean (*SgenObjectPredicateFunc) (GCObject *obj, void *user_data);
772 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track);
774 gboolean sgen_gc_is_object_ready_for_finalization (GCObject *object);
775 void sgen_gc_lock (void);
776 void sgen_gc_unlock (void);
778 void sgen_queue_finalization_entry (GCObject *obj);
779 const char* sgen_generation_name (int generation);
781 void sgen_finalize_in_range (int generation, ScanCopyContext ctx);
782 void sgen_null_link_in_range (int generation, ScanCopyContext ctx, gboolean track);
783 void sgen_process_fin_stage_entries (void);
784 gboolean sgen_have_pending_finalizers (void);
785 void sgen_object_register_for_finalization (GCObject *obj, void *user_data);
787 int sgen_gather_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, GCObject **out_array, int out_size);
788 void sgen_remove_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, int generation);
790 void sgen_register_disappearing_link (GCObject *obj, void **link, gboolean track, gboolean in_gc);
792 GCObject* sgen_weak_link_get (void **link_addr);
794 gboolean sgen_drain_gray_stack (ScanCopyContext ctx);
802 void sgen_pin_object (GCObject *object, SgenGrayQueue *queue);
803 void sgen_set_pinned_from_failed_allocation (mword objsize);
805 void sgen_ensure_free_space (size_t size, int generation);
806 void sgen_gc_collect (int generation);
807 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish);
809 int sgen_gc_collection_count (int generation);
810 /* FIXME: what exactly does this return? */
811 size_t sgen_gc_get_used_size (void);
812 size_t sgen_gc_get_total_heap_allocation (void);
819 gboolean is_overflow;
825 void sgen_stop_world (int generation);
826 void sgen_restart_world (int generation, GGTimingInfo *timing);
827 gboolean sgen_is_world_stopped (void);
829 gboolean sgen_set_allow_synchronous_major (gboolean flag);
833 typedef struct _LOSObject LOSObject;
836 mword size; /* this is the object size, lowest bit used for pin/mark */
837 guint8 * volatile cardtable_mod_union; /* only used by the concurrent collector */
838 #if SIZEOF_VOID_P < 8
839 mword dummy; /* to align object to sizeof (double) */
841 GCObject data [MONO_ZERO_LEN_ARRAY];
844 extern LOSObject *los_object_list;
845 extern mword los_memory_usage;
847 void sgen_los_free_object (LOSObject *obj);
848 void* sgen_los_alloc_large_inner (GCVTable vtable, size_t size);
849 void sgen_los_sweep (void);
850 gboolean sgen_ptr_is_in_los (char *ptr, char **start);
851 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data);
852 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
853 void sgen_los_scan_card_table (gboolean mod_union, ScanCopyContext ctx);
854 void sgen_los_update_cardtable_mod_union (void);
855 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards);
856 gboolean sgen_los_is_valid_object (char *object);
857 gboolean mono_sgen_los_describe_pointer (char *ptr);
858 LOSObject* sgen_los_header_for_object (GCObject *data);
859 mword sgen_los_object_size (LOSObject *obj);
860 void sgen_los_pin_object (GCObject *obj);
861 gboolean sgen_los_object_is_pinned (GCObject *obj);
862 void sgen_los_mark_mod_union_card (GCObject *mono_obj, void **ptr);
865 /* nursery allocator */
867 void sgen_clear_nursery_fragments (void);
868 void sgen_nursery_allocator_prepare_for_pinning (void);
869 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end);
870 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue);
871 void sgen_init_nursery_allocator (void);
872 void sgen_nursery_allocator_init_heavy_stats (void);
873 void sgen_init_allocator (void);
874 char* sgen_nursery_alloc_get_upper_alloc_bound (void);
875 void* sgen_nursery_alloc (size_t size);
876 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size);
877 gboolean sgen_can_alloc_size (size_t size);
878 void sgen_nursery_retire_region (void *address, ptrdiff_t size);
880 void sgen_nursery_alloc_prepare_for_minor (void);
881 void sgen_nursery_alloc_prepare_for_major (void);
883 GCObject* sgen_alloc_for_promotion (GCObject *obj, size_t objsize, gboolean has_references);
885 GCObject* sgen_alloc_obj_nolock (GCVTable vtable, size_t size);
886 GCObject* sgen_try_alloc_obj_nolock (GCVTable vtable, size_t size);
890 void* sgen_thread_register (SgenThreadInfo* info, void *addr);
891 void sgen_thread_unregister (SgenThreadInfo *p);
893 /* Finalization/ephemeron support */
895 static inline gboolean
896 sgen_major_is_object_alive (GCObject *object)
900 /* Oldgen objects can be pinned and forwarded too */
901 if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
905 * FIXME: major_collector.is_object_live() also calculates the
906 * size. Avoid the double calculation.
908 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (object));
909 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
910 return sgen_los_object_is_pinned (object);
912 return major_collector.is_object_live (object);
916 * This function returns true if @object is either alive or it belongs to the old gen
917 * and we're currently doing a minor collection.
920 sgen_is_object_alive_for_current_gen (GCObject *object)
922 if (sgen_ptr_in_nursery (object))
923 return sgen_nursery_is_object_alive (object);
925 if (current_collection_generation == GENERATION_NURSERY)
928 return sgen_major_is_object_alive (object);
931 int sgen_gc_invoke_finalizers (void);
935 void sgen_init_gchandles (void);
937 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track);
939 typedef gpointer (*SgenGCHandleIterateCallback) (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user);
941 void sgen_gchandle_iterate (GCHandleType handle_type, int max_generation, SgenGCHandleIterateCallback callback, gpointer user);
942 void sgen_gchandle_set_target (guint32 gchandle, GCObject *obj);
943 void sgen_mark_normal_gc_handles (void *addr, SgenUserMarkFunc mark_func, void *gc_data);
944 gpointer sgen_gchandle_get_metadata (guint32 gchandle);
948 extern GCMemSection *nursery_section;
949 extern guint32 collect_before_allocs;
950 extern guint32 verify_before_allocs;
951 extern gboolean has_per_allocation_action;
952 extern size_t degraded_mode;
953 extern int default_nursery_size;
954 extern guint32 tlab_size;
955 extern NurseryClearPolicy nursery_clear_policy;
956 extern gboolean sgen_try_free_some_memory;
958 extern MonoCoopMutex gc_mutex;
960 /* Nursery helpers. */
963 sgen_set_nursery_scan_start (char *p)
965 size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
966 char *old = nursery_section->scan_starts [idx];
968 nursery_section->scan_starts [idx] = p;
972 /* Object Allocation */
982 void sgen_init_tlab_info (SgenThreadInfo* info);
983 void sgen_clear_tlabs (void);
985 GCObject* sgen_alloc_obj (GCVTable vtable, size_t size);
986 GCObject* sgen_alloc_obj_pinned (GCVTable vtable, size_t size);
987 GCObject* sgen_alloc_obj_mature (GCVTable vtable, size_t size);
991 void sgen_check_consistency (void);
992 void sgen_check_mod_union_consistency (void);
993 void sgen_check_major_refs (void);
994 void sgen_check_whole_heap (gboolean allow_missing_pinning);
995 void sgen_check_whole_heap_stw (void);
996 void sgen_check_objref (char *obj);
997 void sgen_check_heap_marked (gboolean nursery_must_be_pinned);
998 void sgen_check_nursery_objects_pinned (gboolean pinned);
999 void sgen_check_for_xdomain_refs (void);
1000 GCObject* sgen_find_object_for_ptr (char *ptr);
1002 void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise);
1004 void sgen_debug_enable_heap_dump (const char *filename);
1005 void sgen_debug_dump_heap (const char *type, int num, const char *reason);
1007 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content);
1008 void sgen_debug_check_nursery_is_clean (void);
1010 /* Environment variable parsing */
1012 #define MONO_GC_PARAMS_NAME "MONO_GC_PARAMS"
1013 #define MONO_GC_DEBUG_NAME "MONO_GC_DEBUG"
1015 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...);
1019 void sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*));
1020 gint64 sgen_timestamp (void);
1023 * Canary (guard word) support
1025 * - CANARY_SIZE must be multiple of word size in bytes
1026 * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1029 gboolean nursery_canaries_enabled (void);
1031 #define CANARY_SIZE 8
1032 #define CANARY_STRING "koupepia"
1034 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) { \
1035 size = size + CANARY_SIZE; \
1038 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) { \
1039 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE); \
1042 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1044 #define CHECK_CANARY_FOR_OBJECT(addr,fail) if (nursery_canaries_enabled ()) { \
1045 char* canary_ptr = (char*) (addr) + sgen_safe_object_get_size_unaligned ((GCObject *) (addr)); \
1046 if (!CANARY_VALID(canary_ptr)) { \
1047 char canary_copy[CANARY_SIZE +1]; \
1048 strncpy (canary_copy, canary_ptr, CANARY_SIZE); \
1049 canary_copy[CANARY_SIZE] = 0; \
1051 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); \
1053 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); \
1057 * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1060 sgen_dummy_use (gpointer v)
1062 #if defined(__GNUC__)
1063 __asm__ volatile ("" : "=r"(v) : "r"(v));
1064 #elif defined(_MSC_VER)
1065 static volatile gpointer ptr;
1068 #error "Implement sgen_dummy_use for your compiler"
1072 #endif /* HAVE_SGEN_GC */
1074 #endif /* __MONO_SGENGC_H__ */