1 /**
2  * \file
3  * Simple generational GC.
4  *
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
9  *
10  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11  */
12 #ifndef __MONO_SGENGC_H__
13 #define __MONO_SGENGC_H__
14 
15 /* pthread impl */
16 #include "config.h"
17 
18 #ifdef HAVE_SGEN_GC
19 
20 typedef struct _SgenThreadInfo SgenThreadInfo;
21 #undef THREAD_INFO_TYPE
22 #define THREAD_INFO_TYPE SgenThreadInfo
23 
24 #include <glib.h>
25 #include <stdio.h>
26 #ifdef HAVE_PTHREAD_H
27 #include <pthread.h>
28 #endif
29 #include <stdint.h>
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/utils/ward.h"
35 #include "mono/sgen/sgen-conf.h"
36 #include "mono/sgen/sgen-hash-table.h"
37 #include "mono/sgen/sgen-protocol.h"
38 #include "mono/sgen/gc-internal-agnostic.h"
39 #include "mono/sgen/sgen-thread-pool.h"
40 
41 /* The method used to clear the nursery */
42 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
43  * Clearing at TLAB creation is much faster, but more complex and it might expose hard
44  * to find bugs.
45  */
46 typedef enum {
47 	CLEAR_AT_GC,
48 	CLEAR_AT_TLAB_CREATION,
49 	CLEAR_AT_TLAB_CREATION_DEBUG
50 } NurseryClearPolicy;
51 
52 NurseryClearPolicy sgen_get_nursery_clear_policy (void);
53 
54 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
55 #define SGEN_POSIX_STW 1
56 #endif
57 
58 /*
59  * The nursery section uses this struct.
60  */
61 typedef struct _GCMemSection GCMemSection;
62 struct _GCMemSection {
63 	char *data;
64 	char *end_data;
65 	/*
66 	 * scan starts is an array of pointers to objects equally spaced in the allocation area
67 	 * They let use quickly find pinned objects from pinning pointers.
68 	 */
69 	char **scan_starts;
70 	/* in major collections indexes in the pin_queue for objects that pin this section */
71 	size_t pin_queue_first_entry;
72 	size_t pin_queue_last_entry;
73 	size_t num_scan_start;
74 };
75 
76 /*
77  * Recursion is not allowed for the thread lock.
78  */
79 #define LOCK_DECLARE(name) mono_mutex_t name
80 /* if changing LOCK_INIT to something that isn't idempotent, look at
81    its use in mono_gc_base_init in sgen-gc.c */
82 #define LOCK_INIT(name)	mono_os_mutex_init (&(name))
83 #define LOCK_GC do { sgen_gc_lock (); } while (0)
84 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
85 
86 extern MonoCoopMutex sgen_interruption_mutex;
87 
88 #define LOCK_INTERRUPTION mono_coop_mutex_lock (&sgen_interruption_mutex)
89 #define UNLOCK_INTERRUPTION mono_coop_mutex_unlock (&sgen_interruption_mutex)
90 
91 /* FIXME: Use mono_atomic_add_i32 & mono_atomic_add_i64 to reduce the CAS cost. */
92 #define SGEN_CAS	mono_atomic_cas_i32
93 #define SGEN_CAS_PTR	mono_atomic_cas_ptr
94 #define SGEN_ATOMIC_ADD(x,i)	do {					\
95 		int __old_x;						\
96 		do {							\
97 			__old_x = (x);					\
98 		} while (mono_atomic_cas_i32 (&(x), __old_x + (i), __old_x) != __old_x); \
99 	} while (0)
100 #define SGEN_ATOMIC_ADD_P(x,i) do { \
101 		size_t __old_x;                                            \
102 		do {                                                    \
103 			__old_x = (x);                                  \
104 		} while (mono_atomic_cas_ptr ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
105 	} while (0)
106 
107 #ifdef HEAVY_STATISTICS
108 extern guint64 stat_objects_alloced_degraded;
109 extern guint64 stat_bytes_alloced_degraded;
110 extern guint64 stat_copy_object_called_major;
111 extern guint64 stat_objects_copied_major;
112 #endif
113 
114 #define SGEN_ASSERT(level, a, ...) do {	\
115 	if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) {	\
116 		g_error (__VA_ARGS__);	\
117 } } while (0)
118 
119 #ifdef HAVE_LOCALTIME_R
120 # define LOG_TIMESTAMP  \
121 	do {	\
122 		time_t t;									\
123 		struct tm tod;									\
124 		time(&t);									\
125 		localtime_r(&t, &tod);								\
126 		strftime(logTime, sizeof(logTime), "%Y-%m-%d %H:%M:%S", &tod);			\
127 	} while (0)
128 #else
129 # define LOG_TIMESTAMP  \
130 	do {	\
131 		time_t t;									\
132 		struct tm *tod;									\
133 		time(&t);									\
134 		tod = localtime(&t);								\
135 		strftime(logTime, sizeof(logTime), "%F %T", tod);				\
136 	} while (0)
137 #endif
138 
139 #define SGEN_LOG(level, format, ...) do {      \
140 	if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {	\
141 		char logTime[80];								\
142 		LOG_TIMESTAMP;									\
143 		mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__);	\
144 } } while (0)
145 
146 #define SGEN_COND_LOG(level, cond, format, ...) do {	\
147 	if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {		\
148 		if (cond) {										\
149 			char logTime[80];								\
150 			LOG_TIMESTAMP;									\
151 			mono_gc_printf (gc_debug_file, "%s " format "\n", logTime, ##__VA_ARGS__);	\
152 		}											\
153 } } while (0)
154 
155 extern int gc_debug_level;
156 extern FILE* gc_debug_file;
157 
158 extern int current_collection_generation;
159 
160 extern unsigned int sgen_global_stop_count;
161 
162 #define SGEN_ALIGN_UP_TO(val,align)	(((val) + (align - 1)) & ~(align - 1))
163 #define SGEN_ALIGN_DOWN_TO(val,align)	((val) & ~(align - 1))
164 
165 #define SGEN_ALLOC_ALIGN		8
166 #define SGEN_ALLOC_ALIGN_BITS	3
167 
168 /* s must be non-negative */
169 #define SGEN_CAN_ALIGN_UP(s)		((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
170 #define SGEN_ALIGN_UP(s)		SGEN_ALIGN_UP_TO(s, SGEN_ALLOC_ALIGN)
171 #define SGEN_ALIGN_DOWN(s)		SGEN_ALIGN_DOWN_TO(s, SGEN_ALLOC_ALIGN)
172 
173 #if SIZEOF_VOID_P == 4
174 #define ONE_P 1
175 #else
176 #define ONE_P 1ll
177 #endif
178 
179 static inline guint
sgen_aligned_addr_hash(gconstpointer ptr)180 sgen_aligned_addr_hash (gconstpointer ptr)
181 {
182 	return GPOINTER_TO_UINT (ptr) >> 3;
183 }
184 
185 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)	(((mword)(p) & ~(((mword)1 << (bits)) - 1)) == (mword)(start))
186 
187 extern size_t sgen_nursery_size;
188 extern size_t sgen_nursery_max_size;
189 extern int sgen_nursery_bits;
190 
191 extern char *sgen_nursery_start;
192 extern char *sgen_nursery_end;
193 
194 static inline MONO_ALWAYS_INLINE gboolean
sgen_ptr_in_nursery(void * p)195 sgen_ptr_in_nursery (void *p)
196 {
197 	return SGEN_PTR_IN_NURSERY ((p), sgen_nursery_bits, sgen_nursery_start, sgen_nursery_end);
198 }
199 
200 static inline MONO_ALWAYS_INLINE char*
sgen_get_nursery_start(void)201 sgen_get_nursery_start (void)
202 {
203 	return sgen_nursery_start;
204 }
205 
206 static inline MONO_ALWAYS_INLINE char*
sgen_get_nursery_end(void)207 sgen_get_nursery_end (void)
208 {
209 	return sgen_nursery_end;
210 }
211 
212 /*
213  * We use the lowest three bits in the vtable pointer of objects to tag whether they're
214  * forwarded, pinned, and/or cemented.  These are the valid states:
215  *
216  * | State            | bits |
217  * |------------------+------+
218  * | default          |  000 |
219  * | forwarded        |  001 |
220  * | pinned           |  010 |
221  * | pinned, cemented |  110 |
222  *
223  * We store them in the vtable slot because the bits are used in the sync block for other
224  * purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
225  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
226  * would be an invalid combination for the monitor and hash code).
227  */
228 
229 #include "sgen-tagged-pointer.h"
230 
231 #define SGEN_VTABLE_BITS_MASK	SGEN_TAGGED_POINTER_MASK
232 
233 #define SGEN_POINTER_IS_TAGGED_FORWARDED(p)	SGEN_POINTER_IS_TAGGED_1((p))
234 #define SGEN_POINTER_TAG_FORWARDED(p)		SGEN_POINTER_TAG_1((p))
235 
236 #define SGEN_POINTER_IS_TAGGED_PINNED(p)	SGEN_POINTER_IS_TAGGED_2((p))
237 #define SGEN_POINTER_TAG_PINNED(p)		SGEN_POINTER_TAG_2((p))
238 
239 #define SGEN_POINTER_IS_TAGGED_CEMENTED(p)	SGEN_POINTER_IS_TAGGED_4((p))
240 #define SGEN_POINTER_TAG_CEMENTED(p)		SGEN_POINTER_TAG_4((p))
241 
242 #define SGEN_POINTER_UNTAG_VTABLE(p)		SGEN_POINTER_UNTAG_ALL((p))
243 
244 /* returns NULL if not forwarded, or the forwarded address */
245 #define SGEN_VTABLE_IS_FORWARDED(vtable) ((GCObject *)(SGEN_POINTER_IS_TAGGED_FORWARDED ((vtable)) ? SGEN_POINTER_UNTAG_VTABLE ((vtable)) : NULL))
246 #define SGEN_OBJECT_IS_FORWARDED(obj) ((GCObject *)SGEN_VTABLE_IS_FORWARDED (((mword*)(obj))[0]))
247 
248 #define SGEN_VTABLE_IS_PINNED(vtable) SGEN_POINTER_IS_TAGGED_PINNED ((vtable))
249 #define SGEN_OBJECT_IS_PINNED(obj) (SGEN_VTABLE_IS_PINNED (((mword*)(obj))[0]))
250 
251 #define SGEN_OBJECT_IS_CEMENTED(obj) (SGEN_POINTER_IS_TAGGED_CEMENTED (((mword*)(obj))[0]))
252 
253 /* set the forwarded address fw_addr for object obj */
254 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {				\
255 		*(void**)(obj) = SGEN_POINTER_TAG_FORWARDED ((fw_addr));	\
256 	} while (0)
257 #define SGEN_FORWARD_OBJECT_PAR(obj,fw_addr,final_fw_addr) do {			\
258 		gpointer old_vtable_word = *(gpointer*)obj;			\
259 		gpointer new_vtable_word;					\
260 		final_fw_addr = SGEN_VTABLE_IS_FORWARDED (old_vtable_word);	\
261 		if (final_fw_addr)						\
262 			break;							\
263 		new_vtable_word = SGEN_POINTER_TAG_FORWARDED ((fw_addr));	\
264 		old_vtable_word = mono_atomic_cas_ptr ((gpointer*)obj, new_vtable_word, old_vtable_word); \
265 		final_fw_addr = SGEN_VTABLE_IS_FORWARDED (old_vtable_word);	\
266 		if (!final_fw_addr)						\
267 			final_fw_addr = (fw_addr);				\
268 	} while (0)
269 #define SGEN_PIN_OBJECT(obj) do {	\
270 		*(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
271 	} while (0)
272 #define SGEN_CEMENT_OBJECT(obj) do {	\
273 		*(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
274 	} while (0)
275 /* Unpins and uncements */
276 #define SGEN_UNPIN_OBJECT(obj) do {	\
277 		*(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
278 	} while (0)
279 
280 /*
281  * Since we set bits in the vtable, use the macro to load it from the pointer to
282  * an object that is potentially pinned.
283  */
284 #define SGEN_LOAD_VTABLE(obj)		((GCVTable)(SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((GCObject *)(obj)))))
285 
286 /*
287 List of what each bit on of the vtable gc bits means.
288 */
289 enum {
290 	// When the Java bridge has determined an object is "bridged", it uses these two bits to cache that information.
291 	SGEN_GC_BIT_BRIDGE_OBJECT = 1,
292 	SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT = 2,
293 	SGEN_GC_BIT_FINALIZER_AWARE = 4,
294 };
295 
296 void sgen_gc_init (void)
297     MONO_PERMIT (need (sgen_lock_gc));
298 
299 void sgen_os_init (void);
300 
301 void sgen_update_heap_boundaries (mword low, mword high);
302 
303 void sgen_check_section_scan_starts (GCMemSection *section);
304 
305 void sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type);
306 
307 gboolean sgen_gc_initialized (void);
308 
309 /* Keep in sync with description_for_type() in sgen-internal.c! */
310 enum {
311 	INTERNAL_MEM_PIN_QUEUE,
312 	INTERNAL_MEM_FRAGMENT,
313 	INTERNAL_MEM_SECTION,
314 	INTERNAL_MEM_SCAN_STARTS,
315 	INTERNAL_MEM_FIN_TABLE,
316 	INTERNAL_MEM_FINALIZE_ENTRY,
317 	INTERNAL_MEM_FINALIZE_READY,
318 	INTERNAL_MEM_DISLINK_TABLE,
319 	INTERNAL_MEM_DISLINK,
320 	INTERNAL_MEM_ROOTS_TABLE,
321 	INTERNAL_MEM_ROOT_RECORD,
322 	INTERNAL_MEM_STATISTICS,
323 	INTERNAL_MEM_STAT_PINNED_CLASS,
324 	INTERNAL_MEM_STAT_REMSET_CLASS,
325 	INTERNAL_MEM_GRAY_QUEUE,
326 	INTERNAL_MEM_MS_TABLES,
327 	INTERNAL_MEM_MS_BLOCK_INFO,
328 	INTERNAL_MEM_MS_BLOCK_INFO_SORT,
329 	INTERNAL_MEM_WORKER_DATA,
330 	INTERNAL_MEM_THREAD_POOL_JOB,
331 	INTERNAL_MEM_BRIDGE_DATA,
332 	INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE,
333 	INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY,
334 	INTERNAL_MEM_BRIDGE_HASH_TABLE,
335 	INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
336 	INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
337 	INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
338 	INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE,
339 	INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY,
340 	INTERNAL_MEM_TARJAN_OBJ_BUCKET,
341 	INTERNAL_MEM_BRIDGE_DEBUG,
342 	INTERNAL_MEM_TOGGLEREF_DATA,
343 	INTERNAL_MEM_CARDTABLE_MOD_UNION,
344 	INTERNAL_MEM_BINARY_PROTOCOL,
345 	INTERNAL_MEM_TEMPORARY,
346 	INTERNAL_MEM_LOG_ENTRY,
347 	INTERNAL_MEM_COMPLEX_DESCRIPTORS,
348 	INTERNAL_MEM_FIRST_CLIENT
349 };
350 
351 enum {
352 	GENERATION_NURSERY,
353 	GENERATION_OLD,
354 	GENERATION_MAX
355 };
356 
357 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
358 #define BINARY_PROTOCOL_ARG(x)	,x
359 #else
360 #define BINARY_PROTOCOL_ARG(x)
361 #endif
362 
363 void sgen_init_internal_allocator (void);
364 
365 #define SGEN_DEFINE_OBJECT_VTABLE
366 #ifdef SGEN_CLIENT_HEADER
367 #include SGEN_CLIENT_HEADER
368 #else
369 #include "metadata/sgen-client-mono.h"
370 #endif
371 #undef SGEN_DEFINE_OBJECT_VTABLE
372 
373 #include "mono/sgen/sgen-descriptor.h"
374 #include "mono/sgen/sgen-gray.h"
375 
376 /* the runtime can register areas of memory as roots: we keep two lists of roots,
377  * a pinned root set for conservatively scanned roots and a normal one for
378  * precisely scanned roots (currently implemented as a single list).
379  */
380 typedef struct _RootRecord RootRecord;
381 struct _RootRecord {
382 	char *end_root;
383 	SgenDescriptor root_desc;
384 	int source;
385 	const char *msg;
386 };
387 
388 enum {
389 	ROOT_TYPE_NORMAL = 0, /* "normal" roots */
390 	ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
391 	ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
392 	ROOT_TYPE_NUM
393 };
394 
395 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
396 
397 int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, int source, const char *msg)
398 	MONO_PERMIT (need (sgen_lock_gc));
399 void sgen_deregister_root (char* addr)
400 	MONO_PERMIT (need (sgen_lock_gc));
401 
402 typedef void (*IterateObjectCallbackFunc) (GCObject*, size_t, void*);
403 
404 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags, gboolean fail_on_canaries);
405 
406 /* eventually share with MonoThread? */
407 /*
408  * This structure extends the MonoThreadInfo structure.
409  */
410 struct _SgenThreadInfo {
411 	SgenClientThreadInfo client_info;
412 
413 	char *tlab_start;
414 	char *tlab_next;
415 	char *tlab_temp_end;
416 	char *tlab_real_end;
417 };
418 
419 gboolean sgen_is_worker_thread (MonoNativeThreadId thread);
420 
421 typedef void (*CopyOrMarkObjectFunc) (GCObject**, SgenGrayQueue*);
422 typedef void (*ScanObjectFunc) (GCObject *obj, SgenDescriptor desc, SgenGrayQueue*);
423 typedef void (*ScanVTypeFunc) (GCObject *full_object, char *start, SgenDescriptor desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
424 typedef void (*ScanPtrFieldFunc) (GCObject *obj, GCObject **ptr, SgenGrayQueue* queue);
425 typedef gboolean (*DrainGrayStackFunc) (SgenGrayQueue *queue);
426 
427 typedef struct {
428 	CopyOrMarkObjectFunc copy_or_mark_object;
429 	ScanObjectFunc scan_object;
430 	ScanVTypeFunc scan_vtype;
431 	ScanPtrFieldFunc scan_ptr_field;
432 	/* Drain stack optimized for the above functions */
433 	DrainGrayStackFunc drain_gray_stack;
434 	/*FIXME add allocation function? */
435 } SgenObjectOperations;
436 
437 typedef struct
438 {
439 	SgenObjectOperations *ops;
440 	SgenGrayQueue *queue;
441 } ScanCopyContext;
442 
443 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
444 
445 void sgen_report_internal_mem_usage (void);
446 void sgen_dump_internal_mem_usage (FILE *heap_dump_file);
447 void sgen_dump_section (GCMemSection *section, const char *type);
448 void sgen_dump_occupied (char *start, char *end, char *section_start);
449 
450 void sgen_register_fixed_internal_mem_type (int type, size_t size);
451 
452 void* sgen_alloc_internal (int type);
453 void sgen_free_internal (void *addr, int type);
454 
455 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure);
456 void sgen_free_internal_dynamic (void *addr, size_t size, int type);
457 
458 void sgen_pin_stats_enable (void);
459 void sgen_pin_stats_register_object (GCObject *obj, int generation);
460 void sgen_pin_stats_register_global_remset (GCObject *obj);
461 void sgen_pin_stats_report (void);
462 
463 void sgen_sort_addresses (void **array, size_t size);
464 void sgen_add_to_global_remset (gpointer ptr, GCObject *obj);
465 
466 int sgen_get_current_collection_generation (void);
467 gboolean sgen_collection_is_concurrent (void);
468 gboolean sgen_concurrent_collection_in_progress (void);
469 
470 typedef struct _SgenFragment SgenFragment;
471 
472 struct _SgenFragment {
473 	SgenFragment *next;
474 	char *fragment_start;
475 	char *fragment_next; /* the current soft limit for allocation */
476 	char *fragment_end;
477 	SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
478 };
479 
480 typedef struct {
481 	SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
482 	SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
483 } SgenFragmentAllocator;
484 
485 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end);
486 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator);
487 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size);
488 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
489 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
490 SgenFragment* sgen_fragment_allocator_alloc (void);
491 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator);
492 void sgen_clear_range (char *start, char *end);
493 
494 
495 /*
496 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
497 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
498 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
499 
500 Experimental results on how much space we waste with a 4Mb nursery:
501 
502 Note that the wastage applies to the half nursery, or 2Mb:
503 
504 Test 1 (compiling corlib):
505 9: avg: 3.1k
506 8: avg: 1.6k
507 
508 */
509 #define SGEN_TO_SPACE_GRANULE_BITS 9
510 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
511 
512 extern char *sgen_space_bitmap;
513 extern size_t sgen_space_bitmap_size;
514 
515 static inline gboolean
sgen_nursery_is_to_space(void * object)516 sgen_nursery_is_to_space (void *object)
517 {
518 	size_t idx = ((char*)object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
519 	size_t byte = idx >> 3;
520 	size_t bit = idx & 0x7;
521 
522 	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 ());
523 	SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %zd out of range (%zd)", byte, sgen_space_bitmap_size);
524 
525 	return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
526 }
527 
528 static inline gboolean
sgen_nursery_is_from_space(void * object)529 sgen_nursery_is_from_space (void *object)
530 {
531 	return !sgen_nursery_is_to_space (object);
532 }
533 
534 static inline gboolean
sgen_nursery_is_object_alive(GCObject * obj)535 sgen_nursery_is_object_alive (GCObject *obj)
536 {
537 	/* FIXME put this asserts under a non default level */
538 	g_assert (sgen_ptr_in_nursery (obj));
539 
540 	if (sgen_nursery_is_to_space (obj))
541 		return TRUE;
542 
543 	if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
544 		return TRUE;
545 
546 	return FALSE;
547 }
548 
549 typedef struct {
550 	gboolean is_split;
551 	gboolean is_parallel;
552 
553 	GCObject* (*alloc_for_promotion) (GCVTable vtable, GCObject *obj, size_t objsize, gboolean has_references);
554 	GCObject* (*alloc_for_promotion_par) (GCVTable vtable, GCObject *obj, size_t objsize, gboolean has_references);
555 
556 	SgenObjectOperations serial_ops;
557 	SgenObjectOperations serial_ops_with_concurrent_major;
558 	SgenObjectOperations parallel_ops;
559 	SgenObjectOperations parallel_ops_with_concurrent_major;
560 
561 	void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
562 	void (*clear_fragments) (void);
563 	SgenFragment* (*build_fragments_get_exclude_head) (void);
564 	void (*build_fragments_release_exclude_head) (void);
565 	void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
566 	void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
567 
568 	gboolean (*handle_gc_param) (const char *opt); /* Optional */
569 	void (*print_gc_param_usage) (void); /* Optional */
570 } SgenMinorCollector;
571 
572 extern SgenMinorCollector sgen_minor_collector;
573 
574 void sgen_simple_nursery_init (SgenMinorCollector *collector, gboolean parallel);
575 void sgen_split_nursery_init (SgenMinorCollector *collector);
576 
577 /* Updating references */
578 
579 #ifdef SGEN_CHECK_UPDATE_REFERENCE
580 gboolean sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread);
581 
582 static inline void
sgen_update_reference(GCObject ** p,GCObject * o,gboolean allow_null)583 sgen_update_reference (GCObject **p, GCObject *o, gboolean allow_null)
584 {
585 	if (!allow_null)
586 		SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
587 	SGEN_ASSERT (0, !sgen_workers_is_worker_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
588 	*p = o;
589 }
590 
591 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)	sgen_update_reference ((GCObject**)(p), (GCObject*)(o), TRUE)
592 #define SGEN_UPDATE_REFERENCE(p,o)		sgen_update_reference ((GCObject**)(p), (GCObject*)(o), FALSE)
593 #else
594 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)	(*(GCObject**)(p) = (GCObject*)(o))
595 #define SGEN_UPDATE_REFERENCE(p,o)		SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
596 #endif
597 
598 /* Major collector */
599 
600 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
601 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
602 void sgen_major_collector_iterate_block_ranges (sgen_cardtable_block_callback callback);
603 
604 typedef enum {
605 	ITERATE_OBJECTS_SWEEP = 1,
606 	ITERATE_OBJECTS_NON_PINNED = 2,
607 	ITERATE_OBJECTS_PINNED = 4,
608 	ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
609 	ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
610 	ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
611 } IterateObjectsFlags;
612 
613 typedef struct
614 {
615 	size_t num_scanned_objects;
616 	size_t num_unique_scanned_objects;
617 } ScannedObjectCounts;
618 
619 typedef enum {
620 	CARDTABLE_SCAN_GLOBAL = 0,
621 	CARDTABLE_SCAN_MOD_UNION = 1,
622 	CARDTABLE_SCAN_MOD_UNION_PRECLEAN = CARDTABLE_SCAN_MOD_UNION | 2,
623 } CardTableScanType;
624 
625 typedef struct _SgenMajorCollector SgenMajorCollector;
626 struct _SgenMajorCollector {
627 	size_t section_size;
628 	gboolean is_concurrent;
629 	gboolean is_parallel;
630 	gboolean supports_cardtable;
631 	gboolean sweeps_lazily;
632 
633 	void* (*alloc_heap) (mword nursery_size, mword nursery_align);
634 	gboolean (*is_object_live) (GCObject *obj);
635 	GCObject* (*alloc_small_pinned_obj) (GCVTable vtable, size_t size, gboolean has_references);
636 	GCObject* (*alloc_degraded) (GCVTable vtable, size_t size);
637 
638 	SgenObjectOperations major_ops_serial;
639 	SgenObjectOperations major_ops_concurrent_start;
640 	SgenObjectOperations major_ops_concurrent_finish;
641 	SgenObjectOperations major_ops_conc_par_start;
642 	SgenObjectOperations major_ops_conc_par_finish;
643 
644 	GCObject* (*alloc_object) (GCVTable vtable, size_t size, gboolean has_references);
645 	GCObject* (*alloc_object_par) (GCVTable vtable, size_t size, gboolean has_references);
646 	void (*free_pinned_object) (GCObject *obj, size_t size);
647 
648 	/*
649 	 * This is used for domain unloading, heap walking from the logging profiler, and
650 	 * debugging.  Can assume the world is stopped.
651 	 */
652 	void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
653 
654 	void (*free_non_pinned_object) (GCObject *obj, size_t size);
655 	void (*pin_objects) (SgenGrayQueue *queue);
656 	void (*pin_major_object) (GCObject *obj, SgenGrayQueue *queue);
657 	void (*scan_card_table) (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count, int block_count);
658 	void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
659 	void (*iterate_block_ranges) (sgen_cardtable_block_callback callback);
660 	void (*update_cardtable_mod_union) (void);
661 	void (*init_to_space) (void);
662 	void (*sweep) (void);
663 	gboolean (*have_swept) (void);
664 	void (*finish_sweeping) (void);
665 	void (*free_swept_blocks) (size_t section_reserve);
666 	void (*check_scan_starts) (void);
667 	void (*dump_heap) (FILE *heap_dump_file);
668 	gint64 (*get_used_size) (void);
669 	void (*start_nursery_collection) (void);
670 	void (*finish_nursery_collection) (void);
671 	void (*start_major_collection) (void);
672 	void (*finish_major_collection) (ScannedObjectCounts *counts);
673 	gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
674 	gboolean (*ptr_is_from_pinned_alloc) (char *ptr);
675 	void (*report_pinned_memory_usage) (void);
676 	size_t (*get_num_major_sections) (void);
677 	size_t (*get_bytes_survived_last_sweep) (void);
678 	gboolean (*handle_gc_param) (const char *opt);
679 	void (*print_gc_param_usage) (void);
680 	void (*post_param_init) (SgenMajorCollector *collector);
681 	gboolean (*is_valid_object) (char *ptr);
682 	GCVTable (*describe_pointer) (char *pointer);
683 	guint8* (*get_cardtable_mod_union_for_reference) (char *object);
684 	long long (*get_and_reset_num_major_objects_marked) (void);
685 	void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
686 	void (*init_block_free_lists) (gpointer *list_p);
687 };
688 
689 extern SgenMajorCollector major_collector;
690 
691 void sgen_marksweep_init (SgenMajorCollector *collector);
692 void sgen_marksweep_conc_init (SgenMajorCollector *collector);
693 void sgen_marksweep_conc_par_init (SgenMajorCollector *collector);
694 SgenMajorCollector* sgen_get_major_collector (void);
695 SgenMinorCollector* sgen_get_minor_collector (void);
696 
697 
698 typedef struct _SgenRememberedSet {
699 	void (*wbarrier_set_field) (GCObject *obj, gpointer field_ptr, GCObject* value);
700 	void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
701 	void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, size_t element_size);
702 	void (*wbarrier_object_copy) (GCObject* obj, GCObject *src);
703 	void (*wbarrier_generic_nostore) (gpointer ptr);
704 	void (*record_pointer) (gpointer ptr);
705 	void (*wbarrier_range_copy) (gpointer dest, gpointer src, int count);
706 
707 	void (*start_scan_remsets) (void);
708 
709 	void (*clear_cards) (void);
710 
711 	gboolean (*find_address) (char *addr);
712 	gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
713 } SgenRememberedSet;
714 
715 SgenRememberedSet *sgen_get_remset (void);
716 
717 /*
718  * These must be kept in sync with object.h.  They're here for using SGen independently of
719  * Mono.
720  */
721 void mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count);
722 void mono_gc_wbarrier_generic_nostore (gpointer ptr);
723 void mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value);
724 void mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value);
725 
726 void sgen_wbarrier_range_copy (gpointer _dest, gpointer _src, int size);
727 
728 static inline SgenDescriptor
sgen_obj_get_descriptor(GCObject * obj)729 sgen_obj_get_descriptor (GCObject *obj)
730 {
731 	GCVTable vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
732 	SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable), "Object can't be tagged");
733 	return sgen_vtable_get_descriptor (vtable);
734 }
735 
736 static inline SgenDescriptor
sgen_obj_get_descriptor_safe(GCObject * obj)737 sgen_obj_get_descriptor_safe (GCObject *obj)
738 {
739 	GCVTable vtable = SGEN_LOAD_VTABLE (obj);
740 	return sgen_vtable_get_descriptor (vtable);
741 }
742 
743 static mword sgen_client_par_object_get_size (GCVTable vtable, GCObject* o);
744 static mword sgen_client_slow_object_get_size (GCVTable vtable, GCObject* o);
745 
746 static inline mword
sgen_safe_object_get_size(GCObject * obj)747 sgen_safe_object_get_size (GCObject *obj)
748 {
749 	GCObject *forwarded;
750 	GCVTable vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
751 
752 	/*
753 	 * Once we load the vtable, we must always use it, in case we are in parallel case.
754 	 * Otherwise the object might get forwarded in the meantime and we would read an
755 	 * invalid vtable. An object cannot be forwarded for a second time during same GC.
756 	 */
757 	if ((forwarded = SGEN_VTABLE_IS_FORWARDED (vtable)))
758 		return sgen_client_par_object_get_size (SGEN_LOAD_VTABLE (forwarded), obj);
759 	else
760 		return sgen_client_par_object_get_size ((GCVTable)SGEN_POINTER_UNTAG_ALL (vtable), obj);
761 }
762 
763 static inline gboolean
sgen_safe_object_is_small(GCObject * obj,int type)764 sgen_safe_object_is_small (GCObject *obj, int type)
765 {
766 	if (type <= DESC_TYPE_MAX_SMALL_OBJ)
767 		return TRUE;
768 	return SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject*)obj)) <= SGEN_MAX_SMALL_OBJ_SIZE;
769 }
770 
771 /*
772  * This variant guarantees to return the exact size of the object
773  * before alignment. Needed for canary support.
774  */
775 static inline guint
sgen_safe_object_get_size_unaligned(GCObject * obj)776 sgen_safe_object_get_size_unaligned (GCObject *obj)
777 {
778 	GCObject *forwarded;
779 
780 	if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
781 		obj = (GCObject*)forwarded;
782 	}
783 
784 	return sgen_client_slow_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
785 }
786 
787 #ifdef SGEN_CLIENT_HEADER
788 #include SGEN_CLIENT_HEADER
789 #else
790 #include "metadata/sgen-client-mono.h"
791 #endif
792 
793 gboolean sgen_object_is_live (GCObject *obj);
794 
795 void  sgen_init_fin_weak_hash (void);
796 
797 void sgen_register_obj_with_weak_fields (GCObject *obj);
798 
799 /* FIXME: move the toggleref stuff out of here */
800 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx);
801 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx);
802 
803 void sgen_process_togglerefs (void);
804 void sgen_register_test_toggleref_callback (void);
805 
806 void sgen_mark_bridge_object (GCObject *obj)
807 	MONO_PERMIT (need (sgen_gc_locked));
808 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx)
809 	MONO_PERMIT (need (sgen_gc_locked));
810 
811 typedef gboolean (*SgenObjectPredicateFunc) (GCObject *obj, void *user_data);
812 
813 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track)
814 	MONO_PERMIT (need (sgen_gc_locked, sgen_world_stopped));
815 
816 gboolean sgen_gc_is_object_ready_for_finalization (GCObject *object);
817 void sgen_gc_lock (void) MONO_PERMIT (use (sgen_lock_gc), grant (sgen_gc_locked), revoke (sgen_lock_gc));
818 void sgen_gc_unlock (void) MONO_PERMIT (use (sgen_gc_locked), revoke (sgen_gc_locked), grant (sgen_lock_gc));
819 
820 void sgen_queue_finalization_entry (GCObject *obj);
821 const char* sgen_generation_name (int generation);
822 
823 void sgen_finalize_in_range (int generation, ScanCopyContext ctx)
824 	MONO_PERMIT (need (sgen_gc_locked));
825 void sgen_null_link_in_range (int generation, ScanCopyContext ctx, gboolean track)
826 	MONO_PERMIT (need (sgen_gc_locked, sgen_world_stopped));
827 void sgen_process_fin_stage_entries (void)
828 	MONO_PERMIT (need (sgen_gc_locked));
829 gboolean sgen_have_pending_finalizers (void);
830 void sgen_object_register_for_finalization (GCObject *obj, void *user_data)
831 	MONO_PERMIT (need (sgen_lock_gc));
832 
833 void sgen_finalize_if (SgenObjectPredicateFunc predicate, void *user_data)
834 	MONO_PERMIT (need (sgen_lock_gc));
835 void sgen_remove_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, int generation);
836 void sgen_set_suspend_finalizers (void);
837 
838 void sgen_wbroots_iterate_live_block_ranges (sgen_cardtable_block_callback cb);
839 void sgen_wbroots_scan_card_table (ScanCopyContext ctx);
840 
841 void sgen_register_disappearing_link (GCObject *obj, void **link, gboolean track, gboolean in_gc);
842 
843 GCObject* sgen_weak_link_get (void **link_addr);
844 
845 gboolean sgen_drain_gray_stack (ScanCopyContext ctx);
846 
847 enum {
848 	SPACE_NURSERY,
849 	SPACE_MAJOR,
850 	SPACE_LOS
851 };
852 
853 void sgen_pin_object (GCObject *object, SgenGrayQueue *queue);
854 void sgen_set_pinned_from_failed_allocation (mword objsize);
855 
856 void sgen_ensure_free_space (size_t size, int generation)
857 	MONO_PERMIT (need (sgen_gc_locked, sgen_stop_world));
858 void sgen_gc_collect (int generation)
859 	MONO_PERMIT (need (sgen_lock_gc, sgen_stop_world));
860 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish, gboolean stw)
861 	MONO_PERMIT (need (sgen_gc_locked, sgen_stop_world));
862 
863 int sgen_gc_collection_count (int generation);
864 /* FIXME: what exactly does this return? */
865 size_t sgen_gc_get_used_size (void)
866 	MONO_PERMIT (need (sgen_lock_gc));
867 size_t sgen_gc_get_total_heap_allocation (void);
868 
869 /* STW */
870 
871 void sgen_stop_world (int generation)
872 	MONO_PERMIT (need (sgen_gc_locked), use (sgen_stop_world), grant (sgen_world_stopped), revoke (sgen_stop_world));
873 void sgen_restart_world (int generation)
874 	MONO_PERMIT (need (sgen_gc_locked), use (sgen_world_stopped), revoke (sgen_world_stopped), grant (sgen_stop_world));
875 gboolean sgen_is_world_stopped (void);
876 
877 gboolean sgen_set_allow_synchronous_major (gboolean flag);
878 
879 /* LOS */
880 
881 typedef struct _LOSObject LOSObject;
882 struct _LOSObject {
883 	LOSObject *next;
884 	mword size; /* this is the object size, lowest bit used for pin/mark */
885 	guint8 * volatile cardtable_mod_union; /* only used by the concurrent collector */
886 #if SIZEOF_VOID_P < 8
887 	mword dummy;		/* to align object to sizeof (double) */
888 #endif
889 	GCObject data [MONO_ZERO_LEN_ARRAY];
890 };
891 
892 extern LOSObject *los_object_list;
893 extern mword los_memory_usage;
894 extern mword los_memory_usage_total;
895 
896 void sgen_los_free_object (LOSObject *obj);
897 void* sgen_los_alloc_large_inner (GCVTable vtable, size_t size)
898 	MONO_PERMIT (need (sgen_gc_locked, sgen_stop_world));
899 void sgen_los_sweep (void);
900 gboolean sgen_ptr_is_in_los (char *ptr, char **start);
901 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data);
902 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
903 void sgen_los_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count);
904 void sgen_los_update_cardtable_mod_union (void);
905 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards);
906 gboolean sgen_los_is_valid_object (char *object);
907 gboolean mono_sgen_los_describe_pointer (char *ptr);
908 LOSObject* sgen_los_header_for_object (GCObject *data);
909 mword sgen_los_object_size (LOSObject *obj);
910 void sgen_los_pin_object (GCObject *obj);
911 gboolean sgen_los_pin_object_par (GCObject *obj);
912 gboolean sgen_los_object_is_pinned (GCObject *obj);
913 void sgen_los_mark_mod_union_card (GCObject *mono_obj, void **ptr);
914 
915 
916 /* nursery allocator */
917 
918 void sgen_clear_nursery_fragments (void);
919 void sgen_nursery_allocator_prepare_for_pinning (void);
920 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, size_t min_size, size_t max_size);
921 void sgen_resize_nursery (gboolean need_shrink);
922 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue);
923 void sgen_init_nursery_allocator (void);
924 void sgen_nursery_allocator_init_heavy_stats (void);
925 void sgen_init_allocator (void);
926 void* sgen_nursery_alloc (size_t size);
927 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size);
928 gboolean sgen_can_alloc_size (size_t size);
929 void sgen_nursery_retire_region (void *address, ptrdiff_t size);
930 
931 void sgen_nursery_alloc_prepare_for_minor (void);
932 void sgen_nursery_alloc_prepare_for_major (void);
933 
934 GCObject* sgen_alloc_for_promotion (GCObject *obj, size_t objsize, gboolean has_references);
935 
936 GCObject* sgen_alloc_obj_nolock (GCVTable vtable, size_t size)
937 	MONO_PERMIT (need (sgen_gc_locked, sgen_stop_world));
938 GCObject* sgen_try_alloc_obj_nolock (GCVTable vtable, size_t size);
939 
940 /* Threads */
941 
942 void* sgen_thread_attach (SgenThreadInfo* info);
943 void sgen_thread_detach_with_lock (SgenThreadInfo *p);
944 
945 /* Finalization/ephemeron support */
946 
947 static inline gboolean
sgen_major_is_object_alive(GCObject * object)948 sgen_major_is_object_alive (GCObject *object)
949 {
950 	mword objsize;
951 
952 	/* Oldgen objects can be pinned and forwarded too */
953 	if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
954 		return TRUE;
955 
956 	/*
957 	 * FIXME: major_collector.is_object_live() also calculates the
958 	 * size.  Avoid the double calculation.
959 	 */
960 	objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (object));
961 	if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
962 		return sgen_los_object_is_pinned (object);
963 
964 	return major_collector.is_object_live (object);
965 }
966 
967 
968 /*
969  * If the object has been forwarded it means it's still referenced from a root.
970  * If it is pinned it's still alive as well.
971  * A LOS object is only alive if we have pinned it.
972  * Return TRUE if @obj is ready to be finalized.
973  */
974 static inline gboolean
sgen_is_object_alive(GCObject * object)975 sgen_is_object_alive (GCObject *object)
976 {
977 	if (sgen_ptr_in_nursery (object))
978 		return sgen_nursery_is_object_alive (object);
979 
980 	return sgen_major_is_object_alive (object);
981 }
982 
983 
984 /*
985  * This function returns true if @object is either alive or it belongs to the old gen
986  * and we're currently doing a minor collection.
987  */
988 static inline int
sgen_is_object_alive_for_current_gen(GCObject * object)989 sgen_is_object_alive_for_current_gen (GCObject *object)
990 {
991 	if (sgen_ptr_in_nursery (object))
992 		return sgen_nursery_is_object_alive (object);
993 
994 	if (current_collection_generation == GENERATION_NURSERY)
995 		return TRUE;
996 
997 	return sgen_major_is_object_alive (object);
998 }
999 
1000 int sgen_gc_invoke_finalizers (void)
1001 	MONO_PERMIT (need (sgen_lock_gc));
1002 
1003 /* GC handles */
1004 
1005 void sgen_init_gchandles (void);
1006 
1007 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation, gboolean track)
1008 	MONO_PERMIT (need (sgen_gc_locked));
1009 
1010 typedef gpointer (*SgenGCHandleIterateCallback) (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user);
1011 
1012 guint32 sgen_gchandle_new (GCObject *obj, gboolean pinned);
1013 guint32 sgen_gchandle_new_weakref (GCObject *obj, gboolean track_resurrection);
1014 void sgen_gchandle_iterate (GCHandleType handle_type, int max_generation, SgenGCHandleIterateCallback callback, gpointer user)
1015 	MONO_PERMIT (need (sgen_world_stopped));
1016 void sgen_gchandle_set_target (guint32 gchandle, GCObject *obj);
1017 void sgen_mark_normal_gc_handles (void *addr, SgenUserMarkFunc mark_func, void *gc_data)
1018 	MONO_PERMIT (need (sgen_world_stopped));
1019 gpointer sgen_gchandle_get_metadata (guint32 gchandle);
1020 GCObject *sgen_gchandle_get_target (guint32 gchandle);
1021 void sgen_gchandle_free (guint32 gchandle);
1022 
1023 /* Other globals */
1024 
1025 extern GCMemSection *nursery_section;
1026 extern guint32 collect_before_allocs;
1027 extern guint32 verify_before_allocs;
1028 extern gboolean has_per_allocation_action;
1029 extern size_t degraded_mode;
1030 extern int default_nursery_size;
1031 extern guint32 tlab_size;
1032 extern NurseryClearPolicy nursery_clear_policy;
1033 extern gboolean sgen_try_free_some_memory;
1034 extern mword total_promoted_size;
1035 extern mword total_allocated_major;
1036 extern volatile gboolean sgen_suspend_finalizers;
1037 extern MonoCoopMutex gc_mutex;
1038 extern volatile gboolean concurrent_collection_in_progress;
1039 
1040 /* Nursery helpers. */
1041 
1042 static inline void
sgen_set_nursery_scan_start(char * p)1043 sgen_set_nursery_scan_start (char *p)
1044 {
1045 	size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
1046 	char *old = nursery_section->scan_starts [idx];
1047 	if (!old || old > p)
1048 		nursery_section->scan_starts [idx] = p;
1049 }
1050 
1051 
1052 /* Object Allocation */
1053 
1054 typedef enum {
1055 	ATYPE_NORMAL,
1056 	ATYPE_VECTOR,
1057 	ATYPE_SMALL,
1058 	ATYPE_STRING,
1059 	ATYPE_NUM
1060 } SgenAllocatorType;
1061 
1062 void sgen_clear_tlabs (void);
1063 
1064 GCObject* sgen_alloc_obj (GCVTable vtable, size_t size)
1065 	MONO_PERMIT (need (sgen_lock_gc, sgen_stop_world));
1066 GCObject* sgen_alloc_obj_pinned (GCVTable vtable, size_t size)
1067 	MONO_PERMIT (need (sgen_lock_gc, sgen_stop_world));
1068 GCObject* sgen_alloc_obj_mature (GCVTable vtable, size_t size)
1069 	MONO_PERMIT (need (sgen_lock_gc, sgen_stop_world));
1070 
1071 /* Debug support */
1072 
1073 void sgen_check_remset_consistency (void);
1074 void sgen_check_mod_union_consistency (void);
1075 void sgen_check_major_refs (void);
1076 void sgen_check_whole_heap (gboolean allow_missing_pinning);
1077 void sgen_check_whole_heap_stw (void)
1078 	MONO_PERMIT (need (sgen_gc_locked, sgen_stop_world));
1079 void sgen_check_objref (char *obj);
1080 void sgen_check_heap_marked (gboolean nursery_must_be_pinned);
1081 void sgen_check_nursery_objects_pinned (gboolean pinned);
1082 void sgen_check_for_xdomain_refs (void);
1083 GCObject* sgen_find_object_for_ptr (char *ptr);
1084 
1085 void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise);
1086 
1087 void sgen_debug_enable_heap_dump (const char *filename);
1088 void sgen_debug_dump_heap (const char *type, int num, const char *reason);
1089 
1090 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content);
1091 void sgen_debug_check_nursery_is_clean (void);
1092 
1093 /* Environment variable parsing */
1094 
1095 #define MONO_GC_PARAMS_NAME	"MONO_GC_PARAMS"
1096 #define MONO_GC_DEBUG_NAME	"MONO_GC_DEBUG"
1097 
1098 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...);
1099 
1100 /* Utilities */
1101 
1102 void sgen_qsort (void *array, size_t count, size_t element_size, int (*compare) (const void*, const void*));
1103 gint64 sgen_timestamp (void);
1104 
1105 /*
1106  * Canary (guard word) support
1107  * Notes:
1108  * - CANARY_SIZE must be multiple of word size in bytes
1109  * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1110  */
1111 
1112 gboolean nursery_canaries_enabled (void);
1113 
1114 #define CANARY_SIZE 8
1115 #define CANARY_STRING  "koupepia"
1116 
1117 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) {	\
1118 			size = size + CANARY_SIZE;	\
1119 		}
1120 
1121 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) {	\
1122 				memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE);	\
1123 			}
1124 
1125 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1126 
1127 #define CHECK_CANARY_FOR_OBJECT(addr,fail) if (nursery_canaries_enabled ()) {	\
1128 				guint size = sgen_safe_object_get_size_unaligned ((GCObject *) (addr)); \
1129 				char* canary_ptr = (char*) (addr) + size;	\
1130 				if (!CANARY_VALID(canary_ptr)) {	\
1131 					char *window_start, *window_end; \
1132 					window_start = (char*)(addr) - 128; \
1133 					if (!sgen_ptr_in_nursery (window_start)) \
1134 						window_start = sgen_get_nursery_start (); \
1135 					window_end = (char*)(addr) + 128; \
1136 					if (!sgen_ptr_in_nursery (window_end)) \
1137 						window_end = sgen_get_nursery_end (); \
1138 					fprintf (stderr, "\nCANARY ERROR - Type:%s Size:%d Address:%p Data:\n", sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), size,  (char*) addr); \
1139 					fwrite (addr, sizeof (char), size, stderr); \
1140 					fprintf (stderr, "\nCanary zone (next 12 chars):\n"); \
1141 					fwrite (canary_ptr, sizeof (char), 12, stderr); \
1142 					fprintf (stderr, "\nOriginal canary string:\n"); \
1143 					fwrite (CANARY_STRING, sizeof (char), 8, stderr); \
1144 					for (int x = -8; x <= 8; x++) { \
1145 						if (canary_ptr + x < (char*) addr); \
1146 							continue; \
1147 						if (CANARY_VALID(canary_ptr +x)) \
1148 							fprintf (stderr, "\nCANARY ERROR - canary found at offset %d\n", x); \
1149 					} \
1150 					fprintf (stderr, "\nSurrounding nursery (%p - %p):\n", window_start, window_end); \
1151 					fwrite (window_start, sizeof (char), window_end - window_start, stderr); \
1152 				} }
1153 
1154 /*
1155  * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1156  */
1157 static inline void
sgen_dummy_use(gpointer v)1158 sgen_dummy_use (gpointer v)
1159 {
1160 #if defined(_MSC_VER) || defined(HOST_WASM)
1161 	static volatile gpointer ptr;
1162 	ptr = v;
1163 #elif defined(__GNUC__)
1164 	__asm__ volatile ("" : "=r"(v) : "r"(v));
1165 #else
1166 #error "Implement sgen_dummy_use for your compiler"
1167 #endif
1168 }
1169 
1170 #endif /* HAVE_SGEN_GC */
1171 
1172 #endif /* __MONO_SGENGC_H__ */
1173