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