Fix Thread.VolatileRead/Write for floats/doubles. Fixes #1578.
[mono.git] / mono / metadata / sgen-marksweep.c
1 /*
2  * sgen-marksweep.c: Simple generational GC.
3  *
4  * Author:
5  *      Mark Probst <mark.probst@gmail.com>
6  *
7  * Copyright 2009-2010 Novell, Inc.
8  * 
9  * Permission is hereby granted, free of charge, to any person obtaining
10  * a copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 #include "config.h"
30
31 #ifdef HAVE_SGEN_GC
32
33 #include <math.h>
34 #include <errno.h>
35
36 #include "utils/mono-counters.h"
37 #include "utils/mono-semaphore.h"
38 #include "utils/mono-time.h"
39 #include "metadata/object-internals.h"
40 #include "metadata/profiler-private.h"
41
42 #include "metadata/sgen-gc.h"
43 #include "metadata/sgen-protocol.h"
44 #include "metadata/sgen-cardtable.h"
45 #include "metadata/gc-internal.h"
46
47 #define MS_BLOCK_SIZE   (16*1024)
48 #define MS_BLOCK_SIZE_SHIFT     14
49 #define MAJOR_SECTION_SIZE      MS_BLOCK_SIZE
50 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
51
52 #ifdef FIXED_HEAP
53 #define MS_DEFAULT_HEAP_NUM_BLOCKS      (32 * 1024) /* 512 MB */
54 #endif
55
56 /*
57  * Don't allocate single blocks, but alloc a contingent of this many
58  * blocks in one swoop.
59  */
60 #define MS_BLOCK_ALLOC_NUM      32
61
62 /*
63  * Number of bytes before the first object in a block.  At the start
64  * of a block is the MSBlockHeader, then opional padding, then come
65  * the objects, so this must be >= sizeof (MSBlockHeader).
66  */
67 #ifdef FIXED_HEAP
68 #define MS_BLOCK_SKIP   0
69 #else
70 #define MS_BLOCK_SKIP   16
71 #endif
72
73 #define MS_BLOCK_FREE   (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
74
75 #define MS_NUM_MARK_WORDS       ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
76
77 #if SGEN_MAX_SMALL_OBJ_SIZE > MS_BLOCK_FREE / 2
78 #error MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2
79 #endif
80
81 typedef struct _MSBlockInfo MSBlockInfo;
82 struct _MSBlockInfo {
83         int obj_size;
84         int obj_size_index;
85         int pin_queue_num_entries;
86         unsigned int pinned : 1;
87         unsigned int has_references : 1;
88         unsigned int has_pinned : 1;    /* means cannot evacuate */
89         unsigned int is_to_space : 1;
90 #ifdef FIXED_HEAP
91         unsigned int used : 1;
92         unsigned int zeroed : 1;
93 #endif
94         MSBlockInfo *next;
95         char *block;
96         void **free_list;
97         MSBlockInfo *next_free;
98         void **pin_queue_start;
99         mword mark_words [MS_NUM_MARK_WORDS];
100 };
101
102 #ifdef FIXED_HEAP
103 static int ms_heap_num_blocks = MS_DEFAULT_HEAP_NUM_BLOCKS;
104
105 #define ms_heap_start   nursery_end
106 static char *ms_heap_end;
107
108 #define MS_PTR_IN_SMALL_MAJOR_HEAP(p)   ((char*)(p) >= ms_heap_start && (char*)(p) < ms_heap_end)
109
110 /* array of all all block infos in the system */
111 static MSBlockInfo *block_infos;
112 #endif
113
114 #define MS_BLOCK_OBJ(b,i)               ((b)->block + MS_BLOCK_SKIP + (b)->obj_size * (i))
115 #define MS_BLOCK_DATA_FOR_OBJ(o)        ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
116
117 #ifdef FIXED_HEAP
118 #define MS_BLOCK_FOR_OBJ(o)             (&block_infos [(mword)((char*)(o) - ms_heap_start) >> MS_BLOCK_SIZE_SHIFT])
119 #else
120 typedef struct {
121         MSBlockInfo *info;
122 } MSBlockHeader;
123
124 #define MS_BLOCK_FOR_OBJ(o)             (((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
125 #endif
126
127 #define MS_BLOCK_OBJ_INDEX(o,b) (((char*)(o) - ((b)->block + MS_BLOCK_SKIP)) / (b)->obj_size)
128
129 #define MS_CALC_MARK_BIT(w,b,o)         do {                            \
130                 int i = ((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o))) >> SGEN_ALLOC_ALIGN_BITS; \
131                 if (sizeof (mword) == 4) {                              \
132                         (w) = i >> 5;                                   \
133                         (b) = i & 31;                                   \
134                 } else {                                                \
135                         (w) = i >> 6;                                   \
136                         (b) = i & 63;                                   \
137                 }                                                       \
138         } while (0)
139
140 #define MS_MARK_BIT(bl,w,b)     ((bl)->mark_words [(w)] & (1L << (b)))
141 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (1L << (b)))
142 #define MS_PAR_SET_MARK_BIT(was_marked,bl,w,b)  do {                    \
143                 mword __old = (bl)->mark_words [(w)];                   \
144                 mword __bitmask = 1L << (b);                            \
145                 if (__old & __bitmask) {                                \
146                         was_marked = TRUE;                              \
147                         break;                                          \
148                 }                                                       \
149                 if (SGEN_CAS_PTR ((gpointer*)&(bl)->mark_words [(w)],   \
150                                                 (gpointer)(__old | __bitmask), \
151                                                 (gpointer)__old) ==     \
152                                 (gpointer)__old) {                      \
153                         was_marked = FALSE;                             \
154                         break;                                          \
155                 }                                                       \
156         } while (1)
157
158 #define MS_OBJ_ALLOCED(o,b)     (*(void**)(o) && (*(char**)(o) < (b)->block || *(char**)(o) >= (b)->block + MS_BLOCK_SIZE))
159
160 #define MS_BLOCK_OBJ_SIZE_FACTOR        (sqrt (2.0))
161
162 /*
163  * This way we can lookup block object size indexes for sizes up to
164  * 256 bytes with a single load.
165  */
166 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES      32
167
168 static int *block_obj_sizes;
169 static int num_block_obj_sizes;
170 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
171
172 #define MS_BLOCK_FLAG_PINNED    1
173 #define MS_BLOCK_FLAG_REFS      2
174
175 #define MS_BLOCK_TYPE_MAX       4
176
177 #ifdef SGEN_PARALLEL_MARK
178 static LOCK_DECLARE (ms_block_list_mutex);
179 #define LOCK_MS_BLOCK_LIST mono_mutex_lock (&ms_block_list_mutex)
180 #define UNLOCK_MS_BLOCK_LIST mono_mutex_unlock (&ms_block_list_mutex)
181 #endif
182
183 /* we get this at init */
184 static int nursery_bits;
185 static char *nursery_start;
186 static char *nursery_end;
187
188 static gboolean *evacuate_block_obj_sizes;
189 static float evacuation_threshold = 0.666;
190
191 static gboolean concurrent_sweep = FALSE;
192 static gboolean have_swept;
193
194 #define ptr_in_nursery(p)       (SGEN_PTR_IN_NURSERY ((p), nursery_bits, nursery_start, nursery_end))
195
196 /* all allocated blocks in the system */
197 static MSBlockInfo *all_blocks;
198
199 #ifdef FIXED_HEAP
200 /* non-allocated block free-list */
201 static MSBlockInfo *empty_blocks = NULL;
202 #else
203 /* non-allocated block free-list */
204 static void *empty_blocks = NULL;
205 static int num_empty_blocks = 0;
206 #endif
207
208 #define FOREACH_BLOCK(bl)       for ((bl) = all_blocks; (bl); (bl) = (bl)->next) {
209 #define END_FOREACH_BLOCK       }
210
211 static int num_major_sections = 0;
212 /* one free block list for each block object size */
213 static MSBlockInfo **free_block_lists [MS_BLOCK_TYPE_MAX];
214
215 #ifdef SGEN_PARALLEL_MARK
216 #ifdef HAVE_KW_THREAD
217 static __thread MSBlockInfo ***workers_free_block_lists;
218 #else
219 static MonoNativeTlsKey workers_free_block_lists_key;
220 #endif
221 #endif
222
223 static long long stat_major_blocks_alloced = 0;
224 static long long stat_major_blocks_freed = 0;
225 static long long stat_major_objects_evacuated = 0;
226 static long long stat_time_wait_for_sweep = 0;
227 #ifdef SGEN_PARALLEL_MARK
228 static long long stat_slots_allocated_in_vain = 0;
229 #endif
230
231 static gboolean ms_sweep_in_progress = FALSE;
232 static MonoNativeThreadId ms_sweep_thread;
233 static MonoSemType ms_sweep_cmd_semaphore;
234 static MonoSemType ms_sweep_done_semaphore;
235
236 static void
237 ms_signal_sweep_command (void)
238 {
239         if (!concurrent_sweep)
240                 return;
241
242         g_assert (!ms_sweep_in_progress);
243         ms_sweep_in_progress = TRUE;
244         MONO_SEM_POST (&ms_sweep_cmd_semaphore);
245 }
246
247 static void
248 ms_signal_sweep_done (void)
249 {
250         if (!concurrent_sweep)
251                 return;
252
253         MONO_SEM_POST (&ms_sweep_done_semaphore);
254 }
255
256 static void
257 ms_wait_for_sweep_done (void)
258 {
259         SGEN_TV_DECLARE (atv);
260         SGEN_TV_DECLARE (btv);
261         int result;
262
263         if (!concurrent_sweep)
264                 return;
265
266         if (!ms_sweep_in_progress)
267                 return;
268
269         SGEN_TV_GETTIME (atv);
270         while ((result = MONO_SEM_WAIT (&ms_sweep_done_semaphore)) != 0) {
271                 if (errno != EINTR)
272                         g_error ("MONO_SEM_WAIT");
273         }
274         SGEN_TV_GETTIME (btv);
275         stat_time_wait_for_sweep += SGEN_TV_ELAPSED_MS (atv, btv);
276
277         g_assert (ms_sweep_in_progress);
278         ms_sweep_in_progress = FALSE;
279 }
280
281 static int
282 ms_find_block_obj_size_index (int size)
283 {
284         int i;
285         DEBUG (9, g_assert (size <= SGEN_MAX_SMALL_OBJ_SIZE));
286         for (i = 0; i < num_block_obj_sizes; ++i)
287                 if (block_obj_sizes [i] >= size)
288                         return i;
289         g_assert_not_reached ();
290 }
291
292 #define FREE_BLOCKS_FROM(lists,p,r)     (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
293 #define FREE_BLOCKS(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
294 #ifdef SGEN_PARALLEL_MARK
295 #ifdef HAVE_KW_THREAD
296 #define FREE_BLOCKS_LOCAL(p,r)          (FREE_BLOCKS_FROM (workers_free_block_lists, (p), (r)))
297 #else
298 #define FREE_BLOCKS_LOCAL(p,r)          (FREE_BLOCKS_FROM (((MSBlockInfo***)(mono_native_tls_get_value (workers_free_block_lists_key))), (p), (r)))
299 #endif
300 #else
301 //#define FREE_BLOCKS_LOCAL(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
302 #endif
303
304 #define MS_BLOCK_OBJ_SIZE_INDEX(s)                              \
305         (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ?      \
306          fast_block_obj_size_indexes [((s)+7)>>3] :             \
307          ms_find_block_obj_size_index ((s)))
308
309 #ifdef FIXED_HEAP
310 static void*
311 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
312 {
313         char *heap_start;
314         mword major_heap_size = ms_heap_num_blocks * MS_BLOCK_SIZE;
315         mword alloc_size = nursery_size + major_heap_size;
316         int i;
317
318         g_assert (ms_heap_num_blocks > 0);
319         g_assert (nursery_size % MS_BLOCK_SIZE == 0);
320         if (nursery_align)
321                 g_assert (nursery_align % MS_BLOCK_SIZE == 0);
322
323         nursery_start = mono_sgen_alloc_os_memory_aligned (alloc_size, nursery_align ? nursery_align : MS_BLOCK_SIZE, TRUE);
324         nursery_end = heap_start = nursery_start + nursery_size;
325         nursery_bits = the_nursery_bits;
326
327         ms_heap_end = heap_start + major_heap_size;
328
329         block_infos = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo) * ms_heap_num_blocks, INTERNAL_MEM_MS_BLOCK_INFO);
330
331         for (i = 0; i < ms_heap_num_blocks; ++i) {
332                 block_infos [i].block = heap_start + i * MS_BLOCK_SIZE;
333                 if (i < ms_heap_num_blocks - 1)
334                         block_infos [i].next_free = &block_infos [i + 1];
335                 else
336                         block_infos [i].next_free = NULL;
337                 block_infos [i].zeroed = TRUE;
338         }
339
340         empty_blocks = &block_infos [0];
341
342         return nursery_start;
343 }
344 #else
345 static void*
346 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
347 {
348         if (nursery_align)
349                 nursery_start = mono_sgen_alloc_os_memory_aligned (nursery_size, nursery_align, TRUE);
350         else
351                 nursery_start = mono_sgen_alloc_os_memory (nursery_size, TRUE);
352
353         nursery_end = nursery_start + nursery_size;
354         nursery_bits = the_nursery_bits;
355
356         return nursery_start;
357 }
358 #endif
359
360 static void
361 update_heap_boundaries_for_block (MSBlockInfo *block)
362 {
363         mono_sgen_update_heap_boundaries ((mword)block->block, (mword)block->block + MS_BLOCK_SIZE);
364 }
365
366 #ifdef FIXED_HEAP
367 static MSBlockInfo*
368 ms_get_empty_block (void)
369 {
370         MSBlockInfo *block;
371
372         g_assert (empty_blocks);
373
374         do {
375                 block = empty_blocks;
376         } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block->next_free, block) != block);
377
378         block->used = TRUE;
379
380         if (!block->zeroed)
381                 memset (block->block, 0, MS_BLOCK_SIZE);
382
383         return block;
384 }
385
386 static void
387 ms_free_block (MSBlockInfo *block)
388 {
389         block->next_free = empty_blocks;
390         empty_blocks = block;
391         block->used = FALSE;
392         block->zeroed = FALSE;
393         mono_sgen_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
394 }
395 #else
396 static void*
397 ms_get_empty_block (void)
398 {
399         char *p;
400         int i;
401         void *block, *empty, *next;
402
403  retry:
404         if (!empty_blocks) {
405                 p = mono_sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * MS_BLOCK_ALLOC_NUM, MS_BLOCK_SIZE, TRUE);
406
407                 for (i = 0; i < MS_BLOCK_ALLOC_NUM; ++i) {
408                         block = p;
409                         /*
410                          * We do the free list update one after the
411                          * other so that other threads can use the new
412                          * blocks as quickly as possible.
413                          */
414                         do {
415                                 empty = empty_blocks;
416                                 *(void**)block = empty;
417                         } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
418                         p += MS_BLOCK_SIZE;
419                 }
420
421                 SGEN_ATOMIC_ADD (num_empty_blocks, MS_BLOCK_ALLOC_NUM);
422
423                 stat_major_blocks_alloced += MS_BLOCK_ALLOC_NUM;
424         }
425
426         do {
427                 empty = empty_blocks;
428                 if (!empty)
429                         goto retry;
430                 block = empty;
431                 next = *(void**)block;
432         } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
433
434         SGEN_ATOMIC_ADD (num_empty_blocks, -1);
435
436         *(void**)block = NULL;
437
438         g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
439
440         return block;
441 }
442
443 static void
444 ms_free_block (void *block)
445 {
446         void *empty;
447
448         mono_sgen_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
449         memset (block, 0, MS_BLOCK_SIZE);
450
451         do {
452                 empty = empty_blocks;
453                 *(void**)block = empty;
454         } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
455
456         SGEN_ATOMIC_ADD (num_empty_blocks, 1);
457 }
458 #endif
459
460 //#define MARKSWEEP_CONSISTENCY_CHECK
461
462 #ifdef MARKSWEEP_CONSISTENCY_CHECK
463 static void
464 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
465 {
466         MSBlockInfo *b;
467
468         for (; block; block = block->next_free) {
469                 g_assert (block->obj_size == size);
470                 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
471
472                 /* blocks in the free lists must have at least
473                    one free slot */
474                 g_assert (block->free_list);
475
476 #ifdef FIXED_HEAP
477                 /* the block must not be in the empty_blocks list */
478                 for (b = empty_blocks; b; b = b->next_free)
479                         g_assert (b != block);
480 #endif
481                 /* the block must be in the all_blocks list */
482                 for (b = all_blocks; b; b = b->next) {
483                         if (b == block)
484                                 break;
485                 }
486                 g_assert (b == block);
487         }
488 }
489
490 static void
491 check_empty_blocks (void)
492 {
493 #ifndef FIXED_HEAP
494         void *p;
495         int i = 0;
496         for (p = empty_blocks; p; p = *(void**)p)
497                 ++i;
498         g_assert (i == num_empty_blocks);
499 #endif
500 }
501
502 static void
503 consistency_check (void)
504 {
505         MSBlockInfo *block;
506         int i;
507
508         /* check all blocks */
509         FOREACH_BLOCK (block) {
510                 int count = MS_BLOCK_FREE / block->obj_size;
511                 int num_free = 0;
512                 void **free;
513
514 #ifndef FIXED_HEAP
515                 /* check block header */
516                 g_assert (((MSBlockHeader*)block->block)->info == block);
517 #endif
518
519                 /* count number of free slots */
520                 for (i = 0; i < count; ++i) {
521                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
522                         if (!MS_OBJ_ALLOCED (obj, block))
523                                 ++num_free;
524                 }
525
526                 /* check free list */
527                 for (free = block->free_list; free; free = (void**)*free) {
528                         g_assert (MS_BLOCK_FOR_OBJ (free) == block);
529                         --num_free;
530                 }
531                 g_assert (num_free == 0);
532
533                 /* check all mark words are zero */
534                 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
535                         g_assert (block->mark_words [i] == 0);
536         } END_FOREACH_BLOCK;
537
538         /* check free blocks */
539         for (i = 0; i < num_block_obj_sizes; ++i) {
540                 int j;
541                 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
542                         check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
543         }
544
545         check_empty_blocks ();
546 }
547 #endif
548
549 static gboolean
550 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
551 {
552         int size = block_obj_sizes [size_index];
553         int count = MS_BLOCK_FREE / size;
554         MSBlockInfo *info;
555 #ifdef SGEN_PARALLEL_MARK
556         MSBlockInfo *next;
557 #endif
558 #ifndef FIXED_HEAP
559         MSBlockHeader *header;
560 #endif
561         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
562         char *obj_start;
563         int i;
564
565         if (!mono_sgen_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
566                 return FALSE;
567
568 #ifdef FIXED_HEAP
569         info = ms_get_empty_block ();
570 #else
571         info = mono_sgen_alloc_internal (INTERNAL_MEM_MS_BLOCK_INFO);
572 #endif
573
574         DEBUG (9, g_assert (count >= 2));
575
576         info->obj_size = size;
577         info->obj_size_index = size_index;
578         info->pinned = pinned;
579         info->has_references = has_references;
580         info->has_pinned = pinned;
581         info->is_to_space = (mono_sgen_get_current_collection_generation () == GENERATION_OLD);
582 #ifndef FIXED_HEAP
583         info->block = ms_get_empty_block ();
584
585         header = (MSBlockHeader*) info->block;
586         header->info = info;
587 #endif
588
589         update_heap_boundaries_for_block (info);
590
591         /* build free list */
592         obj_start = info->block + MS_BLOCK_SKIP;
593         info->free_list = (void**)obj_start;
594         /* we're skipping the last one - it must be nulled */
595         for (i = 0; i < count - 1; ++i) {
596                 char *next_obj_start = obj_start + size;
597                 *(void**)obj_start = next_obj_start;
598                 obj_start = next_obj_start;
599         }
600         /* the last one */
601         *(void**)obj_start = NULL;
602
603 #ifdef SGEN_PARALLEL_MARK
604         do {
605                 next = info->next_free = free_blocks [size_index];
606         } while (SGEN_CAS_PTR ((void**)&free_blocks [size_index], info, next) != next);
607
608         do {
609                 next = info->next = all_blocks;
610         } while (SGEN_CAS_PTR ((void**)&all_blocks, info, next) != next);
611 #else
612         info->next_free = free_blocks [size_index];
613         free_blocks [size_index] = info;
614
615         info->next = all_blocks;
616         all_blocks = info;
617 #endif
618
619         ++num_major_sections;
620         return TRUE;
621 }
622
623 static gboolean
624 obj_is_from_pinned_alloc (char *ptr)
625 {
626         MSBlockInfo *block;
627
628         FOREACH_BLOCK (block) {
629                 if (ptr >= block->block && ptr <= block->block + MS_BLOCK_SIZE)
630                         return block->pinned;
631         } END_FOREACH_BLOCK;
632         return FALSE;
633 }
634
635 static void*
636 unlink_slot_from_free_list_uncontested (MSBlockInfo **free_blocks, int size_index)
637 {
638         MSBlockInfo *block;
639         void *obj;
640
641         block = free_blocks [size_index];
642         DEBUG (9, g_assert (block));
643
644         obj = block->free_list;
645         DEBUG (9, g_assert (obj));
646
647         block->free_list = *(void**)obj;
648         if (!block->free_list) {
649                 free_blocks [size_index] = block->next_free;
650                 block->next_free = NULL;
651         }
652
653         return obj;
654 }
655
656 #ifdef SGEN_PARALLEL_MARK
657 static gboolean
658 try_remove_block_from_free_list (MSBlockInfo *block, MSBlockInfo **free_blocks, int size_index)
659 {
660         /*
661          * No more free slots in the block, so try to free the block.
662          * Don't try again if we don't succeed - another thread will
663          * already have done it.
664          */
665         MSBlockInfo *next_block = block->next_free;
666         if (SGEN_CAS_PTR ((void**)&free_blocks [size_index], next_block, block) == block) {
667                 /*
668                 void *old = SGEN_CAS_PTR ((void**)&block->next_free, NULL, next_block);
669                 g_assert (old == next_block);
670                 */
671                 block->next_free = NULL;
672                 return TRUE;
673         }
674         return FALSE;
675 }
676
677 static void*
678 alloc_obj_par (int size, gboolean pinned, gboolean has_references)
679 {
680         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
681         MSBlockInfo **free_blocks_local = FREE_BLOCKS_LOCAL (pinned, has_references);
682         MSBlockInfo *block;
683         void *obj;
684
685         DEBUG (9, g_assert (!ms_sweep_in_progress));
686         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
687
688         if (free_blocks_local [size_index]) {
689         get_slot:
690                 obj = unlink_slot_from_free_list_uncontested (free_blocks_local, size_index);
691         } else {
692                 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
693
694         get_block:
695                 block = free_blocks [size_index];
696                 if (block) {
697                         if (!try_remove_block_from_free_list (block, free_blocks, size_index))
698                                 goto get_block;
699
700                         g_assert (block->next_free == NULL);
701                         g_assert (block->free_list);
702                         block->next_free = free_blocks_local [size_index];
703                         free_blocks_local [size_index] = block;
704
705                         goto get_slot;
706                 } else {
707                         gboolean success;
708
709                         LOCK_MS_BLOCK_LIST;
710                         success = ms_alloc_block (size_index, pinned, has_references);
711                         UNLOCK_MS_BLOCK_LIST;
712
713                         if (G_UNLIKELY (!success))
714                                 return NULL;
715
716                         goto get_block;
717                 }
718         }
719
720         /*
721          * FIXME: This should not be necessary because it'll be
722          * overwritten by the vtable immediately.
723          */
724         *(void**)obj = NULL;
725
726         return obj;
727 }
728 #endif
729
730 static void*
731 alloc_obj (int size, gboolean pinned, gboolean has_references)
732 {
733         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
734         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
735         void *obj;
736
737 #ifdef SGEN_PARALLEL_MARK
738         DEBUG (9, g_assert (current_collection_generation != GENERATION_OLD));
739 #endif
740
741         DEBUG (9, g_assert (!ms_sweep_in_progress));
742
743         if (!free_blocks [size_index]) {
744                 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
745                         return NULL;
746         }
747
748         obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
749
750         /*
751          * FIXME: This should not be necessary because it'll be
752          * overwritten by the vtable immediately.
753          */
754         *(void**)obj = NULL;
755
756         return obj;
757 }
758
759 static void*
760 major_alloc_object (int size, gboolean has_references)
761 {
762         return alloc_obj (size, FALSE, has_references);
763 }
764
765 /*
766  * We're not freeing the block if it's empty.  We leave that work for
767  * the next major collection.
768  *
769  * This is just called from the domain clearing code, which runs in a
770  * single thread and has the GC lock, so we don't need an extra lock.
771  */
772 static void
773 free_object (char *obj, size_t size, gboolean pinned)
774 {
775         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
776         int word, bit;
777         DEBUG (9, g_assert ((pinned && block->pinned) || (!pinned && !block->pinned)));
778         DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
779         MS_CALC_MARK_BIT (word, bit, obj);
780         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
781         if (!block->free_list) {
782                 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, block->has_references);
783                 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
784                 DEBUG (9, g_assert (!block->next_free));
785                 block->next_free = free_blocks [size_index];
786                 free_blocks [size_index] = block;
787         }
788         memset (obj, 0, size);
789         *(void**)obj = block->free_list;
790         block->free_list = (void**)obj;
791 }
792
793 static void
794 major_free_non_pinned_object (char *obj, size_t size)
795 {
796         free_object (obj, size, FALSE);
797 }
798
799 /* size is a multiple of SGEN_ALLOC_ALIGN */
800 static void*
801 major_alloc_small_pinned_obj (size_t size, gboolean has_references)
802 {
803         void *res;
804
805         ms_wait_for_sweep_done ();
806
807         res = alloc_obj (size, TRUE, has_references);
808          /*If we failed to alloc memory, we better try releasing memory
809           *as pinned alloc is requested by the runtime.
810           */
811          if (!res) {
812                  sgen_collect_major_no_lock ("pinned alloc failure");
813                  res = alloc_obj (size, TRUE, has_references);
814          }
815          return res;
816 }
817
818 static void
819 free_pinned_object (char *obj, size_t size)
820 {
821         free_object (obj, size, TRUE);
822 }
823
824 /*
825  * size is already rounded up and we hold the GC lock.
826  */
827 static void*
828 major_alloc_degraded (MonoVTable *vtable, size_t size)
829 {
830         void *obj;
831         int old_num_sections;
832
833         ms_wait_for_sweep_done ();
834
835         old_num_sections = num_major_sections;
836
837         obj = alloc_obj (size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
838         if (G_LIKELY (obj)) {
839                 *(MonoVTable**)obj = vtable;
840                 HEAVY_STAT (++stat_objects_alloced_degraded);
841                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
842                 g_assert (num_major_sections >= old_num_sections);
843                 mono_sgen_register_major_sections_alloced (num_major_sections - old_num_sections);
844         }
845         return obj;
846 }
847
848 #define MAJOR_OBJ_IS_IN_TO_SPACE(obj)   FALSE
849
850 /*
851  * obj is some object.  If it's not in the major heap (i.e. if it's in
852  * the nursery or LOS), return FALSE.  Otherwise return whether it's
853  * been marked or copied.
854  */
855 static gboolean
856 major_is_object_live (char *obj)
857 {
858         MSBlockInfo *block;
859         int word, bit;
860 #ifndef FIXED_HEAP
861         mword objsize;
862 #endif
863
864         if (ptr_in_nursery (obj))
865                 return FALSE;
866
867 #ifdef FIXED_HEAP
868         /* LOS */
869         if (!MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
870                 return FALSE;
871 #else
872         objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
873
874         /* LOS */
875         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
876                 return FALSE;
877 #endif
878
879         /* now we know it's in a major block */
880         block = MS_BLOCK_FOR_OBJ (obj);
881         DEBUG (9, g_assert (!block->pinned));
882         MS_CALC_MARK_BIT (word, bit, obj);
883         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
884 }
885
886 static gboolean
887 major_ptr_is_in_non_pinned_space (char *ptr)
888 {
889         MSBlockInfo *block;
890
891         FOREACH_BLOCK (block) {
892                 if (ptr >= block->block && ptr <= block->block + MS_BLOCK_SIZE)
893                         return !block->pinned;
894         } END_FOREACH_BLOCK;
895         return FALSE;
896 }
897
898 static void
899 major_iterate_objects (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data)
900 {
901         MSBlockInfo *block;
902
903         ms_wait_for_sweep_done ();
904
905         FOREACH_BLOCK (block) {
906                 int count = MS_BLOCK_FREE / block->obj_size;
907                 int i;
908
909                 if (block->pinned && !pinned)
910                         continue;
911                 if (!block->pinned && !non_pinned)
912                         continue;
913
914                 for (i = 0; i < count; ++i) {
915                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
916                         if (MS_OBJ_ALLOCED (obj, block))
917                                 callback ((char*)obj, block->obj_size, data);
918                 }
919         } END_FOREACH_BLOCK;
920 }
921
922 static void
923 major_check_scan_starts (void)
924 {
925 }
926
927 static void
928 major_dump_heap (FILE *heap_dump_file)
929 {
930         MSBlockInfo *block;
931         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
932         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
933         int i;
934
935         for (i = 0; i < num_block_obj_sizes; ++i)
936                 slots_available [i] = slots_used [i] = 0;
937
938         FOREACH_BLOCK (block) {
939                 int index = ms_find_block_obj_size_index (block->obj_size);
940                 int count = MS_BLOCK_FREE / block->obj_size;
941
942                 slots_available [index] += count;
943                 for (i = 0; i < count; ++i) {
944                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
945                                 ++slots_used [index];
946                 }
947         } END_FOREACH_BLOCK;
948
949         fprintf (heap_dump_file, "<occupancies>\n");
950         for (i = 0; i < num_block_obj_sizes; ++i) {
951                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
952                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
953         }
954         fprintf (heap_dump_file, "</occupancies>\n");
955
956         FOREACH_BLOCK (block) {
957                 int count = MS_BLOCK_FREE / block->obj_size;
958                 int i;
959                 int start = -1;
960
961                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
962
963                 for (i = 0; i <= count; ++i) {
964                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
965                                 if (start < 0)
966                                         start = i;
967                         } else {
968                                 if (start >= 0) {
969                                         mono_sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), block->block);
970                                         start = -1;
971                                 }
972                         }
973                 }
974
975                 fprintf (heap_dump_file, "</section>\n");
976         } END_FOREACH_BLOCK;
977 }
978
979 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
980
981 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,block,queue) do {        \
982                 int __word, __bit;                                      \
983                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
984                 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
985                         MS_SET_MARK_BIT ((block), __word, __bit);       \
986                         if ((block)->has_references)                    \
987                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
988                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
989                 }                                                       \
990         } while (0)
991 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,block,queue) do {                \
992                 int __word, __bit;                                      \
993                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
994                 DEBUG (9, g_assert (MS_OBJ_ALLOCED ((obj), (block))));  \
995                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
996                         MS_SET_MARK_BIT ((block), __word, __bit);       \
997                         if ((block)->has_references)                    \
998                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
999                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
1000                 }                                                       \
1001         } while (0)
1002 #define MS_PAR_MARK_OBJECT_AND_ENQUEUE(obj,block,queue) do {            \
1003                 int __word, __bit;                                      \
1004                 gboolean __was_marked;                                  \
1005                 DEBUG (9, g_assert (MS_OBJ_ALLOCED ((obj), (block))));  \
1006                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1007                 MS_PAR_SET_MARK_BIT (__was_marked, (block), __word, __bit); \
1008                 if (!__was_marked) {                                    \
1009                         if ((block)->has_references)                    \
1010                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
1011                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
1012                 }                                                       \
1013         } while (0)
1014
1015 static void
1016 pin_major_object (void *obj, SgenGrayQueue *queue)
1017 {
1018         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
1019         block->has_pinned = TRUE;
1020         MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1021 }
1022
1023 #ifdef SGEN_PARALLEL_MARK
1024 static void
1025 pin_or_update_par (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue)
1026 {
1027         for (;;) {
1028                 mword vtable_word;
1029
1030                 if (ptr_in_nursery (obj)) {
1031                         if (SGEN_CAS_PTR (obj, (void*)((mword)vt | SGEN_PINNED_BIT), vt) == vt) {
1032                                 mono_sgen_pin_object (obj, queue);
1033                                 break;
1034                         }
1035                 } else {
1036                         pin_major_object (obj, queue);
1037                 }
1038
1039                 vtable_word = *(mword*)obj;
1040                 /*someone else forwarded it, update the pointer and bail out*/
1041                 if (vtable_word & SGEN_FORWARDED_BIT) {
1042                         *ptr = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1043                         break;
1044                 }
1045
1046                 /*someone pinned it, nothing to do.*/
1047                 if (vtable_word & SGEN_PINNED_BIT)
1048                         break;
1049         }
1050 }
1051 #endif
1052
1053 #include "sgen-major-copy-object.h"
1054
1055 #ifdef SGEN_PARALLEL_MARK
1056 static void
1057 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1058 {
1059         void *obj = *ptr;
1060         mword objsize;
1061         MSBlockInfo *block;
1062         MonoVTable *vt;
1063
1064         HEAVY_STAT (++stat_copy_object_called_major);
1065
1066         DEBUG (9, g_assert (obj));
1067         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1068
1069         if (ptr_in_nursery (obj)) {
1070                 int word, bit;
1071                 gboolean has_references;
1072                 void *destination;
1073                 mword vtable_word = *(mword*)obj;
1074                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1075
1076                 if (vtable_word & SGEN_FORWARDED_BIT) {
1077                         *ptr = (void*)vt;
1078                         return;
1079                 }
1080
1081                 if (vtable_word & SGEN_PINNED_BIT)
1082                         return;
1083
1084                 HEAVY_STAT (++stat_objects_copied_major);
1085
1086         do_copy_object:
1087                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1088                 has_references = SGEN_VTABLE_HAS_REFERENCES (vt);
1089
1090                 destination = alloc_obj_par (objsize, FALSE, has_references);
1091                 if (G_UNLIKELY (!destination)) {
1092                         if (!ptr_in_nursery (obj)) {
1093                                 int size_index;
1094                                 block = MS_BLOCK_FOR_OBJ (obj);
1095                                 size_index = block->obj_size_index;
1096                                 evacuate_block_obj_sizes [size_index] = FALSE;
1097                         }
1098
1099                         pin_or_update_par (ptr, obj, vt, queue);
1100                         mono_sgen_set_pinned_from_failed_allocation (objsize);
1101                         return;
1102                 }
1103
1104                 /*
1105                  * We do this before the CAS because we want to make
1106                  * sure that if another thread sees the destination
1107                  * pointer the VTable is already in place.  Not doing
1108                  * this can crash binary protocols.
1109                  */
1110                 *(MonoVTable**)destination = vt;
1111
1112                 if (SGEN_CAS_PTR (obj, (void*)((mword)destination | SGEN_FORWARDED_BIT), vt) == vt) {
1113                         gboolean was_marked;
1114
1115                         par_copy_object_no_checks (destination, vt, obj, objsize, has_references ? queue : NULL);
1116                         obj = destination;
1117                         *ptr = obj;
1118
1119                         /*
1120                          * FIXME: If we make major_alloc_object() give
1121                          * us the block info, too, we won't have to
1122                          * re-fetch it here.
1123                          */
1124                         block = MS_BLOCK_FOR_OBJ (obj);
1125                         MS_CALC_MARK_BIT (word, bit, obj);
1126                         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1127                         MS_PAR_SET_MARK_BIT (was_marked, block, word, bit);
1128                 } else {
1129                         /*
1130                          * FIXME: We have allocated destination, but
1131                          * we cannot use it.  Give it back to the
1132                          * allocator.
1133                          */
1134                         *(void**)destination = NULL;
1135
1136                         vtable_word = *(mword*)obj;
1137                         g_assert (vtable_word & SGEN_FORWARDED_BIT);
1138
1139                         obj = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1140
1141                         *ptr = obj;
1142
1143                         ++stat_slots_allocated_in_vain;
1144                 }
1145         } else {
1146 #ifdef FIXED_HEAP
1147                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1148 #else
1149                 mword vtable_word = *(mword*)obj;
1150                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1151
1152                 /* see comment in the non-parallel version below */
1153                 if (vtable_word & SGEN_FORWARDED_BIT) {
1154                         *ptr = (void*)vt;
1155                         return;
1156                 }
1157                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1158
1159                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1160 #endif
1161                 {
1162                         int size_index;
1163
1164                         block = MS_BLOCK_FOR_OBJ (obj);
1165                         size_index = block->obj_size_index;
1166
1167                         if (!block->has_pinned && evacuate_block_obj_sizes [size_index]) {
1168                                 if (block->is_to_space)
1169                                         return;
1170
1171 #ifdef FIXED_HEAP
1172                                 {
1173                                         mword vtable_word = *(mword*)obj;
1174                                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1175
1176                                         if (vtable_word & SGEN_FORWARDED_BIT) {
1177                                                 *ptr = (void*)vt;
1178                                                 return;
1179                                         }
1180                                 }
1181 #endif
1182
1183                                 HEAVY_STAT (++stat_major_objects_evacuated);
1184                                 goto do_copy_object;
1185                         }
1186
1187                         MS_PAR_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1188                 } else {
1189 #ifdef FIXED_HEAP
1190                         mword vtable_word = *(mword*)obj;
1191                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1192 #endif
1193
1194                         if (vtable_word & SGEN_PINNED_BIT)
1195                                 return;
1196                         binary_protocol_pin (obj, vt, mono_sgen_safe_object_get_size ((MonoObject*)obj));
1197                         if (SGEN_CAS_PTR (obj, (void*)(vtable_word | SGEN_PINNED_BIT), (void*)vtable_word) == (void*)vtable_word) {
1198                                 if (SGEN_VTABLE_HAS_REFERENCES (vt))
1199                                         GRAY_OBJECT_ENQUEUE (queue, obj);
1200                         } else {
1201                                 g_assert (SGEN_OBJECT_IS_PINNED (obj));
1202                         }
1203                 }
1204         }
1205 }
1206 #else
1207 static void
1208 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1209 {
1210         void *obj = *ptr;
1211         MSBlockInfo *block;
1212
1213         HEAVY_STAT (++stat_copy_object_called_major);
1214
1215         DEBUG (9, g_assert (obj));
1216         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1217
1218         if (ptr_in_nursery (obj)) {
1219                 int word, bit;
1220                 char *forwarded, *old_obj;
1221
1222                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1223                         *ptr = forwarded;
1224                         return;
1225                 }
1226                 if (SGEN_OBJECT_IS_PINNED (obj))
1227                         return;
1228
1229                 HEAVY_STAT (++stat_objects_copied_major);
1230
1231         do_copy_object:
1232                 old_obj = obj;
1233                 obj = copy_object_no_checks (obj, queue);
1234                 if (G_UNLIKELY (old_obj == obj)) {
1235                         /*If we fail to evacuate an object we just stop doing it for a given block size as all other will surely fail too.*/
1236                         if (!ptr_in_nursery (obj)) {
1237                                 int size_index;
1238                                 block = MS_BLOCK_FOR_OBJ (obj);
1239                                 size_index = block->obj_size_index;
1240                                 evacuate_block_obj_sizes [size_index] = FALSE;
1241                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1242                         }
1243                         return;
1244                 }
1245                 *ptr = obj;
1246
1247                 /*
1248                  * FIXME: See comment for copy_object_no_checks().  If
1249                  * we have that, we can let the allocation function
1250                  * give us the block info, too, and we won't have to
1251                  * re-fetch it.
1252                  */
1253                 block = MS_BLOCK_FOR_OBJ (obj);
1254                 MS_CALC_MARK_BIT (word, bit, obj);
1255                 DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1256                 MS_SET_MARK_BIT (block, word, bit);
1257         } else {
1258                 char *forwarded;
1259 #ifdef FIXED_HEAP
1260                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1261 #else
1262                 mword objsize;
1263
1264                 /*
1265                  * If we have don't have a fixed heap we cannot know
1266                  * whether an object is in the LOS or in the small
1267                  * object major heap without checking its size.  To do
1268                  * that, however, we need to know that we actually
1269                  * have a valid object, not a forwarding pointer, so
1270                  * we have to do this check first.
1271                  */
1272                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1273                         *ptr = forwarded;
1274                         return;
1275                 }
1276
1277                 objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
1278
1279                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1280 #endif
1281                 {
1282                         int size_index;
1283                         gboolean evacuate;
1284
1285                         block = MS_BLOCK_FOR_OBJ (obj);
1286                         size_index = block->obj_size_index;
1287                         evacuate = evacuate_block_obj_sizes [size_index];
1288
1289 #ifdef FIXED_HEAP
1290                         /*
1291                          * We could also check for !block->has_pinned
1292                          * here, but it would only make an uncommon case
1293                          * faster, namely objects that are in blocks
1294                          * whose slot sizes are evacuated but which have
1295                          * pinned objects.
1296                          */
1297                         if (evacuate && (forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1298                                 *ptr = forwarded;
1299                                 return;
1300                         }
1301 #endif
1302
1303                         if (evacuate && !block->has_pinned) {
1304                                 g_assert (!SGEN_OBJECT_IS_PINNED (obj));
1305                                 if (block->is_to_space)
1306                                         return;
1307                                 HEAVY_STAT (++stat_major_objects_evacuated);
1308                                 goto do_copy_object;
1309                         } else {
1310                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1311                         }
1312                 } else {
1313                         if (SGEN_OBJECT_IS_PINNED (obj))
1314                                 return;
1315                         binary_protocol_pin (obj, (gpointer)SGEN_LOAD_VTABLE (obj), mono_sgen_safe_object_get_size ((MonoObject*)obj));
1316                         SGEN_PIN_OBJECT (obj);
1317                         /* FIXME: only enqueue if object has references */
1318                         GRAY_OBJECT_ENQUEUE (queue, obj);
1319                 }
1320         }
1321 }
1322 #endif
1323
1324 #include "sgen-major-scan-object.h"
1325
1326 static void
1327 mark_pinned_objects_in_block (MSBlockInfo *block, SgenGrayQueue *queue)
1328 {
1329         int i;
1330         int last_index = -1;
1331
1332         if (!block->pin_queue_num_entries)
1333                 return;
1334
1335         block->has_pinned = TRUE;
1336
1337         for (i = 0; i < block->pin_queue_num_entries; ++i) {
1338                 int index = MS_BLOCK_OBJ_INDEX (block->pin_queue_start [i], block);
1339                 DEBUG (9, g_assert (index >= 0 && index < MS_BLOCK_FREE / block->obj_size));
1340                 if (index == last_index)
1341                         continue;
1342                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (MS_BLOCK_OBJ (block, index), block, queue);
1343                 last_index = index;
1344         }
1345 }
1346
1347 static void
1348 ms_sweep (void)
1349 {
1350         int i;
1351         MSBlockInfo **iter;
1352
1353         /* statistics for evacuation */
1354         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1355         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1356         int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1357
1358         for (i = 0; i < num_block_obj_sizes; ++i)
1359                 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1360
1361         /* clear all the free lists */
1362         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1363                 MSBlockInfo **free_blocks = free_block_lists [i];
1364                 int j;
1365                 for (j = 0; j < num_block_obj_sizes; ++j)
1366                         free_blocks [j] = NULL;
1367         }
1368
1369         /* traverse all blocks, free and zero unmarked objects */
1370         iter = &all_blocks;
1371         while (*iter) {
1372                 MSBlockInfo *block = *iter;
1373                 int count;
1374                 gboolean have_live = FALSE;
1375                 gboolean has_pinned;
1376                 int obj_index;
1377                 int obj_size_index;
1378
1379                 obj_size_index = block->obj_size_index;
1380
1381                 has_pinned = block->has_pinned;
1382                 block->has_pinned = block->pinned;
1383
1384                 block->is_to_space = FALSE;
1385
1386                 count = MS_BLOCK_FREE / block->obj_size;
1387                 block->free_list = NULL;
1388
1389                 for (obj_index = 0; obj_index < count; ++obj_index) {
1390                         int word, bit;
1391                         void *obj = MS_BLOCK_OBJ (block, obj_index);
1392
1393                         MS_CALC_MARK_BIT (word, bit, obj);
1394                         if (MS_MARK_BIT (block, word, bit)) {
1395                                 DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
1396                                 have_live = TRUE;
1397                                 if (!has_pinned)
1398                                         ++slots_used [obj_size_index];
1399                         } else {
1400                                 /* an unmarked object */
1401                                 if (MS_OBJ_ALLOCED (obj, block)) {
1402                                         binary_protocol_empty (obj, block->obj_size);
1403                                         memset (obj, 0, block->obj_size);
1404                                 }
1405                                 *(void**)obj = block->free_list;
1406                                 block->free_list = obj;
1407                         }
1408                 }
1409
1410                 /* reset mark bits */
1411                 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1412
1413                 /*
1414                  * FIXME: reverse free list so that it's in address
1415                  * order
1416                  */
1417
1418                 if (have_live) {
1419                         if (!has_pinned) {
1420                                 ++num_blocks [obj_size_index];
1421                                 slots_available [obj_size_index] += count;
1422                         }
1423
1424                         iter = &block->next;
1425
1426                         /*
1427                          * If there are free slots in the block, add
1428                          * the block to the corresponding free list.
1429                          */
1430                         if (block->free_list) {
1431                                 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1432                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1433                                 block->next_free = free_blocks [index];
1434                                 free_blocks [index] = block;
1435                         }
1436
1437                         update_heap_boundaries_for_block (block);
1438                 } else {
1439                         /*
1440                          * Blocks without live objects are removed from the
1441                          * block list and freed.
1442                          */
1443                         *iter = block->next;
1444
1445 #ifdef FIXED_HEAP
1446                         ms_free_block (block);
1447 #else
1448                         ms_free_block (block->block);
1449
1450                         mono_sgen_free_internal (block, INTERNAL_MEM_MS_BLOCK_INFO);
1451 #endif
1452
1453                         --num_major_sections;
1454                 }
1455         }
1456
1457         for (i = 0; i < num_block_obj_sizes; ++i) {
1458                 float usage = (float)slots_used [i] / (float)slots_available [i];
1459                 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1460                         evacuate_block_obj_sizes [i] = TRUE;
1461                         /*
1462                         g_print ("slot size %d - %d of %d used\n",
1463                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1464                         */
1465                 } else {
1466                         evacuate_block_obj_sizes [i] = FALSE;
1467                 }
1468         }
1469
1470         have_swept = TRUE;
1471 }
1472
1473 static mono_native_thread_return_t
1474 ms_sweep_thread_func (void *dummy)
1475 {
1476         g_assert (concurrent_sweep);
1477
1478         for (;;) {
1479                 int result;
1480
1481                 while ((result = MONO_SEM_WAIT (&ms_sweep_cmd_semaphore)) != 0) {
1482                         if (errno != EINTR)
1483                                 g_error ("MONO_SEM_WAIT");
1484                 }
1485
1486                 ms_sweep ();
1487
1488                 ms_signal_sweep_done ();
1489         }
1490
1491         return NULL;
1492 }
1493
1494 static void
1495 major_sweep (void)
1496 {
1497         if (concurrent_sweep) {
1498                 g_assert (ms_sweep_thread);
1499                 ms_signal_sweep_command ();
1500         } else {
1501                 ms_sweep ();
1502         }
1503 }
1504
1505 static int count_pinned_ref;
1506 static int count_pinned_nonref;
1507 static int count_nonpinned_ref;
1508 static int count_nonpinned_nonref;
1509
1510 static void
1511 count_nonpinned_callback (char *obj, size_t size, void *data)
1512 {
1513         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1514
1515         if (vtable->klass->has_references)
1516                 ++count_nonpinned_ref;
1517         else
1518                 ++count_nonpinned_nonref;
1519 }
1520
1521 static void
1522 count_pinned_callback (char *obj, size_t size, void *data)
1523 {
1524         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1525
1526         if (vtable->klass->has_references)
1527                 ++count_pinned_ref;
1528         else
1529                 ++count_pinned_nonref;
1530 }
1531
1532 static void __attribute__ ((unused))
1533 count_ref_nonref_objs (void)
1534 {
1535         int total;
1536
1537         count_pinned_ref = 0;
1538         count_pinned_nonref = 0;
1539         count_nonpinned_ref = 0;
1540         count_nonpinned_nonref = 0;
1541
1542         major_iterate_objects (TRUE, FALSE, count_nonpinned_callback, NULL);
1543         major_iterate_objects (FALSE, TRUE, count_pinned_callback, NULL);
1544
1545         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1546
1547         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1548                         count_pinned_ref, count_nonpinned_ref,
1549                         count_pinned_nonref, count_nonpinned_nonref,
1550                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1551 }
1552
1553 static int
1554 ms_calculate_block_obj_sizes (double factor, int *arr)
1555 {
1556         double target_size = sizeof (MonoObject);
1557         int num_sizes = 0;
1558         int last_size = 0;
1559
1560         do {
1561                 int target_count = ceil (MS_BLOCK_FREE / target_size);
1562                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1563
1564                 if (size != last_size) {
1565                         if (arr)
1566                                 arr [num_sizes] = size;
1567                         ++num_sizes;
1568                         last_size = size;
1569                 }
1570
1571                 target_size *= factor;
1572         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1573
1574         return num_sizes;
1575 }
1576
1577 /* only valid during minor collections */
1578 static int old_num_major_sections;
1579
1580 static void
1581 major_start_nursery_collection (void)
1582 {
1583         ms_wait_for_sweep_done ();
1584
1585 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1586         consistency_check ();
1587 #endif
1588
1589         old_num_major_sections = num_major_sections;
1590 }
1591
1592 static void
1593 major_finish_nursery_collection (void)
1594 {
1595 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1596         consistency_check ();
1597 #endif
1598         mono_sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1599 }
1600
1601 static void
1602 major_start_major_collection (void)
1603 {
1604         int i;
1605
1606         ms_wait_for_sweep_done ();
1607
1608         /* clear the free lists */
1609         for (i = 0; i < num_block_obj_sizes; ++i) {
1610                 if (!evacuate_block_obj_sizes [i])
1611                         continue;
1612
1613                 free_block_lists [0][i] = NULL;
1614                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1615         }
1616 }
1617
1618 static void
1619 major_finish_major_collection (void)
1620 {
1621 }
1622
1623 static void
1624 major_have_computer_minor_collection_allowance (void)
1625 {
1626 #ifndef FIXED_HEAP
1627         int section_reserve = mono_sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1628
1629         g_assert (have_swept);
1630         ms_wait_for_sweep_done ();
1631         g_assert (!ms_sweep_in_progress);
1632
1633         /*
1634          * FIXME: We don't free blocks on 32 bit platforms because it
1635          * can lead to address space fragmentation, since we're
1636          * allocating blocks in larger contingents.
1637          */
1638         if (sizeof (mword) < 8)
1639                 return;
1640
1641         while (num_empty_blocks > section_reserve) {
1642                 void *next = *(void**)empty_blocks;
1643                 mono_sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE);
1644                 empty_blocks = next;
1645                 /*
1646                  * Needs not be atomic because this is running
1647                  * single-threaded.
1648                  */
1649                 --num_empty_blocks;
1650
1651                 ++stat_major_blocks_freed;
1652         }
1653 #endif
1654 }
1655
1656 static void
1657 major_find_pin_queue_start_ends (SgenGrayQueue *queue)
1658 {
1659         MSBlockInfo *block;
1660
1661         FOREACH_BLOCK (block) {
1662                 block->pin_queue_start = mono_sgen_find_optimized_pin_queue_area (block->block + MS_BLOCK_SKIP, block->block + MS_BLOCK_SIZE,
1663                                 &block->pin_queue_num_entries);
1664         } END_FOREACH_BLOCK;
1665 }
1666
1667 static void
1668 major_pin_objects (SgenGrayQueue *queue)
1669 {
1670         MSBlockInfo *block;
1671
1672         FOREACH_BLOCK (block) {
1673                 mark_pinned_objects_in_block (block, queue);
1674         } END_FOREACH_BLOCK;
1675 }
1676
1677 static void
1678 major_init_to_space (void)
1679 {
1680 }
1681
1682 static void
1683 major_report_pinned_memory_usage (void)
1684 {
1685         g_assert_not_reached ();
1686 }
1687
1688 static gint64
1689 major_get_used_size (void)
1690 {
1691         gint64 size = 0;
1692         MSBlockInfo *block;
1693
1694         FOREACH_BLOCK (block) {
1695                 int count = MS_BLOCK_FREE / block->obj_size;
1696                 void **iter;
1697                 size += count * block->obj_size;
1698                 for (iter = block->free_list; iter; iter = (void**)*iter)
1699                         size -= block->obj_size;
1700         } END_FOREACH_BLOCK;
1701
1702         return size;
1703 }
1704
1705 static int
1706 get_num_major_sections (void)
1707 {
1708         return num_major_sections;
1709 }
1710
1711 static gboolean
1712 major_handle_gc_param (const char *opt)
1713 {
1714 #ifdef FIXED_HEAP
1715         if (g_str_has_prefix (opt, "major-heap-size=")) {
1716                 const char *arg = strchr (opt, '=') + 1;
1717                 glong size;
1718                 if (!mono_gc_parse_environment_string_extract_number (arg, &size))
1719                         return FALSE;
1720                 ms_heap_num_blocks = (size + MS_BLOCK_SIZE - 1) / MS_BLOCK_SIZE;
1721                 g_assert (ms_heap_num_blocks > 0);
1722                 return TRUE;
1723         } else
1724 #endif
1725         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1726                 const char *arg = strchr (opt, '=') + 1;
1727                 int percentage = atoi (arg);
1728                 if (percentage < 0 || percentage > 100) {
1729                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1730                         exit (1);
1731                 }
1732                 evacuation_threshold = (float)percentage / 100.0;
1733                 return TRUE;
1734         } else if (!strcmp (opt, "concurrent-sweep")) {
1735                 concurrent_sweep = TRUE;
1736                 return TRUE;
1737         } else if (!strcmp (opt, "no-concurrent-sweep")) {
1738                 concurrent_sweep = FALSE;
1739                 return TRUE;
1740         }
1741
1742         return FALSE;
1743 }
1744
1745 static void
1746 major_print_gc_param_usage (void)
1747 {
1748         fprintf (stderr,
1749                         ""
1750 #ifdef FIXED_HEAP
1751                         "  major-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n"
1752 #endif
1753                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1754                         "  (no-)concurrent-sweep\n"
1755                         );
1756 }
1757
1758 #ifdef SGEN_HAVE_CARDTABLE
1759 static void
1760 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1761 {
1762         MSBlockInfo *block;
1763
1764         FOREACH_BLOCK (block) {
1765                 if (block->has_references)
1766                         callback ((mword)block->block, MS_BLOCK_SIZE);
1767         } END_FOREACH_BLOCK;
1768 }
1769
1770 #ifdef HEAVY_STATISTICS
1771 extern long long marked_cards;
1772 extern long long scanned_cards;
1773 extern long long scanned_objects;
1774
1775 #endif
1776
1777 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1778 /*
1779  * MS blocks are 16K aligned.
1780  * Cardtables are 4K aligned, at least.
1781  * This means that the cardtable of a given block is 32 bytes aligned.
1782  */
1783 static guint8*
1784 initial_skip_card (guint8 *card_data)
1785 {
1786         mword *cards = (mword*)card_data;
1787         mword card;
1788         int i;
1789         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1790                 card = cards [i];
1791                 if (card)
1792                         break;
1793         }
1794
1795         if (i == CARD_WORDS_PER_BLOCK)
1796                 return card_data + CARDS_PER_BLOCK;
1797
1798 #if defined(__i386__) && defined(__GNUC__)
1799         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1800 #elif defined(__x86_64__) && defined(__GNUC__)
1801         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1802 #elif defined(__s390x__) && defined(__GNUC__)
1803         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1804 #else
1805         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1806                 if (card_data [i])
1807                         return &card_data [i];
1808         }
1809         return card_data;
1810 #endif
1811 }
1812
1813
1814 static G_GNUC_UNUSED guint8*
1815 skip_card (guint8 *card_data, guint8 *card_data_end)
1816 {
1817         while (card_data < card_data_end && !*card_data)
1818                 ++card_data;
1819         return card_data;
1820 }
1821
1822 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1823 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1824 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1825
1826 static void
1827 major_scan_card_table (SgenGrayQueue *queue)
1828 {
1829         MSBlockInfo *block;
1830
1831         FOREACH_BLOCK (block) {
1832                 int block_obj_size;
1833                 char *block_start;
1834
1835                 if (!block->has_references)
1836                         continue;
1837
1838                 block_obj_size = block->obj_size;
1839                 block_start = block->block;
1840
1841                 if (block_obj_size >= CARD_SIZE_IN_BYTES) {
1842                         guint8 *cards;
1843 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1844                         guint8 cards_data [CARDS_PER_BLOCK];
1845 #endif
1846                         char *obj, *end, *base;
1847
1848                         /*We can avoid the extra copy since the remark cardtable was cleaned before */
1849 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1850                         cards = sgen_card_table_get_card_scan_address ((mword)block_start);
1851 #else
1852                         cards = cards_data;
1853                         if (!sgen_card_table_get_card_data (cards_data, (mword)block_start, CARDS_PER_BLOCK))
1854                                 continue;
1855 #endif
1856
1857                         obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, 0);
1858                         end = block_start + MS_BLOCK_SIZE;
1859                         base = sgen_card_table_align_pointer (obj);
1860
1861                         while (obj < end) {
1862                                 if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1863                                         int card_offset = (obj - base) >> CARD_BITS;
1864                                         sgen_cardtable_scan_object (obj, block_obj_size, cards + card_offset, queue);
1865                                 }
1866                                 obj += block_obj_size;
1867                         }
1868                 } else {
1869                         ScanObjectFunc scan_func = mono_sgen_get_minor_scan_object ();
1870                         guint8 *card_data, *card_base;
1871                         guint8 *card_data_end;
1872
1873                         /*
1874                          * This is safe in face of card aliasing for the following reason:
1875                          *
1876                          * Major blocks are 16k aligned, or 32 cards aligned.
1877                          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1878                          * sizes, they won't overflow the cardtable overlap modulus.
1879                          */
1880                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1881                         card_data_end = card_data + CARDS_PER_BLOCK;
1882
1883                         for (card_data = initial_skip_card (card_data); card_data < card_data_end; ++card_data) { //card_data = skip_card (card_data + 1, card_data_end)) {
1884                                 int index;
1885                                 int idx = card_data - card_base;
1886                                 char *start = (char*)(block_start + idx * CARD_SIZE_IN_BYTES);
1887                                 char *end = start + CARD_SIZE_IN_BYTES;
1888                                 char *obj;
1889
1890                                 HEAVY_STAT (++scanned_cards);
1891
1892                                 if (!*card_data)
1893                                         continue;
1894
1895                                 HEAVY_STAT (++marked_cards);
1896
1897                                 sgen_card_table_prepare_card_for_scanning (card_data);
1898
1899                                 if (idx == 0)
1900                                         index = 0;
1901                                 else
1902                                         index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1903
1904                                 obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, index);
1905                                 while (obj < end) {
1906                                         if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1907                                                 HEAVY_STAT (++scanned_objects);
1908                                                 scan_func (obj, queue);
1909                                         }
1910                                         obj += block_obj_size;
1911                                 }
1912                         }
1913                 }
1914         } END_FOREACH_BLOCK;
1915 }
1916 #endif
1917
1918 static gboolean
1919 major_is_worker_thread (MonoNativeThreadId thread)
1920 {
1921         if (concurrent_sweep)
1922                 return thread == ms_sweep_thread;
1923         else
1924                 return FALSE;
1925 }
1926
1927 static void
1928 alloc_free_block_lists (MSBlockInfo ***lists)
1929 {
1930         int i;
1931         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1932                 lists [i] = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1933 }
1934
1935 #ifdef SGEN_PARALLEL_MARK
1936 static void*
1937 major_alloc_worker_data (void)
1938 {
1939         /* FIXME: free this when the workers come down */
1940         MSBlockInfo ***lists = malloc (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX);
1941         alloc_free_block_lists (lists);
1942         return lists;
1943 }
1944
1945 static void
1946 major_init_worker_thread (void *data)
1947 {
1948         MSBlockInfo ***lists = data;
1949         int i;
1950
1951         g_assert (lists && lists != free_block_lists);
1952         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1953                 int j;
1954                 for (j = 0; j < num_block_obj_sizes; ++j)
1955                         g_assert (!lists [i][j]);
1956         }
1957
1958 #ifdef HAVE_KW_THREAD
1959         workers_free_block_lists = data;
1960 #else
1961         mono_native_tls_set_value (workers_free_block_lists_key, data);
1962 #endif
1963 }
1964
1965 static void
1966 major_reset_worker_data (void *data)
1967 {
1968         MSBlockInfo ***lists = data;
1969         int i;
1970         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1971                 int j;
1972                 for (j = 0; j < num_block_obj_sizes; ++j)
1973                         lists [i][j] = NULL;
1974         }
1975 }
1976 #endif
1977
1978 #undef pthread_create
1979
1980 static void
1981 post_param_init (void)
1982 {
1983         if (concurrent_sweep) {
1984                 if (mono_native_thread_create (&ms_sweep_thread, ms_sweep_thread_func, NULL)) {
1985                         fprintf (stderr, "Error: Could not create sweep thread.\n");
1986                         exit (1);
1987                 }
1988         }
1989 }
1990
1991 void
1992 #ifdef SGEN_PARALLEL_MARK
1993 #ifdef FIXED_HEAP
1994 mono_sgen_marksweep_fixed_par_init
1995 #else
1996 mono_sgen_marksweep_par_init
1997 #endif
1998 #else
1999 #ifdef FIXED_HEAP
2000 mono_sgen_marksweep_fixed_init
2001 #else
2002 mono_sgen_marksweep_init
2003 #endif
2004 #endif
2005         (SgenMajorCollector *collector)
2006 {
2007         int i;
2008
2009 #ifndef FIXED_HEAP
2010         mono_sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2011 #endif
2012
2013         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2014         block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
2015         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2016
2017         evacuate_block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
2018         for (i = 0; i < num_block_obj_sizes; ++i)
2019                 evacuate_block_obj_sizes [i] = FALSE;
2020
2021         /*
2022         {
2023                 int i;
2024                 g_print ("block object sizes:\n");
2025                 for (i = 0; i < num_block_obj_sizes; ++i)
2026                         g_print ("%d\n", block_obj_sizes [i]);
2027         }
2028         */
2029
2030         alloc_free_block_lists (free_block_lists);
2031
2032         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2033                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2034         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2035                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2036
2037 #ifdef SGEN_PARALLEL_MARK
2038         LOCK_INIT (ms_block_list_mutex);
2039 #endif
2040
2041         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_alloced);
2042         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_freed);
2043         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_objects_evacuated);
2044         mono_counters_register ("Wait for sweep time", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_time_wait_for_sweep);
2045 #ifdef SGEN_PARALLEL_MARK
2046         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
2047
2048 #ifndef HAVE_KW_THREAD
2049         mono_native_tls_alloc (&workers_free_block_lists_key, NULL);
2050 #endif
2051 #endif
2052
2053         /*
2054          * FIXME: These are superfluous if concurrent sweep is
2055          * disabled.  We might want to create them lazily.
2056          */
2057         MONO_SEM_INIT (&ms_sweep_cmd_semaphore, 0);
2058         MONO_SEM_INIT (&ms_sweep_done_semaphore, 0);
2059
2060         collector->section_size = MAJOR_SECTION_SIZE;
2061 #ifdef SGEN_PARALLEL_MARK
2062         collector->is_parallel = TRUE;
2063         collector->alloc_worker_data = major_alloc_worker_data;
2064         collector->init_worker_thread = major_init_worker_thread;
2065         collector->reset_worker_data = major_reset_worker_data;
2066 #else
2067         collector->is_parallel = FALSE;
2068 #endif
2069         collector->supports_cardtable = TRUE;
2070
2071         collector->have_swept = &have_swept;
2072
2073         collector->alloc_heap = major_alloc_heap;
2074         collector->is_object_live = major_is_object_live;
2075         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2076         collector->alloc_degraded = major_alloc_degraded;
2077         collector->copy_or_mark_object = major_copy_or_mark_object;
2078         collector->alloc_object = major_alloc_object;
2079         collector->free_pinned_object = free_pinned_object;
2080         collector->iterate_objects = major_iterate_objects;
2081         collector->free_non_pinned_object = major_free_non_pinned_object;
2082         collector->find_pin_queue_start_ends = major_find_pin_queue_start_ends;
2083         collector->pin_objects = major_pin_objects;
2084 #ifdef SGEN_HAVE_CARDTABLE
2085         collector->scan_card_table = major_scan_card_table;
2086         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2087 #endif
2088         collector->init_to_space = major_init_to_space;
2089         collector->sweep = major_sweep;
2090         collector->check_scan_starts = major_check_scan_starts;
2091         collector->dump_heap = major_dump_heap;
2092         collector->get_used_size = major_get_used_size;
2093         collector->start_nursery_collection = major_start_nursery_collection;
2094         collector->finish_nursery_collection = major_finish_nursery_collection;
2095         collector->start_major_collection = major_start_major_collection;
2096         collector->finish_major_collection = major_finish_major_collection;
2097         collector->have_computed_minor_collection_allowance = major_have_computer_minor_collection_allowance;
2098         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2099         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2100         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2101         collector->get_num_major_sections = get_num_major_sections;
2102         collector->handle_gc_param = major_handle_gc_param;
2103         collector->print_gc_param_usage = major_print_gc_param_usage;
2104         collector->is_worker_thread = major_is_worker_thread;
2105         collector->post_param_init = post_param_init;
2106
2107         FILL_COLLECTOR_COPY_OBJECT (collector);
2108         FILL_COLLECTOR_SCAN_OBJECT (collector);
2109
2110 #ifdef SGEN_HAVE_CARDTABLE
2111         /*cardtable requires major pages to be 8 cards aligned*/
2112         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2113 #endif
2114 }
2115
2116 #endif