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