[sgen] Move stack scanning to client code.
[mono.git] / mono / metadata / sgen-gc.h
1 /*
2  * sgen-gc.c: Simple generational GC.
3  *
4  * Copyright 2001-2003 Ximian, Inc
5  * Copyright 2003-2010 Novell, Inc.
6  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
7  * Copyright (C) 2012 Xamarin Inc
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License 2.0 as published by the Free Software Foundation;
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License 2.0 along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22 #ifndef __MONO_SGENGC_H__
23 #define __MONO_SGENGC_H__
24
25 /* pthread impl */
26 #include "config.h"
27
28 #ifdef HAVE_SGEN_GC
29
30 typedef struct _SgenThreadInfo SgenThreadInfo;
31 #undef THREAD_INFO_TYPE
32 #define THREAD_INFO_TYPE SgenThreadInfo
33
34 #include <glib.h>
35 #ifdef HAVE_PTHREAD_H
36 #include <pthread.h>
37 #endif
38 #include <mono/utils/mono-compiler.h>
39 #include <mono/utils/atomic.h>
40 #include <mono/utils/mono-mutex.h>
41 #include <mono/metadata/sgen-conf.h>
42 #include <mono/metadata/sgen-archdep.h>
43 #include <mono/metadata/sgen-descriptor.h>
44 #include <mono/metadata/sgen-gray.h>
45 #include <mono/metadata/sgen-hash-table.h>
46 #include <mono/metadata/sgen-bridge.h>
47 #include <mono/metadata/sgen-protocol.h>
48
49 /* The method used to clear the nursery */
50 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
51  * Clearing at TLAB creation is much faster, but more complex and it might expose hard
52  * to find bugs.
53  */
54 typedef enum {
55         CLEAR_AT_GC,
56         CLEAR_AT_TLAB_CREATION,
57         CLEAR_AT_TLAB_CREATION_DEBUG
58 } NurseryClearPolicy;
59
60 NurseryClearPolicy sgen_get_nursery_clear_policy (void);
61
62 #define SGEN_TV_DECLARE(name) gint64 name
63 #define SGEN_TV_GETTIME(tv) tv = mono_100ns_ticks ()
64 #define SGEN_TV_ELAPSED(start,end) (int)((end-start))
65
66 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
67 #define SGEN_POSIX_STW 1
68 #endif
69
70 /*
71  * The nursery section uses this struct.
72  */
73 typedef struct _GCMemSection GCMemSection;
74 struct _GCMemSection {
75         char *data;
76         mword size;
77         /* pointer where more data could be allocated if it fits */
78         char *next_data;
79         char *end_data;
80         /*
81          * scan starts is an array of pointers to objects equally spaced in the allocation area
82          * They let use quickly find pinned objects from pinning pointers.
83          */
84         char **scan_starts;
85         /* in major collections indexes in the pin_queue for objects that pin this section */
86         size_t pin_queue_first_entry;
87         size_t pin_queue_last_entry;
88         size_t num_scan_start;
89 };
90
91 /*
92  * Recursion is not allowed for the thread lock.
93  */
94 #define LOCK_DECLARE(name) mono_mutex_t name
95 /* if changing LOCK_INIT to something that isn't idempotent, look at
96    its use in mono_gc_base_init in sgen-gc.c */
97 #define LOCK_INIT(name) mono_mutex_init (&(name))
98 #define LOCK_GC do {                                            \
99                 MONO_TRY_BLOCKING       \
100                 mono_mutex_lock (&gc_mutex);                    \
101                 MONO_FINISH_TRY_BLOCKING        \
102         } while (0)
103 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
104
105 extern LOCK_DECLARE (sgen_interruption_mutex);
106
107 #define LOCK_INTERRUPTION mono_mutex_lock (&sgen_interruption_mutex)
108 #define UNLOCK_INTERRUPTION mono_mutex_unlock (&sgen_interruption_mutex)
109
110 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
111 #define SGEN_CAS        InterlockedCompareExchange
112 #define SGEN_CAS_PTR    InterlockedCompareExchangePointer
113 #define SGEN_ATOMIC_ADD(x,i)    do {                                    \
114                 int __old_x;                                            \
115                 do {                                                    \
116                         __old_x = (x);                                  \
117                 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
118         } while (0)
119 #define SGEN_ATOMIC_ADD_P(x,i) do { \
120                 size_t __old_x;                                            \
121                 do {                                                    \
122                         __old_x = (x);                                  \
123                 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
124         } while (0)
125
126
127 #ifndef HOST_WIN32
128 /* we intercept pthread_create calls to know which threads exist */
129 #define USE_PTHREAD_INTERCEPT 1
130 #endif
131
132 #ifdef HEAVY_STATISTICS
133 extern guint64 stat_objects_alloced_degraded;
134 extern guint64 stat_bytes_alloced_degraded;
135 extern guint64 stat_copy_object_called_major;
136 extern guint64 stat_objects_copied_major;
137 #endif
138
139 #define SGEN_ASSERT(level, a, ...) do { \
140         if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) {    \
141                 g_error (__VA_ARGS__);  \
142 } } while (0)
143
144
145 #define SGEN_LOG(level, format, ...) do {      \
146         if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {        \
147                 mono_gc_printf (gc_debug_file, format, ##__VA_ARGS__);  \
148 } } while (0)
149
150 #define SGEN_COND_LOG(level, cond, format, ...) do {    \
151         if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {        \
152                 if (cond)       \
153                         mono_gc_printf (gc_debug_file, format, ##__VA_ARGS__);  \
154 } } while (0)
155
156 extern int gc_debug_level;
157 extern FILE* gc_debug_file;
158
159 extern int current_collection_generation;
160
161 extern unsigned int sgen_global_stop_count;
162
163 extern gboolean bridge_processing_in_progress;
164 extern MonoGCBridgeCallbacks bridge_callbacks;
165
166 #define SGEN_ALLOC_ALIGN                8
167 #define SGEN_ALLOC_ALIGN_BITS   3
168
169 /* s must be non-negative */
170 #define SGEN_CAN_ALIGN_UP(s)            ((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
171 #define SGEN_ALIGN_UP(s)                (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
172
173 #if SIZEOF_VOID_P == 4
174 #define ONE_P 1
175 #else
176 #define ONE_P 1ll
177 #endif
178
179 /*
180  * The link pointer is hidden by negating each bit.  We use the lowest
181  * bit of the link (before negation) to store whether it needs
182  * resurrection tracking.
183  */
184 #define HIDE_POINTER(p,t)       ((gpointer)(~((size_t)(p)|((t)?1:0))))
185 #define REVEAL_POINTER(p)       ((gpointer)((~(size_t)(p))&~3L))
186
187 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
188
189 #ifdef USER_CONFIG
190
191 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
192 #define DEFAULT_NURSERY_SIZE (sgen_nursery_size)
193 extern size_t sgen_nursery_size;
194 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
195 #define DEFAULT_NURSERY_BITS (sgen_nursery_bits)
196 extern int sgen_nursery_bits;
197
198 #else
199
200 #define DEFAULT_NURSERY_SIZE (4*1024*1024)
201 #define DEFAULT_NURSERY_BITS 22
202
203 #endif
204
205 extern char *sgen_nursery_start;
206 extern char *sgen_nursery_end;
207
208 static inline MONO_ALWAYS_INLINE gboolean
209 sgen_ptr_in_nursery (void *p)
210 {
211         return SGEN_PTR_IN_NURSERY ((p), DEFAULT_NURSERY_BITS, sgen_nursery_start, sgen_nursery_end);
212 }
213
214 static inline MONO_ALWAYS_INLINE char*
215 sgen_get_nursery_start (void)
216 {
217         return sgen_nursery_start;
218 }
219
220 static inline MONO_ALWAYS_INLINE char*
221 sgen_get_nursery_end (void)
222 {
223         return sgen_nursery_end;
224 }
225
226 /*
227  * We use the lowest three bits in the vtable pointer of objects to tag whether they're
228  * forwarded, pinned, and/or cemented.  These are the valid states:
229  *
230  * | State            | bits |
231  * |------------------+------+
232  * | default          |  000 |
233  * | forwarded        |  001 |
234  * | pinned           |  010 |
235  * | pinned, cemented |  110 |
236  *
237  * We store them in the vtable slot because the bits are used in the sync block for other
238  * purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
239  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
240  * would be an invalid combination for the monitor and hash code).
241  */
242
243 #include "sgen-tagged-pointer.h"
244
245 #define SGEN_VTABLE_BITS_MASK   SGEN_TAGGED_POINTER_MASK
246
247 #define SGEN_POINTER_IS_TAGGED_FORWARDED(p)     SGEN_POINTER_IS_TAGGED_1((p))
248 #define SGEN_POINTER_TAG_FORWARDED(p)           SGEN_POINTER_TAG_1((p))
249
250 #define SGEN_POINTER_IS_TAGGED_PINNED(p)        SGEN_POINTER_IS_TAGGED_2((p))
251 #define SGEN_POINTER_TAG_PINNED(p)              SGEN_POINTER_TAG_2((p))
252
253 #define SGEN_POINTER_IS_TAGGED_CEMENTED(p)      SGEN_POINTER_IS_TAGGED_4((p))
254 #define SGEN_POINTER_TAG_CEMENTED(p)            SGEN_POINTER_TAG_4((p))
255
256 #define SGEN_POINTER_UNTAG_VTABLE(p)            SGEN_POINTER_UNTAG_ALL((p))
257
258 /* returns NULL if not forwarded, or the forwarded address */
259 #define SGEN_VTABLE_IS_FORWARDED(vtable) (SGEN_POINTER_IS_TAGGED_FORWARDED ((vtable)) ? SGEN_POINTER_UNTAG_VTABLE ((vtable)) : NULL)
260 #define SGEN_OBJECT_IS_FORWARDED(obj) (SGEN_VTABLE_IS_FORWARDED (((mword*)(obj))[0]))
261
262 #define SGEN_VTABLE_IS_PINNED(vtable) SGEN_POINTER_IS_TAGGED_PINNED ((vtable))
263 #define SGEN_OBJECT_IS_PINNED(obj) (SGEN_VTABLE_IS_PINNED (((mword*)(obj))[0]))
264
265 #define SGEN_OBJECT_IS_CEMENTED(obj) (SGEN_POINTER_IS_TAGGED_CEMENTED (((mword*)(obj))[0]))
266
267 /* set the forwarded address fw_addr for object obj */
268 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {                           \
269                 *(void**)(obj) = SGEN_POINTER_TAG_FORWARDED ((fw_addr));        \
270         } while (0)
271 #define SGEN_PIN_OBJECT(obj) do {       \
272                 *(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
273         } while (0)
274 #define SGEN_CEMENT_OBJECT(obj) do {    \
275                 *(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
276         } while (0)
277 /* Unpins and uncements */
278 #define SGEN_UNPIN_OBJECT(obj) do {     \
279                 *(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
280         } while (0)
281
282 /*
283  * Since we set bits in the vtable, use the macro to load it from the pointer to
284  * an object that is potentially pinned.
285  */
286 #define SGEN_LOAD_VTABLE(obj)           SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((obj)))
287
288 /*
289 List of what each bit on of the vtable gc bits means. 
290 */
291 enum {
292         SGEN_GC_BIT_BRIDGE_OBJECT = 1,
293         SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT = 2,
294         SGEN_GC_BIT_FINALIZER_AWARE = 4,
295 };
296
297 /* the runtime can register areas of memory as roots: we keep two lists of roots,
298  * a pinned root set for conservatively scanned roots and a normal one for
299  * precisely scanned roots (currently implemented as a single list).
300  */
301 typedef struct _RootRecord RootRecord;
302 struct _RootRecord {
303         char *end_root;
304         mword root_desc;
305 };
306
307 enum {
308         ROOT_TYPE_NORMAL = 0, /* "normal" roots */
309         ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
310         ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
311         ROOT_TYPE_NUM
312 };
313
314 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
315
316 typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
317
318 void sgen_os_init (void);
319
320 void sgen_update_heap_boundaries (mword low, mword high);
321
322 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags);
323 void sgen_check_section_scan_starts (GCMemSection *section);
324
325 void sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type);
326
327 /* Keep in sync with description_for_type() in sgen-internal.c! */
328 enum {
329         INTERNAL_MEM_PIN_QUEUE,
330         INTERNAL_MEM_FRAGMENT,
331         INTERNAL_MEM_SECTION,
332         INTERNAL_MEM_SCAN_STARTS,
333         INTERNAL_MEM_FIN_TABLE,
334         INTERNAL_MEM_FINALIZE_ENTRY,
335         INTERNAL_MEM_FINALIZE_READY,
336         INTERNAL_MEM_DISLINK_TABLE,
337         INTERNAL_MEM_DISLINK,
338         INTERNAL_MEM_ROOTS_TABLE,
339         INTERNAL_MEM_ROOT_RECORD,
340         INTERNAL_MEM_STATISTICS,
341         INTERNAL_MEM_STAT_PINNED_CLASS,
342         INTERNAL_MEM_STAT_REMSET_CLASS,
343         INTERNAL_MEM_GRAY_QUEUE,
344         INTERNAL_MEM_MS_TABLES,
345         INTERNAL_MEM_MS_BLOCK_INFO,
346         INTERNAL_MEM_MS_BLOCK_INFO_SORT,
347         INTERNAL_MEM_WORKER_DATA,
348         INTERNAL_MEM_THREAD_POOL_JOB,
349         INTERNAL_MEM_BRIDGE_DATA,
350         INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE,
351         INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY,
352         INTERNAL_MEM_BRIDGE_HASH_TABLE,
353         INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
354         INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
355         INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
356         INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE,
357         INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY,
358         INTERNAL_MEM_TARJAN_OBJ_BUCKET,
359         INTERNAL_MEM_BRIDGE_DEBUG,
360         INTERNAL_MEM_TOGGLEREF_DATA,
361         INTERNAL_MEM_CARDTABLE_MOD_UNION,
362         INTERNAL_MEM_BINARY_PROTOCOL,
363         INTERNAL_MEM_TEMPORARY,
364         INTERNAL_MEM_FIRST_CLIENT
365 };
366
367 enum {
368         GENERATION_NURSERY,
369         GENERATION_OLD,
370         GENERATION_MAX
371 };
372
373 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
374 #define BINARY_PROTOCOL_ARG(x)  ,x
375 #else
376 #define BINARY_PROTOCOL_ARG(x)
377 #endif
378
379 void sgen_init_internal_allocator (void);
380
381 #define SGEN_DEFINE_OBJECT_VTABLE
382 #include "sgen-client-mono.h"
383 #undef SGEN_DEFINE_OBJECT_VTABLE
384
385 /* eventually share with MonoThread? */
386 /*
387  * This structure extends the MonoThreadInfo structure.
388  */
389 struct _SgenThreadInfo {
390         SgenClientThreadInfo client_info;
391
392         /*
393         This is set to TRUE when STW fails to suspend a thread, most probably because the
394         underlying thread is dead.
395         */
396         gboolean skip, suspend_done;
397         volatile int in_critical_region;
398
399         /*
400         This is set the argument of mono_gc_set_skip_thread.
401
402         A thread that knowingly holds no managed state can call this
403         function around blocking loops to reduce the GC burden by not
404         been scanned.
405         */
406         gboolean gc_disabled;
407         void *stack_end;
408         void *stack_start;
409         void *stack_start_limit;
410         char **tlab_next_addr;
411         char **tlab_start_addr;
412         char **tlab_temp_end_addr;
413         char **tlab_real_end_addr;
414         gpointer runtime_data;
415
416 #ifdef SGEN_POSIX_STW
417         /* This is -1 until the first suspend. */
418         int signal;
419         /* FIXME: kill this, we only use signals on systems that have rt-posix, which doesn't have issues with duplicates. */
420         unsigned int stop_count; /* to catch duplicate signals. */
421 #endif
422
423         /*FIXME pretty please finish killing ARCH_NUM_REGS */
424 #ifdef USE_MONO_CTX
425         MonoContext ctx;                /* ditto */
426 #else
427         gpointer regs[ARCH_NUM_REGS];       /* ditto */
428 #endif
429
430 #ifndef HAVE_KW_THREAD
431         char *tlab_start;
432         char *tlab_next;
433         char *tlab_temp_end;
434         char *tlab_real_end;
435 #endif
436 };
437
438 gboolean sgen_is_worker_thread (MonoNativeThreadId thread);
439
440 typedef void (*CopyOrMarkObjectFunc) (void**, SgenGrayQueue*);
441 typedef void (*ScanObjectFunc) (char *obj, mword desc, SgenGrayQueue*);
442 typedef void (*ScanVTypeFunc) (char *full_object, char *start, mword desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
443
444 typedef struct {
445         CopyOrMarkObjectFunc copy_or_mark_object;
446         ScanObjectFunc scan_object;
447         ScanVTypeFunc scan_vtype;
448         /*FIXME add allocation function? */
449 } SgenObjectOperations;
450
451 typedef struct
452 {
453         SgenObjectOperations *ops;
454         SgenGrayQueue *queue;
455 } ScanCopyContext;
456
457 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
458
459 void sgen_report_internal_mem_usage (void);
460 void sgen_dump_internal_mem_usage (FILE *heap_dump_file);
461 void sgen_dump_section (GCMemSection *section, const char *type);
462 void sgen_dump_occupied (char *start, char *end, char *section_start);
463
464 void sgen_register_fixed_internal_mem_type (int type, size_t size);
465
466 void* sgen_alloc_internal (int type);
467 void sgen_free_internal (void *addr, int type);
468
469 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure);
470 void sgen_free_internal_dynamic (void *addr, size_t size, int type);
471
472 void sgen_pin_stats_enable (void);
473 void sgen_pin_stats_register_object (char *obj, size_t size);
474 void sgen_pin_stats_register_global_remset (char *obj);
475 void sgen_pin_stats_print_class_stats (void);
476
477 void sgen_sort_addresses (void **array, size_t size);
478 void sgen_add_to_global_remset (gpointer ptr, gpointer obj);
479
480 int sgen_get_current_collection_generation (void);
481 gboolean sgen_collection_is_concurrent (void);
482 gboolean sgen_concurrent_collection_in_progress (void);
483
484 typedef struct _SgenFragment SgenFragment;
485
486 struct _SgenFragment {
487         SgenFragment *next;
488         char *fragment_start;
489         char *fragment_next; /* the current soft limit for allocation */
490         char *fragment_end;
491         SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
492 };
493
494 typedef struct {
495         SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
496         SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
497 } SgenFragmentAllocator;
498
499 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end);
500 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator);
501 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size);
502 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size);
503 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
504 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
505 SgenFragment* sgen_fragment_allocator_alloc (void);
506 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator);
507 void sgen_clear_range (char *start, char *end);
508
509
510 /*
511 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
512 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
513 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
514
515 Experimental results on how much space we waste with a 4Mb nursery:
516
517 Note that the wastage applies to the half nursery, or 2Mb:
518
519 Test 1 (compiling corlib):
520 9: avg: 3.1k
521 8: avg: 1.6k
522
523 */
524 #define SGEN_TO_SPACE_GRANULE_BITS 9
525 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
526
527 extern char *sgen_space_bitmap;
528 extern size_t sgen_space_bitmap_size;
529
530 static inline gboolean
531 sgen_nursery_is_to_space (char *object)
532 {
533         size_t idx = (object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
534         size_t byte = idx >> 3;
535         size_t bit = idx & 0x7;
536
537         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 ());
538         SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %d out of range", byte, sgen_space_bitmap_size);
539
540         return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
541 }
542
543 static inline gboolean
544 sgen_nursery_is_from_space (char *object)
545 {
546         return !sgen_nursery_is_to_space (object);
547 }
548
549 static inline gboolean
550 sgen_nursery_is_object_alive (char *obj)
551 {
552         /* FIXME put this asserts under a non default level */
553         g_assert (sgen_ptr_in_nursery (obj));
554
555         if (sgen_nursery_is_to_space (obj))
556                 return TRUE;
557
558         if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
559                 return TRUE;
560
561         return FALSE;
562 }
563
564 typedef struct {
565         gboolean is_split;
566
567         char* (*alloc_for_promotion) (GCVTable *vtable, char *obj, size_t objsize, gboolean has_references);
568
569         SgenObjectOperations serial_ops;
570
571         void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
572         void (*clear_fragments) (void);
573         SgenFragment* (*build_fragments_get_exclude_head) (void);
574         void (*build_fragments_release_exclude_head) (void);
575         void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
576         void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
577
578         gboolean (*handle_gc_param) (const char *opt); /* Optional */
579         void (*print_gc_param_usage) (void); /* Optional */
580 } SgenMinorCollector;
581
582 extern SgenMinorCollector sgen_minor_collector;
583
584 void sgen_simple_nursery_init (SgenMinorCollector *collector);
585 void sgen_split_nursery_init (SgenMinorCollector *collector);
586
587 /* Updating references */
588
589 #ifdef SGEN_CHECK_UPDATE_REFERENCE
590 gboolean sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread) MONO_INTERNAL;
591 static inline void
592 sgen_update_reference (void **p, void *o, gboolean allow_null)
593 {
594         if (!allow_null)
595                 SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
596         SGEN_ASSERT (0, !sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
597         *p = o;
598 }
599
600 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   sgen_update_reference ((void**)(p), (void*)(o), TRUE)
601 #define SGEN_UPDATE_REFERENCE(p,o)              sgen_update_reference ((void**)(p), (void*)(o), FALSE)
602 #else
603 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   (*(void**)(p) = (void*)(o))
604 #define SGEN_UPDATE_REFERENCE(p,o)              SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
605 #endif
606
607 /* Major collector */
608
609 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
610 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
611
612 typedef enum {
613         ITERATE_OBJECTS_SWEEP = 1,
614         ITERATE_OBJECTS_NON_PINNED = 2,
615         ITERATE_OBJECTS_PINNED = 4,
616         ITERATE_OBJECTS_ALL = ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED,
617         ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
618         ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
619         ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
620 } IterateObjectsFlags;
621
622 typedef struct
623 {
624         size_t num_scanned_objects;
625         size_t num_unique_scanned_objects;
626 } ScannedObjectCounts;
627
628 typedef struct _SgenMajorCollector SgenMajorCollector;
629 struct _SgenMajorCollector {
630         size_t section_size;
631         gboolean is_concurrent;
632         gboolean needs_thread_pool;
633         gboolean supports_cardtable;
634         gboolean sweeps_lazily;
635
636         /*
637          * This is set to TRUE by the sweep if the next major
638          * collection should be synchronous (for evacuation).  For
639          * non-concurrent collectors, this should be NULL.
640          */
641         gboolean *want_synchronous_collection;
642
643         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
644         gboolean (*is_object_live) (char *obj);
645         void* (*alloc_small_pinned_obj) (GCVTable *vtable, size_t size, gboolean has_references);
646         void* (*alloc_degraded) (GCVTable *vtable, size_t size);
647
648         SgenObjectOperations major_ops_serial;
649         SgenObjectOperations major_ops_concurrent_start;
650         SgenObjectOperations major_ops_concurrent;
651         SgenObjectOperations major_ops_concurrent_finish;
652
653         void* (*alloc_object) (GCVTable *vtable, size_t size, gboolean has_references);
654         void (*free_pinned_object) (char *obj, size_t size);
655
656         /*
657          * This is used for domain unloading, heap walking from the logging profiler, and
658          * debugging.  Can assume the world is stopped.
659          */
660         void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
661
662         void (*free_non_pinned_object) (char *obj, size_t size);
663         void (*pin_objects) (SgenGrayQueue *queue);
664         void (*pin_major_object) (char *obj, SgenGrayQueue *queue);
665         void (*scan_card_table) (gboolean mod_union, ScanCopyContext ctx);
666         void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
667         void (*update_cardtable_mod_union) (void);
668         void (*init_to_space) (void);
669         void (*sweep) (void);
670         gboolean (*have_swept) (void);
671         void (*finish_sweeping) (void);
672         void (*free_swept_blocks) (size_t allowance);
673         void (*check_scan_starts) (void);
674         void (*dump_heap) (FILE *heap_dump_file);
675         gint64 (*get_used_size) (void);
676         void (*start_nursery_collection) (void);
677         void (*finish_nursery_collection) (void);
678         void (*start_major_collection) (void);
679         void (*finish_major_collection) (ScannedObjectCounts *counts);
680         gboolean (*drain_gray_stack) (ScanCopyContext ctx);
681         gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
682         gboolean (*obj_is_from_pinned_alloc) (char *obj);
683         void (*report_pinned_memory_usage) (void);
684         size_t (*get_num_major_sections) (void);
685         size_t (*get_bytes_survived_last_sweep) (void);
686         gboolean (*handle_gc_param) (const char *opt);
687         void (*print_gc_param_usage) (void);
688         void (*post_param_init) (SgenMajorCollector *collector);
689         gboolean (*is_valid_object) (char *object);
690         GCVTable* (*describe_pointer) (char *pointer);
691         guint8* (*get_cardtable_mod_union_for_object) (char *object);
692         long long (*get_and_reset_num_major_objects_marked) (void);
693         void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
694 };
695
696 extern SgenMajorCollector major_collector;
697
698 void sgen_marksweep_init (SgenMajorCollector *collector);
699 void sgen_marksweep_fixed_init (SgenMajorCollector *collector);
700 void sgen_marksweep_par_init (SgenMajorCollector *collector);
701 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector);
702 void sgen_marksweep_conc_init (SgenMajorCollector *collector);
703 SgenMajorCollector* sgen_get_major_collector (void);
704
705
706 typedef struct _SgenRememberedSet {
707         void (*wbarrier_set_field) (MonoObject *obj, gpointer field_ptr, MonoObject* value);
708         void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
709         void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, size_t element_size);
710         void (*wbarrier_object_copy) (GCObject* obj, GCObject *src);
711         void (*wbarrier_generic_nostore) (gpointer ptr);
712         void (*record_pointer) (gpointer ptr);
713
714         void (*scan_remsets) (ScanCopyContext ctx);
715
716         void (*clear_cards) (void);
717
718         void (*finish_minor_collection) (void);
719         gboolean (*find_address) (char *addr);
720         gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
721 } SgenRememberedSet;
722
723 SgenRememberedSet *sgen_get_remset (void);
724
725 static inline mword
726 sgen_obj_get_descriptor (char *obj)
727 {
728         GCVTable *vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
729         SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable), "Object can't be tagged");
730         return sgen_vtable_get_descriptor (vtable);
731 }
732
733 static inline mword
734 sgen_obj_get_descriptor_safe (char *obj)
735 {
736         GCVTable *vtable = (GCVTable*)SGEN_LOAD_VTABLE (obj);
737         return sgen_vtable_get_descriptor (vtable);
738 }
739
740 static inline mword
741 sgen_safe_object_get_size (GCObject *obj)
742 {
743        char *forwarded;
744
745        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
746                obj = (GCObject*)forwarded;
747
748        return sgen_client_par_object_get_size ((GCVTable*)SGEN_LOAD_VTABLE (obj), obj);
749 }
750
751 static inline gboolean
752 sgen_safe_object_is_small (MonoObject *obj, int type)
753 {
754         if (type <= DESC_TYPE_MAX_SMALL_OBJ)
755                 return TRUE;
756         return SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj)) <= SGEN_MAX_SMALL_OBJ_SIZE;
757 }
758
759 /*
760  * This variant guarantees to return the exact size of the object
761  * before alignment. Needed for canary support.
762  */
763 static inline guint
764 sgen_safe_object_get_size_unaligned (GCObject *obj)
765 {
766        char *forwarded;
767
768        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
769                obj = (GCObject*)forwarded;
770        }
771
772        return sgen_client_slow_object_get_size ((GCVTable*)SGEN_LOAD_VTABLE (obj), obj);
773 }
774
775 #include "metadata/sgen-client-mono.h"
776
777 gboolean sgen_object_is_live (void *obj);
778
779 void  sgen_init_fin_weak_hash (void);
780
781 gboolean sgen_need_bridge_processing (void);
782 void sgen_bridge_reset_data (void);
783 void sgen_bridge_processing_stw_step (void);
784 void sgen_bridge_processing_finish (int generation);
785 void sgen_register_test_bridge_callbacks (const char *bridge_class_name);
786 gboolean sgen_is_bridge_object (GCObject *obj);
787 MonoGCBridgeObjectKind sgen_bridge_class_kind (MonoClass *klass);
788 void sgen_mark_bridge_object (GCObject *obj);
789 void sgen_bridge_register_finalized_object (GCObject *object);
790 void sgen_bridge_describe_pointer (GCObject *object);
791
792 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx);
793 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx);
794
795 void sgen_process_togglerefs (void);
796 void sgen_register_test_toggleref_callback (void);
797
798 gboolean sgen_is_bridge_object (GCObject *obj);
799 void sgen_mark_bridge_object (GCObject *obj);
800
801 gboolean sgen_bridge_handle_gc_debug (const char *opt);
802 void sgen_bridge_print_gc_debug_usage (void);
803
804 typedef struct {
805         void (*reset_data) (void);
806         void (*processing_stw_step) (void);
807         void (*processing_build_callback_data) (int generation);
808         void (*processing_after_callback) (int generation);
809         MonoGCBridgeObjectKind (*class_kind) (MonoClass *class);
810         void (*register_finalized_object) (GCObject *object);
811         void (*describe_pointer) (GCObject *object);
812         void (*enable_accounting) (void);
813         void (*set_dump_prefix) (const char *prefix);
814
815         /*
816          * These are set by processing_build_callback_data().
817          */
818         int num_sccs;
819         MonoGCBridgeSCC **api_sccs;
820
821         int num_xrefs;
822         MonoGCBridgeXRef *api_xrefs;
823 } SgenBridgeProcessor;
824
825 void sgen_old_bridge_init (SgenBridgeProcessor *collector);
826 void sgen_new_bridge_init (SgenBridgeProcessor *collector);
827 void sgen_tarjan_bridge_init (SgenBridgeProcessor *collector);
828 void sgen_set_bridge_implementation (const char *name);
829 void sgen_bridge_set_dump_prefix (const char *prefix);
830
831 gboolean sgen_compare_bridge_processor_results (SgenBridgeProcessor *a, SgenBridgeProcessor *b);
832
833 typedef mono_bool (*WeakLinkAlivePredicateFunc) (GCObject*, void*);
834
835 void sgen_null_links_with_predicate (int generation, WeakLinkAlivePredicateFunc predicate, void *data);
836
837 gboolean sgen_gc_is_object_ready_for_finalization (void *object);
838 void sgen_gc_lock (void);
839 void sgen_gc_unlock (void);
840
841 void sgen_queue_finalization_entry (GCObject *obj);
842 const char* sgen_generation_name (int generation);
843
844 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx);
845 void sgen_finalize_in_range (int generation, ScanCopyContext ctx);
846 void sgen_null_link_in_range (int generation, gboolean before_finalization, ScanCopyContext ctx);
847 void sgen_null_links_for_domain (MonoDomain *domain, int generation);
848 void sgen_remove_finalizers_for_domain (MonoDomain *domain, int generation);
849 void sgen_process_fin_stage_entries (void);
850 void sgen_process_dislink_stage_entries (void);
851 void sgen_register_disappearing_link (GCObject *obj, void **link, gboolean track, gboolean in_gc);
852
853 gboolean sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx);
854
855 enum {
856         SPACE_NURSERY,
857         SPACE_MAJOR,
858         SPACE_LOS
859 };
860
861 void sgen_pin_object (void *object, SgenGrayQueue *queue);
862 void sgen_set_pinned_from_failed_allocation (mword objsize);
863
864 void sgen_ensure_free_space (size_t size);
865 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish);
866 gboolean sgen_has_critical_method (void);
867 gboolean sgen_is_critical_method (MonoMethod *method);
868
869 /* STW */
870
871 typedef struct {
872         int generation;
873         const char *reason;
874         gboolean is_overflow;
875         SGEN_TV_DECLARE (total_time);
876         SGEN_TV_DECLARE (stw_time);
877         SGEN_TV_DECLARE (bridge_time);
878 } GGTimingInfo;
879
880 int sgen_stop_world (int generation);
881 int sgen_restart_world (int generation, GGTimingInfo *timing);
882 gboolean sgen_is_world_stopped (void);
883
884 /* LOS */
885
886 typedef struct _LOSObject LOSObject;
887 struct _LOSObject {
888         LOSObject *next;
889         mword size; /* this is the object size, lowest bit used for pin/mark */
890         guint8 * volatile cardtable_mod_union; /* only used by the concurrent collector */
891 #if SIZEOF_VOID_P < 8
892         mword dummy;            /* to align object to sizeof (double) */
893 #endif
894         char data [MONO_ZERO_LEN_ARRAY];
895 };
896
897 extern LOSObject *los_object_list;
898 extern mword los_memory_usage;
899
900 void sgen_los_free_object (LOSObject *obj);
901 void* sgen_los_alloc_large_inner (GCVTable *vtable, size_t size);
902 void sgen_los_sweep (void);
903 gboolean sgen_ptr_is_in_los (char *ptr, char **start);
904 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data);
905 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
906 void sgen_los_scan_card_table (gboolean mod_union, ScanCopyContext ctx);
907 void sgen_los_update_cardtable_mod_union (void);
908 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards);
909 gboolean sgen_los_is_valid_object (char *object);
910 gboolean mono_sgen_los_describe_pointer (char *ptr);
911 LOSObject* sgen_los_header_for_object (char *data);
912 mword sgen_los_object_size (LOSObject *obj);
913 void sgen_los_pin_object (char *obj);
914 gboolean sgen_los_object_is_pinned (char *obj);
915 void sgen_los_mark_mod_union_card (MonoObject *mono_obj, void **ptr);
916
917
918 /* nursery allocator */
919
920 void sgen_clear_nursery_fragments (void);
921 void sgen_nursery_allocator_prepare_for_pinning (void);
922 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end);
923 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue);
924 void sgen_init_nursery_allocator (void);
925 void sgen_nursery_allocator_init_heavy_stats (void);
926 void sgen_init_allocator (void);
927 char* sgen_nursery_alloc_get_upper_alloc_bound (void);
928 void* sgen_nursery_alloc (size_t size);
929 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size);
930 gboolean sgen_can_alloc_size (size_t size);
931 void sgen_nursery_retire_region (void *address, ptrdiff_t size);
932
933 void sgen_nursery_alloc_prepare_for_minor (void);
934 void sgen_nursery_alloc_prepare_for_major (void);
935
936 char* sgen_alloc_for_promotion (char *obj, size_t objsize, gboolean has_references);
937
938 void* sgen_alloc_obj_nolock (GCVTable *vtable, size_t size);
939 void* sgen_try_alloc_obj_nolock (GCVTable *vtable, size_t size);
940
941 /* Threads */
942
943 void* sgen_thread_register (SgenThreadInfo* info, void *addr);
944 void sgen_thread_unregister (SgenThreadInfo *p);
945 void sgen_thread_attach (SgenThreadInfo *info);
946
947 /* Finalization/ephemeron support */
948
949 static inline gboolean
950 sgen_major_is_object_alive (void *object)
951 {
952         mword objsize;
953
954         /* Oldgen objects can be pinned and forwarded too */
955         if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
956                 return TRUE;
957
958         /*
959          * FIXME: major_collector.is_object_live() also calculates the
960          * size.  Avoid the double calculation.
961          */
962         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject*)object));
963         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
964                 return sgen_los_object_is_pinned (object);
965
966         return major_collector.is_object_live (object);
967 }
968
969 /*
970  * This function returns true if @object is either alive or it belongs to the old gen
971  * and we're currently doing a minor collection.
972  */
973 static inline int
974 sgen_is_object_alive_for_current_gen (char *object)
975 {
976         if (sgen_ptr_in_nursery (object))
977                 return sgen_nursery_is_object_alive (object);
978
979         if (current_collection_generation == GENERATION_NURSERY)
980                 return TRUE;
981
982         return sgen_major_is_object_alive (object);
983 }
984
985 /* TLS Data */
986
987 extern MonoNativeTlsKey thread_info_key;
988
989 #ifdef HAVE_KW_THREAD
990 extern __thread SgenThreadInfo *sgen_thread_info;
991 extern __thread char *stack_end;
992 #endif
993
994 #ifdef HAVE_KW_THREAD
995 #define TLAB_ACCESS_INIT
996 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
997 #else
998 #define TLAB_ACCESS_INIT        SgenThreadInfo *__thread_info__ = mono_native_tls_get_value (thread_info_key)
999 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
1000 #endif
1001
1002 #ifndef DISABLE_CRITICAL_REGION
1003
1004 #ifdef HAVE_KW_THREAD
1005 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
1006 #else
1007 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
1008 #endif
1009
1010 /* Enter must be visible before anything is done in the critical region. */
1011 #define ENTER_CRITICAL_REGION do { mono_atomic_store_acquire (&IN_CRITICAL_REGION, 1); } while (0)
1012
1013 /* Exit must make sure all critical regions stores are visible before it signal the end of the region. 
1014  * We don't need to emit a full barrier since we
1015  */
1016 #define EXIT_CRITICAL_REGION  do { mono_atomic_store_release (&IN_CRITICAL_REGION, 0); } while (0)
1017
1018 #endif
1019
1020 /* Other globals */
1021
1022 extern GCMemSection *nursery_section;
1023 extern guint32 collect_before_allocs;
1024 extern guint32 verify_before_allocs;
1025 extern gboolean has_per_allocation_action;
1026 extern size_t degraded_mode;
1027 extern int default_nursery_size;
1028 extern guint32 tlab_size;
1029 extern NurseryClearPolicy nursery_clear_policy;
1030 extern gboolean sgen_try_free_some_memory;
1031
1032 extern LOCK_DECLARE (gc_mutex);
1033
1034 /* Nursery helpers. */
1035
1036 static inline void
1037 sgen_set_nursery_scan_start (char *p)
1038 {
1039         size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
1040         char *old = nursery_section->scan_starts [idx];
1041         if (!old || old > p)
1042                 nursery_section->scan_starts [idx] = p;
1043 }
1044
1045
1046 /* Object Allocation */
1047
1048 typedef enum {
1049         ATYPE_NORMAL,
1050         ATYPE_VECTOR,
1051         ATYPE_SMALL,
1052         ATYPE_STRING,
1053         ATYPE_NUM
1054 } SgenAllocatorType;
1055
1056 void sgen_init_tlab_info (SgenThreadInfo* info);
1057 void sgen_clear_tlabs (void);
1058 void sgen_set_use_managed_allocator (gboolean flag);
1059 gboolean sgen_is_managed_allocator (MonoMethod *method);
1060 gboolean sgen_has_managed_allocator (void);
1061
1062 /* Debug support */
1063
1064 void sgen_check_consistency (void);
1065 void sgen_check_mod_union_consistency (void);
1066 void sgen_check_major_refs (void);
1067 void sgen_check_whole_heap (gboolean allow_missing_pinning);
1068 void sgen_check_whole_heap_stw (void);
1069 void sgen_check_objref (char *obj);
1070 void sgen_check_heap_marked (gboolean nursery_must_be_pinned);
1071 void sgen_check_nursery_objects_pinned (gboolean pinned);
1072 void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type);
1073 void sgen_check_for_xdomain_refs (void);
1074 char* sgen_find_object_for_ptr (char *ptr);
1075
1076 void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise);
1077
1078 void sgen_debug_enable_heap_dump (const char *filename);
1079 void sgen_debug_dump_heap (const char *type, int num, const char *reason);
1080
1081 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content);
1082 void sgen_debug_check_nursery_is_clean (void);
1083
1084 /* Write barrier support */
1085
1086 /*
1087  * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1088  */
1089 static inline void
1090 sgen_dummy_use (gpointer v) {
1091 #if defined(__GNUC__)
1092         __asm__ volatile ("" : "=r"(v) : "r"(v));
1093 #elif defined(_MSC_VER)
1094         static volatile gpointer ptr;
1095         ptr = v;
1096 #else
1097 #error "Implement sgen_dummy_use for your compiler"
1098 #endif
1099 }
1100
1101 /* Environment variable parsing */
1102
1103 #define MONO_GC_PARAMS_NAME     "MONO_GC_PARAMS"
1104 #define MONO_GC_DEBUG_NAME      "MONO_GC_DEBUG"
1105
1106 gboolean sgen_parse_environment_string_extract_number (const char *str, size_t *out);
1107 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...);
1108
1109 /* Utilities */
1110
1111 void sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*));
1112 gint64 sgen_timestamp (void);
1113
1114 /*
1115  * Canary (guard word) support
1116  * Notes:
1117  * - CANARY_SIZE must be multiple of word size in bytes
1118  * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1119  */
1120  
1121 gboolean nursery_canaries_enabled (void);
1122
1123 #define CANARY_SIZE 8
1124 #define CANARY_STRING  "koupepia"
1125
1126 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) {  \
1127                         size = size + CANARY_SIZE;      \
1128                 }
1129
1130 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) {    \
1131                                 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE);   \
1132                         }
1133
1134 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1135
1136 #define CHECK_CANARY_FOR_OBJECT(addr) if (nursery_canaries_enabled ()) {        \
1137                                 char* canary_ptr = (char*) (addr) + sgen_safe_object_get_size_unaligned ((GCObject *) (addr));  \
1138                                 if (!CANARY_VALID(canary_ptr)) {        \
1139                                         char canary_copy[CANARY_SIZE +1];       \
1140                                         strncpy (canary_copy, canary_ptr, CANARY_SIZE); \
1141                                         canary_copy[CANARY_SIZE] = 0;   \
1142                                         g_error ("CORRUPT CANARY:\naddr->%p\ntype->%s\nexcepted->'%s'\nfound->'%s'\n", (char*) addr, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), CANARY_STRING, canary_copy);      \
1143                                 } }
1144
1145 #endif /* HAVE_SGEN_GC */
1146
1147 #endif /* __MONO_SGENGC_H__ */