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