3 * Simple generational GC.
5 * Copyright 2001-2003 Ximian, Inc
6 * Copyright 2003-2010 Novell, Inc.
7 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
8 * Copyright (C) 2012 Xamarin Inc
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12 #ifndef __MONO_SGENGC_H__
13 #define __MONO_SGENGC_H__
20 typedef struct _SgenThreadInfo SgenThreadInfo
;
21 #undef THREAD_INFO_TYPE
22 #define THREAD_INFO_TYPE SgenThreadInfo
30 #include "mono/utils/mono-compiler.h"
31 #include "mono/utils/atomic.h"
32 #include "mono/utils/mono-os-mutex.h"
33 #include "mono/utils/mono-coop-mutex.h"
34 #include "mono/sgen/sgen-conf.h"
35 #include "mono/sgen/sgen-hash-table.h"
36 #include "mono/sgen/sgen-protocol.h"
37 #include "mono/sgen/gc-internal-agnostic.h"
38 #include "mono/sgen/sgen-thread-pool.h"
40 /* The method used to clear the nursery */
41 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
42 * Clearing at TLAB creation is much faster, but more complex and it might expose hard
47 CLEAR_AT_TLAB_CREATION
,
48 CLEAR_AT_TLAB_CREATION_DEBUG
51 NurseryClearPolicy
sgen_get_nursery_clear_policy (void);
53 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
54 #define SGEN_POSIX_STW 1
58 * The nursery section uses this struct.
60 typedef struct _GCMemSection GCMemSection
;
61 struct _GCMemSection
{
65 * scan starts is an array of pointers to objects equally spaced in the allocation area
66 * They let use quickly find pinned objects from pinning pointers.
69 /* in major collections indexes in the pin_queue for objects that pin this section */
70 size_t pin_queue_first_entry
;
71 size_t pin_queue_last_entry
;
72 size_t num_scan_start
;
76 * Recursion is not allowed for the thread lock.
78 #define LOCK_DECLARE(name) mono_mutex_t name
79 /* if changing LOCK_INIT to something that isn't idempotent, look at
80 its use in mono_gc_base_init in sgen-gc.c */
81 #define LOCK_INIT(name) mono_os_mutex_init (&(name))
82 #define LOCK_GC do { sgen_gc_lock (); } while (0)
83 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
85 extern MonoCoopMutex sgen_interruption_mutex
;
87 #define LOCK_INTERRUPTION mono_coop_mutex_lock (&sgen_interruption_mutex)
88 #define UNLOCK_INTERRUPTION mono_coop_mutex_unlock (&sgen_interruption_mutex)
90 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
91 #define SGEN_CAS InterlockedCompareExchange
92 #define SGEN_CAS_PTR InterlockedCompareExchangePointer
93 #define SGEN_ATOMIC_ADD(x,i) do { \
97 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
99 #define SGEN_ATOMIC_ADD_P(x,i) do { \
103 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
106 #ifdef HEAVY_STATISTICS
107 extern guint64 stat_objects_alloced_degraded
;
108 extern guint64 stat_bytes_alloced_degraded
;
109 extern guint64 stat_copy_object_called_major
;
110 extern guint64 stat_objects_copied_major
;
113 #define SGEN_ASSERT(level, a, ...) do { \
114 if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) { \
115 g_error (__VA_ARGS__); \
118 #ifdef HAVE_LOCALTIME_R
119 # define LOG_TIMESTAMP \
124 localtime_r(&t, &tod); \
125 strftime(logTime, sizeof(logTime), "%Y-%m-%d %H:%M:%S", &tod); \
128 # define LOG_TIMESTAMP \
133 tod = localtime(&t); \
134 strftime(logTime, sizeof(logTime), "%F %T", tod); \
138 #define SGEN_LOG(level, format, ...) do { \
139 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
142 mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__); \
145 #define SGEN_COND_LOG(level, cond, format, ...) do { \
146 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
150 mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__); \
154 extern int gc_debug_level
;
155 extern FILE* gc_debug_file
;
157 extern int current_collection_generation
;
159 extern unsigned int sgen_global_stop_count
;
161 #define SGEN_ALIGN_UP_TO(val,align) (((val) + (align - 1)) & ~(align - 1))
162 #define SGEN_ALIGN_DOWN_TO(val,align) ((val) & ~(align - 1))
164 #define SGEN_ALLOC_ALIGN 8
165 #define SGEN_ALLOC_ALIGN_BITS 3
167 /* s must be non-negative */
168 #define SGEN_CAN_ALIGN_UP(s) ((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
169 #define SGEN_ALIGN_UP(s) SGEN_ALIGN_UP_TO(s, SGEN_ALLOC_ALIGN)
170 #define SGEN_ALIGN_DOWN(s) SGEN_ALIGN_DOWN_TO(s, SGEN_ALLOC_ALIGN)
172 #if SIZEOF_VOID_P == 4
179 sgen_aligned_addr_hash (gconstpointer ptr
)
181 return GPOINTER_TO_UINT (ptr
) >> 3;
184 #define SGEN_PTR_IN_NURSERY(p,bits,start,end) (((mword)(p) & ~(((mword)1 << (bits)) - 1)) == (mword)(start))
186 extern size_t sgen_nursery_size
;
187 extern size_t sgen_nursery_max_size
;
188 extern int sgen_nursery_bits
;
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
), sgen_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) ((GCObject *)(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_FORWARD_OBJECT_PAR(obj,fw_addr,final_fw_addr) do { \
257 gpointer old_vtable_word = *(gpointer*)obj; \
258 gpointer new_vtable_word; \
259 final_fw_addr = SGEN_VTABLE_IS_FORWARDED (old_vtable_word); \
262 new_vtable_word = SGEN_POINTER_TAG_FORWARDED ((fw_addr)); \
263 old_vtable_word = InterlockedCompareExchangePointer ((gpointer*)obj, new_vtable_word, old_vtable_word); \
264 final_fw_addr = SGEN_VTABLE_IS_FORWARDED (old_vtable_word); \
265 if (!final_fw_addr) \
266 final_fw_addr = (fw_addr); \
268 #define SGEN_PIN_OBJECT(obj) do { \
269 *(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
271 #define SGEN_CEMENT_OBJECT(obj) do { \
272 *(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
274 /* Unpins and uncements */
275 #define SGEN_UNPIN_OBJECT(obj) do { \
276 *(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
280 * Since we set bits in the vtable, use the macro to load it from the pointer to
281 * an object that is potentially pinned.
283 #define SGEN_LOAD_VTABLE(obj) ((GCVTable)(SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((GCObject *)(obj)))))
286 List of what each bit on of the vtable gc bits means.
289 // When the Java bridge has determined an object is "bridged", it uses these two bits to cache that information.
290 SGEN_GC_BIT_BRIDGE_OBJECT
= 1,
291 SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT
= 2,
292 SGEN_GC_BIT_FINALIZER_AWARE
= 4,
295 void sgen_gc_init (void);
297 void sgen_os_init (void);
299 void sgen_update_heap_boundaries (mword low
, mword high
);
301 void sgen_check_section_scan_starts (GCMemSection
*section
);
303 void sgen_conservatively_pin_objects_from (void **start
, void **end
, void *start_nursery
, void *end_nursery
, int pin_type
);
305 gboolean
sgen_gc_initialized (void);
307 /* Keep in sync with description_for_type() in sgen-internal.c! */
309 INTERNAL_MEM_PIN_QUEUE
,
310 INTERNAL_MEM_FRAGMENT
,
311 INTERNAL_MEM_SECTION
,
312 INTERNAL_MEM_SCAN_STARTS
,
313 INTERNAL_MEM_FIN_TABLE
,
314 INTERNAL_MEM_FINALIZE_ENTRY
,
315 INTERNAL_MEM_FINALIZE_READY
,
316 INTERNAL_MEM_DISLINK_TABLE
,
317 INTERNAL_MEM_DISLINK
,
318 INTERNAL_MEM_ROOTS_TABLE
,
319 INTERNAL_MEM_ROOT_RECORD
,
320 INTERNAL_MEM_STATISTICS
,
321 INTERNAL_MEM_STAT_PINNED_CLASS
,
322 INTERNAL_MEM_STAT_REMSET_CLASS
,
323 INTERNAL_MEM_GRAY_QUEUE
,
324 INTERNAL_MEM_MS_TABLES
,
325 INTERNAL_MEM_MS_BLOCK_INFO
,
326 INTERNAL_MEM_MS_BLOCK_INFO_SORT
,
327 INTERNAL_MEM_WORKER_DATA
,
328 INTERNAL_MEM_THREAD_POOL_JOB
,
329 INTERNAL_MEM_BRIDGE_DATA
,
330 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE
,
331 INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY
,
332 INTERNAL_MEM_BRIDGE_HASH_TABLE
,
333 INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY
,
334 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE
,
335 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY
,
336 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE
,
337 INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY
,
338 INTERNAL_MEM_TARJAN_OBJ_BUCKET
,
339 INTERNAL_MEM_BRIDGE_DEBUG
,
340 INTERNAL_MEM_TOGGLEREF_DATA
,
341 INTERNAL_MEM_CARDTABLE_MOD_UNION
,
342 INTERNAL_MEM_BINARY_PROTOCOL
,
343 INTERNAL_MEM_TEMPORARY
,
344 INTERNAL_MEM_LOG_ENTRY
,
345 INTERNAL_MEM_COMPLEX_DESCRIPTORS
,
346 INTERNAL_MEM_FIRST_CLIENT
355 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
356 #define BINARY_PROTOCOL_ARG(x) ,x
358 #define BINARY_PROTOCOL_ARG(x)
361 void sgen_init_internal_allocator (void);
363 #define SGEN_DEFINE_OBJECT_VTABLE
364 #ifdef SGEN_CLIENT_HEADER
365 #include SGEN_CLIENT_HEADER
367 #include "metadata/sgen-client-mono.h"
369 #undef SGEN_DEFINE_OBJECT_VTABLE
371 #include "mono/sgen/sgen-descriptor.h"
372 #include "mono/sgen/sgen-gray.h"
374 /* the runtime can register areas of memory as roots: we keep two lists of roots,
375 * a pinned root set for conservatively scanned roots and a normal one for
376 * precisely scanned roots (currently implemented as a single list).
378 typedef struct _RootRecord RootRecord
;
381 SgenDescriptor root_desc
;
387 ROOT_TYPE_NORMAL
= 0, /* "normal" roots */
388 ROOT_TYPE_PINNED
= 1, /* roots without a GC descriptor */
389 ROOT_TYPE_WBARRIER
= 2, /* roots with a write barrier */
393 extern SgenHashTable roots_hash
[ROOT_TYPE_NUM
];
395 int sgen_register_root (char *start
, size_t size
, SgenDescriptor descr
, int root_type
, int source
, const char *msg
);
396 void sgen_deregister_root (char* addr
);
398 typedef void (*IterateObjectCallbackFunc
) (GCObject
*, size_t, void*);
400 void sgen_scan_area_with_callback (char *start
, char *end
, IterateObjectCallbackFunc callback
, void *data
, gboolean allow_flags
, gboolean fail_on_canaries
);
402 /* eventually share with MonoThread? */
404 * This structure extends the MonoThreadInfo structure.
406 struct _SgenThreadInfo
{
407 SgenClientThreadInfo client_info
;
415 gboolean
sgen_is_worker_thread (MonoNativeThreadId thread
);
417 typedef void (*CopyOrMarkObjectFunc
) (GCObject
**, SgenGrayQueue
*);
418 typedef void (*ScanObjectFunc
) (GCObject
*obj
, SgenDescriptor desc
, SgenGrayQueue
*);
419 typedef void (*ScanVTypeFunc
) (GCObject
*full_object
, char *start
, SgenDescriptor desc
, SgenGrayQueue
* BINARY_PROTOCOL_ARG (size_t size
));
420 typedef void (*ScanPtrFieldFunc
) (GCObject
*obj
, GCObject
**ptr
, SgenGrayQueue
* queue
);
421 typedef gboolean (*DrainGrayStackFunc
) (SgenGrayQueue
*queue
);
424 CopyOrMarkObjectFunc copy_or_mark_object
;
425 ScanObjectFunc scan_object
;
426 ScanVTypeFunc scan_vtype
;
427 ScanPtrFieldFunc scan_ptr_field
;
428 /* Drain stack optimized for the above functions */
429 DrainGrayStackFunc drain_gray_stack
;
430 /*FIXME add allocation function? */
431 } SgenObjectOperations
;
435 SgenObjectOperations
*ops
;
436 SgenGrayQueue
*queue
;
439 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
441 void sgen_report_internal_mem_usage (void);
442 void sgen_dump_internal_mem_usage (FILE *heap_dump_file
);
443 void sgen_dump_section (GCMemSection
*section
, const char *type
);
444 void sgen_dump_occupied (char *start
, char *end
, char *section_start
);
446 void sgen_register_fixed_internal_mem_type (int type
, size_t size
);
448 void* sgen_alloc_internal (int type
);
449 void sgen_free_internal (void *addr
, int type
);
451 void* sgen_alloc_internal_dynamic (size_t size
, int type
, gboolean assert_on_failure
);
452 void sgen_free_internal_dynamic (void *addr
, size_t size
, int type
);
454 void sgen_pin_stats_enable (void);
455 void sgen_pin_stats_register_object (GCObject
*obj
, int generation
);
456 void sgen_pin_stats_register_global_remset (GCObject
*obj
);
457 void sgen_pin_stats_report (void);
459 void sgen_sort_addresses (void **array
, size_t size
);
460 void sgen_add_to_global_remset (gpointer ptr
, GCObject
*obj
);
462 int sgen_get_current_collection_generation (void);
463 gboolean
sgen_collection_is_concurrent (void);
464 gboolean
sgen_concurrent_collection_in_progress (void);
466 typedef struct _SgenFragment SgenFragment
;
468 struct _SgenFragment
{
470 char *fragment_start
;
471 char *fragment_next
; /* the current soft limit for allocation */
473 SgenFragment
*next_in_order
; /* We use a different entry for all active fragments so we can avoid SMR. */
477 SgenFragment
*alloc_head
; /* List head to be used when allocating memory. Walk with fragment_next. */
478 SgenFragment
*region_head
; /* List head of the region used by this allocator. Walk with next_in_order. */
479 } SgenFragmentAllocator
;
481 void sgen_fragment_allocator_add (SgenFragmentAllocator
*allocator
, char *start
, char *end
);
482 void sgen_fragment_allocator_release (SgenFragmentAllocator
*allocator
);
483 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator
*allocator
, size_t size
);
484 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator
*allocator
, size_t desired_size
, size_t minimum_size
, size_t *out_alloc_size
);
485 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator
*allocator
, size_t desired_size
, size_t minimum_size
, size_t *out_alloc_size
);
486 SgenFragment
* sgen_fragment_allocator_alloc (void);
487 void sgen_clear_allocator_fragments (SgenFragmentAllocator
*allocator
);
488 void sgen_clear_range (char *start
, char *end
);
492 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
493 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
494 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
496 Experimental results on how much space we waste with a 4Mb nursery:
498 Note that the wastage applies to the half nursery, or 2Mb:
500 Test 1 (compiling corlib):
505 #define SGEN_TO_SPACE_GRANULE_BITS 9
506 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
508 extern char *sgen_space_bitmap
;
509 extern size_t sgen_space_bitmap_size
;
511 static inline gboolean
512 sgen_nursery_is_to_space (void *object
)
514 size_t idx
= ((char*)object
- sgen_nursery_start
) >> SGEN_TO_SPACE_GRANULE_BITS
;
515 size_t byte
= idx
>> 3;
516 size_t bit
= idx
& 0x7;
518 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 ());
519 SGEN_ASSERT (4, byte
< sgen_space_bitmap_size
, "byte index %zd out of range (%zd)", byte
, sgen_space_bitmap_size
);
521 return (sgen_space_bitmap
[byte
] & (1 << bit
)) != 0;
524 static inline gboolean
525 sgen_nursery_is_from_space (void *object
)
527 return !sgen_nursery_is_to_space (object
);
530 static inline gboolean
531 sgen_nursery_is_object_alive (GCObject
*obj
)
533 /* FIXME put this asserts under a non default level */
534 g_assert (sgen_ptr_in_nursery (obj
));
536 if (sgen_nursery_is_to_space (obj
))
539 if (SGEN_OBJECT_IS_PINNED (obj
) || SGEN_OBJECT_IS_FORWARDED (obj
))
547 gboolean is_parallel
;
549 GCObject
* (*alloc_for_promotion
) (GCVTable vtable
, GCObject
*obj
, size_t objsize
, gboolean has_references
);
550 GCObject
* (*alloc_for_promotion_par
) (GCVTable vtable
, GCObject
*obj
, size_t objsize
, gboolean has_references
);
552 SgenObjectOperations serial_ops
;
553 SgenObjectOperations serial_ops_with_concurrent_major
;
554 SgenObjectOperations parallel_ops
;
555 SgenObjectOperations parallel_ops_with_concurrent_major
;
557 void (*prepare_to_space
) (char *to_space_bitmap
, size_t space_bitmap_size
);
558 void (*clear_fragments
) (void);
559 SgenFragment
* (*build_fragments_get_exclude_head
) (void);
560 void (*build_fragments_release_exclude_head
) (void);
561 void (*build_fragments_finish
) (SgenFragmentAllocator
*allocator
);
562 void (*init_nursery
) (SgenFragmentAllocator
*allocator
, char *start
, char *end
);
564 gboolean (*handle_gc_param
) (const char *opt
); /* Optional */
565 void (*print_gc_param_usage
) (void); /* Optional */
566 } SgenMinorCollector
;
568 extern SgenMinorCollector sgen_minor_collector
;
570 void sgen_simple_nursery_init (SgenMinorCollector
*collector
, gboolean parallel
);
571 void sgen_split_nursery_init (SgenMinorCollector
*collector
);
573 /* Updating references */
575 #ifdef SGEN_CHECK_UPDATE_REFERENCE
576 gboolean
sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread
);
579 sgen_update_reference (GCObject
**p
, GCObject
*o
, gboolean allow_null
)
582 SGEN_ASSERT (0, o
, "Cannot update a reference with a NULL pointer");
583 SGEN_ASSERT (0, !sgen_workers_is_worker_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
587 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), TRUE)
588 #define SGEN_UPDATE_REFERENCE(p,o) sgen_update_reference ((GCObject**)(p), (GCObject*)(o), FALSE)
590 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o) (*(GCObject**)(p) = (GCObject*)(o))
591 #define SGEN_UPDATE_REFERENCE(p,o) SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
594 /* Major collector */
596 typedef void (*sgen_cardtable_block_callback
) (mword start
, mword size
);
597 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback
);
598 void sgen_major_collector_iterate_block_ranges (sgen_cardtable_block_callback callback
);
601 ITERATE_OBJECTS_SWEEP
= 1,
602 ITERATE_OBJECTS_NON_PINNED
= 2,
603 ITERATE_OBJECTS_PINNED
= 4,
604 ITERATE_OBJECTS_SWEEP_NON_PINNED
= ITERATE_OBJECTS_SWEEP
| ITERATE_OBJECTS_NON_PINNED
,
605 ITERATE_OBJECTS_SWEEP_PINNED
= ITERATE_OBJECTS_SWEEP
| ITERATE_OBJECTS_PINNED
,
606 ITERATE_OBJECTS_SWEEP_ALL
= ITERATE_OBJECTS_SWEEP
| ITERATE_OBJECTS_NON_PINNED
| ITERATE_OBJECTS_PINNED
607 } IterateObjectsFlags
;
611 size_t num_scanned_objects
;
612 size_t num_unique_scanned_objects
;
613 } ScannedObjectCounts
;
616 CARDTABLE_SCAN_GLOBAL
= 0,
617 CARDTABLE_SCAN_MOD_UNION
= 1,
618 CARDTABLE_SCAN_MOD_UNION_PRECLEAN
= CARDTABLE_SCAN_MOD_UNION
| 2,
621 typedef struct _SgenMajorCollector SgenMajorCollector
;
622 struct _SgenMajorCollector
{
624 gboolean is_concurrent
;
625 gboolean is_parallel
;
626 gboolean supports_cardtable
;
627 gboolean sweeps_lazily
;
629 void* (*alloc_heap
) (mword nursery_size
, mword nursery_align
);
630 gboolean (*is_object_live
) (GCObject
*obj
);
631 GCObject
* (*alloc_small_pinned_obj
) (GCVTable vtable
, size_t size
, gboolean has_references
);
632 GCObject
* (*alloc_degraded
) (GCVTable vtable
, size_t size
);
634 SgenObjectOperations major_ops_serial
;
635 SgenObjectOperations major_ops_concurrent_start
;
636 SgenObjectOperations major_ops_concurrent_finish
;
637 SgenObjectOperations major_ops_conc_par_start
;
638 SgenObjectOperations major_ops_conc_par_finish
;
640 GCObject
* (*alloc_object
) (GCVTable vtable
, size_t size
, gboolean has_references
);
641 GCObject
* (*alloc_object_par
) (GCVTable vtable
, size_t size
, gboolean has_references
);
642 void (*free_pinned_object
) (GCObject
*obj
, size_t size
);
645 * This is used for domain unloading, heap walking from the logging profiler, and
646 * debugging. Can assume the world is stopped.
648 void (*iterate_objects
) (IterateObjectsFlags flags
, IterateObjectCallbackFunc callback
, void *data
);
650 void (*free_non_pinned_object
) (GCObject
*obj
, size_t size
);
651 void (*pin_objects
) (SgenGrayQueue
*queue
);
652 void (*pin_major_object
) (GCObject
*obj
, SgenGrayQueue
*queue
);
653 void (*scan_card_table
) (CardTableScanType scan_type
, ScanCopyContext ctx
, int job_index
, int job_split_count
);
654 void (*iterate_live_block_ranges
) (sgen_cardtable_block_callback callback
);
655 void (*iterate_block_ranges
) (sgen_cardtable_block_callback callback
);
656 void (*update_cardtable_mod_union
) (void);
657 void (*init_to_space
) (void);
658 void (*sweep
) (void);
659 gboolean (*have_swept
) (void);
660 void (*finish_sweeping
) (void);
661 void (*free_swept_blocks
) (size_t section_reserve
);
662 void (*check_scan_starts
) (void);
663 void (*dump_heap
) (FILE *heap_dump_file
);
664 gint64 (*get_used_size
) (void);
665 void (*start_nursery_collection
) (void);
666 void (*finish_nursery_collection
) (void);
667 void (*start_major_collection
) (void);
668 void (*finish_major_collection
) (ScannedObjectCounts
*counts
);
669 gboolean (*ptr_is_in_non_pinned_space
) (char *ptr
, char **start
);
670 gboolean (*ptr_is_from_pinned_alloc
) (char *ptr
);
671 void (*report_pinned_memory_usage
) (void);
672 size_t (*get_num_major_sections
) (void);
673 size_t (*get_bytes_survived_last_sweep
) (void);
674 gboolean (*handle_gc_param
) (const char *opt
);
675 void (*print_gc_param_usage
) (void);
676 void (*post_param_init
) (SgenMajorCollector
*collector
);
677 gboolean (*is_valid_object
) (char *ptr
);
678 GCVTable (*describe_pointer
) (char *pointer
);
679 guint8
* (*get_cardtable_mod_union_for_reference
) (char *object
);
680 long long (*get_and_reset_num_major_objects_marked
) (void);
681 void (*count_cards
) (long long *num_total_cards
, long long *num_marked_cards
);
682 void (*init_block_free_lists
) (gpointer
*list_p
);
685 extern SgenMajorCollector major_collector
;
687 void sgen_marksweep_init (SgenMajorCollector
*collector
);
688 void sgen_marksweep_conc_init (SgenMajorCollector
*collector
);
689 void sgen_marksweep_conc_par_init (SgenMajorCollector
*collector
);
690 SgenMajorCollector
* sgen_get_major_collector (void);
691 SgenMinorCollector
* sgen_get_minor_collector (void);
694 typedef struct _SgenRememberedSet
{
695 void (*wbarrier_set_field
) (GCObject
*obj
, gpointer field_ptr
, GCObject
* value
);
696 void (*wbarrier_arrayref_copy
) (gpointer dest_ptr
, gpointer src_ptr
, int count
);
697 void (*wbarrier_value_copy
) (gpointer dest
, gpointer src
, int count
, size_t element_size
);
698 void (*wbarrier_object_copy
) (GCObject
* obj
, GCObject
*src
);
699 void (*wbarrier_generic_nostore
) (gpointer ptr
);
700 void (*record_pointer
) (gpointer ptr
);
701 void (*wbarrier_range_copy
) (gpointer dest
, gpointer src
, int count
);
703 void (*start_scan_remsets
) (void);
705 void (*clear_cards
) (void);
707 gboolean (*find_address
) (char *addr
);
708 gboolean (*find_address_with_cards
) (char *cards_start
, guint8
*cards
, char *addr
);
711 SgenRememberedSet
*sgen_get_remset (void);
714 * These must be kept in sync with object.h. They're here for using SGen independently of
717 void mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr
, gpointer src_ptr
, int count
);
718 void mono_gc_wbarrier_generic_nostore (gpointer ptr
);
719 void mono_gc_wbarrier_generic_store (gpointer ptr
, GCObject
* value
);
720 void mono_gc_wbarrier_generic_store_atomic (gpointer ptr
, GCObject
*value
);
722 void sgen_wbarrier_range_copy (gpointer _dest
, gpointer _src
, int size
);
724 static inline SgenDescriptor
725 sgen_obj_get_descriptor (GCObject
*obj
)
727 GCVTable vtable
= SGEN_LOAD_VTABLE_UNCHECKED (obj
);
728 SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable
), "Object can't be tagged");
729 return sgen_vtable_get_descriptor (vtable
);
732 static inline SgenDescriptor
733 sgen_obj_get_descriptor_safe (GCObject
*obj
)
735 GCVTable vtable
= SGEN_LOAD_VTABLE (obj
);
736 return sgen_vtable_get_descriptor (vtable
);
739 static mword
sgen_client_par_object_get_size (GCVTable vtable
, GCObject
* o
);
740 static mword
sgen_client_slow_object_get_size (GCVTable vtable
, GCObject
* o
);
743 sgen_safe_object_get_size (GCObject
*obj
)
746 GCVTable vtable
= SGEN_LOAD_VTABLE_UNCHECKED (obj
);
749 * Once we load the vtable, we must always use it, in case we are in parallel case.
750 * Otherwise the object might get forwarded in the meantime and we would read an
751 * invalid vtable. An object cannot be forwarded for a second time during same GC.
753 if ((forwarded
= SGEN_VTABLE_IS_FORWARDED (vtable
)))
754 return sgen_client_par_object_get_size (SGEN_LOAD_VTABLE (forwarded
), obj
);
756 return sgen_client_par_object_get_size ((GCVTable
)SGEN_POINTER_UNTAG_ALL (vtable
), obj
);
759 static inline gboolean
760 sgen_safe_object_is_small (GCObject
*obj
, int type
)
762 if (type
<= DESC_TYPE_MAX_SMALL_OBJ
)
764 return SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject
*)obj
)) <= SGEN_MAX_SMALL_OBJ_SIZE
;
768 * This variant guarantees to return the exact size of the object
769 * before alignment. Needed for canary support.
772 sgen_safe_object_get_size_unaligned (GCObject
*obj
)
776 if ((forwarded
= SGEN_OBJECT_IS_FORWARDED (obj
))) {
777 obj
= (GCObject
*)forwarded
;
780 return sgen_client_slow_object_get_size (SGEN_LOAD_VTABLE (obj
), obj
);
783 #ifdef SGEN_CLIENT_HEADER
784 #include SGEN_CLIENT_HEADER
786 #include "metadata/sgen-client-mono.h"
789 gboolean
sgen_object_is_live (GCObject
*obj
);
791 void sgen_init_fin_weak_hash (void);
793 /* FIXME: move the toggleref stuff out of here */
794 void sgen_mark_togglerefs (char *start
, char *end
, ScanCopyContext ctx
);
795 void sgen_clear_togglerefs (char *start
, char *end
, ScanCopyContext ctx
);
797 void sgen_process_togglerefs (void);
798 void sgen_register_test_toggleref_callback (void);
800 void sgen_mark_bridge_object (GCObject
*obj
);
801 void sgen_collect_bridge_objects (int generation
, ScanCopyContext ctx
);
803 typedef gboolean (*SgenObjectPredicateFunc
) (GCObject
*obj
, void *user_data
);
805 void sgen_null_links_if (SgenObjectPredicateFunc predicate
, void *data
, int generation
, gboolean track
);
807 gboolean
sgen_gc_is_object_ready_for_finalization (GCObject
*object
);
808 void sgen_gc_lock (void);
809 void sgen_gc_unlock (void);
811 void sgen_queue_finalization_entry (GCObject
*obj
);
812 const char* sgen_generation_name (int generation
);
814 void sgen_finalize_in_range (int generation
, ScanCopyContext ctx
);
815 void sgen_null_link_in_range (int generation
, ScanCopyContext ctx
, gboolean track
);
816 void sgen_process_fin_stage_entries (void);
817 gboolean
sgen_have_pending_finalizers (void);
818 void sgen_object_register_for_finalization (GCObject
*obj
, void *user_data
);
820 void sgen_finalize_if (SgenObjectPredicateFunc predicate
, void *user_data
);
821 void sgen_remove_finalizers_if (SgenObjectPredicateFunc predicate
, void *user_data
, int generation
);
822 void sgen_set_suspend_finalizers (void);
824 void sgen_wbroots_iterate_live_block_ranges (sgen_cardtable_block_callback cb
);
825 void sgen_wbroots_scan_card_table (ScanCopyContext ctx
);
827 void sgen_register_disappearing_link (GCObject
*obj
, void **link
, gboolean track
, gboolean in_gc
);
829 GCObject
* sgen_weak_link_get (void **link_addr
);
831 gboolean
sgen_drain_gray_stack (ScanCopyContext ctx
);
839 void sgen_pin_object (GCObject
*object
, SgenGrayQueue
*queue
);
840 void sgen_set_pinned_from_failed_allocation (mword objsize
);
842 void sgen_ensure_free_space (size_t size
, int generation
);
843 void sgen_gc_collect (int generation
);
844 void sgen_perform_collection (size_t requested_size
, int generation_to_collect
, const char *reason
, gboolean wait_to_finish
, gboolean stw
);
846 int sgen_gc_collection_count (int generation
);
847 /* FIXME: what exactly does this return? */
848 size_t sgen_gc_get_used_size (void);
849 size_t sgen_gc_get_total_heap_allocation (void);
853 void sgen_stop_world (int generation
);
854 void sgen_restart_world (int generation
);
855 gboolean
sgen_is_world_stopped (void);
857 gboolean
sgen_set_allow_synchronous_major (gboolean flag
);
861 typedef struct _LOSObject LOSObject
;
864 mword size
; /* this is the object size, lowest bit used for pin/mark */
865 guint8
* volatile cardtable_mod_union
; /* only used by the concurrent collector */
866 #if SIZEOF_VOID_P < 8
867 mword dummy
; /* to align object to sizeof (double) */
869 GCObject data
[MONO_ZERO_LEN_ARRAY
];
872 extern LOSObject
*los_object_list
;
873 extern mword los_memory_usage
;
874 extern mword los_memory_usage_total
;
876 void sgen_los_free_object (LOSObject
*obj
);
877 void* sgen_los_alloc_large_inner (GCVTable vtable
, size_t size
);
878 void sgen_los_sweep (void);
879 gboolean
sgen_ptr_is_in_los (char *ptr
, char **start
);
880 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb
, void *user_data
);
881 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback
);
882 void sgen_los_scan_card_table (CardTableScanType scan_type
, ScanCopyContext ctx
, int job_index
, int job_split_count
);
883 void sgen_los_update_cardtable_mod_union (void);
884 void sgen_los_count_cards (long long *num_total_cards
, long long *num_marked_cards
);
885 gboolean
sgen_los_is_valid_object (char *object
);
886 gboolean
mono_sgen_los_describe_pointer (char *ptr
);
887 LOSObject
* sgen_los_header_for_object (GCObject
*data
);
888 mword
sgen_los_object_size (LOSObject
*obj
);
889 void sgen_los_pin_object (GCObject
*obj
);
890 gboolean
sgen_los_pin_object_par (GCObject
*obj
);
891 gboolean
sgen_los_object_is_pinned (GCObject
*obj
);
892 void sgen_los_mark_mod_union_card (GCObject
*mono_obj
, void **ptr
);
895 /* nursery allocator */
897 void sgen_clear_nursery_fragments (void);
898 void sgen_nursery_allocator_prepare_for_pinning (void);
899 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start
, size_t min_size
, size_t max_size
);
900 void sgen_resize_nursery (gboolean need_shrink
);
901 mword
sgen_build_nursery_fragments (GCMemSection
*nursery_section
, SgenGrayQueue
*unpin_queue
);
902 void sgen_init_nursery_allocator (void);
903 void sgen_nursery_allocator_init_heavy_stats (void);
904 void sgen_init_allocator (void);
905 void* sgen_nursery_alloc (size_t size
);
906 void* sgen_nursery_alloc_range (size_t size
, size_t min_size
, size_t *out_alloc_size
);
907 gboolean
sgen_can_alloc_size (size_t size
);
908 void sgen_nursery_retire_region (void *address
, ptrdiff_t size
);
910 void sgen_nursery_alloc_prepare_for_minor (void);
911 void sgen_nursery_alloc_prepare_for_major (void);
913 GCObject
* sgen_alloc_for_promotion (GCObject
*obj
, size_t objsize
, gboolean has_references
);
915 GCObject
* sgen_alloc_obj_nolock (GCVTable vtable
, size_t size
);
916 GCObject
* sgen_try_alloc_obj_nolock (GCVTable vtable
, size_t size
);
920 void* sgen_thread_attach (SgenThreadInfo
* info
);
921 void sgen_thread_detach_with_lock (SgenThreadInfo
*p
);
923 /* Finalization/ephemeron support */
925 static inline gboolean
926 sgen_major_is_object_alive (GCObject
*object
)
930 /* Oldgen objects can be pinned and forwarded too */
931 if (SGEN_OBJECT_IS_PINNED (object
) || SGEN_OBJECT_IS_FORWARDED (object
))
935 * FIXME: major_collector.is_object_live() also calculates the
936 * size. Avoid the double calculation.
938 objsize
= SGEN_ALIGN_UP (sgen_safe_object_get_size (object
));
939 if (objsize
> SGEN_MAX_SMALL_OBJ_SIZE
)
940 return sgen_los_object_is_pinned (object
);
942 return major_collector
.is_object_live (object
);
946 * This function returns true if @object is either alive or it belongs to the old gen
947 * and we're currently doing a minor collection.
950 sgen_is_object_alive_for_current_gen (GCObject
*object
)
952 if (sgen_ptr_in_nursery (object
))
953 return sgen_nursery_is_object_alive (object
);
955 if (current_collection_generation
== GENERATION_NURSERY
)
958 return sgen_major_is_object_alive (object
);
961 int sgen_gc_invoke_finalizers (void);
965 void sgen_init_gchandles (void);
967 void sgen_null_links_if (SgenObjectPredicateFunc predicate
, void *data
, int generation
, gboolean track
);
969 typedef gpointer (*SgenGCHandleIterateCallback
) (gpointer hidden
, GCHandleType handle_type
, int max_generation
, gpointer user
);
971 void sgen_gchandle_iterate (GCHandleType handle_type
, int max_generation
, SgenGCHandleIterateCallback callback
, gpointer user
);
972 void sgen_gchandle_set_target (guint32 gchandle
, GCObject
*obj
);
973 void sgen_mark_normal_gc_handles (void *addr
, SgenUserMarkFunc mark_func
, void *gc_data
);
974 gpointer
sgen_gchandle_get_metadata (guint32 gchandle
);
978 extern GCMemSection
*nursery_section
;
979 extern guint32 collect_before_allocs
;
980 extern guint32 verify_before_allocs
;
981 extern gboolean has_per_allocation_action
;
982 extern size_t degraded_mode
;
983 extern int default_nursery_size
;
984 extern guint32 tlab_size
;
985 extern NurseryClearPolicy nursery_clear_policy
;
986 extern gboolean sgen_try_free_some_memory
;
987 extern mword total_promoted_size
;
988 extern mword total_allocated_major
;
989 extern volatile gboolean sgen_suspend_finalizers
;
990 extern MonoCoopMutex gc_mutex
;
991 extern volatile gboolean concurrent_collection_in_progress
;
993 /* Nursery helpers. */
996 sgen_set_nursery_scan_start (char *p
)
998 size_t idx
= (p
- (char*)nursery_section
->data
) / SGEN_SCAN_START_SIZE
;
999 char *old
= nursery_section
->scan_starts
[idx
];
1000 if (!old
|| old
> p
)
1001 nursery_section
->scan_starts
[idx
] = p
;
1005 /* Object Allocation */
1013 } SgenAllocatorType
;
1015 void sgen_clear_tlabs (void);
1017 GCObject
* sgen_alloc_obj (GCVTable vtable
, size_t size
);
1018 GCObject
* sgen_alloc_obj_pinned (GCVTable vtable
, size_t size
);
1019 GCObject
* sgen_alloc_obj_mature (GCVTable vtable
, size_t size
);
1023 void sgen_check_remset_consistency (void);
1024 void sgen_check_mod_union_consistency (void);
1025 void sgen_check_major_refs (void);
1026 void sgen_check_whole_heap (gboolean allow_missing_pinning
);
1027 void sgen_check_whole_heap_stw (void);
1028 void sgen_check_objref (char *obj
);
1029 void sgen_check_heap_marked (gboolean nursery_must_be_pinned
);
1030 void sgen_check_nursery_objects_pinned (gboolean pinned
);
1031 void sgen_check_for_xdomain_refs (void);
1032 GCObject
* sgen_find_object_for_ptr (char *ptr
);
1034 void mono_gc_scan_for_specific_ref (GCObject
*key
, gboolean precise
);
1036 void sgen_debug_enable_heap_dump (const char *filename
);
1037 void sgen_debug_dump_heap (const char *type
, int num
, const char *reason
);
1039 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content
);
1040 void sgen_debug_check_nursery_is_clean (void);
1042 /* Environment variable parsing */
1044 #define MONO_GC_PARAMS_NAME "MONO_GC_PARAMS"
1045 #define MONO_GC_DEBUG_NAME "MONO_GC_DEBUG"
1047 void sgen_env_var_error (const char *env_var
, const char *fallback
, const char *description_format
, ...);
1051 void sgen_qsort (void *array
, size_t count
, size_t element_size
, int (*compare
) (const void*, const void*));
1052 gint64
sgen_timestamp (void);
1055 * Canary (guard word) support
1057 * - CANARY_SIZE must be multiple of word size in bytes
1058 * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1061 gboolean
nursery_canaries_enabled (void);
1063 #define CANARY_SIZE 8
1064 #define CANARY_STRING "koupepia"
1066 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) { \
1067 size = size + CANARY_SIZE; \
1070 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) { \
1071 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE); \
1074 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1076 #define CHECK_CANARY_FOR_OBJECT(addr,fail) if (nursery_canaries_enabled ()) { \
1077 guint size = sgen_safe_object_get_size_unaligned ((GCObject *) (addr)); \
1078 char* canary_ptr = (char*) (addr) + size; \
1079 if (!CANARY_VALID(canary_ptr)) { \
1080 char *window_start, *window_end; \
1081 window_start = (char*)(addr) - 128; \
1082 if (!sgen_ptr_in_nursery (window_start)) \
1083 window_start = sgen_get_nursery_start (); \
1084 window_end = (char*)(addr) + 128; \
1085 if (!sgen_ptr_in_nursery (window_end)) \
1086 window_end = sgen_get_nursery_end (); \
1087 fprintf (stderr, "\nCANARY ERROR - Type:%s Size:%d Address:%p Data:\n", sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), size, (char*) addr); \
1088 fwrite (addr, sizeof (char), size, stderr); \
1089 fprintf (stderr, "\nCanary zone (next 12 chars):\n"); \
1090 fwrite (canary_ptr, sizeof (char), 12, stderr); \
1091 fprintf (stderr, "\nOriginal canary string:\n"); \
1092 fwrite (CANARY_STRING, sizeof (char), 8, stderr); \
1093 for (int x = -8; x <= 8; x++) { \
1094 if (canary_ptr + x < (char*) addr); \
1096 if (CANARY_VALID(canary_ptr +x)) \
1097 fprintf (stderr, "\nCANARY ERROR - canary found at offset %d\n", x); \
1099 fprintf (stderr, "\nSurrounding nursery (%p - %p):\n", window_start, window_end); \
1100 fwrite (window_start, sizeof (char), window_end - window_start, stderr); \
1104 * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1107 sgen_dummy_use (gpointer v
)
1109 #if defined(__GNUC__)
1110 __asm__
volatile ("" : "=r"(v
) : "r"(v
));
1111 #elif defined(_MSC_VER)
1112 static volatile gpointer ptr
;
1115 #error "Implement sgen_dummy_use for your compiler"
1119 #endif /* HAVE_SGEN_GC */
1121 #endif /* __MONO_SGENGC_H__ */