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