Merge pull request #1388 from schani/fix-23401
[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_TEMPORARY,
441         INTERNAL_MEM_MAX
442 };
443
444 enum {
445         GENERATION_NURSERY,
446         GENERATION_OLD,
447         GENERATION_MAX
448 };
449
450 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
451 #define BINARY_PROTOCOL_ARG(x)  ,x
452 #else
453 #define BINARY_PROTOCOL_ARG(x)
454 #endif
455
456 void sgen_init_internal_allocator (void) MONO_INTERNAL;
457
458 typedef struct _ObjectList ObjectList;
459 struct _ObjectList {
460         MonoObject *obj;
461         ObjectList *next;
462 };
463
464 typedef void (*CopyOrMarkObjectFunc) (void**, SgenGrayQueue*);
465 typedef void (*ScanObjectFunc) (char *obj, mword desc, SgenGrayQueue*);
466 typedef void (*ScanVTypeFunc) (char*, mword desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
467
468 typedef struct
469 {
470         ScanObjectFunc scan_func;
471         CopyOrMarkObjectFunc copy_func;
472         SgenGrayQueue *queue;
473 } ScanCopyContext;
474
475 void sgen_report_internal_mem_usage (void) MONO_INTERNAL;
476 void sgen_dump_internal_mem_usage (FILE *heap_dump_file) MONO_INTERNAL;
477 void sgen_dump_section (GCMemSection *section, const char *type) MONO_INTERNAL;
478 void sgen_dump_occupied (char *start, char *end, char *section_start) MONO_INTERNAL;
479
480 void sgen_register_moved_object (void *obj, void *destination) MONO_INTERNAL;
481
482 void sgen_register_fixed_internal_mem_type (int type, size_t size) MONO_INTERNAL;
483
484 void* sgen_alloc_internal (int type) MONO_INTERNAL;
485 void sgen_free_internal (void *addr, int type) MONO_INTERNAL;
486
487 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure) MONO_INTERNAL;
488 void sgen_free_internal_dynamic (void *addr, size_t size, int type) MONO_INTERNAL;
489
490 void sgen_pin_stats_register_object (char *obj, size_t size);
491 void sgen_pin_stats_register_global_remset (char *obj);
492 void sgen_pin_stats_print_class_stats (void);
493
494 void sgen_sort_addresses (void **array, size_t size) MONO_INTERNAL;
495 void sgen_add_to_global_remset (gpointer ptr, gpointer obj) MONO_INTERNAL;
496
497 int sgen_get_current_collection_generation (void) MONO_INTERNAL;
498 gboolean sgen_collection_is_concurrent (void) MONO_INTERNAL;
499 gboolean sgen_concurrent_collection_in_progress (void) MONO_INTERNAL;
500
501 typedef struct {
502         CopyOrMarkObjectFunc copy_or_mark_object;
503         ScanObjectFunc scan_object;
504         ScanVTypeFunc scan_vtype;
505         /*FIXME add allocation function? */
506 } SgenObjectOperations;
507
508 SgenObjectOperations *sgen_get_current_object_ops (void) MONO_INTERNAL;
509
510 typedef struct _SgenFragment SgenFragment;
511
512 struct _SgenFragment {
513         SgenFragment *next;
514         char *fragment_start;
515         char *fragment_next; /* the current soft limit for allocation */
516         char *fragment_end;
517         SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
518 };
519
520 typedef struct {
521         SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
522         SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
523 } SgenFragmentAllocator;
524
525 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end) MONO_INTERNAL;
526 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator) MONO_INTERNAL;
527 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size) MONO_INTERNAL;
528 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size) MONO_INTERNAL;
529 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size) MONO_INTERNAL;
530 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size) MONO_INTERNAL;
531 SgenFragment* sgen_fragment_allocator_alloc (void) MONO_INTERNAL;
532 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator) MONO_INTERNAL;
533 void sgen_clear_range (char *start, char *end) MONO_INTERNAL;
534
535
536 /*
537 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
538 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
539 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
540
541 Experimental results on how much space we waste with a 4Mb nursery:
542
543 Note that the wastage applies to the half nursery, or 2Mb:
544
545 Test 1 (compiling corlib):
546 9: avg: 3.1k
547 8: avg: 1.6k
548
549 */
550 #define SGEN_TO_SPACE_GRANULE_BITS 9
551 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
552
553 extern char *sgen_space_bitmap MONO_INTERNAL;
554 extern size_t sgen_space_bitmap_size MONO_INTERNAL;
555
556 static inline gboolean
557 sgen_nursery_is_to_space (char *object)
558 {
559         size_t idx = (object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
560         size_t byte = idx >> 3;
561         size_t bit = idx & 0x7;
562
563         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 ());
564         SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %d out of range", byte, sgen_space_bitmap_size);
565
566         return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
567 }
568
569 static inline gboolean
570 sgen_nursery_is_from_space (char *object)
571 {
572         return !sgen_nursery_is_to_space (object);
573 }
574
575 static inline gboolean
576 sgen_nursery_is_object_alive (char *obj)
577 {
578         /* FIXME put this asserts under a non default level */
579         g_assert (sgen_ptr_in_nursery (obj));
580
581         if (sgen_nursery_is_to_space (obj))
582                 return TRUE;
583
584         if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
585                 return TRUE;
586
587         return FALSE;
588 }
589
590 typedef struct {
591         gboolean is_split;
592
593         char* (*alloc_for_promotion) (MonoVTable *vtable, char *obj, size_t objsize, gboolean has_references);
594
595         SgenObjectOperations serial_ops;
596
597         void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
598         void (*clear_fragments) (void);
599         SgenFragment* (*build_fragments_get_exclude_head) (void);
600         void (*build_fragments_release_exclude_head) (void);
601         void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
602         void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
603
604         gboolean (*handle_gc_param) (const char *opt); /* Optional */
605         void (*print_gc_param_usage) (void); /* Optional */
606 } SgenMinorCollector;
607
608 extern SgenMinorCollector sgen_minor_collector;
609
610 void sgen_simple_nursery_init (SgenMinorCollector *collector) MONO_INTERNAL;
611 void sgen_split_nursery_init (SgenMinorCollector *collector) MONO_INTERNAL;
612
613 /* Updating references */
614
615 #ifdef SGEN_CHECK_UPDATE_REFERENCE
616 static inline void
617 sgen_update_reference (void **p, void *o, gboolean allow_null)
618 {
619         if (!allow_null)
620                 SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
621         SGEN_ASSERT (0, !sgen_is_worker_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
622         *p = o;
623 }
624
625 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   sgen_update_reference ((void**)(p), (void*)(o), TRUE)
626 #define SGEN_UPDATE_REFERENCE(p,o)              sgen_update_reference ((void**)(p), (void*)(o), FALSE)
627 #else
628 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   (*(void**)(p) = (void*)(o))
629 #define SGEN_UPDATE_REFERENCE(p,o)              SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
630 #endif
631
632 /* Major collector */
633
634 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
635 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
636
637 typedef enum {
638         ITERATE_OBJECTS_SWEEP = 1,
639         ITERATE_OBJECTS_NON_PINNED = 2,
640         ITERATE_OBJECTS_PINNED = 4,
641         ITERATE_OBJECTS_ALL = ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED,
642         ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
643         ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
644         ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
645 } IterateObjectsFlags;
646
647 typedef struct _SgenMajorCollector SgenMajorCollector;
648 struct _SgenMajorCollector {
649         size_t section_size;
650         gboolean is_concurrent;
651         gboolean supports_cardtable;
652         gboolean sweeps_lazily;
653
654         /*
655          * This is set to TRUE if the sweep for the last major
656          * collection has been completed.
657          */
658         gboolean *have_swept;
659         /*
660          * This is set to TRUE by the sweep if the next major
661          * collection should be synchronous (for evacuation).  For
662          * non-concurrent collectors, this should be NULL.
663          */
664         gboolean *want_synchronous_collection;
665
666         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
667         gboolean (*is_object_live) (char *obj);
668         void* (*alloc_small_pinned_obj) (MonoVTable *vtable, size_t size, gboolean has_references);
669         void* (*alloc_degraded) (MonoVTable *vtable, size_t size);
670
671         SgenObjectOperations major_ops;
672         SgenObjectOperations major_concurrent_ops;
673
674         void* (*alloc_object) (MonoVTable *vtable, size_t size, gboolean has_references);
675         void (*free_pinned_object) (char *obj, size_t size);
676         void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
677         void (*free_non_pinned_object) (char *obj, size_t size);
678         void (*find_pin_queue_start_ends) (SgenGrayQueue *queue);
679         void (*pin_objects) (SgenGrayQueue *queue);
680         void (*pin_major_object) (char *obj, SgenGrayQueue *queue);
681         void (*scan_card_table) (gboolean mod_union, SgenGrayQueue *queue);
682         void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
683         void (*update_cardtable_mod_union) (void);
684         void (*init_to_space) (void);
685         void (*sweep) (void);
686         void (*check_scan_starts) (void);
687         void (*dump_heap) (FILE *heap_dump_file);
688         gint64 (*get_used_size) (void);
689         void (*start_nursery_collection) (void);
690         void (*finish_nursery_collection) (void);
691         void (*start_major_collection) (void);
692         void (*finish_major_collection) (void);
693         void (*have_computed_minor_collection_allowance) (void);
694         gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
695         gboolean (*obj_is_from_pinned_alloc) (char *obj);
696         void (*report_pinned_memory_usage) (void);
697         size_t (*get_num_major_sections) (void);
698         gboolean (*handle_gc_param) (const char *opt);
699         void (*print_gc_param_usage) (void);
700         gboolean (*is_worker_thread) (MonoNativeThreadId thread);
701         void (*post_param_init) (SgenMajorCollector *collector);
702         void* (*alloc_worker_data) (void);
703         void (*init_worker_thread) (void *data);
704         void (*reset_worker_data) (void *data);
705         gboolean (*is_valid_object) (char *object);
706         MonoVTable* (*describe_pointer) (char *pointer);
707         guint8* (*get_cardtable_mod_union_for_object) (char *object);
708         long long (*get_and_reset_num_major_objects_marked) (void);
709         void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
710 };
711
712 extern SgenMajorCollector major_collector;
713
714 void sgen_marksweep_init (SgenMajorCollector *collector) MONO_INTERNAL;
715 void sgen_marksweep_fixed_init (SgenMajorCollector *collector) MONO_INTERNAL;
716 void sgen_marksweep_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
717 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
718 void sgen_marksweep_conc_init (SgenMajorCollector *collector) MONO_INTERNAL;
719 SgenMajorCollector* sgen_get_major_collector (void) MONO_INTERNAL;
720
721
722 typedef struct _SgenRemeberedSet {
723         void (*wbarrier_set_field) (MonoObject *obj, gpointer field_ptr, MonoObject* value);
724         void (*wbarrier_set_arrayref) (MonoArray *arr, gpointer slot_ptr, MonoObject* value);
725         void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
726         void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, MonoClass *klass);
727         void (*wbarrier_object_copy) (MonoObject* obj, MonoObject *src);
728         void (*wbarrier_generic_nostore) (gpointer ptr);
729         void (*record_pointer) (gpointer ptr);
730
731         void (*finish_scan_remsets) (void *start_nursery, void *end_nursery, SgenGrayQueue *queue);
732
733         void (*prepare_for_major_collection) (void);
734
735         void (*finish_minor_collection) (void);
736         gboolean (*find_address) (char *addr);
737         gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
738 } SgenRemeberedSet;
739
740 SgenRemeberedSet *sgen_get_remset (void) MONO_INTERNAL;
741
742 static mword /*__attribute__((noinline)) not sure if this hint is a good idea*/
743 slow_object_get_size (MonoVTable *vtable, MonoObject* o)
744 {
745         MonoClass *klass = vtable->klass;
746
747         /*
748          * We depend on mono_string_length_fast and
749          * mono_array_length_fast not using the object's vtable.
750          */
751         if (klass == mono_defaults.string_class) {
752                 return offsetof (MonoString, chars) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
753         } else if (klass->rank) {
754                 MonoArray *array = (MonoArray*)o;
755                 size_t size = sizeof (MonoArray) + klass->sizes.element_size * mono_array_length_fast (array);
756                 if (G_UNLIKELY (array->bounds)) {
757                         size += sizeof (mono_array_size_t) - 1;
758                         size &= ~(sizeof (mono_array_size_t) - 1);
759                         size += sizeof (MonoArrayBounds) * klass->rank;
760                 }
761                 return size;
762         } else {
763                 /* from a created object: the class must be inited already */
764                 return klass->instance_size;
765         }
766 }
767
768 static inline mword
769 sgen_vtable_get_descriptor (MonoVTable *vtable)
770 {
771         return (mword)vtable->gc_descr;
772 }
773
774 static inline mword
775 sgen_obj_get_descriptor (char *obj)
776 {
777         MonoVTable *vtable = ((MonoObject*)obj)->vtable;
778         SGEN_ASSERT (0, !SGEN_POINTER_IS_TAGGED_1_OR_2 (vtable), "Object can't be tagged");
779         return sgen_vtable_get_descriptor (vtable);
780 }
781
782 static inline mword
783 sgen_obj_get_descriptor_safe (char *obj)
784 {
785         MonoVTable *vtable = (MonoVTable*)SGEN_LOAD_VTABLE (obj);
786         return sgen_vtable_get_descriptor (vtable);
787 }
788
789 /*
790  * This function can be called on an object whose first word, the
791  * vtable field, is not intact.  This is necessary for the parallel
792  * collector.
793  */
794 static inline mword
795 sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
796 {
797         mword descr = (mword)vtable->gc_descr;
798         mword type = descr & 0x7;
799
800         if (type == DESC_TYPE_RUN_LENGTH || type == DESC_TYPE_SMALL_BITMAP) {
801                 mword size = descr & 0xfff8;
802                 if (size == 0) /* This is used to encode a string */
803                         return offsetof (MonoString, chars) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
804                 return size;
805         } else if (type == DESC_TYPE_VECTOR) {
806                 int element_size = ((descr) >> VECTOR_ELSIZE_SHIFT) & MAX_ELEMENT_SIZE;
807                 MonoArray *array = (MonoArray*)o;
808                 size_t size = sizeof (MonoArray) + element_size * mono_array_length_fast (array);
809
810                 if (descr & VECTOR_KIND_ARRAY) {
811                         size += sizeof (mono_array_size_t) - 1;
812                         size &= ~(sizeof (mono_array_size_t) - 1);
813                         size += sizeof (MonoArrayBounds) * vtable->klass->rank;
814                 }
815                 return size;
816         }
817
818         return slow_object_get_size (vtable, o);
819 }
820
821 static inline mword
822 sgen_safe_object_get_size (MonoObject *obj)
823 {
824        char *forwarded;
825
826        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
827                obj = (MonoObject*)forwarded;
828
829        return sgen_par_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE (obj), obj);
830 }
831
832 /*
833  * This variant guarantees to return the exact size of the object
834  * before alignment. Needed for canary support.
835  */
836 static inline guint
837 sgen_safe_object_get_size_unaligned (MonoObject *obj)
838 {
839        char *forwarded;
840
841        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
842                obj = (MonoObject*)forwarded;
843        }
844
845        return slow_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE (obj), obj);
846 }
847
848 const char* sgen_safe_name (void* obj) MONO_INTERNAL;
849
850 gboolean sgen_object_is_live (void *obj) MONO_INTERNAL;
851
852 void  sgen_init_fin_weak_hash (void) MONO_INTERNAL;
853
854 gboolean sgen_need_bridge_processing (void) MONO_INTERNAL;
855 void sgen_bridge_reset_data (void) MONO_INTERNAL;
856 void sgen_bridge_processing_stw_step (void) MONO_INTERNAL;
857 void sgen_bridge_processing_finish (int generation) MONO_INTERNAL;
858 void sgen_register_test_bridge_callbacks (const char *bridge_class_name) MONO_INTERNAL;
859 gboolean sgen_is_bridge_object (MonoObject *obj) MONO_INTERNAL;
860 MonoGCBridgeObjectKind sgen_bridge_class_kind (MonoClass *klass) MONO_INTERNAL;
861 void sgen_mark_bridge_object (MonoObject *obj) MONO_INTERNAL;
862 void sgen_bridge_register_finalized_object (MonoObject *object) MONO_INTERNAL;
863 void sgen_bridge_describe_pointer (MonoObject *object) MONO_INTERNAL;
864
865 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx) MONO_INTERNAL;
866 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx) MONO_INTERNAL;
867
868 void sgen_process_togglerefs (void) MONO_INTERNAL;
869 void sgen_register_test_toggleref_callback (void) MONO_INTERNAL;
870
871 gboolean sgen_is_bridge_object (MonoObject *obj) MONO_INTERNAL;
872 void sgen_mark_bridge_object (MonoObject *obj) MONO_INTERNAL;
873
874 gboolean sgen_bridge_handle_gc_debug (const char *opt) MONO_INTERNAL;
875 void sgen_bridge_print_gc_debug_usage (void) MONO_INTERNAL;
876
877 typedef struct {
878         void (*reset_data) (void);
879         void (*processing_stw_step) (void);
880         void (*processing_build_callback_data) (int generation);
881         void (*processing_after_callback) (int generation);
882         MonoGCBridgeObjectKind (*class_kind) (MonoClass *class);
883         void (*register_finalized_object) (MonoObject *object);
884         void (*describe_pointer) (MonoObject *object);
885         void (*enable_accounting) (void);
886         void (*set_dump_prefix) (const char *prefix);
887
888         /*
889          * These are set by processing_build_callback_data().
890          */
891         int num_sccs;
892         MonoGCBridgeSCC **api_sccs;
893
894         int num_xrefs;
895         MonoGCBridgeXRef *api_xrefs;
896 } SgenBridgeProcessor;
897
898 void sgen_old_bridge_init (SgenBridgeProcessor *collector) MONO_INTERNAL;
899 void sgen_new_bridge_init (SgenBridgeProcessor *collector) MONO_INTERNAL;
900 void sgen_tarjan_bridge_init (SgenBridgeProcessor *collector) MONO_INTERNAL;
901 void sgen_set_bridge_implementation (const char *name) MONO_INTERNAL;
902 void sgen_bridge_set_dump_prefix (const char *prefix) MONO_INTERNAL;
903
904 gboolean sgen_compare_bridge_processor_results (SgenBridgeProcessor *a, SgenBridgeProcessor *b) MONO_INTERNAL;
905
906 typedef mono_bool (*WeakLinkAlivePredicateFunc) (MonoObject*, void*);
907
908 void sgen_null_links_with_predicate (int generation, WeakLinkAlivePredicateFunc predicate, void *data) MONO_INTERNAL;
909
910 gboolean sgen_gc_is_object_ready_for_finalization (void *object) MONO_INTERNAL;
911 void sgen_gc_lock (void) MONO_INTERNAL;
912 void sgen_gc_unlock (void) MONO_INTERNAL;
913 void sgen_gc_event_moves (void) MONO_INTERNAL;
914
915 void sgen_queue_finalization_entry (MonoObject *obj) MONO_INTERNAL;
916 const char* sgen_generation_name (int generation) MONO_INTERNAL;
917
918 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx) MONO_INTERNAL;
919 void sgen_finalize_in_range (int generation, ScanCopyContext ctx) MONO_INTERNAL;
920 void sgen_null_link_in_range (int generation, gboolean before_finalization, ScanCopyContext ctx) MONO_INTERNAL;
921 void sgen_null_links_for_domain (MonoDomain *domain, int generation) MONO_INTERNAL;
922 void sgen_remove_finalizers_for_domain (MonoDomain *domain, int generation) MONO_INTERNAL;
923 void sgen_process_fin_stage_entries (void) MONO_INTERNAL;
924 void sgen_process_dislink_stage_entries (void) MONO_INTERNAL;
925 void sgen_register_disappearing_link (MonoObject *obj, void **link, gboolean track, gboolean in_gc) MONO_INTERNAL;
926
927 gboolean sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx) MONO_INTERNAL;
928
929 enum {
930         SPACE_NURSERY,
931         SPACE_MAJOR,
932         SPACE_LOS
933 };
934
935 void sgen_pin_object (void *object, SgenGrayQueue *queue) MONO_INTERNAL;
936 void sgen_parallel_pin_or_update (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue) MONO_INTERNAL;
937 void sgen_set_pinned_from_failed_allocation (mword objsize) MONO_INTERNAL;
938
939 void sgen_ensure_free_space (size_t size) MONO_INTERNAL;
940 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish) MONO_INTERNAL;
941 gboolean sgen_has_critical_method (void) MONO_INTERNAL;
942 gboolean sgen_is_critical_method (MonoMethod *method) MONO_INTERNAL;
943
944 /* STW */
945
946 typedef struct {
947         int generation;
948         const char *reason;
949         gboolean is_overflow;
950         SGEN_TV_DECLARE (total_time);
951         SGEN_TV_DECLARE (stw_time);
952         SGEN_TV_DECLARE (bridge_time);
953 } GGTimingInfo;
954
955 int sgen_stop_world (int generation) MONO_INTERNAL;
956 int sgen_restart_world (int generation, GGTimingInfo *timing) MONO_INTERNAL;
957 void sgen_init_stw (void) MONO_INTERNAL;
958
959 /* LOS */
960
961 typedef struct _LOSObject LOSObject;
962 struct _LOSObject {
963         LOSObject *next;
964         mword size; /* this is the object size, lowest bit used for pin/mark */
965         guint8 *cardtable_mod_union; /* only used by the concurrent collector */
966 #if SIZEOF_VOID_P < 8
967         mword dummy;            /* to align object to sizeof (double) */
968 #endif
969         char data [MONO_ZERO_LEN_ARRAY];
970 };
971
972 extern LOSObject *los_object_list;
973 extern mword los_memory_usage;
974
975 void sgen_los_free_object (LOSObject *obj) MONO_INTERNAL;
976 void* sgen_los_alloc_large_inner (MonoVTable *vtable, size_t size) MONO_INTERNAL;
977 void sgen_los_sweep (void) MONO_INTERNAL;
978 gboolean sgen_ptr_is_in_los (char *ptr, char **start) MONO_INTERNAL;
979 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data) MONO_INTERNAL;
980 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
981 void sgen_los_scan_card_table (gboolean mod_union, SgenGrayQueue *queue) MONO_INTERNAL;
982 void sgen_los_update_cardtable_mod_union (void) MONO_INTERNAL;
983 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards) MONO_INTERNAL;
984 void sgen_major_collector_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
985 gboolean sgen_los_is_valid_object (char *object) MONO_INTERNAL;
986 gboolean mono_sgen_los_describe_pointer (char *ptr) MONO_INTERNAL;
987 LOSObject* sgen_los_header_for_object (char *data) MONO_INTERNAL;
988 mword sgen_los_object_size (LOSObject *obj) MONO_INTERNAL;
989 void sgen_los_pin_object (char *obj) MONO_INTERNAL;
990 void sgen_los_unpin_object (char *obj) MONO_INTERNAL;
991 gboolean sgen_los_object_is_pinned (char *obj) MONO_INTERNAL;
992
993
994 /* nursery allocator */
995
996 void sgen_clear_nursery_fragments (void) MONO_INTERNAL;
997 void sgen_nursery_allocator_prepare_for_pinning (void) MONO_INTERNAL;
998 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end) MONO_INTERNAL;
999 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue) MONO_INTERNAL;
1000 void sgen_init_nursery_allocator (void) MONO_INTERNAL;
1001 void sgen_nursery_allocator_init_heavy_stats (void) MONO_INTERNAL;
1002 void sgen_alloc_init_heavy_stats (void) MONO_INTERNAL;
1003 char* sgen_nursery_alloc_get_upper_alloc_bound (void) MONO_INTERNAL;
1004 void* sgen_nursery_alloc (size_t size) MONO_INTERNAL;
1005 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size) MONO_INTERNAL;
1006 MonoVTable* sgen_get_array_fill_vtable (void) MONO_INTERNAL;
1007 gboolean sgen_can_alloc_size (size_t size) MONO_INTERNAL;
1008 void sgen_nursery_retire_region (void *address, ptrdiff_t size) MONO_INTERNAL;
1009
1010 void sgen_nursery_alloc_prepare_for_minor (void) MONO_INTERNAL;
1011 void sgen_nursery_alloc_prepare_for_major (void) MONO_INTERNAL;
1012
1013 char* sgen_alloc_for_promotion (char *obj, size_t objsize, gboolean has_references) MONO_INTERNAL;
1014
1015 /* TLS Data */
1016
1017 extern MonoNativeTlsKey thread_info_key;
1018
1019 #ifdef HAVE_KW_THREAD
1020 extern __thread SgenThreadInfo *sgen_thread_info;
1021 extern __thread char *stack_end;
1022 #endif
1023
1024 #ifdef HAVE_KW_THREAD
1025 #define TLAB_ACCESS_INIT
1026 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
1027 #else
1028 #define TLAB_ACCESS_INIT        SgenThreadInfo *__thread_info__ = mono_native_tls_get_value (thread_info_key)
1029 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
1030 #endif
1031
1032 #ifndef DISABLE_CRITICAL_REGION
1033
1034 #ifdef HAVE_KW_THREAD
1035 #define IN_CRITICAL_REGION sgen_thread_info->in_critical_region
1036 #else
1037 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
1038 #endif
1039
1040 /* Enter must be visible before anything is done in the critical region. */
1041 #define ENTER_CRITICAL_REGION do { mono_atomic_store_acquire (&IN_CRITICAL_REGION, 1); } while (0)
1042
1043 /* Exit must make sure all critical regions stores are visible before it signal the end of the region. 
1044  * We don't need to emit a full barrier since we
1045  */
1046 #define EXIT_CRITICAL_REGION  do { mono_atomic_store_release (&IN_CRITICAL_REGION, 0); } while (0)
1047
1048 #endif
1049
1050 #ifdef HAVE_KW_THREAD
1051
1052 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do {    \
1053         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1054         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1055         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_TLAB_NEXT_ADDR);            \
1056         } while (0)
1057
1058 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do {    \
1059         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1060         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1061         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_TLAB_TEMP_END);             \
1062         } while (0)
1063
1064 #else
1065
1066 #if defined(__APPLE__) || defined (HOST_WIN32)
1067 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do {    \
1068         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1069         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1070         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_THREAD_INFO);       \
1071         mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_next_addr));  \
1072         mono_mb_emit_byte ((mb), CEE_ADD);              \
1073         mono_mb_emit_byte ((mb), CEE_LDIND_I);          \
1074         } while (0)
1075
1076 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do {    \
1077         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
1078         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
1079         mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_THREAD_INFO);       \
1080         mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_temp_end));   \
1081         mono_mb_emit_byte ((mb), CEE_ADD);              \
1082         mono_mb_emit_byte ((mb), CEE_LDIND_I);          \
1083         } while (0)
1084
1085 #else
1086 #define EMIT_TLS_ACCESS_NEXT_ADDR(mb)   do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
1087 #define EMIT_TLS_ACCESS_TEMP_END(mb)    do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
1088 #endif
1089
1090 #endif
1091
1092 /* Other globals */
1093
1094 extern GCMemSection *nursery_section;
1095 extern guint32 collect_before_allocs;
1096 extern guint32 verify_before_allocs;
1097 extern gboolean has_per_allocation_action;
1098 extern size_t degraded_mode;
1099 extern int default_nursery_size;
1100 extern guint32 tlab_size;
1101 extern NurseryClearPolicy nursery_clear_policy;
1102 extern gboolean sgen_try_free_some_memory;
1103
1104 extern LOCK_DECLARE (gc_mutex);
1105
1106 extern int do_pin_stats;
1107
1108 /* Nursery helpers. */
1109
1110 static inline void
1111 sgen_set_nursery_scan_start (char *p)
1112 {
1113         size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
1114         char *old = nursery_section->scan_starts [idx];
1115         if (!old || old > p)
1116                 nursery_section->scan_starts [idx] = p;
1117 }
1118
1119
1120 /* Object Allocation */
1121
1122 typedef enum {
1123         ATYPE_NORMAL,
1124         ATYPE_VECTOR,
1125         ATYPE_SMALL,
1126         ATYPE_STRING,
1127         ATYPE_NUM
1128 } SgenAllocatorType;
1129
1130 void sgen_init_tlab_info (SgenThreadInfo* info);
1131 void sgen_clear_tlabs (void);
1132 void sgen_set_use_managed_allocator (gboolean flag);
1133 gboolean sgen_is_managed_allocator (MonoMethod *method);
1134 gboolean sgen_has_managed_allocator (void);
1135
1136 /* Debug support */
1137
1138 void sgen_check_consistency (void);
1139 void sgen_check_mod_union_consistency (void);
1140 void sgen_check_major_refs (void);
1141 void sgen_check_whole_heap (gboolean allow_missing_pinning);
1142 void sgen_check_whole_heap_stw (void) MONO_INTERNAL;
1143 void sgen_check_objref (char *obj);
1144 void sgen_check_heap_marked (gboolean nursery_must_be_pinned) MONO_INTERNAL;
1145 void sgen_check_nursery_objects_pinned (gboolean pinned) MONO_INTERNAL;
1146 void sgen_scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type) MONO_INTERNAL;
1147 void sgen_check_for_xdomain_refs (void) MONO_INTERNAL;
1148
1149 void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise) MONO_INTERNAL;
1150
1151 /* Write barrier support */
1152
1153 /*
1154  * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1155  */
1156 static inline void
1157 sgen_dummy_use (gpointer v) {
1158 #if defined(__GNUC__)
1159         __asm__ volatile ("" : "=r"(v) : "r"(v));
1160 #elif defined(_MSC_VER)
1161         static volatile gpointer ptr;
1162         ptr = v;
1163 #else
1164 #error "Implement sgen_dummy_use for your compiler"
1165 #endif
1166 }
1167
1168 /* Environment variable parsing */
1169
1170 #define MONO_GC_PARAMS_NAME     "MONO_GC_PARAMS"
1171 #define MONO_GC_DEBUG_NAME      "MONO_GC_DEBUG"
1172
1173 gboolean sgen_parse_environment_string_extract_number (const char *str, size_t *out) MONO_INTERNAL;
1174 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...) MONO_INTERNAL;
1175
1176 /* Utilities */
1177
1178 void sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*)) MONO_INTERNAL;
1179 gint64 sgen_timestamp (void) MONO_INTERNAL;
1180
1181 /*
1182  * Canary (guard word) support
1183  * Notes:
1184  * - CANARY_SIZE must be multiple of word size in bytes
1185  * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1186  */
1187  
1188 gboolean nursery_canaries_enabled (void) MONO_INTERNAL;
1189
1190 #define CANARY_SIZE 8
1191 #define CANARY_STRING  "koupepia"
1192
1193 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) {  \
1194                         size = size + CANARY_SIZE;      \
1195                 }
1196
1197 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) {    \
1198                                 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE);   \
1199                         }
1200
1201 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1202
1203 #define CHECK_CANARY_FOR_OBJECT(addr) if (nursery_canaries_enabled ()) {        \
1204                                 char* canary_ptr = (char*) (addr) + sgen_safe_object_get_size_unaligned ((MonoObject *) (addr));        \
1205                                 if (!CANARY_VALID(canary_ptr)) {        \
1206                                         char canary_copy[CANARY_SIZE +1];       \
1207                                         strncpy (canary_copy, canary_ptr, 8);   \
1208                                         canary_copy[CANARY_SIZE] = 0;   \
1209                                         g_error ("CORRUPT CANARY:\naddr->%p\ntype->%s\nexcepted->'%s'\nfound->'%s'\n", (char*) addr, ((MonoObject*)addr)->vtable->klass->name, CANARY_STRING, canary_copy);     \
1210                                 } }
1211                                  
1212 #endif /* HAVE_SGEN_GC */
1213
1214 #endif /* __MONO_SGENGC_H__ */