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