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