Add regression test for #691057
[mono.git] / mono / metadata / sgen-gc.h
1 /*
2  * Copyright 2001-2003 Ximian, Inc
3  * Copyright 2003-2010 Novell, Inc.
4  * 
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  * 
13  * The above copyright notice and this permission notice shall be
14  * included in all copies or substantial portions of the Software.
15  * 
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 #ifndef __MONO_SGENGC_H__
25 #define __MONO_SGENGC_H__
26
27 /* pthread impl */
28 #include "config.h"
29
30 #ifdef HAVE_SGEN_GC
31
32 typedef struct _SgenThreadInfo SgenThreadInfo;
33 #define THREAD_INFO_TYPE SgenThreadInfo
34
35 #include <glib.h>
36 #include <pthread.h>
37 #include <signal.h>
38 #include <mono/utils/mono-compiler.h>
39 #include <mono/utils/mono-threads.h>
40 #include <mono/metadata/class-internals.h>
41 #include <mono/metadata/object-internals.h>
42 #include <mono/metadata/sgen-archdep.h>
43 #if defined(__MACH__)
44         #include <mach/mach_port.h>
45 #endif
46
47 /*
48  * Turning on heavy statistics will turn off the managed allocator and
49  * the managed write barrier.
50  */
51 //#define HEAVY_STATISTICS
52
53 /*
54  * If this is set, the nursery is aligned to an address aligned to its size, ie.
55  * a 1MB nursery will be aligned to an address divisible by 1MB. This allows us to
56  * speed up ptr_in_nursery () checks which are very frequent. This requires the
57  * nursery size to be a compile time constant.
58  */
59 #define SGEN_ALIGN_NURSERY 1
60
61 //#define SGEN_BINARY_PROTOCOL
62
63 #define SGEN_MAX_DEBUG_LEVEL 2
64
65 #define GC_BITS_PER_WORD (sizeof (mword) * 8)
66
67
68 #if SIZEOF_VOID_P == 4
69 typedef guint32 mword;
70 #else
71 typedef guint64 mword;
72 #endif
73
74 #define SGEN_TV_DECLARE(name) gint64 name
75 #define SGEN_TV_GETTIME(tv) tv = mono_100ns_ticks ()
76 #define SGEN_TV_ELAPSED(start,end) (int)((end-start) / 10)
77 #define SGEN_TV_ELAPSED_MS(start,end) ((SGEN_TV_ELAPSED((start),(end)) + 500) / 1000)
78
79 /* for use with write barriers */
80 typedef struct _RememberedSet RememberedSet;
81 struct _RememberedSet {
82         mword *store_next;
83         mword *end_set;
84         RememberedSet *next;
85         mword data [MONO_ZERO_LEN_ARRAY];
86 };
87
88 /* eventually share with MonoThread? */
89 struct _SgenThreadInfo {
90         MonoThreadInfo info;
91 #if defined(__MACH__)
92         thread_port_t mach_port;
93 #endif
94         
95         unsigned int stop_count; /* to catch duplicate signals */
96         int signal;
97         int skip;
98         volatile int in_critical_region;
99         void *stack_end;
100         void *stack_start;
101         void *stack_start_limit;
102         char **tlab_next_addr;
103         char **tlab_start_addr;
104         char **tlab_temp_end_addr;
105         char **tlab_real_end_addr;
106         gpointer **store_remset_buffer_addr;
107         long *store_remset_buffer_index_addr;
108         RememberedSet *remset;
109         gpointer runtime_data;
110         gpointer stopped_ip;    /* only valid if the thread is stopped */
111         MonoDomain *stopped_domain; /* ditto */
112
113 #if defined(__MACH__)
114 #ifdef USE_MONO_CTX
115         MonoContext ctx;                /* ditto */
116 #else
117         gpointer regs[ARCH_NUM_REGS];       /* ditto */
118 #endif
119 #endif
120
121 #ifdef USE_MONO_CTX
122         MonoContext *monoctx;   /* ditto */
123 #else
124         gpointer *stopped_regs;     /* ditto */
125 #endif
126 #ifndef HAVE_KW_THREAD
127         char *tlab_start;
128         char *tlab_next;
129         char *tlab_temp_end;
130         char *tlab_real_end;
131         gpointer *store_remset_buffer;
132         long store_remset_buffer_index;
133 #endif
134 };
135
136 enum {
137         MEMORY_ROLE_GEN0,
138         MEMORY_ROLE_GEN1,
139         MEMORY_ROLE_PINNED
140 };
141
142 typedef struct _SgenBlock SgenBlock;
143 struct _SgenBlock {
144         void *next;
145         unsigned char role;
146 };
147
148 /*
149  * The nursery section and the major copying collector's sections use
150  * this struct.
151  */
152 typedef struct _GCMemSection GCMemSection;
153 struct _GCMemSection {
154         SgenBlock block;
155         char *data;
156         mword size;
157         /* pointer where more data could be allocated if it fits */
158         char *next_data;
159         char *end_data;
160         /*
161          * scan starts is an array of pointers to objects equally spaced in the allocation area
162          * They let use quickly find pinned objects from pinning pointers.
163          */
164         char **scan_starts;
165         /* in major collections indexes in the pin_queue for objects that pin this section */
166         void **pin_queue_start;
167         int pin_queue_num_entries;
168         unsigned short num_scan_start;
169         gboolean is_to_space;
170 };
171
172 #define SGEN_SIZEOF_GC_MEM_SECTION      ((sizeof (GCMemSection) + 7) & ~7)
173
174 /*
175  * to quickly find the head of an object pinned by a conservative
176  * address we keep track of the objects allocated for each
177  * SGEN_SCAN_START_SIZE memory chunk in the nursery or other memory
178  * sections. Larger values have less memory overhead and bigger
179  * runtime cost. 4-8 KB are reasonable values.
180  */
181 #define SGEN_SCAN_START_SIZE (4096*2)
182
183 /*
184  * Objects bigger then this go into the large object space.  This size
185  * has a few constraints.  It must fit into the major heap, which in
186  * the case of the copying collector means that it must fit into a
187  * pinned chunk.  It must also play well with the GC descriptors, some
188  * of which (DESC_TYPE_RUN_LENGTH, DESC_TYPE_SMALL_BITMAP) encode the
189  * object size.
190  */
191 #define SGEN_MAX_SMALL_OBJ_SIZE 8000
192
193 /* This is also the MAJOR_SECTION_SIZE for the copying major
194    collector */
195 #define SGEN_PINNED_CHUNK_SIZE  (128 * 1024)
196
197 #define SGEN_PINNED_CHUNK_FOR_PTR(o)    ((SgenBlock*)(((mword)(o)) & ~(SGEN_PINNED_CHUNK_SIZE - 1)))
198
199 typedef struct _SgenPinnedChunk SgenPinnedChunk;
200
201 #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__)
202 const static int suspend_signal_num = SIGXFSZ;
203 #else
204 const static int suspend_signal_num = SIGPWR;
205 #endif
206 const static int restart_signal_num = SIGXCPU;
207
208 /*
209  * Recursion is not allowed for the thread lock.
210  */
211 #define LOCK_DECLARE(name) pthread_mutex_t name = PTHREAD_MUTEX_INITIALIZER
212 /* if changing LOCK_INIT to something that isn't idempotent, look at
213    its use in mono_gc_base_init in sgen-gc.c */
214 #define LOCK_INIT(name)
215 #define LOCK_GC pthread_mutex_lock (&gc_mutex)
216 #define UNLOCK_GC pthread_mutex_unlock (&gc_mutex)
217 #define LOCK_INTERRUPTION pthread_mutex_lock (&interruption_mutex)
218 #define UNLOCK_INTERRUPTION pthread_mutex_unlock (&interruption_mutex)
219
220 #define SGEN_CAS_PTR    InterlockedCompareExchangePointer
221 #define SGEN_ATOMIC_ADD(x,i)    do {                                    \
222                 int __old_x;                                            \
223                 do {                                                    \
224                         __old_x = (x);                                  \
225                 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
226         } while (0)
227
228 /* non-pthread will need to provide their own version of start/stop */
229 #define USE_SIGNAL_BASED_START_STOP_WORLD 1
230 /* we intercept pthread_create calls to know which threads exist */
231 #define USE_PTHREAD_INTERCEPT 1
232
233 #ifdef HEAVY_STATISTICS
234 #define HEAVY_STAT(x)   x
235
236 extern long long stat_objects_alloced_degraded;
237 extern long long stat_bytes_alloced_degraded;
238 extern long long stat_copy_object_called_major;
239 extern long long stat_objects_copied_major;
240 #else
241 #define HEAVY_STAT(x)
242 #endif
243
244 #define DEBUG(level,a) do {if (G_UNLIKELY ((level) <= SGEN_MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) a;} while (0)
245
246 extern int gc_debug_level;
247 extern FILE* gc_debug_file;
248
249 extern int current_collection_generation;
250
251 #define SGEN_ALLOC_ALIGN                8
252 #define SGEN_ALLOC_ALIGN_BITS   3
253
254 #define SGEN_ALIGN_UP(s)                (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
255
256 #ifdef SGEN_ALIGN_NURSERY
257 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
258 #else
259 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   ((char*)(p) >= (start) && (char*)(p) < (end))
260 #endif
261
262 /* Structure that corresponds to a MonoVTable: desc is a mword so requires
263  * no cast from a pointer to an integer
264  */
265 typedef struct {
266         MonoClass *klass;
267         mword desc;
268 } GCVTable;
269
270 /* these bits are set in the object vtable: we could merge them since an object can be
271  * either pinned or forwarded but not both.
272  * We store them in the vtable slot because the bits are used in the sync block for
273  * other purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
274  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
275  * would be an invalid combination for the monitor and hash code).
276  * The values are already shifted.
277  * The forwarding address is stored in the sync block.
278  */
279 #define SGEN_FORWARDED_BIT 1
280 #define SGEN_PINNED_BIT 2
281 #define SGEN_VTABLE_BITS_MASK 0x3
282
283 /* returns NULL if not forwarded, or the forwarded address */
284 #define SGEN_OBJECT_IS_FORWARDED(obj) (((mword*)(obj))[0] & SGEN_FORWARDED_BIT ? (void*)(((mword*)(obj))[0] & ~SGEN_VTABLE_BITS_MASK) : NULL)
285 #define SGEN_OBJECT_IS_PINNED(obj) (((mword*)(obj))[0] & SGEN_PINNED_BIT)
286
287 /* set the forwarded address fw_addr for object obj */
288 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {                           \
289                 ((mword*)(obj))[0] = (mword)(fw_addr) | SGEN_FORWARDED_BIT; \
290         } while (0)
291 #define SGEN_PIN_OBJECT(obj) do {       \
292                 ((mword*)(obj))[0] |= SGEN_PINNED_BIT;  \
293         } while (0)
294 #define SGEN_UNPIN_OBJECT(obj) do {     \
295                 ((mword*)(obj))[0] &= ~SGEN_PINNED_BIT; \
296         } while (0)
297
298 /*
299  * Since we set bits in the vtable, use the macro to load it from the pointer to
300  * an object that is potentially pinned.
301  */
302 #define SGEN_LOAD_VTABLE(addr) ((*(mword*)(addr)) & ~SGEN_VTABLE_BITS_MASK)
303
304 /*
305  * ######################################################################
306  * ########  GC descriptors
307  * ######################################################################
308  * Used to quickly get the info the GC needs about an object: size and
309  * where the references are held.
310  */
311 #define OBJECT_HEADER_WORDS (sizeof(MonoObject)/sizeof(gpointer))
312 #define LOW_TYPE_BITS 3
313 #define SMALL_BITMAP_SHIFT 16
314 #define SMALL_BITMAP_SIZE (GC_BITS_PER_WORD - SMALL_BITMAP_SHIFT)
315 #define VECTOR_INFO_SHIFT 14
316 #define VECTOR_ELSIZE_SHIFT 3
317 #define LARGE_BITMAP_SIZE (GC_BITS_PER_WORD - LOW_TYPE_BITS)
318 #define MAX_ELEMENT_SIZE 0x3ff
319 #define VECTOR_SUBTYPE_PTRFREE (DESC_TYPE_V_PTRFREE << VECTOR_INFO_SHIFT)
320 #define VECTOR_SUBTYPE_REFS    (DESC_TYPE_V_REFS << VECTOR_INFO_SHIFT)
321 #define VECTOR_SUBTYPE_RUN_LEN (DESC_TYPE_V_RUN_LEN << VECTOR_INFO_SHIFT)
322 #define VECTOR_SUBTYPE_BITMAP  (DESC_TYPE_V_BITMAP << VECTOR_INFO_SHIFT)
323
324 /* objects are aligned to 8 bytes boundaries
325  * A descriptor is a pointer in MonoVTable, so 32 or 64 bits of size.
326  * The low 3 bits define the type of the descriptor. The other bits
327  * depend on the type.
328  * As a general rule the 13 remaining low bits define the size, either
329  * of the whole object or of the elements in the arrays. While for objects
330  * the size is already in bytes, for arrays we need to shift, because
331  * array elements might be smaller than 8 bytes. In case of arrays, we
332  * use two bits to describe what the additional high bits represents,
333  * so the default behaviour can handle element sizes less than 2048 bytes.
334  * The high 16 bits, if 0 it means the object is pointer-free.
335  * This design should make it easy and fast to skip over ptr-free data.
336  * The first 4 types should cover >95% of the objects.
337  * Note that since the size of objects is limited to 64K, larger objects
338  * will be allocated in the large object heap.
339  * If we want 4-bytes alignment, we need to put vector and small bitmap
340  * inside complex.
341  */
342 enum {
343         /*
344          * We don't use 0 so that 0 isn't a valid GC descriptor.  No
345          * deep reason for this other than to be able to identify a
346          * non-inited descriptor for debugging.
347          *
348          * If an object contains no references, its GC descriptor is
349          * always DESC_TYPE_RUN_LENGTH, without a size, no exceptions.
350          * This is so that we can quickly check for that in
351          * copy_object_no_checks(), without having to fetch the
352          * object's class.
353          */
354         DESC_TYPE_RUN_LENGTH = 1, /* 15 bits aligned byte size | 1-3 (offset, numptr) bytes tuples */
355         DESC_TYPE_SMALL_BITMAP, /* 15 bits aligned byte size | 16-48 bit bitmap */
356         DESC_TYPE_COMPLEX,      /* index for bitmap into complex_descriptors */
357         DESC_TYPE_VECTOR,       /* 10 bits element size | 1 bit array | 2 bits desc | element desc */
358         DESC_TYPE_ARRAY,        /* 10 bits element size | 1 bit array | 2 bits desc | element desc */
359         DESC_TYPE_LARGE_BITMAP, /* | 29-61 bitmap bits */
360         DESC_TYPE_COMPLEX_ARR,  /* index for bitmap into complex_descriptors */
361         /* subtypes for arrays and vectors */
362         DESC_TYPE_V_PTRFREE = 0,/* there are no refs: keep first so it has a zero value  */
363         DESC_TYPE_V_REFS,       /* all the array elements are refs */
364         DESC_TYPE_V_RUN_LEN,    /* elements are run-length encoded as DESC_TYPE_RUN_LENGTH */
365         DESC_TYPE_V_BITMAP      /* elements are as the bitmap in DESC_TYPE_SMALL_BITMAP */
366 };
367
368 #define SGEN_VTABLE_HAS_REFERENCES(vt)  (((MonoVTable*)(vt))->gc_descr != (void*)DESC_TYPE_RUN_LENGTH)
369 #define SGEN_CLASS_HAS_REFERENCES(c)    ((c)->gc_descr != (void*)DESC_TYPE_RUN_LENGTH)
370
371 /* helper macros to scan and traverse objects, macros because we resue them in many functions */
372 #define OBJ_RUN_LEN_SIZE(size,desc,obj) do { \
373                 (size) = ((desc) & 0xfff8) >> 1;        \
374     } while (0)
375
376 #define OBJ_BITMAP_SIZE(size,desc,obj) do { \
377                 (size) = ((desc) & 0xfff8) >> 1;        \
378     } while (0)
379
380 #ifdef __GNUC__
381 #define PREFETCH(addr)  __builtin_prefetch ((addr))
382 #else
383 #define PREFETCH(addr)
384 #endif
385
386 /* code using these macros must define a HANDLE_PTR(ptr) macro that does the work */
387 #define OBJ_RUN_LEN_FOREACH_PTR(desc,obj)       do {    \
388                 if ((desc) & 0xffff0000) {      \
389                         /* there are pointers */        \
390                         void **_objptr_end;     \
391                         void **_objptr = (void**)(obj); \
392                         _objptr += ((desc) >> 16) & 0xff;       \
393                         _objptr_end = _objptr + (((desc) >> 24) & 0xff);        \
394                         while (_objptr < _objptr_end) { \
395                                 HANDLE_PTR (_objptr, (obj));    \
396                                 _objptr++;      \
397                         }       \
398                 }       \
399         } while (0)
400
401 /* a bitmap desc means that there are pointer references or we'd have
402  * choosen run-length, instead: add an assert to check.
403  */
404 #define OBJ_BITMAP_FOREACH_PTR(desc,obj)        do {    \
405                 /* there are pointers */        \
406                 void **_objptr = (void**)(obj); \
407                 gsize _bmap = (desc) >> 16;     \
408                 _objptr += OBJECT_HEADER_WORDS; \
409                 while (_bmap) { \
410                         if ((_bmap & 1)) {      \
411                                 HANDLE_PTR (_objptr, (obj));    \
412                         }       \
413                         _bmap >>= 1;    \
414                         ++_objptr;      \
415                 }       \
416         } while (0)
417
418 #define OBJ_LARGE_BITMAP_FOREACH_PTR(vt,obj)    do {    \
419                 /* there are pointers */        \
420                 void **_objptr = (void**)(obj); \
421                 gsize _bmap = (vt)->desc >> LOW_TYPE_BITS;      \
422                 _objptr += OBJECT_HEADER_WORDS; \
423                 while (_bmap) { \
424                         if ((_bmap & 1)) {      \
425                                 HANDLE_PTR (_objptr, (obj));    \
426                         }       \
427                         _bmap >>= 1;    \
428                         ++_objptr;      \
429                 }       \
430         } while (0)
431
432 gsize* mono_sgen_get_complex_descriptor (GCVTable *vt) MONO_INTERNAL;
433
434 #define OBJ_COMPLEX_FOREACH_PTR(vt,obj) do {    \
435                 /* there are pointers */        \
436                 void **_objptr = (void**)(obj); \
437                 gsize *bitmap_data = mono_sgen_get_complex_descriptor ((vt)); \
438                 int bwords = (*bitmap_data) - 1;        \
439                 void **start_run = _objptr;     \
440                 bitmap_data++;  \
441                 if (0) {        \
442                         MonoObject *myobj = (MonoObject*)obj;   \
443                         g_print ("found %d at %p (0x%zx): %s.%s\n", bwords, (obj), (vt)->desc, myobj->vtable->klass->name_space, myobj->vtable->klass->name);   \
444                 }       \
445                 while (bwords-- > 0) {  \
446                         gsize _bmap = *bitmap_data++;   \
447                         _objptr = start_run;    \
448                         /*g_print ("bitmap: 0x%x/%d at %p\n", _bmap, bwords, _objptr);*/        \
449                         while (_bmap) { \
450                                 if ((_bmap & 1)) {      \
451                                         HANDLE_PTR (_objptr, (obj));    \
452                                 }       \
453                                 _bmap >>= 1;    \
454                                 ++_objptr;      \
455                         }       \
456                         start_run += GC_BITS_PER_WORD;  \
457                 }       \
458         } while (0)
459
460 /* this one is untested */
461 #define OBJ_COMPLEX_ARR_FOREACH_PTR(vt,obj)     do {    \
462                 /* there are pointers */        \
463                 gsize *mbitmap_data = mono_sgen_get_complex_descriptor ((vt)); \
464                 int mbwords = (*mbitmap_data++) - 1;    \
465                 int el_size = mono_array_element_size (vt->klass);      \
466                 char *e_start = (char*)(obj) +  G_STRUCT_OFFSET (MonoArray, vector);    \
467                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
468                 if (0)                                                  \
469                         g_print ("found %d at %p (0x%zx): %s.%s\n", mbwords, (obj), (vt)->desc, vt->klass->name_space, vt->klass->name); \
470                 while (e_start < e_end) {       \
471                         void **_objptr = (void**)e_start;       \
472                         gsize *bitmap_data = mbitmap_data;      \
473                         unsigned int bwords = mbwords;  \
474                         while (bwords-- > 0) {  \
475                                 gsize _bmap = *bitmap_data++;   \
476                                 void **start_run = _objptr;     \
477                                 /*g_print ("bitmap: 0x%x\n", _bmap);*/  \
478                                 while (_bmap) { \
479                                         if ((_bmap & 1)) {      \
480                                                 HANDLE_PTR (_objptr, (obj));    \
481                                         }       \
482                                         _bmap >>= 1;    \
483                                         ++_objptr;      \
484                                 }       \
485                                 _objptr = start_run + GC_BITS_PER_WORD; \
486                         }       \
487                         e_start += el_size;     \
488                 }       \
489         } while (0)
490
491 #define OBJ_VECTOR_FOREACH_PTR(vt,obj)  do {    \
492                 /* note: 0xffffc000 excludes DESC_TYPE_V_PTRFREE */     \
493                 if ((vt)->desc & 0xffffc000) {  \
494                         int el_size = ((vt)->desc >> 3) & MAX_ELEMENT_SIZE;     \
495                         /* there are pointers */        \
496                         int etype = (vt)->desc & 0xc000;        \
497                         if (etype == (DESC_TYPE_V_REFS << 14)) {        \
498                                 void **p = (void**)((char*)(obj) + G_STRUCT_OFFSET (MonoArray, vector));        \
499                                 void **end_refs = (void**)((char*)p + el_size * mono_array_length_fast ((MonoArray*)(obj)));    \
500                                 /* Note: this code can handle also arrays of struct with only references in them */     \
501                                 while (p < end_refs) {  \
502                                         HANDLE_PTR (p, (obj));  \
503                                         ++p;    \
504                                 }       \
505                         } else if (etype == DESC_TYPE_V_RUN_LEN << 14) {        \
506                                 int offset = ((vt)->desc >> 16) & 0xff; \
507                                 int num_refs = ((vt)->desc >> 24) & 0xff;       \
508                                 char *e_start = (char*)(obj) + G_STRUCT_OFFSET (MonoArray, vector);     \
509                                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
510                                 while (e_start < e_end) {       \
511                                         void **p = (void**)e_start;     \
512                                         int i;  \
513                                         p += offset;    \
514                                         for (i = 0; i < num_refs; ++i) {        \
515                                                 HANDLE_PTR (p + i, (obj));      \
516                                         }       \
517                                         e_start += el_size;     \
518                                 }       \
519                         } else if (etype == DESC_TYPE_V_BITMAP << 14) { \
520                                 char *e_start = (char*)(obj) +  G_STRUCT_OFFSET (MonoArray, vector);    \
521                                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
522                                 while (e_start < e_end) {       \
523                                         void **p = (void**)e_start;     \
524                                         gsize _bmap = (vt)->desc >> 16; \
525                                         /* Note: there is no object header here to skip */      \
526                                         while (_bmap) { \
527                                                 if ((_bmap & 1)) {      \
528                                                         HANDLE_PTR (p, (obj));  \
529                                                 }       \
530                                                 _bmap >>= 1;    \
531                                                 ++p;    \
532                                         }       \
533                                         e_start += el_size;     \
534                                 }       \
535                         }       \
536                 }       \
537         } while (0)
538
539 #define SGEN_GRAY_QUEUE_SECTION_SIZE    (128 - 3)
540
541 /*
542  * This is a stack now instead of a queue, so the most recently added items are removed
543  * first, improving cache locality, and keeping the stack size manageable.
544  */
545 typedef struct _GrayQueueSection GrayQueueSection;
546 struct _GrayQueueSection {
547         int end;
548         GrayQueueSection *next;
549         char *objects [SGEN_GRAY_QUEUE_SECTION_SIZE];
550 };
551
552 typedef struct _SgenGrayQueue SgenGrayQueue;
553
554 typedef void (*GrayQueueAllocPrepareFunc) (SgenGrayQueue*);
555
556 struct _SgenGrayQueue {
557         GrayQueueSection *first;
558         GrayQueueSection *free_list;
559         int balance;
560         GrayQueueAllocPrepareFunc alloc_prepare_func;
561         void *alloc_prepare_data;
562 };
563
564 #if SGEN_MAX_DEBUG_LEVEL >= 9
565 #define GRAY_OBJECT_ENQUEUE gray_object_enqueue
566 #define GRAY_OBJECT_DEQUEUE(queue,o) ((o) = gray_object_dequeue ((queue)))
567 #else
568 #define GRAY_OBJECT_ENQUEUE(queue,o) do {                               \
569                 if (G_UNLIKELY (!(queue)->first || (queue)->first->end == SGEN_GRAY_QUEUE_SECTION_SIZE)) \
570                         mono_sgen_gray_object_enqueue ((queue), (o));   \
571                 else                                                    \
572                         (queue)->first->objects [(queue)->first->end++] = (o); \
573                 PREFETCH ((o));                                         \
574         } while (0)
575 #define GRAY_OBJECT_DEQUEUE(queue,o) do {                               \
576                 if (!(queue)->first)                                    \
577                         (o) = NULL;                                     \
578                 else if (G_UNLIKELY ((queue)->first->end == 1))         \
579                         (o) = mono_sgen_gray_object_dequeue ((queue));          \
580                 else                                                    \
581                         (o) = (queue)->first->objects [--(queue)->first->end]; \
582         } while (0)
583 #endif
584
585 void mono_sgen_gray_object_enqueue (SgenGrayQueue *queue, char *obj) MONO_INTERNAL;
586 char* mono_sgen_gray_object_dequeue (SgenGrayQueue *queue) MONO_INTERNAL;
587
588 typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
589
590 void* mono_sgen_alloc_os_memory (size_t size, int activate) MONO_INTERNAL;
591 void* mono_sgen_alloc_os_memory_aligned (mword size, mword alignment, gboolean activate) MONO_INTERNAL;
592 void mono_sgen_free_os_memory (void *addr, size_t size) MONO_INTERNAL;
593
594 int mono_sgen_thread_handshake (int signum) MONO_INTERNAL;
595 gboolean mono_sgen_suspend_thread (SgenThreadInfo *info) MONO_INTERNAL;
596 gboolean mono_sgen_resume_thread (SgenThreadInfo *info) MONO_INTERNAL;
597
598
599 void mono_sgen_wait_for_suspend_ack (int count) MONO_INTERNAL;
600
601 gboolean mono_sgen_is_worker_thread (pthread_t thread) MONO_INTERNAL;
602
603 void mono_sgen_update_heap_boundaries (mword low, mword high) MONO_INTERNAL;
604
605 void mono_sgen_register_major_sections_alloced (int num_sections) MONO_INTERNAL;
606 mword mono_sgen_get_minor_collection_allowance (void) MONO_INTERNAL;
607
608 void mono_sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags) MONO_INTERNAL;
609 void mono_sgen_check_section_scan_starts (GCMemSection *section) MONO_INTERNAL;
610
611 /* Keep in sync with mono_sgen_dump_internal_mem_usage() in dump_heap()! */
612 enum {
613         INTERNAL_MEM_PIN_QUEUE,
614         INTERNAL_MEM_FRAGMENT,
615         INTERNAL_MEM_SECTION,
616         INTERNAL_MEM_SCAN_STARTS,
617         INTERNAL_MEM_FIN_TABLE,
618         INTERNAL_MEM_FINALIZE_ENTRY,
619         INTERNAL_MEM_DISLINK_TABLE,
620         INTERNAL_MEM_DISLINK,
621         INTERNAL_MEM_ROOTS_TABLE,
622         INTERNAL_MEM_ROOT_RECORD,
623         INTERNAL_MEM_STATISTICS,
624         INTERNAL_MEM_REMSET,
625         INTERNAL_MEM_GRAY_QUEUE,
626         INTERNAL_MEM_STORE_REMSET,
627         INTERNAL_MEM_MS_TABLES,
628         INTERNAL_MEM_MS_BLOCK_INFO,
629         INTERNAL_MEM_EPHEMERON_LINK,
630         INTERNAL_MEM_WORKER_DATA,
631         INTERNAL_MEM_BRIDGE_DATA,
632         INTERNAL_MEM_JOB_QUEUE_ENTRY,
633         INTERNAL_MEM_MAX
634 };
635
636 #define SGEN_PINNED_FREELIST_NUM_SLOTS  30
637
638 typedef struct {
639         SgenPinnedChunk *chunk_list;
640         SgenPinnedChunk *free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
641         void *delayed_free_lists [SGEN_PINNED_FREELIST_NUM_SLOTS];
642 } SgenPinnedAllocator;
643
644 enum {
645         GENERATION_NURSERY,
646         GENERATION_OLD,
647         GENERATION_MAX
648 };
649
650 void mono_sgen_init_internal_allocator (void) MONO_INTERNAL;
651 void mono_sgen_init_pinned_allocator (void) MONO_INTERNAL;
652
653 void mono_sgen_report_internal_mem_usage (void) MONO_INTERNAL;
654 void mono_sgen_report_pinned_mem_usage (SgenPinnedAllocator *alc) MONO_INTERNAL;
655 void mono_sgen_dump_internal_mem_usage (FILE *heap_dump_file) MONO_INTERNAL;
656 void mono_sgen_dump_section (GCMemSection *section, const char *type) MONO_INTERNAL;
657 void mono_sgen_dump_occupied (char *start, char *end, char *section_start) MONO_INTERNAL;
658
659 void mono_sgen_register_moved_object (void *obj, void *destination) MONO_INTERNAL;
660
661 void mono_sgen_register_fixed_internal_mem_type (int type, size_t size) MONO_INTERNAL;
662
663 void* mono_sgen_alloc_internal (int type) MONO_INTERNAL;
664 void mono_sgen_free_internal (void *addr, int type) MONO_INTERNAL;
665
666 void* mono_sgen_alloc_internal_dynamic (size_t size, int type) MONO_INTERNAL;
667 void mono_sgen_free_internal_dynamic (void *addr, size_t size, int type) MONO_INTERNAL;
668
669 void* mono_sgen_alloc_pinned (SgenPinnedAllocator *allocator, size_t size) MONO_INTERNAL;
670 void mono_sgen_free_pinned (SgenPinnedAllocator *allocator, void *addr, size_t size) MONO_INTERNAL;
671
672
673 void mono_sgen_debug_printf (int level, const char *format, ...) MONO_INTERNAL;
674
675 gboolean mono_sgen_parse_environment_string_extract_number (const char *str, glong *out) MONO_INTERNAL;
676
677 void mono_sgen_pinned_scan_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
678 void mono_sgen_pinned_scan_pinned_objects (SgenPinnedAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
679
680 void mono_sgen_pinned_update_heap_boundaries (SgenPinnedAllocator *alc) MONO_INTERNAL;
681
682 void** mono_sgen_find_optimized_pin_queue_area (void *start, void *end, int *num) MONO_INTERNAL;
683 void mono_sgen_find_section_pin_queue_start_end (GCMemSection *section) MONO_INTERNAL;
684 void mono_sgen_pin_objects_in_section (GCMemSection *section, SgenGrayQueue *queue) MONO_INTERNAL;
685
686 void mono_sgen_pin_stats_register_object (char *obj, size_t size);
687
688 void mono_sgen_add_to_global_remset (gpointer ptr) MONO_INTERNAL;
689
690 int mono_sgen_get_current_collection_generation (void) MONO_INTERNAL;
691
692 typedef void (*sgen_cardtable_block_callback) (mword start, mword size);
693
694 typedef struct _SgenMajorCollector SgenMajorCollector;
695 struct _SgenMajorCollector {
696         size_t section_size;
697         gboolean is_parallel;
698         gboolean supports_cardtable;
699
700         /*
701          * This is set to TRUE if the sweep for the last major
702          * collection has been completed.
703          */
704         gboolean *have_swept;
705
706         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
707         gboolean (*is_object_live) (char *obj);
708         void* (*alloc_small_pinned_obj) (size_t size, gboolean has_references);
709         void* (*alloc_degraded) (MonoVTable *vtable, size_t size);
710         void (*copy_or_mark_object) (void **obj_slot, SgenGrayQueue *queue);
711         void (*minor_scan_object) (char *start, SgenGrayQueue *queue);
712         char* (*minor_scan_vtype) (char *start, mword desc, char* from_start, char* from_end, SgenGrayQueue *queue);
713         void (*major_scan_object) (char *start, SgenGrayQueue *queue);
714         void (*copy_object) (void **obj_slot, SgenGrayQueue *queue);
715         void* (*alloc_object) (int size, gboolean has_references);
716         void (*free_pinned_object) (char *obj, size_t size);
717         void (*iterate_objects) (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data);
718         void (*free_non_pinned_object) (char *obj, size_t size);
719         void (*find_pin_queue_start_ends) (SgenGrayQueue *queue);
720         void (*pin_objects) (SgenGrayQueue *queue);
721         void (*scan_card_table) (SgenGrayQueue *queue);
722         void (*iterate_live_block_ranges) (sgen_cardtable_block_callback callback);
723         void (*init_to_space) (void);
724         void (*sweep) (void);
725         void (*check_scan_starts) (void);
726         void (*dump_heap) (FILE *heap_dump_file);
727         gint64 (*get_used_size) (void);
728         void (*start_nursery_collection) (void);
729         void (*finish_nursery_collection) (void);
730         void (*start_major_collection) (void);
731         void (*finish_major_collection) (void);
732         void (*have_computed_minor_collection_allowance) (void);
733         gboolean (*ptr_is_in_non_pinned_space) (char *ptr);
734         gboolean (*obj_is_from_pinned_alloc) (char *obj);
735         void (*report_pinned_memory_usage) (void);
736         int (*get_num_major_sections) (void);
737         gboolean (*handle_gc_param) (const char *opt);
738         void (*print_gc_param_usage) (void);
739         gboolean (*is_worker_thread) (pthread_t thread);
740         void (*post_param_init) (void);
741         void* (*alloc_worker_data) (void);
742         void (*init_worker_thread) (void *data);
743         void (*reset_worker_data) (void *data);
744 };
745
746 void mono_sgen_marksweep_init (SgenMajorCollector *collector) MONO_INTERNAL;
747 void mono_sgen_marksweep_fixed_init (SgenMajorCollector *collector) MONO_INTERNAL;
748 void mono_sgen_marksweep_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
749 void mono_sgen_marksweep_fixed_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
750 void mono_sgen_copying_init (SgenMajorCollector *collector) MONO_INTERNAL;
751
752 /*
753  * This function can be called on an object whose first word, the
754  * vtable field, is not intact.  This is necessary for the parallel
755  * collector.
756  */
757 static inline guint
758 mono_sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
759 {
760         MonoClass *klass = vtable->klass;
761         /*
762          * We depend on mono_string_length_fast and
763          * mono_array_length_fast not using the object's vtable.
764          */
765         if (klass == mono_defaults.string_class) {
766                 return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
767         } else if (klass->rank) {
768                 MonoArray *array = (MonoArray*)o;
769                 size_t size = sizeof (MonoArray) + klass->sizes.element_size * mono_array_length_fast (array);
770                 if (G_UNLIKELY (array->bounds)) {
771                         size += sizeof (mono_array_size_t) - 1;
772                         size &= ~(sizeof (mono_array_size_t) - 1);
773                         size += sizeof (MonoArrayBounds) * klass->rank;
774                 }
775                 return size;
776         } else {
777                 /* from a created object: the class must be inited already */
778                 return klass->instance_size;
779         }
780 }
781
782 #define mono_sgen_safe_object_get_size(o)               mono_sgen_par_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE ((o)), (o))
783
784 const char* mono_sgen_safe_name (void* obj) MONO_INTERNAL;
785
786 gboolean mono_sgen_object_is_live (void *obj) MONO_INTERNAL;
787
788 gboolean mono_sgen_need_bridge_processing (void) MONO_INTERNAL;
789 void mono_sgen_bridge_processing (int num_objs, MonoObject **objs) MONO_INTERNAL;
790 void mono_sgen_register_test_bridge_callbacks (void) MONO_INTERNAL;
791
792 enum {
793         SPACE_MAJOR,
794         SPACE_LOS
795 };
796
797 gboolean mono_sgen_try_alloc_space (mword size, int space) MONO_INTERNAL;
798 void mono_sgen_release_space (mword size, int space) MONO_INTERNAL;
799 void mono_sgen_pin_object (void *object, SgenGrayQueue *queue) MONO_INTERNAL;
800 void sgen_collect_major_no_lock (const char *reason) MONO_INTERNAL;
801 gboolean mono_sgen_need_major_collection (mword space_needed) MONO_INTERNAL;
802
803 /* LOS */
804
805 typedef struct _LOSObject LOSObject;
806 struct _LOSObject {
807         LOSObject *next;
808         mword size; /* this is the object size */
809         guint16 huge_object;
810         int dummy; /* to have a sizeof (LOSObject) a multiple of ALLOC_ALIGN  and data starting at same alignment */
811         char data [MONO_ZERO_LEN_ARRAY];
812 };
813
814 #define ARRAY_OBJ_INDEX(ptr,array,elem_size) (((char*)(ptr) - ((char*)(array) + G_STRUCT_OFFSET (MonoArray, vector))) / (elem_size))
815
816 extern LOSObject *los_object_list;
817 extern mword los_memory_usage;
818 extern mword last_los_memory_usage;
819
820 void mono_sgen_los_free_object (LOSObject *obj) MONO_INTERNAL;
821 void* mono_sgen_los_alloc_large_inner (MonoVTable *vtable, size_t size) MONO_INTERNAL;
822 void mono_sgen_los_sweep (void) MONO_INTERNAL;
823 gboolean mono_sgen_ptr_is_in_los (char *ptr, char **start) MONO_INTERNAL;
824 void mono_sgen_los_iterate_objects (IterateObjectCallbackFunc cb, void *user_data) MONO_INTERNAL;
825 void mono_sgen_los_iterate_live_block_ranges (sgen_cardtable_block_callback callback) MONO_INTERNAL;
826 void mono_sgen_los_scan_card_table (SgenGrayQueue *queue) MONO_INTERNAL;
827 FILE *mono_sgen_get_logfile (void) MONO_INTERNAL;
828
829 #endif /* HAVE_SGEN_GC */
830
831 #endif /* __MONO_SGENGC_H__ */