Make sgen compile on OpenBSD, by adding the missing stuff
[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 #include <glib.h>
30 #include <pthread.h>
31 #include <signal.h>
32 #include <mono/utils/mono-compiler.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/object-internals.h>
35
36 /*
37  * Turning on heavy statistics will turn off the managed allocator and
38  * the managed write barrier.
39  */
40 //#define HEAVY_STATISTICS
41
42 /*
43  * If this is set, the nursery is aligned to an address aligned to its size, ie.
44  * a 1MB nursery will be aligned to an address divisible by 1MB. This allows us to
45  * speed up ptr_in_nursery () checks which are very frequent. This requires the
46  * nursery size to be a compile time constant.
47  */
48 #define SGEN_ALIGN_NURSERY 1
49
50 //#define SGEN_BINARY_PROTOCOL
51
52 #if SIZEOF_VOID_P == 4
53 #define SGEN_HAVE_CARDTABLE     1
54 #endif
55
56 #define SGEN_MAX_DEBUG_LEVEL 2
57
58 #define THREAD_HASH_SIZE 11
59
60 #define GC_BITS_PER_WORD (sizeof (mword) * 8)
61
62 #define ARCH_THREAD_TYPE pthread_t
63 #define ARCH_GET_THREAD pthread_self
64 #define ARCH_THREAD_EQUALS(a,b) pthread_equal (a, b)
65
66 #if SIZEOF_VOID_P == 4
67 typedef guint32 mword;
68 #else
69 typedef guint64 mword;
70 #endif
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 /* eventually share with MonoThread? */
82 typedef struct _SgenThreadInfo SgenThreadInfo;
83
84 struct _SgenThreadInfo {
85         SgenThreadInfo *next;
86         ARCH_THREAD_TYPE id;
87         unsigned int stop_count; /* to catch duplicate signals */
88         int signal;
89         int skip;
90         volatile int in_critical_region;
91         void *stack_end;
92         void *stack_start;
93         void *stack_start_limit;
94         char **tlab_next_addr;
95         char **tlab_start_addr;
96         char **tlab_temp_end_addr;
97         char **tlab_real_end_addr;
98         gpointer **store_remset_buffer_addr;
99         long *store_remset_buffer_index_addr;
100         RememberedSet *remset;
101         gpointer runtime_data;
102         gpointer stopped_ip;    /* only valid if the thread is stopped */
103         MonoDomain *stopped_domain; /* ditto */
104         gpointer *stopped_regs;     /* ditto */
105 #ifndef HAVE_KW_THREAD
106         char *tlab_start;
107         char *tlab_next;
108         char *tlab_temp_end;
109         char *tlab_real_end;
110         gpointer *store_remset_buffer;
111         long store_remset_buffer_index;
112 #endif
113 };
114
115 enum {
116         MEMORY_ROLE_GEN0,
117         MEMORY_ROLE_GEN1,
118         MEMORY_ROLE_PINNED,
119         MEMORY_ROLE_INTERNAL
120 };
121
122 typedef struct _SgenBlock SgenBlock;
123 struct _SgenBlock {
124         void *next;
125         unsigned char role;
126 };
127
128 /*
129  * The nursery section and the major copying collector's sections use
130  * this struct.
131  */
132 typedef struct _GCMemSection GCMemSection;
133 struct _GCMemSection {
134         SgenBlock block;
135         char *data;
136         mword size;
137         /* pointer where more data could be allocated if it fits */
138         char *next_data;
139         char *end_data;
140         /*
141          * scan starts is an array of pointers to objects equally spaced in the allocation area
142          * They let use quickly find pinned objects from pinning pointers.
143          */
144         char **scan_starts;
145         /* in major collections indexes in the pin_queue for objects that pin this section */
146         void **pin_queue_start;
147         int pin_queue_num_entries;
148         unsigned short num_scan_start;
149         gboolean is_to_space;
150 };
151
152 #define SGEN_SIZEOF_GC_MEM_SECTION      ((sizeof (GCMemSection) + 7) & ~7)
153
154 /*
155  * to quickly find the head of an object pinned by a conservative
156  * address we keep track of the objects allocated for each
157  * SGEN_SCAN_START_SIZE memory chunk in the nursery or other memory
158  * sections. Larger values have less memory overhead and bigger
159  * runtime cost. 4-8 KB are reasonable values.
160  */
161 #define SGEN_SCAN_START_SIZE (4096*2)
162
163 /*
164  * Objects bigger then this go into the large object space.  This size
165  * has a few constraints.  It must fit into the major heap, which in
166  * the case of the copying collector means that it must fit into a
167  * pinned chunk.  It must also play well with the GC descriptors, some
168  * of which (DESC_TYPE_RUN_LENGTH, DESC_TYPE_SMALL_BITMAP) encode the
169  * object size.
170  */
171 #define SGEN_MAX_SMALL_OBJ_SIZE 8000
172
173 /* This is also the MAJOR_SECTION_SIZE for the copying major
174    collector */
175 #define SGEN_PINNED_CHUNK_SIZE  (128 * 1024)
176
177 #define SGEN_PINNED_CHUNK_FOR_PTR(o)    ((SgenBlock*)(((mword)(o)) & ~(SGEN_PINNED_CHUNK_SIZE - 1)))
178
179 typedef struct _SgenPinnedChunk SgenPinnedChunk;
180
181 #if defined(__APPLE__) || defined(__OpenBSD__)
182 const static int suspend_signal_num = SIGXFSZ;
183 #else
184 const static int suspend_signal_num = SIGPWR;
185 #endif
186 const static int restart_signal_num = SIGXCPU;
187
188 /*
189  * Recursion is not allowed for the thread lock.
190  */
191 #define LOCK_DECLARE(name) pthread_mutex_t name = PTHREAD_MUTEX_INITIALIZER
192 #define LOCK_INIT(name)
193 #define LOCK_GC pthread_mutex_lock (&gc_mutex)
194 #define UNLOCK_GC pthread_mutex_unlock (&gc_mutex)
195 #define LOCK_INTERRUPTION pthread_mutex_lock (&interruption_mutex)
196 #define UNLOCK_INTERRUPTION pthread_mutex_unlock (&interruption_mutex)
197
198 #define SGEN_CAS_PTR    InterlockedCompareExchangePointer
199 #define SGEN_ATOMIC_ADD(x,i)    do {                                    \
200                 int __old_x;                                            \
201                 do {                                                    \
202                         __old_x = (x);                                  \
203                 } while (InterlockedCompareExchange (&(x), __old_x + (i), __old_x) != __old_x); \
204         } while (0)
205
206 /* non-pthread will need to provide their own version of start/stop */
207 #define USE_SIGNAL_BASED_START_STOP_WORLD 1
208 /* we intercept pthread_create calls to know which threads exist */
209 #define USE_PTHREAD_INTERCEPT 1
210
211 #ifdef HEAVY_STATISTICS
212 #define HEAVY_STAT(x)   x
213
214 extern long long stat_objects_alloced_degraded;
215 extern long long stat_bytes_alloced_degraded;
216 extern long long stat_copy_object_called_major;
217 extern long long stat_objects_copied_major;
218 #else
219 #define HEAVY_STAT(x)
220 #endif
221
222 #define SGEN_ALLOC_ALIGN                8
223 #define SGEN_ALLOC_ALIGN_BITS   3
224
225 #define SGEN_ALIGN_UP(s)                (((s)+(SGEN_ALLOC_ALIGN-1)) & ~(SGEN_ALLOC_ALIGN-1))
226
227 #ifdef SGEN_ALIGN_NURSERY
228 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   (((mword)(p) & ~((1 << (bits)) - 1)) == (mword)(start))
229 #else
230 #define SGEN_PTR_IN_NURSERY(p,bits,start,end)   ((char*)(p) >= (start) && (char*)(p) < (end))
231 #endif
232
233 /* Structure that corresponds to a MonoVTable: desc is a mword so requires
234  * no cast from a pointer to an integer
235  */
236 typedef struct {
237         MonoClass *klass;
238         mword desc;
239 } GCVTable;
240
241 /* these bits are set in the object vtable: we could merge them since an object can be
242  * either pinned or forwarded but not both.
243  * We store them in the vtable slot because the bits are used in the sync block for
244  * other purposes: if we merge them and alloc the sync blocks aligned to 8 bytes, we can change
245  * this and use bit 3 in the syncblock (with the lower two bits both set for forwarded, that
246  * would be an invalid combination for the monitor and hash code).
247  * The values are already shifted.
248  * The forwarding address is stored in the sync block.
249  */
250 #define SGEN_FORWARDED_BIT 1
251 #define SGEN_PINNED_BIT 2
252 #define SGEN_VTABLE_BITS_MASK 0x3
253
254 /* returns NULL if not forwarded, or the forwarded address */
255 #define SGEN_OBJECT_IS_FORWARDED(obj) (((mword*)(obj))[0] & SGEN_FORWARDED_BIT ? (void*)(((mword*)(obj))[0] & ~SGEN_VTABLE_BITS_MASK) : NULL)
256 #define SGEN_OBJECT_IS_PINNED(obj) (((mword*)(obj))[0] & SGEN_PINNED_BIT)
257
258 /* set the forwarded address fw_addr for object obj */
259 #define SGEN_FORWARD_OBJECT(obj,fw_addr) do {                           \
260                 ((mword*)(obj))[0] = (mword)(fw_addr) | SGEN_FORWARDED_BIT; \
261         } while (0)
262 #define SGEN_PIN_OBJECT(obj) do {       \
263                 ((mword*)(obj))[0] |= SGEN_PINNED_BIT;  \
264         } while (0)
265 #define SGEN_UNPIN_OBJECT(obj) do {     \
266                 ((mword*)(obj))[0] &= ~SGEN_PINNED_BIT; \
267         } while (0)
268
269 /*
270  * Since we set bits in the vtable, use the macro to load it from the pointer to
271  * an object that is potentially pinned.
272  */
273 #define SGEN_LOAD_VTABLE(addr) ((*(mword*)(addr)) & ~SGEN_VTABLE_BITS_MASK)
274
275 /*
276  * ######################################################################
277  * ########  GC descriptors
278  * ######################################################################
279  * Used to quickly get the info the GC needs about an object: size and
280  * where the references are held.
281  */
282 #define OBJECT_HEADER_WORDS (sizeof(MonoObject)/sizeof(gpointer))
283 #define LOW_TYPE_BITS 3
284 #define SMALL_BITMAP_SHIFT 16
285 #define SMALL_BITMAP_SIZE (GC_BITS_PER_WORD - SMALL_BITMAP_SHIFT)
286 #define VECTOR_INFO_SHIFT 14
287 #define VECTOR_ELSIZE_SHIFT 3
288 #define LARGE_BITMAP_SIZE (GC_BITS_PER_WORD - LOW_TYPE_BITS)
289 #define MAX_ELEMENT_SIZE 0x3ff
290 #define VECTOR_SUBTYPE_PTRFREE (DESC_TYPE_V_PTRFREE << VECTOR_INFO_SHIFT)
291 #define VECTOR_SUBTYPE_REFS    (DESC_TYPE_V_REFS << VECTOR_INFO_SHIFT)
292 #define VECTOR_SUBTYPE_RUN_LEN (DESC_TYPE_V_RUN_LEN << VECTOR_INFO_SHIFT)
293 #define VECTOR_SUBTYPE_BITMAP  (DESC_TYPE_V_BITMAP << VECTOR_INFO_SHIFT)
294
295 /* objects are aligned to 8 bytes boundaries
296  * A descriptor is a pointer in MonoVTable, so 32 or 64 bits of size.
297  * The low 3 bits define the type of the descriptor. The other bits
298  * depend on the type.
299  * As a general rule the 13 remaining low bits define the size, either
300  * of the whole object or of the elements in the arrays. While for objects
301  * the size is already in bytes, for arrays we need to shift, because
302  * array elements might be smaller than 8 bytes. In case of arrays, we
303  * use two bits to describe what the additional high bits represents,
304  * so the default behaviour can handle element sizes less than 2048 bytes.
305  * The high 16 bits, if 0 it means the object is pointer-free.
306  * This design should make it easy and fast to skip over ptr-free data.
307  * The first 4 types should cover >95% of the objects.
308  * Note that since the size of objects is limited to 64K, larger objects
309  * will be allocated in the large object heap.
310  * If we want 4-bytes alignment, we need to put vector and small bitmap
311  * inside complex.
312  */
313 enum {
314         /*
315          * We don't use 0 so that 0 isn't a valid GC descriptor.  No
316          * deep reason for this other than to be able to identify a
317          * non-inited descriptor for debugging.
318          *
319          * If an object contains no references, its GC descriptor is
320          * always DESC_TYPE_RUN_LENGTH, without a size, no exceptions.
321          * This is so that we can quickly check for that in
322          * copy_object_no_checks(), without having to fetch the
323          * object's class.
324          */
325         DESC_TYPE_RUN_LENGTH = 1, /* 15 bits aligned byte size | 1-3 (offset, numptr) bytes tuples */
326         DESC_TYPE_SMALL_BITMAP, /* 15 bits aligned byte size | 16-48 bit bitmap */
327         DESC_TYPE_COMPLEX,      /* index for bitmap into complex_descriptors */
328         DESC_TYPE_VECTOR,       /* 10 bits element size | 1 bit array | 2 bits desc | element desc */
329         DESC_TYPE_ARRAY,        /* 10 bits element size | 1 bit array | 2 bits desc | element desc */
330         DESC_TYPE_LARGE_BITMAP, /* | 29-61 bitmap bits */
331         DESC_TYPE_COMPLEX_ARR,  /* index for bitmap into complex_descriptors */
332         /* subtypes for arrays and vectors */
333         DESC_TYPE_V_PTRFREE = 0,/* there are no refs: keep first so it has a zero value  */
334         DESC_TYPE_V_REFS,       /* all the array elements are refs */
335         DESC_TYPE_V_RUN_LEN,    /* elements are run-length encoded as DESC_TYPE_RUN_LENGTH */
336         DESC_TYPE_V_BITMAP      /* elements are as the bitmap in DESC_TYPE_SMALL_BITMAP */
337 };
338
339 #define SGEN_VTABLE_HAS_REFERENCES(vt)  (((MonoVTable*)(vt))->gc_descr != (void*)DESC_TYPE_RUN_LENGTH)
340
341 /* helper macros to scan and traverse objects, macros because we resue them in many functions */
342 #define OBJ_RUN_LEN_SIZE(size,desc,obj) do { \
343                 (size) = ((desc) & 0xfff8) >> 1;        \
344     } while (0)
345
346 #define OBJ_BITMAP_SIZE(size,desc,obj) do { \
347                 (size) = ((desc) & 0xfff8) >> 1;        \
348     } while (0)
349
350 //#define PREFETCH(addr) __asm__ __volatile__ ("     prefetchnta     %0": : "m"(*(char *)(addr)))
351 #define PREFETCH(addr)
352
353 /* code using these macros must define a HANDLE_PTR(ptr) macro that does the work */
354 #define OBJ_RUN_LEN_FOREACH_PTR(desc,obj)       do {    \
355                 if ((desc) & 0xffff0000) {      \
356                         /* there are pointers */        \
357                         void **_objptr_end;     \
358                         void **_objptr = (void**)(obj); \
359                         _objptr += ((desc) >> 16) & 0xff;       \
360                         _objptr_end = _objptr + (((desc) >> 24) & 0xff);        \
361                         while (_objptr < _objptr_end) { \
362                                 HANDLE_PTR (_objptr, (obj));    \
363                                 _objptr++;      \
364                         }       \
365                 }       \
366         } while (0)
367
368 /* a bitmap desc means that there are pointer references or we'd have
369  * choosen run-length, instead: add an assert to check.
370  */
371 #define OBJ_BITMAP_FOREACH_PTR(desc,obj)        do {    \
372                 /* there are pointers */        \
373                 void **_objptr = (void**)(obj); \
374                 gsize _bmap = (desc) >> 16;     \
375                 _objptr += OBJECT_HEADER_WORDS; \
376                 while (_bmap) { \
377                         if ((_bmap & 1)) {      \
378                                 HANDLE_PTR (_objptr, (obj));    \
379                         }       \
380                         _bmap >>= 1;    \
381                         ++_objptr;      \
382                 }       \
383         } while (0)
384
385 #define OBJ_LARGE_BITMAP_FOREACH_PTR(vt,obj)    do {    \
386                 /* there are pointers */        \
387                 void **_objptr = (void**)(obj); \
388                 gsize _bmap = (vt)->desc >> LOW_TYPE_BITS;      \
389                 _objptr += OBJECT_HEADER_WORDS; \
390                 while (_bmap) { \
391                         if ((_bmap & 1)) {      \
392                                 HANDLE_PTR (_objptr, (obj));    \
393                         }       \
394                         _bmap >>= 1;    \
395                         ++_objptr;      \
396                 }       \
397         } while (0)
398
399 gsize* mono_sgen_get_complex_descriptor (GCVTable *vt) MONO_INTERNAL;
400
401 #define OBJ_COMPLEX_FOREACH_PTR(vt,obj) do {    \
402                 /* there are pointers */        \
403                 void **_objptr = (void**)(obj); \
404                 gsize *bitmap_data = mono_sgen_get_complex_descriptor ((vt)); \
405                 int bwords = (*bitmap_data) - 1;        \
406                 void **start_run = _objptr;     \
407                 bitmap_data++;  \
408                 if (0) {        \
409                         MonoObject *myobj = (MonoObject*)obj;   \
410                         g_print ("found %d at %p (0x%zx): %s.%s\n", bwords, (obj), (vt)->desc, myobj->vtable->klass->name_space, myobj->vtable->klass->name);   \
411                 }       \
412                 while (bwords-- > 0) {  \
413                         gsize _bmap = *bitmap_data++;   \
414                         _objptr = start_run;    \
415                         /*g_print ("bitmap: 0x%x/%d at %p\n", _bmap, bwords, _objptr);*/        \
416                         while (_bmap) { \
417                                 if ((_bmap & 1)) {      \
418                                         HANDLE_PTR (_objptr, (obj));    \
419                                 }       \
420                                 _bmap >>= 1;    \
421                                 ++_objptr;      \
422                         }       \
423                         start_run += GC_BITS_PER_WORD;  \
424                 }       \
425         } while (0)
426
427 /* this one is untested */
428 #define OBJ_COMPLEX_ARR_FOREACH_PTR(vt,obj)     do {    \
429                 /* there are pointers */        \
430                 gsize *mbitmap_data = mono_sgen_get_complex_descriptor ((vt)); \
431                 int mbwords = (*mbitmap_data++) - 1;    \
432                 int el_size = mono_array_element_size (vt->klass);      \
433                 char *e_start = (char*)(obj) +  G_STRUCT_OFFSET (MonoArray, vector);    \
434                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
435                 if (0)                                                  \
436                         g_print ("found %d at %p (0x%zx): %s.%s\n", mbwords, (obj), (vt)->desc, vt->klass->name_space, vt->klass->name); \
437                 while (e_start < e_end) {       \
438                         void **_objptr = (void**)e_start;       \
439                         gsize *bitmap_data = mbitmap_data;      \
440                         unsigned int bwords = mbwords;  \
441                         while (bwords-- > 0) {  \
442                                 gsize _bmap = *bitmap_data++;   \
443                                 void **start_run = _objptr;     \
444                                 /*g_print ("bitmap: 0x%x\n", _bmap);*/  \
445                                 while (_bmap) { \
446                                         if ((_bmap & 1)) {      \
447                                                 HANDLE_PTR (_objptr, (obj));    \
448                                         }       \
449                                         _bmap >>= 1;    \
450                                         ++_objptr;      \
451                                 }       \
452                                 _objptr = start_run + GC_BITS_PER_WORD; \
453                         }       \
454                         e_start += el_size;     \
455                 }       \
456         } while (0)
457
458 #define OBJ_VECTOR_FOREACH_PTR(vt,obj)  do {    \
459                 /* note: 0xffffc000 excludes DESC_TYPE_V_PTRFREE */     \
460                 if ((vt)->desc & 0xffffc000) {  \
461                         int el_size = ((vt)->desc >> 3) & MAX_ELEMENT_SIZE;     \
462                         /* there are pointers */        \
463                         int etype = (vt)->desc & 0xc000;        \
464                         if (etype == (DESC_TYPE_V_REFS << 14)) {        \
465                                 void **p = (void**)((char*)(obj) + G_STRUCT_OFFSET (MonoArray, vector));        \
466                                 void **end_refs = (void**)((char*)p + el_size * mono_array_length_fast ((MonoArray*)(obj)));    \
467                                 /* Note: this code can handle also arrays of struct with only references in them */     \
468                                 while (p < end_refs) {  \
469                                         HANDLE_PTR (p, (obj));  \
470                                         ++p;    \
471                                 }       \
472                         } else if (etype == DESC_TYPE_V_RUN_LEN << 14) {        \
473                                 int offset = ((vt)->desc >> 16) & 0xff; \
474                                 int num_refs = ((vt)->desc >> 24) & 0xff;       \
475                                 char *e_start = (char*)(obj) + G_STRUCT_OFFSET (MonoArray, vector);     \
476                                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
477                                 while (e_start < e_end) {       \
478                                         void **p = (void**)e_start;     \
479                                         int i;  \
480                                         p += offset;    \
481                                         for (i = 0; i < num_refs; ++i) {        \
482                                                 HANDLE_PTR (p + i, (obj));      \
483                                         }       \
484                                         e_start += el_size;     \
485                                 }       \
486                         } else if (etype == DESC_TYPE_V_BITMAP << 14) { \
487                                 char *e_start = (char*)(obj) +  G_STRUCT_OFFSET (MonoArray, vector);    \
488                                 char *e_end = e_start + el_size * mono_array_length_fast ((MonoArray*)(obj));   \
489                                 while (e_start < e_end) {       \
490                                         void **p = (void**)e_start;     \
491                                         gsize _bmap = (vt)->desc >> 16; \
492                                         /* Note: there is no object header here to skip */      \
493                                         while (_bmap) { \
494                                                 if ((_bmap & 1)) {      \
495                                                         HANDLE_PTR (p, (obj));  \
496                                                 }       \
497                                                 _bmap >>= 1;    \
498                                                 ++p;    \
499                                         }       \
500                                         e_start += el_size;     \
501                                 }       \
502                         }       \
503                 }       \
504         } while (0)
505
506 typedef struct _SgenInternalAllocator SgenInternalAllocator;
507
508 #define SGEN_GRAY_QUEUE_SECTION_SIZE    (128 - 3)
509
510 /*
511  * This is a stack now instead of a queue, so the most recently added items are removed
512  * first, improving cache locality, and keeping the stack size manageable.
513  */
514 typedef struct _GrayQueueSection GrayQueueSection;
515 struct _GrayQueueSection {
516         int end;
517         GrayQueueSection *next;
518         char *objects [SGEN_GRAY_QUEUE_SECTION_SIZE];
519 };
520
521 typedef struct _SgenGrayQueue SgenGrayQueue;
522
523 typedef void (*GrayQueueAllocPrepareFunc) (SgenGrayQueue*);
524
525 struct _SgenGrayQueue {
526         SgenInternalAllocator *allocator;
527         GrayQueueSection *first;
528         GrayQueueSection *free_list;
529         int balance;
530         GrayQueueAllocPrepareFunc alloc_prepare_func;
531         void *alloc_prepare_data;
532 };
533
534 #if SGEN_MAX_DEBUG_LEVEL >= 9
535 #define GRAY_OBJECT_ENQUEUE gray_object_enqueue
536 #define GRAY_OBJECT_DEQUEUE(queue,o) ((o) = gray_object_dequeue ((queue)))
537 #else
538 #define GRAY_OBJECT_ENQUEUE(queue,o) do {                               \
539                 if (G_UNLIKELY (!(queue)->first || (queue)->first->end == SGEN_GRAY_QUEUE_SECTION_SIZE)) \
540                         mono_sgen_gray_object_enqueue ((queue), (o));   \
541                 else                                                    \
542                         (queue)->first->objects [(queue)->first->end++] = (o); \
543         } while (0)
544 #define GRAY_OBJECT_DEQUEUE(queue,o) do {                               \
545                 if (!(queue)->first)                                    \
546                         (o) = NULL;                                     \
547                 else if (G_UNLIKELY ((queue)->first->end == 1))         \
548                         (o) = mono_sgen_gray_object_dequeue ((queue));          \
549                 else                                                    \
550                         (o) = (queue)->first->objects [--(queue)->first->end]; \
551         } while (0)
552 #endif
553
554 void mono_sgen_gray_object_enqueue (SgenGrayQueue *queue, char *obj) MONO_INTERNAL;
555 char* mono_sgen_gray_object_dequeue (SgenGrayQueue *queue) MONO_INTERNAL;
556
557 typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
558
559 void* mono_sgen_alloc_os_memory (size_t size, int activate) MONO_INTERNAL;
560 void* mono_sgen_alloc_os_memory_aligned (mword size, mword alignment, gboolean activate) MONO_INTERNAL;
561 void mono_sgen_free_os_memory (void *addr, size_t size) MONO_INTERNAL;
562
563 int mono_sgen_thread_handshake (int signum) MONO_INTERNAL;
564 SgenThreadInfo* mono_sgen_thread_info_lookup (ARCH_THREAD_TYPE id) MONO_INTERNAL;
565 SgenThreadInfo** mono_sgen_get_thread_table (void) MONO_INTERNAL;
566 void mono_sgen_wait_for_suspend_ack (int count) MONO_INTERNAL;
567
568 gboolean mono_sgen_is_worker_thread (pthread_t thread) MONO_INTERNAL;
569
570 void mono_sgen_update_heap_boundaries (mword low, mword high) MONO_INTERNAL;
571
572 void mono_sgen_register_major_sections_alloced (int num_sections) MONO_INTERNAL;
573 mword mono_sgen_get_minor_collection_allowance (void) MONO_INTERNAL;
574
575 void mono_sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data) MONO_INTERNAL;
576 void mono_sgen_check_section_scan_starts (GCMemSection *section) MONO_INTERNAL;
577
578 /* Keep in sync with mono_sgen_dump_internal_mem_usage() in dump_heap()! */
579 enum {
580         INTERNAL_MEM_MANAGED,
581         INTERNAL_MEM_PIN_QUEUE,
582         INTERNAL_MEM_FRAGMENT,
583         INTERNAL_MEM_SECTION,
584         INTERNAL_MEM_SCAN_STARTS,
585         INTERNAL_MEM_FIN_TABLE,
586         INTERNAL_MEM_FINALIZE_ENTRY,
587         INTERNAL_MEM_DISLINK_TABLE,
588         INTERNAL_MEM_DISLINK,
589         INTERNAL_MEM_ROOTS_TABLE,
590         INTERNAL_MEM_ROOT_RECORD,
591         INTERNAL_MEM_STATISTICS,
592         INTERNAL_MEM_REMSET,
593         INTERNAL_MEM_GRAY_QUEUE,
594         INTERNAL_MEM_STORE_REMSET,
595         INTERNAL_MEM_MS_TABLES,
596         INTERNAL_MEM_MS_BLOCK_INFO,
597         INTERNAL_MEM_EPHEMERON_LINK,
598         INTERNAL_MEM_WORKER_DATA,
599         INTERNAL_MEM_MAX
600 };
601
602 #define SGEN_INTERNAL_FREELIST_NUM_SLOTS        30
603
604 struct _SgenInternalAllocator {
605         SgenPinnedChunk *chunk_list;
606         SgenPinnedChunk *free_lists [SGEN_INTERNAL_FREELIST_NUM_SLOTS];
607         void *delayed_free_lists [SGEN_INTERNAL_FREELIST_NUM_SLOTS];
608         long small_internal_mem_bytes [INTERNAL_MEM_MAX];
609 };
610
611 void mono_sgen_init_internal_allocator (void) MONO_INTERNAL;
612
613 SgenInternalAllocator* mono_sgen_get_unmanaged_allocator (void) MONO_INTERNAL;
614
615 const char* mono_sgen_internal_mem_type_name (int type) MONO_INTERNAL;
616 void mono_sgen_report_internal_mem_usage (void) MONO_INTERNAL;
617 void mono_sgen_report_internal_mem_usage_full (SgenInternalAllocator *alc) MONO_INTERNAL;
618 void mono_sgen_dump_internal_mem_usage (FILE *heap_dump_file) MONO_INTERNAL;
619 void mono_sgen_dump_section (GCMemSection *section, const char *type) MONO_INTERNAL;
620 void mono_sgen_dump_occupied (char *start, char *end, char *section_start) MONO_INTERNAL;
621
622 void mono_sgen_register_moved_object (void *obj, void *destination) MONO_INTERNAL;
623
624 void mono_sgen_register_fixed_internal_mem_type (int type, size_t size) MONO_INTERNAL;
625
626 void* mono_sgen_alloc_internal (int type) MONO_INTERNAL;
627 void mono_sgen_free_internal (void *addr, int type) MONO_INTERNAL;
628
629 void* mono_sgen_alloc_internal_dynamic (size_t size, int type) MONO_INTERNAL;
630 void mono_sgen_free_internal_dynamic (void *addr, size_t size, int type) MONO_INTERNAL;
631
632 void* mono_sgen_alloc_internal_fixed (SgenInternalAllocator *allocator, int type) MONO_INTERNAL;
633 void mono_sgen_free_internal_fixed (SgenInternalAllocator *allocator, void *addr, int type) MONO_INTERNAL;
634
635 void* mono_sgen_alloc_internal_full (SgenInternalAllocator *allocator, size_t size, int type) MONO_INTERNAL;
636 void mono_sgen_free_internal_full (SgenInternalAllocator *allocator, void *addr, size_t size, int type) MONO_INTERNAL;
637
638 void mono_sgen_free_internal_delayed (void *addr, int type, SgenInternalAllocator *thread_allocator) MONO_INTERNAL;
639
640 void mono_sgen_debug_printf (int level, const char *format, ...) MONO_INTERNAL;
641
642 gboolean mono_sgen_parse_environment_string_extract_number (const char *str, glong *out) MONO_INTERNAL;
643
644 void mono_sgen_internal_scan_objects (SgenInternalAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
645 void mono_sgen_internal_scan_pinned_objects (SgenInternalAllocator *alc, IterateObjectCallbackFunc callback, void *callback_data) MONO_INTERNAL;
646
647 void** mono_sgen_find_optimized_pin_queue_area (void *start, void *end, int *num) MONO_INTERNAL;
648 void mono_sgen_find_section_pin_queue_start_end (GCMemSection *section) MONO_INTERNAL;
649 void mono_sgen_pin_objects_in_section (GCMemSection *section, SgenGrayQueue *queue) MONO_INTERNAL;
650
651 void mono_sgen_pin_stats_register_object (char *obj, size_t size);
652
653 void mono_sgen_add_to_global_remset (gpointer ptr) MONO_INTERNAL;
654
655 #ifdef SGEN_HAVE_CARDTABLE
656 void sgen_card_table_reset_region (mword start, mword end) MONO_INTERNAL;
657 guint8* sgen_card_table_get_card_address (mword address) MONO_INTERNAL;
658 void* sgen_card_table_align_pointer (void *ptr) MONO_INTERNAL;
659 gboolean sgen_card_table_is_region_marked (mword start, mword end) MONO_INTERNAL;
660 void sgen_card_table_mark_address (mword address) MONO_INTERNAL;
661 void sgen_card_table_mark_range (mword address, mword size) MONO_INTERNAL;
662
663 #define CARD_BITS 9
664 #define CARD_SIZE_IN_BYTES (1 << CARD_BITS)
665 #endif
666
667
668 typedef struct _SgenMajorCollector SgenMajorCollector;
669 struct _SgenMajorCollector {
670         size_t section_size;
671         gboolean is_parallel;
672         gboolean supports_cardtable;
673
674         void* (*alloc_heap) (mword nursery_size, mword nursery_align, int nursery_bits);
675         gboolean (*is_object_live) (char *obj);
676         void* (*alloc_small_pinned_obj) (size_t size, gboolean has_references);
677         void* (*alloc_degraded) (MonoVTable *vtable, size_t size);
678         void (*copy_or_mark_object) (void **obj_slot, SgenGrayQueue *queue);
679         void (*minor_scan_object) (char *start, SgenGrayQueue *queue);
680         char* (*minor_scan_vtype) (char *start, mword desc, char* from_start, char* from_end, SgenGrayQueue *queue);
681         void (*major_scan_object) (char *start, SgenGrayQueue *queue);
682         void (*copy_object) (void **obj_slot, SgenGrayQueue *queue);
683         void* (*alloc_object) (int size, gboolean has_references);
684         void (*free_pinned_object) (char *obj, size_t size);
685         void (*iterate_objects) (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data);
686         void (*free_non_pinned_object) (char *obj, size_t size);
687         void (*find_pin_queue_start_ends) (SgenGrayQueue *queue);
688         void (*pin_objects) (SgenGrayQueue *queue);
689         void (*scan_card_table) (SgenGrayQueue *queue);
690         void (*clear_card_table) (void);
691         void (*init_to_space) (void);
692         void (*sweep) (void);
693         void (*check_scan_starts) (void);
694         void (*dump_heap) (FILE *heap_dump_file);
695         gint64 (*get_used_size) (void);
696         void (*start_nursery_collection) (void);
697         void (*finish_nursery_collection) (void);
698         void (*finish_major_collection) (void);
699         gboolean (*ptr_is_in_non_pinned_space) (char *ptr);
700         gboolean (*obj_is_from_pinned_alloc) (char *obj);
701         void (*report_pinned_memory_usage) (void);
702         int (*get_num_major_sections) (void);
703         gboolean (*handle_gc_param) (const char *opt);
704         void (*print_gc_param_usage) (void);
705 };
706
707 void mono_sgen_marksweep_init (SgenMajorCollector *collector) MONO_INTERNAL;
708 void mono_sgen_marksweep_fixed_init (SgenMajorCollector *collector) MONO_INTERNAL;
709 void mono_sgen_marksweep_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
710 void mono_sgen_marksweep_fixed_par_init (SgenMajorCollector *collector) MONO_INTERNAL;
711 void mono_sgen_copying_init (SgenMajorCollector *collector) MONO_INTERNAL;
712
713 /*
714  * This function can be called on an object whose first word, the
715  * vtable field, is not intact.  This is necessary for the parallel
716  * collector.
717  */
718 static inline guint
719 mono_sgen_par_object_get_size (MonoVTable *vtable, MonoObject* o)
720 {
721         MonoClass *klass = vtable->klass;
722         /*
723          * We depend on mono_string_length_fast and
724          * mono_array_length_fast not using the object's vtable.
725          */
726         if (klass == mono_defaults.string_class) {
727                 return sizeof (MonoString) + 2 * mono_string_length_fast ((MonoString*) o) + 2;
728         } else if (klass->rank) {
729                 MonoArray *array = (MonoArray*)o;
730                 size_t size = sizeof (MonoArray) + klass->sizes.element_size * mono_array_length_fast (array);
731                 if (G_UNLIKELY (array->bounds)) {
732                         size += sizeof (mono_array_size_t) - 1;
733                         size &= ~(sizeof (mono_array_size_t) - 1);
734                         size += sizeof (MonoArrayBounds) * klass->rank;
735                 }
736                 return size;
737         } else {
738                 /* from a created object: the class must be inited already */
739                 return klass->instance_size;
740         }
741 }
742
743 #define mono_sgen_safe_object_get_size(o)               mono_sgen_par_object_get_size ((MonoVTable*)SGEN_LOAD_VTABLE ((o)), (o))
744
745 #endif /* __MONO_SGENGC_H__ */