[sgen] Typedef for GC descriptors.
[mono.git] / mono / sgen / 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 #include <stdio.h>
36 #ifdef HAVE_PTHREAD_H
37 #include <pthread.h>
38 #endif
39 #include <stdint.h>
40 #include "mono/utils/mono-compiler.h"
41 #include "mono/utils/atomic.h"
42 #include "mono/utils/mono-mutex.h"
43 #include "mono/sgen/sgen-conf.h"
44 #include "mono/sgen/sgen-hash-table.h"
45 #include "mono/sgen/sgen-protocol.h"
46
47 /* The method used to clear the nursery */
48 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
49  * Clearing at TLAB creation is much faster, but more complex and it might expose hard
50  * to find bugs.
51  */
52 typedef enum {
53         CLEAR_AT_GC,
54         CLEAR_AT_TLAB_CREATION,
55         CLEAR_AT_TLAB_CREATION_DEBUG
56 } NurseryClearPolicy;
57
58 NurseryClearPolicy sgen_get_nursery_clear_policy (void);
59
60 #if !defined(__MACH__) && !MONO_MACH_ARCH_SUPPORTED && defined(HAVE_PTHREAD_KILL)
61 #define SGEN_POSIX_STW 1
62 #endif
63
64 /*
65  * The nursery section uses this struct.
66  */
67 typedef struct _GCMemSection GCMemSection;
68 struct _GCMemSection {
69         char *data;
70         mword size;
71         /* pointer where more data could be allocated if it fits */
72         char *next_data;
73         char *end_data;
74         /*
75          * scan starts is an array of pointers to objects equally spaced in the allocation area
76          * They let use quickly find pinned objects from pinning pointers.
77          */
78         char **scan_starts;
79         /* in major collections indexes in the pin_queue for objects that pin this section */
80         size_t pin_queue_first_entry;
81         size_t pin_queue_last_entry;
82         size_t num_scan_start;
83 };
84
85 /*
86  * Recursion is not allowed for the thread lock.
87  */
88 #define LOCK_DECLARE(name) mono_mutex_t name
89 /* if changing LOCK_INIT to something that isn't idempotent, look at
90    its use in mono_gc_base_init in sgen-gc.c */
91 #define LOCK_INIT(name) mono_mutex_init (&(name))
92 #define LOCK_GC do {                                            \
93                 MONO_TRY_BLOCKING       \
94                 mono_mutex_lock (&gc_mutex);                    \
95                 MONO_FINISH_TRY_BLOCKING        \
96         } while (0)
97 #define UNLOCK_GC do { sgen_gc_unlock (); } while (0)
98
99 extern LOCK_DECLARE (sgen_interruption_mutex);
100
101 #define LOCK_INTERRUPTION mono_mutex_lock (&sgen_interruption_mutex)
102 #define UNLOCK_INTERRUPTION mono_mutex_unlock (&sgen_interruption_mutex)
103
104 /* FIXME: Use InterlockedAdd & InterlockedAdd64 to reduce the CAS cost. */
105 #define SGEN_CAS        InterlockedCompareExchange
106 #define SGEN_CAS_PTR    InterlockedCompareExchangePointer
107 #define SGEN_ATOMIC_ADD(x,i)    do {                                    \
108                 int __old_x;                                            \
109                 do {                                                    \
110                         __old_x = (x);                                  \
111                 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
112         } while (0)
113 #define SGEN_ATOMIC_ADD_P(x,i) do { \
114                 size_t __old_x;                                            \
115                 do {                                                    \
116                         __old_x = (x);                                  \
117                 } while (InterlockedCompareExchangePointer ((void**)&(x), (void*)(__old_x + (i)), (void*)__old_x) != (void*)__old_x); \
118         } while (0)
119
120 #ifdef HEAVY_STATISTICS
121 extern guint64 stat_objects_alloced_degraded;
122 extern guint64 stat_bytes_alloced_degraded;
123 extern guint64 stat_copy_object_called_major;
124 extern guint64 stat_objects_copied_major;
125 #endif
126
127 #define SGEN_ASSERT(level, a, ...) do { \
128         if (G_UNLIKELY ((level) <= SGEN_MAX_ASSERT_LEVEL && !(a))) {    \
129                 g_error (__VA_ARGS__);  \
130 } } while (0)
131
132
133 #define SGEN_LOG(level, format, ...) do {      \
134         if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {        \
135                 mono_gc_printf (gc_debug_file, format "\n", ##__VA_ARGS__);     \
136 } } while (0)
137
138 #define SGEN_COND_LOG(level, cond, format, ...) do {    \
139         if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) {        \
140                 if (cond)       \
141                         mono_gc_printf (gc_debug_file, format "\n", ##__VA_ARGS__);     \
142 } } while (0)
143
144 extern int gc_debug_level;
145 extern FILE* gc_debug_file;
146
147 extern int current_collection_generation;
148
149 extern unsigned int sgen_global_stop_count;
150
151 #define SGEN_ALLOC_ALIGN                8
152 #define SGEN_ALLOC_ALIGN_BITS   3
153
154 /* s must be non-negative */
155 #define SGEN_CAN_ALIGN_UP(s)            ((s) <= SIZE_MAX - (SGEN_ALLOC_ALIGN - 1))
156 #define SGEN_ALIGN_UP(s)                (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
157
158 #if SIZEOF_VOID_P == 4
159 #define ONE_P 1
160 #else
161 #define ONE_P 1ll
162 #endif
163
164 static inline guint
165 sgen_aligned_addr_hash (gconstpointer ptr)
166 {
167         return GPOINTER_TO_UINT (ptr) >> 3;
168 }
169
170 /*
171  * The link pointer is hidden by negating each bit.  We use the lowest
172  * bit of the link (before negation) to store whether it needs
173  * resurrection tracking.
174  */
175 #define HIDE_POINTER(p,t)       ((gpointer)(~((size_t)(p)|((t)?1:0))))
176 #define REVEAL_POINTER(p)       ((gpointer)((~(size_t)(p))&~3L))
177
178 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
179
180 #ifdef USER_CONFIG
181
182 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
183 #define DEFAULT_NURSERY_SIZE (sgen_nursery_size)
184 extern size_t sgen_nursery_size;
185 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
186 #define DEFAULT_NURSERY_BITS (sgen_nursery_bits)
187 extern int sgen_nursery_bits;
188
189 #else
190
191 #define DEFAULT_NURSERY_SIZE (4*1024*1024)
192 #define DEFAULT_NURSERY_BITS 22
193
194 #endif
195
196 extern char *sgen_nursery_start;
197 extern char *sgen_nursery_end;
198
199 static inline MONO_ALWAYS_INLINE gboolean
200 sgen_ptr_in_nursery (void *p)
201 {
202         return SGEN_PTR_IN_NURSERY ((p), DEFAULT_NURSERY_BITS, sgen_nursery_start, sgen_nursery_end);
203 }
204
205 static inline MONO_ALWAYS_INLINE char*
206 sgen_get_nursery_start (void)
207 {
208         return sgen_nursery_start;
209 }
210
211 static inline MONO_ALWAYS_INLINE char*
212 sgen_get_nursery_end (void)
213 {
214         return sgen_nursery_end;
215 }
216
217 /*
218  * We use the lowest three bits in the vtable pointer of objects to tag whether they're
219  * forwarded, pinned, and/or cemented.  These are the valid states:
220  *
221  * | State            | bits |
222  * |------------------+------+
223  * | default          |  000 |
224  * | forwarded        |  001 |
225  * | pinned           |  010 |
226  * | pinned, cemented |  110 |
227  *
228  * We store them in the vtable slot because the bits are used in the sync block for other
229  * purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
230  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
231  * would be an invalid combination for the monitor and hash code).
232  */
233
234 #include "sgen-tagged-pointer.h"
235
236 #define SGEN_VTABLE_BITS_MASK   SGEN_TAGGED_POINTER_MASK
237
238 #define SGEN_POINTER_IS_TAGGED_FORWARDED(p)     SGEN_POINTER_IS_TAGGED_1((p))
239 #define SGEN_POINTER_TAG_FORWARDED(p)           SGEN_POINTER_TAG_1((p))
240
241 #define SGEN_POINTER_IS_TAGGED_PINNED(p)        SGEN_POINTER_IS_TAGGED_2((p))
242 #define SGEN_POINTER_TAG_PINNED(p)              SGEN_POINTER_TAG_2((p))
243
244 #define SGEN_POINTER_IS_TAGGED_CEMENTED(p)      SGEN_POINTER_IS_TAGGED_4((p))
245 #define SGEN_POINTER_TAG_CEMENTED(p)            SGEN_POINTER_TAG_4((p))
246
247 #define SGEN_POINTER_UNTAG_VTABLE(p)            SGEN_POINTER_UNTAG_ALL((p))
248
249 /* returns NULL if not forwarded, or the forwarded address */
250 #define SGEN_VTABLE_IS_FORWARDED(vtable) (SGEN_POINTER_IS_TAGGED_FORWARDED ((vtable)) ? SGEN_POINTER_UNTAG_VTABLE ((vtable)) : NULL)
251 #define SGEN_OBJECT_IS_FORWARDED(obj) (SGEN_VTABLE_IS_FORWARDED (((mword*)(obj))[0]))
252
253 #define SGEN_VTABLE_IS_PINNED(vtable) SGEN_POINTER_IS_TAGGED_PINNED ((vtable))
254 #define SGEN_OBJECT_IS_PINNED(obj) (SGEN_VTABLE_IS_PINNED (((mword*)(obj))[0]))
255
256 #define SGEN_OBJECT_IS_CEMENTED(obj) (SGEN_POINTER_IS_TAGGED_CEMENTED (((mword*)(obj))[0]))
257
258 /* set the forwarded address fw_addr for object obj */
259 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {                           \
260                 *(void**)(obj) = SGEN_POINTER_TAG_FORWARDED ((fw_addr));        \
261         } while (0)
262 #define SGEN_PIN_OBJECT(obj) do {       \
263                 *(void**)(obj) = SGEN_POINTER_TAG_PINNED (*(void**)(obj)); \
264         } while (0)
265 #define SGEN_CEMENT_OBJECT(obj) do {    \
266                 *(void**)(obj) = SGEN_POINTER_TAG_CEMENTED (*(void**)(obj)); \
267         } while (0)
268 /* Unpins and uncements */
269 #define SGEN_UNPIN_OBJECT(obj) do {     \
270                 *(void**)(obj) = SGEN_POINTER_UNTAG_VTABLE (*(void**)(obj)); \
271         } while (0)
272
273 /*
274  * Since we set bits in the vtable, use the macro to load it from the pointer to
275  * an object that is potentially pinned.
276  */
277 #define SGEN_LOAD_VTABLE(obj)           ((GCVTable)(SGEN_POINTER_UNTAG_ALL (SGEN_LOAD_VTABLE_UNCHECKED ((obj)))))
278
279 /*
280 List of what each bit on of the vtable gc bits means. 
281 */
282 enum {
283         SGEN_GC_BIT_BRIDGE_OBJECT = 1,
284         SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT = 2,
285         SGEN_GC_BIT_FINALIZER_AWARE = 4,
286 };
287
288 typedef mword SgenDescriptor;
289
290 void sgen_gc_init (void);
291
292 void sgen_os_init (void);
293
294 void sgen_update_heap_boundaries (mword low, mword high);
295
296 void sgen_check_section_scan_starts (GCMemSection *section);
297
298 void sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type);
299
300 /* Keep in sync with description_for_type() in sgen-internal.c! */
301 enum {
302         INTERNAL_MEM_PIN_QUEUE,
303         INTERNAL_MEM_FRAGMENT,
304         INTERNAL_MEM_SECTION,
305         INTERNAL_MEM_SCAN_STARTS,
306         INTERNAL_MEM_FIN_TABLE,
307         INTERNAL_MEM_FINALIZE_ENTRY,
308         INTERNAL_MEM_FINALIZE_READY,
309         INTERNAL_MEM_DISLINK_TABLE,
310         INTERNAL_MEM_DISLINK,
311         INTERNAL_MEM_ROOTS_TABLE,
312         INTERNAL_MEM_ROOT_RECORD,
313         INTERNAL_MEM_STATISTICS,
314         INTERNAL_MEM_STAT_PINNED_CLASS,
315         INTERNAL_MEM_STAT_REMSET_CLASS,
316         INTERNAL_MEM_GRAY_QUEUE,
317         INTERNAL_MEM_MS_TABLES,
318         INTERNAL_MEM_MS_BLOCK_INFO,
319         INTERNAL_MEM_MS_BLOCK_INFO_SORT,
320         INTERNAL_MEM_WORKER_DATA,
321         INTERNAL_MEM_THREAD_POOL_JOB,
322         INTERNAL_MEM_BRIDGE_DATA,
323         INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE,
324         INTERNAL_MEM_OLD_BRIDGE_HASH_TABLE_ENTRY,
325         INTERNAL_MEM_BRIDGE_HASH_TABLE,
326         INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY,
327         INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE,
328         INTERNAL_MEM_BRIDGE_ALIVE_HASH_TABLE_ENTRY,
329         INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE,
330         INTERNAL_MEM_TARJAN_BRIDGE_HASH_TABLE_ENTRY,
331         INTERNAL_MEM_TARJAN_OBJ_BUCKET,
332         INTERNAL_MEM_BRIDGE_DEBUG,
333         INTERNAL_MEM_TOGGLEREF_DATA,
334         INTERNAL_MEM_CARDTABLE_MOD_UNION,
335         INTERNAL_MEM_BINARY_PROTOCOL,
336         INTERNAL_MEM_TEMPORARY,
337         INTERNAL_MEM_FIRST_CLIENT
338 };
339
340 enum {
341         GENERATION_NURSERY,
342         GENERATION_OLD,
343         GENERATION_MAX
344 };
345
346 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
347 #define BINARY_PROTOCOL_ARG(x)  ,x
348 #else
349 #define BINARY_PROTOCOL_ARG(x)
350 #endif
351
352 void sgen_init_internal_allocator (void);
353
354 #define SGEN_DEFINE_OBJECT_VTABLE
355 #ifdef SGEN_CLIENT_HEADER
356 #include SGEN_CLIENT_HEADER
357 #else
358 #include "metadata/sgen-client-mono.h"
359 #endif
360 #undef SGEN_DEFINE_OBJECT_VTABLE
361
362 #include "mono/sgen/sgen-descriptor.h"
363 #include "mono/sgen/sgen-gray.h"
364
365 /* the runtime can register areas of memory as roots: we keep two lists of roots,
366  * a pinned root set for conservatively scanned roots and a normal one for
367  * precisely scanned roots (currently implemented as a single list).
368  */
369 typedef struct _RootRecord RootRecord;
370 struct _RootRecord {
371         char *end_root;
372         SgenDescriptor root_desc;
373 };
374
375 enum {
376         ROOT_TYPE_NORMAL = 0, /* "normal" roots */
377         ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
378         ROOT_TYPE_WBARRIER = 2, /* roots with a write barrier */
379         ROOT_TYPE_NUM
380 };
381
382 extern SgenHashTable roots_hash [ROOT_TYPE_NUM];
383
384 int sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type);
385 void sgen_deregister_root (char* addr);
386
387 typedef void (*IterateObjectCallbackFunc) (GCObject*, size_t, void*);
388
389 void sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags);
390
391 /* eventually share with MonoThread? */
392 /*
393  * This structure extends the MonoThreadInfo structure.
394  */
395 struct _SgenThreadInfo {
396         SgenClientThreadInfo client_info;
397
398         char **tlab_next_addr;
399         char **tlab_start_addr;
400         char **tlab_temp_end_addr;
401         char **tlab_real_end_addr;
402
403 #ifndef HAVE_KW_THREAD
404         char *tlab_start;
405         char *tlab_next;
406         char *tlab_temp_end;
407         char *tlab_real_end;
408 #endif
409 };
410
411 gboolean sgen_is_worker_thread (MonoNativeThreadId thread);
412
413 typedef void (*CopyOrMarkObjectFunc) (GCObject**, SgenGrayQueue*);
414 typedef void (*ScanObjectFunc) (GCObject *obj, SgenDescriptor desc, SgenGrayQueue*);
415 typedef void (*ScanVTypeFunc) (GCObject *full_object, char *start, SgenDescriptor desc, SgenGrayQueue* BINARY_PROTOCOL_ARG (size_t size));
416
417 typedef struct {
418         CopyOrMarkObjectFunc copy_or_mark_object;
419         ScanObjectFunc scan_object;
420         ScanVTypeFunc scan_vtype;
421         /*FIXME add allocation function? */
422 } SgenObjectOperations;
423
424 typedef struct
425 {
426         SgenObjectOperations *ops;
427         SgenGrayQueue *queue;
428 } ScanCopyContext;
429
430 #define CONTEXT_FROM_OBJECT_OPERATIONS(ops, queue) ((ScanCopyContext) { (ops), (queue) })
431
432 void sgen_report_internal_mem_usage (void);
433 void sgen_dump_internal_mem_usage (FILE *heap_dump_file);
434 void sgen_dump_section (GCMemSection *section, const char *type);
435 void sgen_dump_occupied (char *start, char *end, char *section_start);
436
437 void sgen_register_fixed_internal_mem_type (int type, size_t size);
438
439 void* sgen_alloc_internal (int type);
440 void sgen_free_internal (void *addr, int type);
441
442 void* sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure);
443 void sgen_free_internal_dynamic (void *addr, size_t size, int type);
444
445 void sgen_pin_stats_enable (void);
446 void sgen_pin_stats_register_object (GCObject *obj, size_t size);
447 void sgen_pin_stats_register_global_remset (GCObject *obj);
448 void sgen_pin_stats_print_class_stats (void);
449
450 void sgen_sort_addresses (void **array, size_t size);
451 void sgen_add_to_global_remset (gpointer ptr, gpointer obj);
452
453 int sgen_get_current_collection_generation (void);
454 gboolean sgen_collection_is_concurrent (void);
455 gboolean sgen_concurrent_collection_in_progress (void);
456
457 typedef struct _SgenFragment SgenFragment;
458
459 struct _SgenFragment {
460         SgenFragment *next;
461         char *fragment_start;
462         char *fragment_next; /* the current soft limit for allocation */
463         char *fragment_end;
464         SgenFragment *next_in_order; /* We use a different entry for all active fragments so we can avoid SMR. */
465 };
466
467 typedef struct {
468         SgenFragment *alloc_head; /* List head to be used when allocating memory. Walk with fragment_next. */
469         SgenFragment *region_head; /* List head of the region used by this allocator. Walk with next_in_order. */
470 } SgenFragmentAllocator;
471
472 void sgen_fragment_allocator_add (SgenFragmentAllocator *allocator, char *start, char *end);
473 void sgen_fragment_allocator_release (SgenFragmentAllocator *allocator);
474 void* sgen_fragment_allocator_serial_alloc (SgenFragmentAllocator *allocator, size_t size);
475 void* sgen_fragment_allocator_par_alloc (SgenFragmentAllocator *allocator, size_t size);
476 void* sgen_fragment_allocator_serial_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
477 void* sgen_fragment_allocator_par_range_alloc (SgenFragmentAllocator *allocator, size_t desired_size, size_t minimum_size, size_t *out_alloc_size);
478 SgenFragment* sgen_fragment_allocator_alloc (void);
479 void sgen_clear_allocator_fragments (SgenFragmentAllocator *allocator);
480 void sgen_clear_range (char *start, char *end);
481
482
483 /*
484 This is a space/speed compromise as we need to make sure the from/to space check is both O(1)
485 and only hit cache hot memory. On a 4Mb nursery it requires 1024 bytes, or 3% of your average
486 L1 cache. On small configs with a 512kb nursery, this goes to 0.4%.
487
488 Experimental results on how much space we waste with a 4Mb nursery:
489
490 Note that the wastage applies to the half nursery, or 2Mb:
491
492 Test 1 (compiling corlib):
493 9: avg: 3.1k
494 8: avg: 1.6k
495
496 */
497 #define SGEN_TO_SPACE_GRANULE_BITS 9
498 #define SGEN_TO_SPACE_GRANULE_IN_BYTES (1 << SGEN_TO_SPACE_GRANULE_BITS)
499
500 extern char *sgen_space_bitmap;
501 extern size_t sgen_space_bitmap_size;
502
503 static inline gboolean
504 sgen_nursery_is_to_space (void *object)
505 {
506         size_t idx = ((char*)object - sgen_nursery_start) >> SGEN_TO_SPACE_GRANULE_BITS;
507         size_t byte = idx >> 3;
508         size_t bit = idx & 0x7;
509
510         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 ());
511         SGEN_ASSERT (4, byte < sgen_space_bitmap_size, "byte index %zd out of range (%zd)", byte, sgen_space_bitmap_size);
512
513         return (sgen_space_bitmap [byte] & (1 << bit)) != 0;
514 }
515
516 static inline gboolean
517 sgen_nursery_is_from_space (void *object)
518 {
519         return !sgen_nursery_is_to_space (object);
520 }
521
522 static inline gboolean
523 sgen_nursery_is_object_alive (GCObject *obj)
524 {
525         /* FIXME put this asserts under a non default level */
526         g_assert (sgen_ptr_in_nursery (obj));
527
528         if (sgen_nursery_is_to_space (obj))
529                 return TRUE;
530
531         if (SGEN_OBJECT_IS_PINNED (obj) || SGEN_OBJECT_IS_FORWARDED (obj))
532                 return TRUE;
533
534         return FALSE;
535 }
536
537 typedef struct {
538         gboolean is_split;
539
540         char* (*alloc_for_promotion) (GCVTable vtable, GCObject *obj, size_t objsize, gboolean has_references);
541
542         SgenObjectOperations serial_ops;
543
544         void (*prepare_to_space) (char *to_space_bitmap, size_t space_bitmap_size);
545         void (*clear_fragments) (void);
546         SgenFragment* (*build_fragments_get_exclude_head) (void);
547         void (*build_fragments_release_exclude_head) (void);
548         void (*build_fragments_finish) (SgenFragmentAllocator *allocator);
549         void (*init_nursery) (SgenFragmentAllocator *allocator, char *start, char *end);
550
551         gboolean (*handle_gc_param) (const char *opt); /* Optional */
552         void (*print_gc_param_usage) (void); /* Optional */
553 } SgenMinorCollector;
554
555 extern SgenMinorCollector sgen_minor_collector;
556
557 void sgen_simple_nursery_init (SgenMinorCollector *collector);
558 void sgen_split_nursery_init (SgenMinorCollector *collector);
559
560 /* Updating references */
561
562 #ifdef SGEN_CHECK_UPDATE_REFERENCE
563 gboolean sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread) MONO_INTERNAL;
564 static inline void
565 sgen_update_reference (void **p, void *o, gboolean allow_null)
566 {
567         if (!allow_null)
568                 SGEN_ASSERT (0, o, "Cannot update a reference with a NULL pointer");
569         SGEN_ASSERT (0, !sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Can't update a reference in the worker thread");
570         *p = o;
571 }
572
573 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   sgen_update_reference ((void**)(p), (void*)(o), TRUE)
574 #define SGEN_UPDATE_REFERENCE(p,o)              sgen_update_reference ((void**)(p), (void*)(o), FALSE)
575 #else
576 #define SGEN_UPDATE_REFERENCE_ALLOW_NULL(p,o)   (*(void**)(p) = (void*)(o))
577 #define SGEN_UPDATE_REFERENCE(p,o)              SGEN_UPDATE_REFERENCE_ALLOW_NULL ((p), (o))
578 #endif
579
580 /* Major collector */
581
582 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
583 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
584
585 typedef enum {
586         ITERATE_OBJECTS_SWEEP = 1,
587         ITERATE_OBJECTS_NON_PINNED = 2,
588         ITERATE_OBJECTS_PINNED = 4,
589         ITERATE_OBJECTS_ALL = ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED,
590         ITERATE_OBJECTS_SWEEP_NON_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED,
591         ITERATE_OBJECTS_SWEEP_PINNED = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_PINNED,
592         ITERATE_OBJECTS_SWEEP_ALL = ITERATE_OBJECTS_SWEEP | ITERATE_OBJECTS_NON_PINNED | ITERATE_OBJECTS_PINNED
593 } IterateObjectsFlags;
594
595 typedef struct
596 {
597         size_t num_scanned_objects;
598         size_t num_unique_scanned_objects;
599 } ScannedObjectCounts;
600
601 typedef struct _SgenMajorCollector SgenMajorCollector;
602 struct _SgenMajorCollector {
603         size_t section_size;
604         gboolean is_concurrent;
605         gboolean needs_thread_pool;
606         gboolean supports_cardtable;
607         gboolean sweeps_lazily;
608
609         /*
610          * This is set to TRUE by the sweep if the next major
611          * collection should be synchronous (for evacuation).  For
612          * non-concurrent collectors, this should be NULL.
613          */
614         gboolean *want_synchronous_collection;
615
616         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
617         gboolean (*is_object_live) (GCObject *obj);
618         void* (*alloc_small_pinned_obj) (GCVTable vtable, size_t size, gboolean has_references);
619         void* (*alloc_degraded) (GCVTable vtable, size_t size);
620
621         SgenObjectOperations major_ops_serial;
622         SgenObjectOperations major_ops_concurrent_start;
623         SgenObjectOperations major_ops_concurrent;
624         SgenObjectOperations major_ops_concurrent_finish;
625
626         void* (*alloc_object) (GCVTable vtable, size_t size, gboolean has_references);
627         void (*free_pinned_object) (GCObject *obj, size_t size);
628
629         /*
630          * This is used for domain unloading, heap walking from the logging profiler, and
631          * debugging.  Can assume the world is stopped.
632          */
633         void (*iterate_objects) (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data);
634
635         void (*free_non_pinned_object) (GCObject *obj, size_t size);
636         void (*pin_objects) (SgenGrayQueue *queue);
637         void (*pin_major_object) (GCObject *obj, SgenGrayQueue *queue);
638         void (*scan_card_table) (gboolean mod_union, ScanCopyContext ctx);
639         void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
640         void (*update_cardtable_mod_union) (void);
641         void (*init_to_space) (void);
642         void (*sweep) (void);
643         gboolean (*have_swept) (void);
644         void (*finish_sweeping) (void);
645         void (*free_swept_blocks) (size_t allowance);
646         void (*check_scan_starts) (void);
647         void (*dump_heap) (FILE *heap_dump_file);
648         gint64 (*get_used_size) (void);
649         void (*start_nursery_collection) (void);
650         void (*finish_nursery_collection) (void);
651         void (*start_major_collection) (void);
652         void (*finish_major_collection) (ScannedObjectCounts *counts);
653         gboolean (*drain_gray_stack) (ScanCopyContext ctx);
654         gboolean (*ptr_is_in_non_pinned_space) (char *ptr, char **start);
655         gboolean (*ptr_is_from_pinned_alloc) (char *ptr);
656         void (*report_pinned_memory_usage) (void);
657         size_t (*get_num_major_sections) (void);
658         size_t (*get_bytes_survived_last_sweep) (void);
659         gboolean (*handle_gc_param) (const char *opt);
660         void (*print_gc_param_usage) (void);
661         void (*post_param_init) (SgenMajorCollector *collector);
662         gboolean (*is_valid_object) (char *ptr);
663         GCVTable (*describe_pointer) (char *pointer);
664         guint8* (*get_cardtable_mod_union_for_reference) (char *object);
665         long long (*get_and_reset_num_major_objects_marked) (void);
666         void (*count_cards) (long long *num_total_cards, long long *num_marked_cards);
667 };
668
669 extern SgenMajorCollector major_collector;
670
671 void sgen_marksweep_init (SgenMajorCollector *collector);
672 void sgen_marksweep_fixed_init (SgenMajorCollector *collector);
673 void sgen_marksweep_par_init (SgenMajorCollector *collector);
674 void sgen_marksweep_fixed_par_init (SgenMajorCollector *collector);
675 void sgen_marksweep_conc_init (SgenMajorCollector *collector);
676 SgenMajorCollector* sgen_get_major_collector (void);
677
678
679 typedef struct _SgenRememberedSet {
680         void (*wbarrier_set_field) (GCObject *obj, gpointer field_ptr, GCObject* value);
681         void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
682         void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, size_t element_size);
683         void (*wbarrier_object_copy) (GCObject* obj, GCObject *src);
684         void (*wbarrier_generic_nostore) (gpointer ptr);
685         void (*record_pointer) (gpointer ptr);
686
687         void (*scan_remsets) (ScanCopyContext ctx);
688
689         void (*clear_cards) (void);
690
691         void (*finish_minor_collection) (void);
692         gboolean (*find_address) (char *addr);
693         gboolean (*find_address_with_cards) (char *cards_start, guint8 *cards, char *addr);
694 } SgenRememberedSet;
695
696 SgenRememberedSet *sgen_get_remset (void);
697
698 /*
699  * These must be kept in sync with object.h.  They're here for using SGen independently of
700  * Mono.
701  */
702 void mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count);
703 void mono_gc_wbarrier_generic_nostore (gpointer ptr);
704 void mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value);
705 void mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value);
706
707 void sgen_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap);
708
709 static inline SgenDescriptor
710 sgen_obj_get_descriptor (GCObject *obj)
711 {
712         GCVTable vtable = SGEN_LOAD_VTABLE_UNCHECKED (obj);
713         SGEN_ASSERT (9, !SGEN_POINTER_IS_TAGGED_ANY (vtable), "Object can't be tagged");
714         return sgen_vtable_get_descriptor (vtable);
715 }
716
717 static inline SgenDescriptor
718 sgen_obj_get_descriptor_safe (GCObject *obj)
719 {
720         GCVTable vtable = SGEN_LOAD_VTABLE (obj);
721         return sgen_vtable_get_descriptor (vtable);
722 }
723
724 static mword sgen_client_par_object_get_size (GCVTable vtable, GCObject* o);
725 static mword sgen_client_slow_object_get_size (GCVTable vtable, GCObject* o);
726
727 static inline mword
728 sgen_safe_object_get_size (GCObject *obj)
729 {
730        GCObject *forwarded;
731
732        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
733                obj = forwarded;
734
735        return sgen_client_par_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
736 }
737
738 static inline gboolean
739 sgen_safe_object_is_small (GCObject *obj, int type)
740 {
741         if (type <= DESC_TYPE_MAX_SMALL_OBJ)
742                 return TRUE;
743         return SGEN_ALIGN_UP (sgen_safe_object_get_size ((GCObject*)obj)) <= SGEN_MAX_SMALL_OBJ_SIZE;
744 }
745
746 /*
747  * This variant guarantees to return the exact size of the object
748  * before alignment. Needed for canary support.
749  */
750 static inline guint
751 sgen_safe_object_get_size_unaligned (GCObject *obj)
752 {
753         GCObject *forwarded;
754
755         if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
756                 obj = (GCObject*)forwarded;
757         }
758
759         return sgen_client_slow_object_get_size (SGEN_LOAD_VTABLE (obj), obj);
760 }
761
762 #ifdef SGEN_CLIENT_HEADER
763 #include SGEN_CLIENT_HEADER
764 #else
765 #include "metadata/sgen-client-mono.h"
766 #endif
767
768 gboolean sgen_object_is_live (void *obj);
769
770 void  sgen_init_fin_weak_hash (void);
771
772 /* FIXME: move the toggleref stuff out of here */
773 void sgen_mark_togglerefs (char *start, char *end, ScanCopyContext ctx);
774 void sgen_clear_togglerefs (char *start, char *end, ScanCopyContext ctx);
775
776 void sgen_process_togglerefs (void);
777 void sgen_register_test_toggleref_callback (void);
778
779 void sgen_mark_bridge_object (GCObject *obj);
780 void sgen_collect_bridge_objects (int generation, ScanCopyContext ctx);
781
782 typedef gboolean (*SgenObjectPredicateFunc) (GCObject *obj, void *user_data);
783
784 void sgen_null_links_if (SgenObjectPredicateFunc predicate, void *data, int generation);
785
786 gboolean sgen_gc_is_object_ready_for_finalization (void *object);
787 void sgen_gc_lock (void);
788 void sgen_gc_unlock (void);
789
790 void sgen_queue_finalization_entry (GCObject *obj);
791 const char* sgen_generation_name (int generation);
792
793 void sgen_finalize_in_range (int generation, ScanCopyContext ctx);
794 void sgen_null_link_in_range (int generation, gboolean before_finalization, ScanCopyContext ctx);
795 void sgen_process_fin_stage_entries (void);
796 gboolean sgen_have_pending_finalizers (void);
797 void sgen_object_register_for_finalization (GCObject *obj, void *user_data);
798
799 int sgen_gather_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, GCObject **out_array, int out_size);
800 void sgen_remove_finalizers_if (SgenObjectPredicateFunc predicate, void *user_data, int generation);
801
802 void sgen_process_dislink_stage_entries (void);
803 void sgen_register_disappearing_link (GCObject *obj, void **link, gboolean track, gboolean in_gc);
804
805 GCObject* sgen_weak_link_get (void **link_addr);
806
807 gboolean sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx);
808
809 enum {
810         SPACE_NURSERY,
811         SPACE_MAJOR,
812         SPACE_LOS
813 };
814
815 void sgen_pin_object (void *object, SgenGrayQueue *queue);
816 void sgen_set_pinned_from_failed_allocation (mword objsize);
817
818 void sgen_ensure_free_space (size_t size);
819 void sgen_gc_collect (int generation);
820 void sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish);
821
822 int sgen_gc_collection_count (int generation);
823 /* FIXME: what exactly does this return? */
824 size_t sgen_gc_get_used_size (void);
825 size_t sgen_gc_get_total_heap_allocation (void);
826
827 /* STW */
828
829 typedef struct {
830         int generation;
831         const char *reason;
832         gboolean is_overflow;
833         gint64 total_time;
834         gint64 stw_time;
835         gint64 bridge_time;
836 } GGTimingInfo;
837
838 void sgen_stop_world (int generation);
839 void sgen_restart_world (int generation, GGTimingInfo *timing);
840 gboolean sgen_is_world_stopped (void);
841
842 gboolean sgen_set_allow_synchronous_major (gboolean flag);
843
844 /* LOS */
845
846 typedef struct _LOSObject LOSObject;
847 struct _LOSObject {
848         LOSObject *next;
849         mword size; /* this is the object size, lowest bit used for pin/mark */
850         guint8 * volatile cardtable_mod_union; /* only used by the concurrent collector */
851 #if SIZEOF_VOID_P < 8
852         mword dummy;            /* to align object to sizeof (double) */
853 #endif
854         GCObject data [MONO_ZERO_LEN_ARRAY];
855 };
856
857 extern LOSObject *los_object_list;
858 extern mword los_memory_usage;
859
860 void sgen_los_free_object (LOSObject *obj);
861 void* sgen_los_alloc_large_inner (GCVTable vtable, size_t size);
862 void sgen_los_sweep (void);
863 gboolean sgen_ptr_is_in_los (char *ptr, char **start);
864 void sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data);
865 void sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback);
866 void sgen_los_scan_card_table (gboolean mod_union, ScanCopyContext ctx);
867 void sgen_los_update_cardtable_mod_union (void);
868 void sgen_los_count_cards (long long *num_total_cards, long long *num_marked_cards);
869 gboolean sgen_los_is_valid_object (char *object);
870 gboolean mono_sgen_los_describe_pointer (char *ptr);
871 LOSObject* sgen_los_header_for_object (GCObject *data);
872 mword sgen_los_object_size (LOSObject *obj);
873 void sgen_los_pin_object (GCObject *obj);
874 gboolean sgen_los_object_is_pinned (GCObject *obj);
875 void sgen_los_mark_mod_union_card (GCObject *mono_obj, void **ptr);
876
877
878 /* nursery allocator */
879
880 void sgen_clear_nursery_fragments (void);
881 void sgen_nursery_allocator_prepare_for_pinning (void);
882 void sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end);
883 mword sgen_build_nursery_fragments (GCMemSection *nursery_section, SgenGrayQueue *unpin_queue);
884 void sgen_init_nursery_allocator (void);
885 void sgen_nursery_allocator_init_heavy_stats (void);
886 void sgen_init_allocator (void);
887 char* sgen_nursery_alloc_get_upper_alloc_bound (void);
888 void* sgen_nursery_alloc (size_t size);
889 void* sgen_nursery_alloc_range (size_t size, size_t min_size, size_t *out_alloc_size);
890 gboolean sgen_can_alloc_size (size_t size);
891 void sgen_nursery_retire_region (void *address, ptrdiff_t size);
892
893 void sgen_nursery_alloc_prepare_for_minor (void);
894 void sgen_nursery_alloc_prepare_for_major (void);
895
896 char* sgen_alloc_for_promotion (GCObject *obj, size_t objsize, gboolean has_references);
897
898 void* sgen_alloc_obj_nolock (GCVTable vtable, size_t size);
899 void* sgen_try_alloc_obj_nolock (GCVTable vtable, size_t size);
900
901 /* Threads */
902
903 void* sgen_thread_register (SgenThreadInfo* info, void *addr);
904 void sgen_thread_unregister (SgenThreadInfo *p);
905
906 /* Finalization/ephemeron support */
907
908 static inline gboolean
909 sgen_major_is_object_alive (GCObject *object)
910 {
911         mword objsize;
912
913         /* Oldgen objects can be pinned and forwarded too */
914         if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
915                 return TRUE;
916
917         /*
918          * FIXME: major_collector.is_object_live() also calculates the
919          * size.  Avoid the double calculation.
920          */
921         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (object));
922         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
923                 return sgen_los_object_is_pinned (object);
924
925         return major_collector.is_object_live (object);
926 }
927
928 /*
929  * This function returns true if @object is either alive or it belongs to the old gen
930  * and we're currently doing a minor collection.
931  */
932 static inline int
933 sgen_is_object_alive_for_current_gen (GCObject *object)
934 {
935         if (sgen_ptr_in_nursery (object))
936                 return sgen_nursery_is_object_alive (object);
937
938         if (current_collection_generation == GENERATION_NURSERY)
939                 return TRUE;
940
941         return sgen_major_is_object_alive (object);
942 }
943
944 int sgen_gc_invoke_finalizers (void);
945
946 /* Other globals */
947
948 extern GCMemSection *nursery_section;
949 extern guint32 collect_before_allocs;
950 extern guint32 verify_before_allocs;
951 extern gboolean has_per_allocation_action;
952 extern size_t degraded_mode;
953 extern int default_nursery_size;
954 extern guint32 tlab_size;
955 extern NurseryClearPolicy nursery_clear_policy;
956 extern gboolean sgen_try_free_some_memory;
957
958 extern LOCK_DECLARE (gc_mutex);
959
960 /* Nursery helpers. */
961
962 static inline void
963 sgen_set_nursery_scan_start (char *p)
964 {
965         size_t idx = (p - (char*)nursery_section->data) / SGEN_SCAN_START_SIZE;
966         char *old = nursery_section->scan_starts [idx];
967         if (!old || old > p)
968                 nursery_section->scan_starts [idx] = p;
969 }
970
971
972 /* Object Allocation */
973
974 typedef enum {
975         ATYPE_NORMAL,
976         ATYPE_VECTOR,
977         ATYPE_SMALL,
978         ATYPE_STRING,
979         ATYPE_NUM
980 } SgenAllocatorType;
981
982 void sgen_init_tlab_info (SgenThreadInfo* info);
983 void sgen_clear_tlabs (void);
984
985 void* sgen_alloc_obj (GCVTable vtable, size_t size);
986 void* sgen_alloc_obj_pinned (GCVTable vtable, size_t size);
987 void* sgen_alloc_obj_mature (GCVTable vtable, size_t size);
988
989 /* Debug support */
990
991 void sgen_check_consistency (void);
992 void sgen_check_mod_union_consistency (void);
993 void sgen_check_major_refs (void);
994 void sgen_check_whole_heap (gboolean allow_missing_pinning);
995 void sgen_check_whole_heap_stw (void);
996 void sgen_check_objref (char *obj);
997 void sgen_check_heap_marked (gboolean nursery_must_be_pinned);
998 void sgen_check_nursery_objects_pinned (gboolean pinned);
999 void sgen_check_for_xdomain_refs (void);
1000 GCObject* sgen_find_object_for_ptr (char *ptr);
1001
1002 void mono_gc_scan_for_specific_ref (GCObject *key, gboolean precise);
1003
1004 void sgen_debug_enable_heap_dump (const char *filename);
1005 void sgen_debug_dump_heap (const char *type, int num, const char *reason);
1006
1007 void sgen_debug_verify_nursery (gboolean do_dump_nursery_content);
1008 void sgen_debug_check_nursery_is_clean (void);
1009
1010 /* Write barrier support */
1011
1012 /*
1013  * This causes the compile to extend the liveness of 'v' till the call to dummy_use
1014  */
1015 static inline void
1016 sgen_dummy_use (gpointer v) {
1017 #if defined(__GNUC__)
1018         __asm__ volatile ("" : "=r"(v) : "r"(v));
1019 #elif defined(_MSC_VER)
1020         static volatile gpointer ptr;
1021         ptr = v;
1022 #else
1023 #error "Implement sgen_dummy_use for your compiler"
1024 #endif
1025 }
1026
1027 /* Environment variable parsing */
1028
1029 #define MONO_GC_PARAMS_NAME     "MONO_GC_PARAMS"
1030 #define MONO_GC_DEBUG_NAME      "MONO_GC_DEBUG"
1031
1032 void sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...);
1033
1034 /* Utilities */
1035
1036 void sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*));
1037 gint64 sgen_timestamp (void);
1038
1039 /*
1040  * Canary (guard word) support
1041  * Notes:
1042  * - CANARY_SIZE must be multiple of word size in bytes
1043  * - Canary space is not included on checks against SGEN_MAX_SMALL_OBJ_SIZE
1044  */
1045  
1046 gboolean nursery_canaries_enabled (void);
1047
1048 #define CANARY_SIZE 8
1049 #define CANARY_STRING  "koupepia"
1050
1051 #define CANARIFY_SIZE(size) if (nursery_canaries_enabled ()) {  \
1052                         size = size + CANARY_SIZE;      \
1053                 }
1054
1055 #define CANARIFY_ALLOC(addr,size) if (nursery_canaries_enabled ()) {    \
1056                                 memcpy ((char*) (addr) + (size), CANARY_STRING, CANARY_SIZE);   \
1057                         }
1058
1059 #define CANARY_VALID(addr) (strncmp ((char*) (addr), CANARY_STRING, CANARY_SIZE) == 0)
1060
1061 #define CHECK_CANARY_FOR_OBJECT(addr) if (nursery_canaries_enabled ()) {        \
1062                                 char* canary_ptr = (char*) (addr) + sgen_safe_object_get_size_unaligned ((GCObject *) (addr));  \
1063                                 if (!CANARY_VALID(canary_ptr)) {        \
1064                                         char canary_copy[CANARY_SIZE +1];       \
1065                                         strncpy (canary_copy, canary_ptr, CANARY_SIZE); \
1066                                         canary_copy[CANARY_SIZE] = 0;   \
1067                                         g_error ("CORRUPT CANARY:\naddr->%p\ntype->%s\nexcepted->'%s'\nfound->'%s'\n", (char*) addr, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE ((addr))), CANARY_STRING, canary_copy);      \
1068                                 } }
1069
1070 #endif /* HAVE_SGEN_GC */
1071
1072 #endif /* __MONO_SGENGC_H__ */