Use the bridge callback to speedup bridge object detection.
[mono.git] / mono / metadata / sgen-gc.h
1 /*
2  * Copyright 2001-2003 Ximian, Inc
3  * Copyright 2003-2010 Novell, Inc.
4  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  * 
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  * 
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 #ifndef __MONO_SGENGC_H__
26 #define __MONO_SGENGC_H__
27
28 /* pthread impl */
29 #include "config.h"
30
31 #ifdef HAVE_SGEN_GC
32
33 typedef struct _SgenThreadInfo SgenThreadInfo;
34 #define THREAD_INFO_TYPE SgenThreadInfo
35
36 #include <glib.h>
37 #ifdef HAVE_PTHREAD_H
38 #include <pthread.h>
39 #endif
40 #include <signal.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-threads.h>
43 #include <mono/io-layer/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
51 #if defined(__MACH__)
52         #include <mach/mach_port.h>
53 #endif
54
55 /* The method used to clear the nursery */
56 /* Clearing at nursery collections is the safest, but has bad interactions with caches.
57  * Clearing at TLAB creation is much faster, but more complex and it might expose hard
58  * to find bugs.
59  */
60 typedef enum {
61         CLEAR_AT_GC,
62         CLEAR_AT_TLAB_CREATION
63 } NurseryClearPolicy;
64
65 NurseryClearPolicy mono_sgen_get_nursery_clear_policy (void) MONO_INTERNAL;
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) / 10)
70 #define SGEN_TV_ELAPSED_MS(start,end) ((SGEN_TV_ELAPSED((start),(end)) + 500) / 1000)
71
72 /* for use with write barriers */
73 typedef struct _RememberedSet RememberedSet;
74 struct _RememberedSet {
75         mword *store_next;
76         mword *end_set;
77         RememberedSet *next;
78         mword data [MONO_ZERO_LEN_ARRAY];
79 };
80
81 /*
82  * We're never actually using the first element.  It's always set to
83  * NULL to simplify the elimination of consecutive duplicate
84  * entries.
85  */
86 #define STORE_REMSET_BUFFER_SIZE        1023
87
88 typedef struct _GenericStoreRememberedSet GenericStoreRememberedSet;
89 struct _GenericStoreRememberedSet {
90         GenericStoreRememberedSet *next;
91         /* We need one entry less because the first entry of store
92            remset buffers is always a dummy and we don't copy it. */
93         gpointer data [STORE_REMSET_BUFFER_SIZE - 1];
94 };
95
96 /* we have 4 possible values in the low 2 bits */
97 enum {
98         REMSET_LOCATION, /* just a pointer to the exact location */
99         REMSET_RANGE,    /* range of pointer fields */
100         REMSET_OBJECT,   /* mark all the object for scanning */
101         REMSET_VTYPE,    /* a valuetype array described by a gc descriptor, a count and a size */
102         REMSET_TYPE_MASK = 0x3
103 };
104
105 /* eventually share with MonoThread? */
106 struct _SgenThreadInfo {
107         MonoThreadInfo info;
108 #if defined(__MACH__)
109         thread_port_t mach_port;
110 #else
111         int signal;
112         unsigned int stop_count; /* to catch duplicate signals */
113 #endif
114         int skip;
115         volatile int in_critical_region;
116         gboolean doing_handshake;
117         gboolean thread_is_dying;
118         gboolean gc_disabled;
119         void *stack_end;
120         void *stack_start;
121         void *stack_start_limit;
122         char **tlab_next_addr;
123         char **tlab_start_addr;
124         char **tlab_temp_end_addr;
125         char **tlab_real_end_addr;
126         gpointer **store_remset_buffer_addr;
127         long *store_remset_buffer_index_addr;
128         RememberedSet *remset;
129         gpointer runtime_data;
130         gpointer stopped_ip;    /* only valid if the thread is stopped */
131         MonoDomain *stopped_domain; /* ditto */
132
133 #ifdef USE_MONO_CTX
134 #ifdef __MACH__
135         MonoContext ctx;                /* ditto */
136 #endif
137         MonoContext *monoctx;   /* ditto */
138
139 #else
140
141 #if defined(__MACH__) || defined(HOST_WIN32)
142         gpointer regs[ARCH_NUM_REGS];       /* ditto */
143 #endif
144         gpointer *stopped_regs;     /* ditto */
145 #endif
146
147 #ifndef HAVE_KW_THREAD
148         char *tlab_start;
149         char *tlab_next;
150         char *tlab_temp_end;
151         char *tlab_real_end;
152         gpointer *store_remset_buffer;
153         long store_remset_buffer_index;
154 #endif
155 };
156
157 enum {
158         MEMORY_ROLE_GEN0,
159         MEMORY_ROLE_GEN1,
160         MEMORY_ROLE_PINNED
161 };
162
163 typedef struct _SgenBlock SgenBlock;
164 struct _SgenBlock {
165         void *next;
166         unsigned char role;
167 };
168
169 /*
170  * The nursery section and the major copying collector's sections use
171  * this struct.
172  */
173 typedef struct _GCMemSection GCMemSection;
174 struct _GCMemSection {
175         SgenBlock block;
176         char *data;
177         mword size;
178         /* pointer where more data could be allocated if it fits */
179         char *next_data;
180         char *end_data;
181         /*
182          * scan starts is an array of pointers to objects equally spaced in the allocation area
183          * They let use quickly find pinned objects from pinning pointers.
184          */
185         char **scan_starts;
186         /* in major collections indexes in the pin_queue for objects that pin this section */
187         void **pin_queue_start;
188         int pin_queue_num_entries;
189         unsigned short num_scan_start;
190         gboolean is_to_space;
191 };
192
193 #define SGEN_PINNED_CHUNK_FOR_PTR(o)    ((SgenBlock*)(((mword)(o)) & ~(SGEN_PINNED_CHUNK_SIZE - 1)))
194
195 typedef struct _SgenPinnedChunk SgenPinnedChunk;
196
197 /*
198  * Recursion is not allowed for the thread lock.
199  */
200 #define LOCK_DECLARE(name) mono_mutex_t name
201 /* if changing LOCK_INIT to something that isn't idempotent, look at
202    its use in mono_gc_base_init in sgen-gc.c */
203 #define LOCK_INIT(name) mono_mutex_init (&(name), NULL)
204 #define LOCK_GC mono_mutex_lock (&gc_mutex)
205 #define TRYLOCK_GC (mono_mutex_trylock (&gc_mutex) == 0)
206 #define UNLOCK_GC mono_mutex_unlock (&gc_mutex)
207 #define LOCK_INTERRUPTION mono_mutex_lock (&interruption_mutex)
208 #define UNLOCK_INTERRUPTION mono_mutex_unlock (&interruption_mutex)
209
210 #define SGEN_CAS_PTR    InterlockedCompareExchangePointer
211 #define SGEN_ATOMIC_ADD(x,i)    do {                                    \
212                 int __old_x;                                            \
213                 do {                                                    \
214                         __old_x = (x);                                  \
215                 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
216         } while (0)
217
218 #ifndef HOST_WIN32
219 /* we intercept pthread_create calls to know which threads exist */
220 #define USE_PTHREAD_INTERCEPT 1
221 #endif
222
223 #ifdef HEAVY_STATISTICS
224 #define HEAVY_STAT(x)   x
225
226 extern long long stat_objects_alloced_degraded;
227 extern long long stat_bytes_alloced_degraded;
228 extern long long stat_copy_object_called_major;
229 extern long long stat_objects_copied_major;
230 #else
231 #define HEAVY_STAT(x)
232 #endif
233
234 #define DEBUG(level,a) do {if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) { a; fflush (gc_debug_file); } } while (0)
235
236 extern int gc_debug_level;
237 extern FILE* gc_debug_file;
238
239 extern int current_collection_generation;
240
241 extern unsigned int mono_sgen_global_stop_count;
242
243 #define SGEN_ALLOC_ALIGN                8
244 #define SGEN_ALLOC_ALIGN_BITS   3
245
246 #define SGEN_ALIGN_UP(s)                (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
247
248 #ifdef SGEN_ALIGN_NURSERY
249 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
250 #else
251 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   ((char*)(p) >= (start) && (char*)(p) < (end))
252 #endif
253
254 /* Structure that corresponds to a MonoVTable: desc is a mword so requires
255  * no cast from a pointer to an integer
256  */
257 typedef struct {
258         MonoClass *klass;
259         mword desc;
260 } GCVTable;
261
262 /* these bits are set in the object vtable: we could merge them since an object can be
263  * either pinned or forwarded but not both.
264  * We store them in the vtable slot because the bits are used in the sync block for
265  * other purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
266  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
267  * would be an invalid combination for the monitor and hash code).
268  * The values are already shifted.
269  * The forwarding address is stored in the sync block.
270  */
271 #define SGEN_FORWARDED_BIT 1
272 #define SGEN_PINNED_BIT 2
273 #define SGEN_VTABLE_BITS_MASK 0x3
274
275 /* returns NULL if not forwarded, or the forwarded address */
276 #define SGEN_OBJECT_IS_FORWARDED(obj) (((mword*)(obj))[0] & SGEN_FORWARDED_BIT ? (void*)(((mword*)(obj))[0] & ~SGEN_VTABLE_BITS_MASK) : NULL)
277 #define SGEN_OBJECT_IS_PINNED(obj) (((mword*)(obj))[0] & SGEN_PINNED_BIT)
278
279 /* set the forwarded address fw_addr for object obj */
280 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {                           \
281                 ((mword*)(obj))[0] = (mword)(fw_addr) | SGEN_FORWARDED_BIT; \
282         } while (0)
283 #define SGEN_PIN_OBJECT(obj) do {       \
284                 ((mword*)(obj))[0] |= SGEN_PINNED_BIT;  \
285         } while (0)
286 #define SGEN_UNPIN_OBJECT(obj) do {     \
287                 ((mword*)(obj))[0] &= ~SGEN_PINNED_BIT; \
288         } while (0)
289
290 /*
291  * Since we set bits in the vtable, use the macro to load it from the pointer to
292  * an object that is potentially pinned.
293  */
294 #define SGEN_LOAD_VTABLE(addr) ((*(mword*)(addr)) & ~SGEN_VTABLE_BITS_MASK)
295
296 typedef void (*CopyOrMarkObjectFunc) (void**, SgenGrayQueue*);
297 typedef void (*ScanObjectFunc) (char*, SgenGrayQueue*);
298 typedef void (*ScanVTypeFunc) (char*, mword desc, SgenGrayQueue*);
299
300 #if SGEN_MAX_DEBUG_LEVEL >= 9
301 #define GRAY_OBJECT_ENQUEUE mono_sgen_gray_object_enqueue
302 #define GRAY_OBJECT_DEQUEUE(queue,o) ((o) = mono_sgen_gray_object_dequeue ((queue)))
303 #else
304 #define GRAY_OBJECT_ENQUEUE(queue,o) do {                               \
305                 if (G_UNLIKELY (!(queue)->first || (queue)->first->end == SGEN_GRAY_QUEUE_SECTION_SIZE)) \
306                         mono_sgen_gray_object_enqueue ((queue), (o));   \
307                 else                                                    \
308                         (queue)->first->objects [(queue)->first->end++] = (o); \
309                 PREFETCH ((o));                                         \
310         } while (0)
311 #define GRAY_OBJECT_DEQUEUE(queue,o) do {                               \
312                 if (!(queue)->first)                                    \
313                         (o) = NULL;                                     \
314                 else if (G_UNLIKELY ((queue)->first->end == 1))         \
315                         (o) = mono_sgen_gray_object_dequeue ((queue));          \
316                 else                                                    \
317                         (o) = (queue)->first->objects [--(queue)->first->end]; \
318         } while (0)
319 #endif
320
321 /*
322 List of what each bit on of the vtable gc bits means. 
323 */
324 enum {
325         SGEN_GC_BIT_BRIDGE_OBJECT = 1,
326 };
327
328 typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
329
330 void* mono_sgen_alloc_os_memory (size_t size, int activate) MONO_INTERNAL;
331 void* mono_sgen_alloc_os_memory_aligned (mword size, mword alignment, gboolean activate) MONO_INTERNAL;
332 void mono_sgen_free_os_memory (void *addr, size_t size) MONO_INTERNAL;
333
334 int mono_sgen_thread_handshake (BOOL suspend) MONO_INTERNAL;
335 gboolean mono_sgen_suspend_thread (SgenThreadInfo *info) MONO_INTERNAL;
336 gboolean mono_sgen_resume_thread (SgenThreadInfo *info) MONO_INTERNAL;
337 void mono_sgen_wait_for_suspend_ack (int count) MONO_INTERNAL;
338 gboolean mono_sgen_park_current_thread_if_doing_handshake (SgenThreadInfo *p) MONO_INTERNAL;
339 void mono_sgen_os_init (void) MONO_INTERNAL;
340
341 void mono_sgen_fill_thread_info_for_suspend (SgenThreadInfo *info) MONO_INTERNAL;
342
343 gboolean mono_sgen_is_worker_thread (MonoNativeThreadId thread) MONO_INTERNAL;
344
345 void mono_sgen_update_heap_boundaries (mword low, mword high) MONO_INTERNAL;
346
347 void mono_sgen_register_major_sections_alloced (int num_sections) MONO_INTERNAL;
348 mword mono_sgen_get_minor_collection_allowance (void) MONO_INTERNAL;
349
350 void mono_sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags) MONO_INTERNAL;
351 void mono_sgen_check_section_scan_starts (GCMemSection *section) MONO_INTERNAL;
352
353 /* Keep in sync with mono_sgen_dump_internal_mem_usage() in dump_heap()! */
354 enum {
355         INTERNAL_MEM_PIN_QUEUE,
356         INTERNAL_MEM_FRAGMENT,
357         INTERNAL_MEM_SECTION,
358         INTERNAL_MEM_SCAN_STARTS,
359         INTERNAL_MEM_FIN_TABLE,
360         INTERNAL_MEM_FINALIZE_ENTRY,
361         INTERNAL_MEM_FINALIZE_READY_ENTRY,
362         INTERNAL_MEM_DISLINK_TABLE,
363         INTERNAL_MEM_DISLINK,
364         INTERNAL_MEM_ROOTS_TABLE,
365         INTERNAL_MEM_ROOT_RECORD,
366         INTERNAL_MEM_STATISTICS,
367         INTERNAL_MEM_STAT_PINNED_CLASS,
368         INTERNAL_MEM_STAT_REMSET_CLASS,
369         INTERNAL_MEM_REMSET,
370         INTERNAL_MEM_GRAY_QUEUE,
371         INTERNAL_MEM_STORE_REMSET,
372         INTERNAL_MEM_MS_TABLES,
373         INTERNAL_MEM_MS_BLOCK_INFO,
374         INTERNAL_MEM_EPHEMERON_LINK,
375         INTERNAL_MEM_WORKER_DATA,
376         INTERNAL_MEM_BRIDGE_DATA,
377         INTERNAL_MEM_JOB_QUEUE_ENTRY,
378         INTERNAL_MEM_TOGGLEREF_DATA,
379         INTERNAL_MEM_MAX
380 };
381
382 #define SGEN_PINNED_FREELIST_NUM_SLOTS  30
383
384 typedef struct {
385         SgenPinnedChunk *chunk_list;
386         SgenPinnedChunk *free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
387         void *delayed_free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
388 } SgenPinnedAllocator;
389
390 enum {
391         GENERATION_NURSERY,
392         GENERATION_OLD,
393         GENERATION_MAX
394 };
395
396 void mono_sgen_init_internal_allocator (void) MONO_INTERNAL;
397 void mono_sgen_init_pinned_allocator (void) MONO_INTERNAL;
398
399 typedef struct _ObjectList ObjectList;
400 struct _ObjectList {
401         MonoObject *obj;
402         ObjectList *next;
403 };
404
405 void mono_sgen_report_internal_mem_usage (void) MONO_INTERNAL;
406 void mono_sgen_report_pinned_mem_usage (SgenPinnedAllocator *alc) MONO_INTERNAL;
407 void mono_sgen_dump_internal_mem_usage (FILE *heap_dump_file) MONO_INTERNAL;
408 void mono_sgen_dump_section (GCMemSection *section, const char *type) MONO_INTERNAL;
409 void mono_sgen_dump_occupied (char *start, char *end, char *section_start) MONO_INTERNAL;
410
411 void mono_sgen_register_moved_object (void *obj, void *destination) MONO_INTERNAL;
412
413 void mono_sgen_register_fixed_internal_mem_type (int type, size_t size) MONO_INTERNAL;
414
415 void* mono_sgen_alloc_internal (int type) MONO_INTERNAL;
416 void mono_sgen_free_internal (void *addr, int type) MONO_INTERNAL;
417
418 void* mono_sgen_alloc_internal_dynamic (size_t size, int type) MONO_INTERNAL;
419 void mono_sgen_free_internal_dynamic (void *addr, size_t size, int type) MONO_INTERNAL;
420
421 void* mono_sgen_alloc_pinned (SgenPinnedAllocator *allocator, size_t size) MONO_INTERNAL;
422 void mono_sgen_free_pinned (SgenPinnedAllocator *allocator, void *addr, size_t size) MONO_INTERNAL;
423
424
425 void mono_sgen_debug_printf (int level, const char *format, ...) MONO_INTERNAL;
426
427 gboolean mono_sgen_parse_environment_string_extract_number (const char *str, glong *out) MONO_INTERNAL;
428
429 void mono_sgen_pinned_scan_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
430 void mono_sgen_pinned_scan_pinned_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
431
432 void mono_sgen_pinned_update_heap_boundaries (SgenPinnedAllocator *alc) MONO_INTERNAL;
433
434 void** mono_sgen_find_optimized_pin_queue_area (void *start, void *end, int *num) MONO_INTERNAL;
435 void mono_sgen_find_section_pin_queue_start_end (GCMemSection *section) MONO_INTERNAL;
436 void mono_sgen_pin_objects_in_section (GCMemSection *section, SgenGrayQueue *queue) MONO_INTERNAL;
437
438 void mono_sgen_pin_stats_register_object (char *obj, size_t size);
439 void mono_sgen_pin_stats_register_global_remset (char *obj);
440 void mono_sgen_pin_stats_print_class_stats (void);
441
442 void mono_sgen_sort_addresses (void **array, int size) MONO_INTERNAL;
443 void mono_sgen_add_to_global_remset (gpointer ptr) MONO_INTERNAL;
444
445 int mono_sgen_get_current_collection_generation (void) MONO_INTERNAL;
446 gboolean mono_sgen_nursery_collection_is_parallel (void) MONO_INTERNAL;
447 CopyOrMarkObjectFunc mono_sgen_get_copy_object (void) MONO_INTERNAL;
448 ScanObjectFunc mono_sgen_get_minor_scan_object (void) MONO_INTERNAL;
449 ScanVTypeFunc mono_sgen_get_minor_scan_vtype (void) MONO_INTERNAL;
450 gboolean mono_sgen_collection_is_parallel (void) MONO_INTERNAL;
451
452
453 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
454 void sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
455
456 typedef struct _SgenMajorCollector SgenMajorCollector;
457 struct _SgenMajorCollector {
458         size_t section_size;
459         gboolean is_parallel;
460         gboolean supports_cardtable;
461
462         /*
463          * This is set to TRUE if the sweep for the last major
464          * collection has been completed.
465          */
466         gboolean *have_swept;
467
468         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
469         gboolean (*is_object_live) (char *obj);
470         void* (*alloc_small_pinned_obj) (size_t size, gboolean has_references);
471         void* (*alloc_degraded) (MonoVTable *vtable, size_t size);
472         void (*copy_or_mark_object) (void **obj_slot, SgenGrayQueue *queue);
473         void (*minor_scan_object) (char *start, SgenGrayQueue *queue);
474         void (*nopar_minor_scan_object) (char *start, SgenGrayQueue *queue);
475         void (*minor_scan_vtype) (char *start, mword desc, SgenGrayQueue *queue);
476         void (*nopar_minor_scan_vtype) (char *start, mword desc, SgenGrayQueue *queue);
477         void (*major_scan_object) (char *start, SgenGrayQueue *queue);
478         void (*copy_object) (void **obj_slot, SgenGrayQueue *queue);
479         void (*nopar_copy_object) (void **obj_slot, SgenGrayQueue *queue);
480         void* (*alloc_object) (int size, gboolean has_references);
481         void (*free_pinned_object) (char *obj, size_t size);
482         void (*iterate_objects) (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data);
483         void (*free_non_pinned_object) (char *obj, size_t size);
484         void (*find_pin_queue_start_ends) (SgenGrayQueue *queue);
485         void (*pin_objects) (SgenGrayQueue *queue);
486         void (*scan_card_table) (SgenGrayQueue *queue);
487         void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
488         void (*init_to_space) (void);
489         void (*sweep) (void);
490         void (*check_scan_starts) (void);
491         void (*dump_heap) (FILE *heap_dump_file);
492         gint64 (*get_used_size) (void);
493         void (*start_nursery_collection) (void);
494         void (*finish_nursery_collection) (void);
495         void (*start_major_collection) (void);
496         void (*finish_major_collection) (void);
497         void (*have_computed_minor_collection_allowance) (void);
498         gboolean (*ptr_is_in_non_pinned_space) (char *ptr);
499         gboolean (*obj_is_from_pinned_alloc) (char *obj);
500         void (*report_pinned_memory_usage) (void);
501         int (*get_num_major_sections) (void);
502         gboolean (*handle_gc_param) (const char *opt);
503         void (*print_gc_param_usage) (void);
504         gboolean (*is_worker_thread) (MonoNativeThreadId thread);
505         void (*post_param_init) (void);
506         void* (*alloc_worker_data) (void);
507         void (*init_worker_thread) (void *data);
508         void (*reset_worker_data) (void *data);
509 };
510
511 extern SgenMajorCollector major_collector;
512
513 void mono_sgen_marksweep_init (SgenMajorCollector *collector) MONO_INTERNAL;
514 void mono_sgen_marksweep_fixed_init (SgenMajorCollector *collector) MONO_INTERNAL;
515 void mono_sgen_marksweep_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
516 void mono_sgen_marksweep_fixed_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
517 void mono_sgen_copying_init (SgenMajorCollector *collector) MONO_INTERNAL;
518 SgenMajorCollector* mono_sgen_get_major_collector (void) MONO_INTERNAL;
519
520
521 typedef struct {
522         void (*wbarrier_set_field) (MonoObject *obj, gpointer field_ptr, MonoObject* value);
523         void (*wbarrier_set_arrayref) (MonoArray *arr, gpointer slot_ptr, MonoObject* value);
524         void (*wbarrier_arrayref_copy) (gpointer dest_ptr, gpointer src_ptr, int count);
525         void (*wbarrier_value_copy) (gpointer dest, gpointer src, int count, MonoClass *klass);
526         void (*wbarrier_object_copy) (MonoObject* obj, MonoObject *src);
527         void (*wbarrier_generic_nostore) (gpointer ptr);
528         void (*record_pointer) (gpointer ptr);
529
530         void (*begin_scan_remsets) (void *start_nursery, void *end_nursery, SgenGrayQueue *queue); /* OPTIONAL */
531         void (*finish_scan_remsets) (void *start_nursery, void *end_nursery, SgenGrayQueue *queue);
532
533         void (*register_thread) (SgenThreadInfo *p); /* OPTIONAL */
534         void (*cleanup_thread) (SgenThreadInfo *p); /* OPTIONAL */
535         void (*prepare_for_minor_collection) (void); /* OPTIONAL */
536         void (*prepare_for_major_collection) (void);
537
538         void (*finish_minor_collection) (void); /* OPTIONAL */
539         gboolean (*find_address) (char *addr);
540 } SgenRemeberedSet;
541
542 SgenRemeberedSet *mono_sgen_get_remset (void) MONO_INTERNAL;
543
544 static guint /*__attribute__((noinline)) not sure if this hint is a good idea*/
545 slow_object_get_size (MonoVTable *vtable, MonoObject* o)
546 {
547         MonoClass *klass = vtable->klass;
548
549         /*
550          * We depend on mono_string_length_fast and
551          * mono_array_length_fast not using the object's vtable.
552          */
553         if (klass == mono_defaults.string_class) {
554                 return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
555         } else if (klass->rank) {
556                 MonoArray *array = (MonoArray*)o;
557                 size_t size = sizeof (MonoArray) + klass->sizes.element_size * mono_array_length_fast (array);
558                 if (G_UNLIKELY (array->bounds)) {
559                         size += sizeof (mono_array_size_t) - 1;
560                         size &= ~(sizeof (mono_array_size_t) - 1);
561                         size += sizeof (MonoArrayBounds) * klass->rank;
562                 }
563                 return size;
564         } else {
565                 /* from a created object: the class must be inited already */
566                 return klass->instance_size;
567         }
568 }
569
570 /*
571  * This function can be called on an object whose first word, the
572  * vtable field, is not intact.  This is necessary for the parallel
573  * collector.
574  */
575 static inline guint
576 mono_sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
577 {
578         mword descr = (mword)vtable->gc_descr;
579         mword type = descr & 0x7;
580
581         if (type == DESC_TYPE_RUN_LENGTH || type == DESC_TYPE_SMALL_BITMAP) {
582                 mword size = descr & 0xfff8;
583                 if (size == 0) /* This is used to encode a string */
584                         return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
585                 return size;
586         } else if (type == DESC_TYPE_VECTOR) {
587                 int element_size = ((descr) >> VECTOR_ELSIZE_SHIFT) & MAX_ELEMENT_SIZE;
588                 MonoArray *array = (MonoArray*)o;
589                 size_t size = sizeof (MonoArray) + element_size * mono_array_length_fast (array);
590
591                 if (descr & VECTOR_KIND_ARRAY) {
592                         size += sizeof (mono_array_size_t) - 1;
593                         size &= ~(sizeof (mono_array_size_t) - 1);
594                         size += sizeof (MonoArrayBounds) * vtable->klass->rank;
595                 }
596                 return size;
597         }
598
599         return slow_object_get_size (vtable, o);
600 }
601
602 static inline guint
603 mono_sgen_safe_object_get_size (MonoObject *obj)
604 {
605        char *forwarded;
606
607        if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj)))
608                obj = (MonoObject*)forwarded;
609
610        return mono_sgen_par_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE (obj), obj);
611 }
612
613 const char* mono_sgen_safe_name (void* obj) MONO_INTERNAL;
614
615 gboolean mono_sgen_object_is_live (void *obj) MONO_INTERNAL;
616
617 gboolean mono_sgen_need_bridge_processing (void) MONO_INTERNAL;
618 void mono_sgen_bridge_reset_data (void) MONO_INTERNAL;
619 void mono_sgen_bridge_processing_stw_step (void) MONO_INTERNAL;
620 void mono_sgen_bridge_processing_finish (void) MONO_INTERNAL;
621 void mono_sgen_register_test_bridge_callbacks (const char *bridge_class_name) MONO_INTERNAL;
622 gboolean mono_sgen_is_bridge_object (MonoObject *obj) MONO_INTERNAL;
623 gboolean mono_sgen_is_bridge_class (MonoClass *class) MONO_INTERNAL;
624 void mono_sgen_mark_bridge_object (MonoObject *obj) MONO_INTERNAL;
625 void mono_sgen_bridge_register_finalized_object (MonoObject *object) MONO_INTERNAL;
626
627 void mono_sgen_scan_togglerefs (CopyOrMarkObjectFunc copy_func, char *start, char *end, SgenGrayQueue *queue) MONO_INTERNAL;
628 void mono_sgen_process_togglerefs (void) MONO_INTERNAL;
629
630
631 gboolean mono_sgen_gc_is_object_ready_for_finalization (void *object) MONO_INTERNAL;
632 void mono_sgen_gc_lock (void) MONO_INTERNAL;
633 void mono_sgen_gc_unlock (void) MONO_INTERNAL;
634
635 enum {
636         SPACE_MAJOR,
637         SPACE_LOS
638 };
639
640 gboolean mono_sgen_try_alloc_space (mword size, int space) MONO_INTERNAL;
641 void mono_sgen_release_space (mword size, int space) MONO_INTERNAL;
642 void mono_sgen_pin_object (void *object, SgenGrayQueue *queue) MONO_INTERNAL;
643 void sgen_collect_major_no_lock (const char *reason) MONO_INTERNAL;
644 void mono_sgen_collect_nursery_no_lock (size_t requested_size) MONO_INTERNAL;
645 void mono_sgen_minor_collect_or_expand_inner (size_t size) MONO_INTERNAL;
646 gboolean mono_sgen_need_major_collection (mword space_needed) MONO_INTERNAL;
647 void mono_sgen_set_pinned_from_failed_allocation (mword objsize) MONO_INTERNAL;
648
649 /* LOS */
650
651 typedef struct _LOSObject LOSObject;
652 struct _LOSObject {
653         LOSObject *next;
654         mword size; /* this is the object size */
655         guint16 huge_object;
656         int dummy; /* to have a sizeof (LOSObject) a multiple of ALLOC_ALIGN  and data starting at same alignment */
657         char data [MONO_ZERO_LEN_ARRAY];
658 };
659
660 #define ARRAY_OBJ_INDEX(ptr,array,elem_size) (((char*)(ptr) - ((char*)(array) + G_STRUCT_OFFSET (MonoArray, vector))) / (elem_size))
661
662 extern LOSObject *los_object_list;
663 extern mword los_memory_usage;
664
665 void mono_sgen_los_free_object (LOSObject *obj) MONO_INTERNAL;
666 void* mono_sgen_los_alloc_large_inner (MonoVTable *vtable, size_t size) MONO_INTERNAL;
667 void mono_sgen_los_sweep (void) MONO_INTERNAL;
668 gboolean mono_sgen_ptr_is_in_los (char *ptr, char **start) MONO_INTERNAL;
669 void mono_sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data) MONO_INTERNAL;
670 void mono_sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
671 void mono_sgen_los_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
672 void sgen_major_collector_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
673 FILE *mono_sgen_get_logfile (void) MONO_INTERNAL;
674
675 /* nursery allocator */
676
677 void mono_sgen_clear_nursery_fragments (void) MONO_INTERNAL;
678 void mono_sgen_nursery_allocator_prepare_for_pinning (void) MONO_INTERNAL;
679 void mono_sgen_clear_current_nursery_fragment (void) MONO_INTERNAL;
680 void mono_sgen_nursery_allocator_set_nursery_bounds (char *nursery_start, char *nursery_end) MONO_INTERNAL;
681 mword mono_sgen_build_nursery_fragments (GCMemSection *nursery_section, void **start, int num_entries) MONO_INTERNAL;
682 void mono_sgen_init_nursery_allocator (void) MONO_INTERNAL;
683 void mono_sgen_nursery_allocator_init_heavy_stats (void) MONO_INTERNAL;
684 void mono_sgen_alloc_init_heavy_stats (void) MONO_INTERNAL;
685 char* mono_sgen_nursery_alloc_get_upper_alloc_bound (void) MONO_INTERNAL;
686 void* mono_sgen_nursery_alloc (size_t size) MONO_INTERNAL;
687 void* mono_sgen_nursery_alloc_range (size_t size, size_t min_size, int *out_alloc_size) MONO_INTERNAL;
688 MonoVTable* mono_sgen_get_array_fill_vtable (void) MONO_INTERNAL;
689 gboolean mono_sgen_can_alloc_size (size_t size) MONO_INTERNAL;
690 void mono_sgen_nursery_retire_region (void *address, ptrdiff_t size) MONO_INTERNAL;
691 gboolean mono_sgen_ptr_in_nursery (void *p) MONO_INTERNAL; /*FIXME make this inline*/
692
693 /* hash tables */
694
695 typedef struct _SgenHashTableEntry SgenHashTableEntry;
696 struct _SgenHashTableEntry {
697         SgenHashTableEntry *next;
698         gpointer key;
699         char data [MONO_ZERO_LEN_ARRAY]; /* data is pointer-aligned */
700 };
701
702 typedef struct {
703         int table_mem_type;
704         int entry_mem_type;
705         size_t data_size;
706         GHashFunc hash_func;
707         GEqualFunc equal_func;
708         SgenHashTableEntry **table;
709         guint size;
710         guint num_entries;
711 } SgenHashTable;
712
713 #define SGEN_HASH_TABLE_INIT(table_type,entry_type,data_size,hash_func,equal_func)      { (table_type), (entry_type), (data_size), (hash_func), (equal_func), NULL, 0, 0 }
714 #define SGEN_HASH_TABLE_ENTRY_SIZE(data_size)                   ((data_size) + sizeof (SgenHashTableEntry*) + sizeof (gpointer))
715
716 gpointer mono_sgen_hash_table_lookup (SgenHashTable *table, gpointer key) MONO_INTERNAL;
717 gboolean mono_sgen_hash_table_replace (SgenHashTable *table, gpointer key, gpointer data) MONO_INTERNAL;
718 gboolean mono_sgen_hash_table_set_value (SgenHashTable *table, gpointer key, gpointer data) MONO_INTERNAL;
719 gboolean mono_sgen_hash_table_set_key (SgenHashTable *hash_table, gpointer old_key, gpointer new_key) MONO_INTERNAL;
720 gboolean mono_sgen_hash_table_remove (SgenHashTable *table, gpointer key, gpointer data_return) MONO_INTERNAL;
721
722 void mono_sgen_hash_table_clean (SgenHashTable *table) MONO_INTERNAL;
723
724 #define mono_sgen_hash_table_num_entries(h)     ((h)->num_entries)
725
726 #define SGEN_HASH_TABLE_FOREACH(h,k,v) do {                             \
727                 SgenHashTable *__hash_table = (h);                      \
728                 SgenHashTableEntry **__table = __hash_table->table;     \
729                 guint __i;                                              \
730                 for (__i = 0; __i < (h)->size; ++__i) {                 \
731                         SgenHashTableEntry **__iter, **__next;                  \
732                         for (__iter = &__table [__i]; *__iter; __iter = __next) {       \
733                                 SgenHashTableEntry *__entry = *__iter;  \
734                                 __next = &__entry->next;        \
735                                 (k) = __entry->key;                     \
736                                 (v) = (gpointer)__entry->data;
737
738 /* The loop must be continue'd after using this! */
739 #define SGEN_HASH_TABLE_FOREACH_REMOVE(free)    do {                    \
740                 *__iter = *__next;      \
741                 __next = __iter;        \
742                 --__hash_table->num_entries;                            \
743                 if ((free))                                             \
744                         mono_sgen_free_internal (__entry, __hash_table->entry_mem_type); \
745         } while (0)
746
747 #define SGEN_HASH_TABLE_FOREACH_SET_KEY(k)      ((__entry)->key = (k))
748
749 #define SGEN_HASH_TABLE_FOREACH_END                                     \
750                         }                                               \
751                 }                                                       \
752         } while (0)
753
754 /* TLS Data */
755
756 extern MonoNativeTlsKey thread_info_key;
757
758 #ifdef HAVE_KW_THREAD
759 extern __thread RememberedSet *remembered_set MONO_TLS_FAST;
760 extern __thread SgenThreadInfo *thread_info;
761 extern __thread gpointer *store_remset_buffer;
762 extern __thread long store_remset_buffer_index;
763 extern __thread char *stack_end;
764 extern __thread long *store_remset_buffer_index_addr;
765 #endif
766
767 #ifdef HAVE_KW_THREAD
768 #define TLAB_ACCESS_INIT
769 #define REMEMBERED_SET  remembered_set
770 #define STORE_REMSET_BUFFER     store_remset_buffer
771 #define STORE_REMSET_BUFFER_INDEX       store_remset_buffer_index
772 #define IN_CRITICAL_REGION thread_info->in_critical_region
773 #else
774 #define TLAB_ACCESS_INIT        SgenThreadInfo *__thread_info__ = mono_native_tls_get_value (thread_info_key)
775 #define REMEMBERED_SET  (__thread_info__->remset)
776 #define STORE_REMSET_BUFFER     (__thread_info__->store_remset_buffer)
777 #define STORE_REMSET_BUFFER_INDEX       (__thread_info__->store_remset_buffer_index)
778 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
779 #endif
780
781 #ifndef DISABLE_CRITICAL_REGION
782
783 #ifdef HAVE_KW_THREAD
784 #define IN_CRITICAL_REGION thread_info->in_critical_region
785 #else
786 #define IN_CRITICAL_REGION (__thread_info__->in_critical_region)
787 #endif
788
789 /* Enter must be visible before anything is done in the critical region. */
790 #define ENTER_CRITICAL_REGION do { mono_atomic_store_acquire (&IN_CRITICAL_REGION, 1); } while (0)
791
792 /* Exit must make sure all critical regions stores are visible before it signal the end of the region. 
793  * We don't need to emit a full barrier since we
794  */
795 #define EXIT_CRITICAL_REGION  do { mono_atomic_store_release (&IN_CRITICAL_REGION, 0); } while (0)
796
797 #endif
798
799 #ifdef HAVE_KW_THREAD
800 #define EMIT_TLS_ACCESS(mb,dummy,offset)        do {    \
801         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
802         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
803         mono_mb_emit_i4 ((mb), (offset));               \
804         } while (0)
805 #else
806
807 /* 
808  * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
809  * where the two are the same.
810  */
811 #if defined(__APPLE__) || defined (HOST_WIN32)
812 #define EMIT_TLS_ACCESS(mb,member,dummy)        do {    \
813         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);   \
814         mono_mb_emit_byte ((mb), CEE_MONO_TLS);         \
815         mono_mb_emit_i4 ((mb), thread_info_key);        \
816         mono_mb_emit_icon ((mb), G_STRUCT_OFFSET (SgenThreadInfo, member));     \
817         mono_mb_emit_byte ((mb), CEE_ADD);              \
818         mono_mb_emit_byte ((mb), CEE_LDIND_I);          \
819         } while (0)
820 #else
821 #define EMIT_TLS_ACCESS(mb,member,dummy)        do { g_error ("sgen is not supported when using --with-tls=pthread.\n"); } while (0)
822 #endif
823
824 #endif
825
826 /* Other globals */
827
828 extern GCMemSection *nursery_section;
829 extern int stat_major_gcs;
830 extern guint32 collect_before_allocs;
831 extern int degraded_mode;
832 extern int default_nursery_size;
833 extern guint32 tlab_size;
834 extern NurseryClearPolicy nursery_clear_policy;
835
836 extern LOCK_DECLARE (gc_mutex);
837
838 extern int do_pin_stats;
839
840 /* Object Allocation */
841
842 typedef enum {
843         ATYPE_NORMAL,
844         ATYPE_VECTOR,
845         ATYPE_SMALL,
846         ATYPE_NUM
847 } SgenAllocatorType;
848
849 void mono_sgen_init_tlab_info (SgenThreadInfo* info);
850 void mono_sgen_clear_tlabs (void);
851 gboolean mono_sgen_is_managed_allocator (MonoMethod *method);
852
853 /* Debug support */
854
855 void mono_sgen_check_consistency (void);
856 void mono_sgen_check_major_refs (void);
857
858
859 /* Write barrier support */
860
861 /*
862  * This causes the compile to extend the liveness of 'v' till the call to dummy_use
863  */
864 static inline void
865 mono_sgen_dummy_use (gpointer v) {
866 #if defined(__GNUC__)
867         __asm__ volatile ("" : "=r"(v) : "r"(v));
868 #elif defined(_MSC_VER)
869         __asm {
870                 mov eax, v;
871                 and eax, eax;
872         };
873 #else
874 #error "Implement mono_sgen_dummy_use for your compiler"
875 #endif
876 }
877
878 #endif /* HAVE_SGEN_GC */
879
880 #endif /* __MONO_SGENGC_H__ */