2 * Copyright 2001-2003 Ximian, Inc
3 * Copyright 2003-2010 Novell, Inc.
4 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #ifndef __MONO_SGENGC_H__
26 #define __MONO_SGENGC_H__
33 typedef struct _SgenThreadInfo SgenThreadInfo;
34 #define THREAD_INFO_TYPE SgenThreadInfo
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-threads.h>
43 #include <mono/utils/dtrace.h>
44 #include <mono/utils/mono-logger-internal.h>
45 #include <mono/io-layer/mono-mutex.h>
46 #include <mono/metadata/class-internals.h>
47 #include <mono/metadata/object-internals.h>
48 #include <mono/metadata/sgen-conf.h>
49 #include <mono/metadata/sgen-archdep.h>
50 #include <mono/metadata/sgen-descriptor.h>
51 #include <mono/metadata/sgen-gray.h>
52 #include <mono/metadata/sgen-hash-table.h>
54 /* The method used to clear the nursery */
55 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
56 * Clearing at TLAB creation is much faster, but more complex and it might expose hard
61 CLEAR_AT_TLAB_CREATION
64 NurseryClearPolicy sgen_get_nursery_clear_policy (void) MONO_INTERNAL;
66 #define SGEN_TV_DECLARE(name) gint64 name
67 #define SGEN_TV_GETTIME(tv) tv = mono_100ns_ticks ()
68 #define SGEN_TV_ELAPSED(start,end) (int)((end-start) / 10)
69 #define SGEN_TV_ELAPSED_MS(start,end) ((SGEN_TV_ELAPSED((start),(end)) + 500) / 1000)
71 /* for use with write barriers */
72 typedef struct _RememberedSet RememberedSet;
73 struct _RememberedSet {
77 mword data [MONO_ZERO_LEN_ARRAY];
81 * We're never actually using the first element. It's always set to
82 * NULL to simplify the elimination of consecutive duplicate
85 #define STORE_REMSET_BUFFER_SIZE 1023
87 typedef struct _GenericStoreRememberedSet GenericStoreRememberedSet;
88 struct _GenericStoreRememberedSet {
89 GenericStoreRememberedSet *next;
90 /* We need one entry less because the first entry of store
91 remset buffers is always a dummy and we don't copy it. */
92 gpointer data [STORE_REMSET_BUFFER_SIZE - 1];
95 /* we have 4 possible values in the low 2 bits */
97 REMSET_LOCATION, /* just a pointer to the exact location */
98 REMSET_RANGE, /* range of pointer fields */
99 REMSET_OBJECT, /* mark all the object for scanning */
100 REMSET_VTYPE, /* a valuetype array described by a gc descriptor, a count and a size */
101 REMSET_TYPE_MASK = 0x3
104 /* eventually share with MonoThread? */
106 * This structure extends the MonoThreadInfo structure.
108 struct _SgenThreadInfo {
111 volatile int in_critical_region;
113 gboolean doing_handshake;
114 gboolean thread_is_dying;
115 gboolean gc_disabled;
118 void *stack_start_limit;
119 char **tlab_next_addr;
120 char **tlab_start_addr;
121 char **tlab_temp_end_addr;
122 char **tlab_real_end_addr;
123 gpointer **store_remset_buffer_addr;
124 long *store_remset_buffer_index_addr;
125 RememberedSet *remset;
126 gpointer runtime_data;
128 /* Only used on POSIX platforms */
131 unsigned int stop_count; /* to catch duplicate signals */
133 gpointer stopped_ip; /* only valid if the thread is stopped */
134 MonoDomain *stopped_domain; /* ditto */
137 MonoContext ctx; /* ditto */
139 gpointer regs[ARCH_NUM_REGS]; /* ditto */
142 #ifndef HAVE_KW_THREAD
147 gpointer *store_remset_buffer;
148 long store_remset_buffer_index;
158 typedef struct _SgenBlock SgenBlock;
165 * The nursery section and the major copying collector's sections use
168 typedef struct _GCMemSection GCMemSection;
169 struct _GCMemSection {
173 /* pointer where more data could be allocated if it fits */
177 * scan starts is an array of pointers to objects equally spaced in the allocation area
178 * They let use quickly find pinned objects from pinning pointers.
181 /* in major collections indexes in the pin_queue for objects that pin this section */
182 void **pin_queue_start;
183 int pin_queue_num_entries;
184 unsigned short num_scan_start;
185 gboolean is_to_space;
188 #define SGEN_PINNED_CHUNK_FOR_PTR(o) ((SgenBlock*)(((mword)(o)) & ~(SGEN_PINNED_CHUNK_SIZE - 1)))
190 typedef struct _SgenPinnedChunk SgenPinnedChunk;
193 * Recursion is not allowed for the thread lock.
195 #define LOCK_DECLARE(name) mono_mutex_t name
196 /* if changing LOCK_INIT to something that isn't idempotent, look at
197 its use in mono_gc_base_init in sgen-gc.c */
198 #define LOCK_INIT(name) mono_mutex_init (&(name), NULL)
199 #define LOCK_GC do { \
200 mono_mutex_lock (&gc_mutex); \
203 #define TRYLOCK_GC (mono_mutex_trylock (&gc_mutex) == 0)
204 #define UNLOCK_GC do { \
205 mono_mutex_unlock (&gc_mutex); \
206 MONO_GC_UNLOCKED (); \
209 extern LOCK_DECLARE (sgen_interruption_mutex);
211 #define LOCK_INTERRUPTION mono_mutex_lock (&sgen_interruption_mutex)
212 #define UNLOCK_INTERRUPTION mono_mutex_unlock (&sgen_interruption_mutex)
214 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
215 #define SGEN_CAS_PTR InterlockedCompareExchangePointer
216 #define SGEN_ATOMIC_ADD(x,i) do { \
220 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
222 #define SGEN_ATOMIC_ADD_P(x,i) do { \
226 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
231 /* we intercept pthread_create calls to know which threads exist */
232 #define USE_PTHREAD_INTERCEPT 1
235 #ifdef HEAVY_STATISTICS
236 #define HEAVY_STAT(x) x
238 extern long long stat_objects_alloced_degraded;
239 extern long long stat_bytes_alloced_degraded;
240 extern long long stat_copy_object_called_major;
241 extern long long stat_objects_copied_major;
243 #define HEAVY_STAT(x)
246 #define SGEN_ASSERT(level, a, ...) do { \
247 if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) { \
248 g_error (__VA_ARGS__); \
252 #define SGEN_LOG(level, format, ...) do { \
253 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
254 mono_gc_printf (gc_debug_file, format, ##__VA_ARGS__); \
257 #define SGEN_COND_LOG(level, cond, format, ...) do { \
258 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
260 mono_gc_printf (gc_debug_file, format, ##__VA_ARGS__); \
263 #define SGEN_LOG_DO(level, fun) do { \
264 if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { \
268 extern int gc_debug_level;
269 extern FILE* gc_debug_file;
271 extern int current_collection_generation;
273 extern unsigned int sgen_global_stop_count;
275 extern gboolean bridge_processing_in_progress;
277 extern int num_ready_finalizers;
279 #define SGEN_ALLOC_ALIGN 8
280 #define SGEN_ALLOC_ALIGN_BITS 3
282 #define SGEN_ALIGN_UP(s) (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
285 * The link pointer is hidden by negating each bit. We use the lowest
286 * bit of the link (before negation) to store whether it needs
287 * resurrection tracking.
289 #define HIDE_POINTER(p,t) ((gpointer)(~((gulong)(p)|((t)?1:0))))
290 #define REVEAL_POINTER(p) ((gpointer)((~(gulong)(p))&~3L))
292 #ifdef SGEN_ALIGN_NURSERY
293 #define SGEN_PTR_IN_NURSERY(p,bits,start,end) (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
295 #define SGEN_PTR_IN_NURSERY(p,bits,start,end) ((char*)(p) >= (start) && (char*)(p) < (end))
300 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
301 #define DEFAULT_NURSERY_SIZE (sgen_nursery_size)
302 extern int sgen_nursery_size MONO_INTERNAL;
303 #ifdef SGEN_ALIGN_NURSERY
304 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
305 #define DEFAULT_NURSERY_BITS (sgen_nursery_bits)
306 extern int sgen_nursery_bits MONO_INTERNAL;
311 #define DEFAULT_NURSERY_SIZE (4*1024*1024)
312 #ifdef SGEN_ALIGN_NURSERY
313 #define DEFAULT_NURSERY_BITS 22
318 #ifndef SGEN_ALIGN_NURSERY
319 #define DEFAULT_NURSERY_BITS -1
322 extern char *sgen_nursery_start MONO_INTERNAL;
323 extern char *sgen_nursery_end MONO_INTERNAL;
325 static inline gboolean
326 sgen_ptr_in_nursery (void *p)
328 return SGEN_PTR_IN_NURSERY ((p), DEFAULT_NURSERY_BITS, sgen_nursery_start, sgen_nursery_end);
332 sgen_get_nursery_start (void)
334 return sgen_nursery_start;
338 sgen_get_nursery_end (void)
340 return sgen_nursery_end;
343 /* Structure that corresponds to a MonoVTable: desc is a mword so requires
344 * no cast from a pointer to an integer
351 /* these bits are set in the object vtable: we could merge them since an object can be
352 * either pinned or forwarded but not both.
353 * We store them in the vtable slot because the bits are used in the sync block for
354 * other purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
355 * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
356 * would be an invalid combination for the monitor and hash code).
357 * The values are already shifted.
358 * The forwarding address is stored in the sync block.
360 #define SGEN_FORWARDED_BIT 1
361 #define SGEN_PINNED_BIT 2
362 #define SGEN_VTABLE_BITS_MASK 0x3
364 /* returns NULL if not forwarded, or the forwarded address */
365 #define SGEN_OBJECT_IS_FORWARDED(obj) (((mword*)(obj))[0] & SGEN_FORWARDED_BIT ? (void*)(((mword*)(obj))[0] & ~SGEN_VTABLE_BITS_MASK) : NULL)
366 #define SGEN_OBJECT_IS_PINNED(obj) (((mword*)(obj))[0] & SGEN_PINNED_BIT)
368 /* set the forwarded address fw_addr for object obj */
369 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do { \
370 ((mword*)(obj))[0] = (mword)(fw_addr) | SGEN_FORWARDED_BIT; \
372 #define SGEN_PIN_OBJECT(obj) do { \
373 ((mword*)(obj))[0] |= SGEN_PINNED_BIT; \
375 #define SGEN_UNPIN_OBJECT(obj) do { \
376 ((mword*)(obj))[0] &= ~SGEN_PINNED_BIT; \
380 * Since we set bits in the vtable, use the macro to load it from the pointer to
381 * an object that is potentially pinned.
383 #define SGEN_LOAD_VTABLE(addr) ((*(mword*)(addr)) & ~SGEN_VTABLE_BITS_MASK)
385 #if SGEN_MAX_DEBUG_LEVEL >= 9
386 #define GRAY_OBJECT_ENQUEUE sgen_gray_object_enqueue
387 #define GRAY_OBJECT_DEQUEUE(queue,o) ((o) = sgen_gray_object_dequeue ((queue)))
389 #define GRAY_OBJECT_ENQUEUE(queue,o) do { \
390 if (G_UNLIKELY (!(queue)->first || (queue)->first->end == SGEN_GRAY_QUEUE_SECTION_SIZE)) \
391 sgen_gray_object_enqueue ((queue), (o)); \
393 (queue)->first->objects [(queue)->first->end++] = (o); \
396 #define GRAY_OBJECT_DEQUEUE(queue,o) do { \
397 if (!(queue)->first) \
399 else if (G_UNLIKELY ((queue)->first->end == 1)) \
400 (o) = sgen_gray_object_dequeue ((queue)); \
402 (o) = (queue)->first->objects [--(queue)->first->end]; \
407 List of what each bit on of the vtable gc bits means.
410 SGEN_GC_BIT_BRIDGE_OBJECT = 1,
413 /* the runtime can register areas of memory as roots: we keep two lists of roots,
414 * a pinned root set for conservatively scanned roots and a normal one for
415 * precisely scanned roots (currently implemented as a single list).
417 typedef struct _RootRecord RootRecord;
424 ROOT_TYPE_NORMAL = 0, /* "normal" roots */
425 ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
426 ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
430 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
432 typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
434 int sgen_thread_handshake (BOOL suspend) MONO_INTERNAL;
435 gboolean sgen_suspend_thread (SgenThreadInfo *info) MONO_INTERNAL;
436 gboolean sgen_resume_thread (SgenThreadInfo *info) MONO_INTERNAL;
437 void sgen_wait_for_suspend_ack (int count) MONO_INTERNAL;
438 gboolean sgen_park_current_thread_if_doing_handshake (SgenThreadInfo *p) MONO_INTERNAL;
439 void sgen_os_init (void) MONO_INTERNAL;
441 void sgen_fill_thread_info_for_suspend (SgenThreadInfo *info) MONO_INTERNAL;
443 gboolean sgen_is_worker_thread (MonoNativeThreadId thread) MONO_INTERNAL;
445 void sgen_update_heap_boundaries (mword low, mword high) MONO_INTERNAL;
447 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags) MONO_INTERNAL;
448 void sgen_check_section_scan_starts (GCMemSection *section) MONO_INTERNAL;
450 /* Keep in sync with description_for_type() in sgen-internal.c! */
452 INTERNAL_MEM_PIN_QUEUE,
453 INTERNAL_MEM_FRAGMENT,
454 INTERNAL_MEM_SECTION,
455 INTERNAL_MEM_SCAN_STARTS,
456 INTERNAL_MEM_FIN_TABLE,
457 INTERNAL_MEM_FINALIZE_ENTRY,
458 INTERNAL_MEM_FINALIZE_READY_ENTRY,
459 INTERNAL_MEM_DISLINK_TABLE,
460 INTERNAL_MEM_DISLINK,
461 INTERNAL_MEM_ROOTS_TABLE,
462 INTERNAL_MEM_ROOT_RECORD,
463 INTERNAL_MEM_STATISTICS,
464 INTERNAL_MEM_STAT_PINNED_CLASS,
465 INTERNAL_MEM_STAT_REMSET_CLASS,
467 INTERNAL_MEM_GRAY_QUEUE,
468 INTERNAL_MEM_STORE_REMSET,
469 INTERNAL_MEM_MS_TABLES,
470 INTERNAL_MEM_MS_BLOCK_INFO,
471 INTERNAL_MEM_EPHEMERON_LINK,
472 INTERNAL_MEM_WORKER_DATA,
473 INTERNAL_MEM_BRIDGE_DATA,
474 INTERNAL_MEM_BRIDGE_HASH_TABLE,
475 INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
476 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
477 INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
478 INTERNAL_MEM_JOB_QUEUE_ENTRY,
479 INTERNAL_MEM_TOGGLEREF_DATA,
483 #define SGEN_PINNED_FREELIST_NUM_SLOTS 30
486 SgenPinnedChunk *chunk_list;
487 SgenPinnedChunk *free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
488 void *delayed_free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
489 } SgenPinnedAllocator;
497 void sgen_init_internal_allocator (void) MONO_INTERNAL;
498 void sgen_init_pinned_allocator (void) MONO_INTERNAL;
500 typedef struct _ObjectList ObjectList;
506 void sgen_report_internal_mem_usage (void) MONO_INTERNAL;
507 void sgen_report_pinned_mem_usage (SgenPinnedAllocator *alc) MONO_INTERNAL;
508 void sgen_dump_internal_mem_usage (FILE *heap_dump_file) MONO_INTERNAL;
509 void sgen_dump_section (GCMemSection *section, const char *type) MONO_INTERNAL;
510 void sgen_dump_occupied (char *start, char *end, char *section_start) MONO_INTERNAL;
512 void sgen_register_moved_object (void *obj, void *destination) MONO_INTERNAL;
514 void sgen_register_fixed_internal_mem_type (int type, size_t size) MONO_INTERNAL;
516 void* sgen_alloc_internal (int type) MONO_INTERNAL;
517 void sgen_free_internal (void *addr, int type) MONO_INTERNAL;
519 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure) MONO_INTERNAL;
520 void sgen_free_internal_dynamic (void *addr, size_t size, int type) MONO_INTERNAL;
522 void* sgen_alloc_pinned (SgenPinnedAllocator *allocator, size_t size) MONO_INTERNAL;
523 void sgen_free_pinned (SgenPinnedAllocator *allocator, void *addr, size_t size) MONO_INTERNAL;
525 gboolean sgen_parse_environment_string_extract_number (const char *str, glong *out) MONO_INTERNAL;
527 void sgen_pinned_scan_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
528 void sgen_pinned_scan_pinned_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
530 void sgen_pinned_update_heap_boundaries (SgenPinnedAllocator *alc) MONO_INTERNAL;
532 void** sgen_find_optimized_pin_queue_area (void *start, void *end, int *num) MONO_INTERNAL;
533 void sgen_find_section_pin_queue_start_end (GCMemSection *section) MONO_INTERNAL;
534 void sgen_pin_objects_in_section (GCMemSection *section, SgenGrayQueue *queue) MONO_INTERNAL;
536 void sgen_pin_stats_register_object (char *obj, size_t size);
537 void sgen_pin_stats_register_global_remset (char *obj);
538 void sgen_pin_stats_print_class_stats (void);
540 void sgen_sort_addresses (void **array, int size) MONO_INTERNAL;
541 void sgen_add_to_global_remset (gpointer ptr) MONO_INTERNAL;
543 typedef void (*CopyOrMarkObjectFunc) (void**, SgenGrayQueue*);
544 typedef void (*ScanObjectFunc) (char*, SgenGrayQueue*);
545 typedef void (*ScanVTypeFunc) (char*, mword desc, SgenGrayQueue*);
547 int sgen_get_current_collection_generation (void) MONO_INTERNAL;
548 gboolean sgen_collection_is_parallel (void) MONO_INTERNAL;
551 CopyOrMarkObjectFunc copy_or_mark_object;
552 ScanObjectFunc scan_object;
553 ScanVTypeFunc scan_vtype;
554 /*FIXME add allocation function? */
555 } SgenObjectOperations;
557 SgenObjectOperations *sgen_get_current_object_ops (void) MONO_INTERNAL;
559 typedef struct _SgenFragment SgenFragment;
561 struct _SgenFragment {
563 char *fragment_start;
564 char *fragment_next; /* the current soft limit for allocation */
566 SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
570 SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
571 SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
572 } SgenFragmentAllocator;
574 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end) MONO_INTERNAL;
575 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator) MONO_INTERNAL;
576 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size) MONO_INTERNAL;
577 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size) MONO_INTERNAL;
578 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size) MONO_INTERNAL;
579 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size) MONO_INTERNAL;
580 SgenFragment* sgen_fragment_allocator_alloc (void) MONO_INTERNAL;
581 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator) MONO_INTERNAL;
582 void sgen_clear_range (char *start, char *end) MONO_INTERNAL;
586 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
587 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
588 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
590 Experimental results on how much space we waste with a 4Mb nursery:
592 Note that the wastage applies to the half nursery, or 2Mb:
594 Test 1 (compiling corlib):
599 #define SGEN_TO_SPACE_GRANULE_BITS 9
600 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
602 extern char *sgen_space_bitmap MONO_INTERNAL;
603 extern int sgen_space_bitmap_size MONO_INTERNAL;
605 static inline gboolean
606 sgen_nursery_is_to_space (char *object)
608 int idx = (object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
612 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 ());
613 SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %d out of range", byte, sgen_space_bitmap_size);
615 return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
618 static inline gboolean
619 sgen_nursery_is_from_space (char *object)
621 return !sgen_nursery_is_to_space (object);
624 static inline gboolean
625 sgen_nursery_is_object_alive (char *obj)
627 /* FIXME put this asserts under a non default level */
628 g_assert (sgen_ptr_in_nursery (obj));
630 if (sgen_nursery_is_to_space (obj))
633 if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
640 char* (*alloc_for_promotion) (char *obj, size_t objsize, gboolean has_references);
641 char* (*par_alloc_for_promotion) (char *obj, size_t objsize, gboolean has_references);
643 SgenObjectOperations serial_ops;
644 SgenObjectOperations parallel_ops;
646 void (*prepare_to_space) (char *to_space_bitmap, int space_bitmap_size);
647 void (*clear_fragments) (void);
648 SgenFragment* (*build_fragments_get_exclude_head) (void);
649 void (*build_fragments_release_exclude_head) (void);
650 void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
651 void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
653 gboolean (*handle_gc_param) (const char *opt); /* Optional */
654 void (*print_gc_param_usage) (void); /* Optional */
655 } SgenMinorCollector;
657 extern SgenMinorCollector sgen_minor_collector;
659 void sgen_simple_nursery_init (SgenMinorCollector *collector) MONO_INTERNAL;
660 void sgen_split_nursery_init (SgenMinorCollector *collector) MONO_INTERNAL;
662 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
663 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
665 typedef struct _SgenMajorCollector SgenMajorCollector;
666 struct _SgenMajorCollector {
668 gboolean is_parallel;
669 gboolean supports_cardtable;
672 * This is set to TRUE if the sweep for the last major
673 * collection has been completed.
675 gboolean *have_swept;
677 void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
678 gboolean (*is_object_live) (char *obj);
679 void* (*alloc_small_pinned_obj) (size_t size, gboolean has_references);
680 void* (*alloc_degraded) (MonoVTable *vtable, size_t size);
682 SgenObjectOperations major_ops;
684 void* (*alloc_object) (int size, gboolean has_references);
685 void* (*par_alloc_object) (int size, gboolean has_references);
686 void (*free_pinned_object) (char *obj, size_t size);
687 void (*iterate_objects) (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data);
688 void (*free_non_pinned_object) (char *obj, size_t size);
689 void (*find_pin_queue_start_ends) (SgenGrayQueue *queue);
690 void (*pin_objects) (SgenGrayQueue *queue);
691 void (*pin_major_object) (char *obj, SgenGrayQueue *queue);
692 void (*scan_card_table) (SgenGrayQueue *queue);
693 void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
694 void (*init_to_space) (void);
695 void (*sweep) (void);
696 void (*check_scan_starts) (void);
697 void (*dump_heap) (FILE *heap_dump_file);
698 gint64 (*get_used_size) (void);
699 void (*start_nursery_collection) (void);
700 void (*finish_nursery_collection) (void);
701 void (*start_major_collection) (void);
702 void (*finish_major_collection) (void);
703 void (*have_computed_minor_collection_allowance) (void);
704 gboolean (*ptr_is_in_non_pinned_space) (char *ptr);
705 gboolean (*obj_is_from_pinned_alloc) (char *obj);
706 void (*report_pinned_memory_usage) (void);
707 int (*get_num_major_sections) (void);
708 gboolean (*handle_gc_param) (const char *opt);
709 void (*print_gc_param_usage) (void);
710 gboolean (*is_worker_thread) (MonoNativeThreadId thread);
711 void (*post_param_init) (void);
712 void* (*alloc_worker_data) (void);
713 void (*init_worker_thread) (void *data);
714 void (*reset_worker_data) (void *data);
715 gboolean (*is_valid_object) (char *object);
716 gboolean (*describe_pointer) (char *pointer);
719 extern SgenMajorCollector major_collector;
721 void sgen_marksweep_init (SgenMajorCollector *collector) MONO_INTERNAL;
722 void sgen_marksweep_fixed_init (SgenMajorCollector *collector) MONO_INTERNAL;
723 void sgen_marksweep_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
724 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
725 void sgen_copying_init (SgenMajorCollector *collector) MONO_INTERNAL;
726 SgenMajorCollector* sgen_get_major_collector (void) MONO_INTERNAL;
730 void (*wbarrier_set_field) (MonoObject *obj, gpointer field_ptr, MonoObject* value);
731 void (*wbarrier_set_arrayref) (MonoArray *arr, gpointer slot_ptr, MonoObject* value);
732 void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
733 void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, MonoClass *klass);
734 void (*wbarrier_object_copy) (MonoObject* obj, MonoObject *src);
735 void (*wbarrier_generic_nostore) (gpointer ptr);
736 void (*record_pointer) (gpointer ptr);
738 void (*begin_scan_remsets) (void *start_nursery, void *end_nursery, SgenGrayQueue *queue); /* OPTIONAL */
739 void (*finish_scan_remsets) (void *start_nursery, void *end_nursery, SgenGrayQueue *queue);
741 void (*register_thread) (SgenThreadInfo *p); /* OPTIONAL */
742 void (*cleanup_thread) (SgenThreadInfo *p); /* OPTIONAL */
743 void (*fill_thread_info_for_suspend) (SgenThreadInfo *info); /* OPTIONAL */
744 void (*prepare_for_minor_collection) (void); /* OPTIONAL */
745 void (*prepare_for_major_collection) (void);
747 void (*finish_minor_collection) (void); /* OPTIONAL */
748 gboolean (*find_address) (char *addr);
751 SgenRemeberedSet *sgen_get_remset (void) MONO_INTERNAL;
753 static guint /*__attribute__((noinline)) not sure if this hint is a good idea*/
754 slow_object_get_size (MonoVTable *vtable, MonoObject* o)
756 MonoClass *klass = vtable->klass;
759 * We depend on mono_string_length_fast and
760 * mono_array_length_fast not using the object's vtable.
762 if (klass == mono_defaults.string_class) {
763 return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
764 } else if (klass->rank) {
765 MonoArray *array = (MonoArray*)o;
766 size_t size = sizeof (MonoArray) + klass->sizes.element_size * mono_array_length_fast (array);
767 if (G_UNLIKELY (array->bounds)) {
768 size += sizeof (mono_array_size_t) - 1;
769 size &= ~(sizeof (mono_array_size_t) - 1);
770 size += sizeof (MonoArrayBounds) * klass->rank;
774 /* from a created object: the class must be inited already */
775 return klass->instance_size;
780 * This function can be called on an object whose first word, the
781 * vtable field, is not intact. This is necessary for the parallel
785 sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
787 mword descr = (mword)vtable->gc_descr;
788 mword type = descr & 0x7;
790 if (type == DESC_TYPE_RUN_LENGTH || type == DESC_TYPE_SMALL_BITMAP) {
791 mword size = descr & 0xfff8;
792 if (size == 0) /* This is used to encode a string */
793 return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
795 } else if (type == DESC_TYPE_VECTOR) {
796 int element_size = ((descr) >> VECTOR_ELSIZE_SHIFT) & MAX_ELEMENT_SIZE;
797 MonoArray *array = (MonoArray*)o;
798 size_t size = sizeof (MonoArray) + element_size * mono_array_length_fast (array);
800 if (descr & VECTOR_KIND_ARRAY) {
801 size += sizeof (mono_array_size_t) - 1;
802 size &= ~(sizeof (mono_array_size_t) - 1);
803 size += sizeof (MonoArrayBounds) * vtable->klass->rank;
808 return slow_object_get_size (vtable, o);
812 sgen_safe_object_get_size (MonoObject *obj)
816 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
817 obj = (MonoObject*)forwarded;
819 return sgen_par_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE (obj), obj);
822 const char* sgen_safe_name (void* obj) MONO_INTERNAL;
824 gboolean sgen_object_is_live (void *obj) MONO_INTERNAL;
826 gboolean sgen_need_bridge_processing (void) MONO_INTERNAL;
827 void sgen_bridge_reset_data (void) MONO_INTERNAL;
828 void sgen_bridge_processing_stw_step (void) MONO_INTERNAL;
829 void sgen_bridge_processing_finish (int generation) MONO_INTERNAL;
830 void sgen_register_test_bridge_callbacks (const char *bridge_class_name) MONO_INTERNAL;
831 gboolean sgen_is_bridge_object (MonoObject *obj) MONO_INTERNAL;
832 gboolean sgen_is_bridge_class (MonoClass *class) MONO_INTERNAL;
833 void sgen_mark_bridge_object (MonoObject *obj) MONO_INTERNAL;
834 void sgen_bridge_register_finalized_object (MonoObject *object) MONO_INTERNAL;
836 void sgen_scan_togglerefs (CopyOrMarkObjectFunc copy_func, char *start, char *end, SgenGrayQueue *queue) MONO_INTERNAL;
837 void sgen_process_togglerefs (void) MONO_INTERNAL;
839 typedef mono_bool (*WeakLinkAlivePredicateFunc) (MonoObject*, void*);
841 void sgen_null_links_with_predicate (int generation, WeakLinkAlivePredicateFunc predicate, void *data) MONO_INTERNAL;
843 gboolean sgen_gc_is_object_ready_for_finalization (void *object) MONO_INTERNAL;
844 void sgen_gc_lock (void) MONO_INTERNAL;
845 void sgen_gc_unlock (void) MONO_INTERNAL;
846 void sgen_gc_event_moves (void) MONO_INTERNAL;
848 void sgen_queue_finalization_entry (MonoObject *obj) MONO_INTERNAL;
849 const char* sgen_generation_name (int generation) MONO_INTERNAL;
851 void sgen_collect_bridge_objects (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, SgenGrayQueue *queue) MONO_INTERNAL;
852 void sgen_finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, SgenGrayQueue *queue) MONO_INTERNAL;
853 void sgen_null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation, gboolean before_finalization, SgenGrayQueue *queue) MONO_INTERNAL;
854 void sgen_null_links_for_domain (MonoDomain *domain, int generation) MONO_INTERNAL;
855 void sgen_remove_finalizers_for_domain (MonoDomain *domain, int generation) MONO_INTERNAL;
856 void sgen_process_fin_stage_entries (void) MONO_INTERNAL;
857 void sgen_process_dislink_stage_entries (void) MONO_INTERNAL;
858 void sgen_register_disappearing_link (MonoObject *obj, void **link, gboolean track, gboolean in_gc) MONO_INTERNAL;
866 void sgen_pin_object (void *object, SgenGrayQueue *queue) MONO_INTERNAL;
867 void sgen_parallel_pin_or_update (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue) MONO_INTERNAL;
868 void sgen_set_pinned_from_failed_allocation (mword objsize) MONO_INTERNAL;
870 void sgen_ensure_free_space (size_t size) MONO_INTERNAL;
871 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason) MONO_INTERNAL;
872 gboolean sgen_has_critical_method (void) MONO_INTERNAL;
873 gboolean sgen_is_critical_method (MonoMethod *method) MONO_INTERNAL;
880 gboolean is_overflow;
881 SGEN_TV_DECLARE (total_time);
882 SGEN_TV_DECLARE (stw_time);
883 SGEN_TV_DECLARE (bridge_time);
886 int sgen_stop_world (int generation) MONO_INTERNAL;
887 int sgen_restart_world (int generation, GGTimingInfo *timing) MONO_INTERNAL;
891 typedef struct _LOSObject LOSObject;
894 mword size; /* this is the object size */
896 int dummy; /* to have a sizeof (LOSObject) a multiple of ALLOC_ALIGN and data starting at same alignment */
897 char data [MONO_ZERO_LEN_ARRAY];
900 #define ARRAY_OBJ_INDEX(ptr,array,elem_size) (((char*)(ptr) - ((char*)(array) + G_STRUCT_OFFSET (MonoArray, vector))) / (elem_size))
902 extern LOSObject *los_object_list;
903 extern mword los_memory_usage;
905 void sgen_los_free_object (LOSObject *obj) MONO_INTERNAL;
906 void* sgen_los_alloc_large_inner (MonoVTable *vtable, size_t size) MONO_INTERNAL;
907 void sgen_los_sweep (void) MONO_INTERNAL;
908 gboolean sgen_ptr_is_in_los (char *ptr, char **start) MONO_INTERNAL;
909 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data) MONO_INTERNAL;
910 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
911 void sgen_los_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
912 void sgen_major_collector_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
913 gboolean sgen_los_is_valid_object (char *object) MONO_INTERNAL;
914 gboolean mono_sgen_los_describe_pointer (char *ptr) MONO_INTERNAL;
916 /* nursery allocator */
918 void sgen_clear_nursery_fragments (void) MONO_INTERNAL;
919 void sgen_nursery_allocator_prepare_for_pinning (void) MONO_INTERNAL;
920 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end) MONO_INTERNAL;
921 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, void **start, int num_entries) MONO_INTERNAL;
922 void sgen_init_nursery_allocator (void) MONO_INTERNAL;
923 void sgen_nursery_allocator_init_heavy_stats (void) MONO_INTERNAL;
924 void sgen_alloc_init_heavy_stats (void) MONO_INTERNAL;
925 char* sgen_nursery_alloc_get_upper_alloc_bound (void) MONO_INTERNAL;
926 void* sgen_nursery_alloc (size_t size) MONO_INTERNAL;
927 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size) MONO_INTERNAL;
928 MonoVTable* sgen_get_array_fill_vtable (void) MONO_INTERNAL;
929 gboolean sgen_can_alloc_size (size_t size) MONO_INTERNAL;
930 void sgen_nursery_retire_region (void *address, ptrdiff_t size) MONO_INTERNAL;
932 void sgen_nursery_alloc_prepare_for_minor (void) MONO_INTERNAL;
933 void sgen_nursery_alloc_prepare_for_major (void) MONO_INTERNAL;
935 char* sgen_alloc_for_promotion (char *obj, size_t objsize, gboolean has_references) MONO_INTERNAL;
936 char* sgen_par_alloc_for_promotion (char *obj, size_t objsize, gboolean has_references) MONO_INTERNAL;
940 extern MonoNativeTlsKey thread_info_key;
942 #ifdef HAVE_KW_THREAD
943 extern __thread SgenThreadInfo *sgen_thread_info;
944 extern __thread gpointer *store_remset_buffer;
945 extern __thread long store_remset_buffer_index;
946 extern __thread char *stack_end;
947 extern __thread long *store_remset_buffer_index_addr;
950 #ifdef HAVE_KW_THREAD
951 #define TLAB_ACCESS_INIT
952 #define REMEMBERED_SET remembered_set
953 #define STORE_REMSET_BUFFER store_remset_buffer
954 #define STORE_REMSET_BUFFER_INDEX store_remset_buffer_index
955 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
957 #define TLAB_ACCESS_INIT SgenThreadInfo *__thread_info__ = mono_native_tls_get_value (thread_info_key)
958 #define REMEMBERED_SET (__thread_info__->remset)
959 #define STORE_REMSET_BUFFER (__thread_info__->store_remset_buffer)
960 #define STORE_REMSET_BUFFER_INDEX (__thread_info__->store_remset_buffer_index)
961 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
964 #ifndef DISABLE_CRITICAL_REGION
966 #ifdef HAVE_KW_THREAD
967 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
969 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
972 /* Enter must be visible before anything is done in the critical region. */
973 #define ENTER_CRITICAL_REGION do { mono_atomic_store_acquire (&IN_CRITICAL_REGION, 1); } while (0)
975 /* Exit must make sure all critical regions stores are visible before it signal the end of the region.
976 * We don't need to emit a full barrier since we
978 #define EXIT_CRITICAL_REGION do { mono_atomic_store_release (&IN_CRITICAL_REGION, 0); } while (0)
982 #ifdef HAVE_KW_THREAD
983 #define EMIT_TLS_ACCESS(mb,dummy,offset) do { \
984 mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX); \
985 mono_mb_emit_byte ((mb), CEE_MONO_TLS); \
986 mono_mb_emit_i4 ((mb), (offset)); \
991 * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
992 * where the two are the same.
994 #if defined(__APPLE__) || defined (HOST_WIN32)
995 #define EMIT_TLS_ACCESS(mb,member,dummy) do { \
996 mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX); \
997 mono_mb_emit_byte ((mb), CEE_MONO_TLS); \
998 mono_mb_emit_i4 ((mb), thread_info_key); \
999 mono_mb_emit_icon ((mb), G_STRUCT_OFFSET (SgenThreadInfo, member)); \
1000 mono_mb_emit_byte ((mb), CEE_ADD); \
1001 mono_mb_emit_byte ((mb), CEE_LDIND_I); \
1004 #define EMIT_TLS_ACCESS(mb,member,dummy) do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
1011 extern GCMemSection *nursery_section;
1012 extern int stat_major_gcs;
1013 extern guint32 collect_before_allocs;
1014 extern guint32 verify_before_allocs;
1015 extern gboolean has_per_allocation_action;
1016 extern int degraded_mode;
1017 extern int default_nursery_size;
1018 extern guint32 tlab_size;
1019 extern NurseryClearPolicy nursery_clear_policy;
1021 extern LOCK_DECLARE (gc_mutex);
1023 extern int do_pin_stats;
1025 /* Nursery helpers. */
1028 sgen_set_nursery_scan_start (char *p)
1030 int idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
1031 char *old = nursery_section->scan_starts [idx];
1032 if (!old || old > p)
1033 nursery_section->scan_starts [idx] = p;
1037 /* Object Allocation */
1044 } SgenAllocatorType;
1046 void sgen_init_tlab_info (SgenThreadInfo* info);
1047 void sgen_clear_tlabs (void);
1048 void sgen_set_use_managed_allocator (gboolean flag);
1049 gboolean sgen_is_managed_allocator (MonoMethod *method);
1050 gboolean sgen_has_managed_allocator (void);
1054 void sgen_check_consistency (void);
1055 void sgen_check_major_refs (void);
1056 void sgen_check_whole_heap (void);
1057 void sgen_check_whole_heap_stw (void) MONO_INTERNAL;
1058 void sgen_check_objref (char *obj);
1060 /* Write barrier support */
1063 * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1066 sgen_dummy_use (gpointer v) {
1067 #if defined(__GNUC__)
1068 __asm__ volatile ("" : "=r"(v) : "r"(v));
1069 #elif defined(_MSC_VER)
1075 #error "Implement sgen_dummy_use for your compiler"
1079 #endif /* HAVE_SGEN_GC */
1081 #endif /* __MONO_SGENGC_H__ */