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