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