[sgen] Never directly pin objects on the M&S major heap.
[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 pthread_mutex_lock (&ms_block_list_mutex)
180 #define UNLOCK_MS_BLOCK_LIST pthread_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 pthread_key_t 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 pthread_t 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***)(pthread_getspecific (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                         return;
1101                 }
1102
1103                 /*
1104                  * We do this before the CAS because we want to make
1105                  * sure that if another thread sees the destination
1106                  * pointer the VTable is already in place.  Not doing
1107                  * this can crash binary protocols.
1108                  */
1109                 *(MonoVTable**)destination = vt;
1110
1111                 if (SGEN_CAS_PTR (obj, (void*)((mword)destination | SGEN_FORWARDED_BIT), vt) == vt) {
1112                         gboolean was_marked;
1113
1114                         par_copy_object_no_checks (destination, vt, obj, objsize, has_references ? queue : NULL);
1115                         obj = destination;
1116                         *ptr = obj;
1117
1118                         /*
1119                          * FIXME: If we make major_alloc_object() give
1120                          * us the block info, too, we won't have to
1121                          * re-fetch it here.
1122                          */
1123                         block = MS_BLOCK_FOR_OBJ (obj);
1124                         MS_CALC_MARK_BIT (word, bit, obj);
1125                         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1126                         MS_PAR_SET_MARK_BIT (was_marked, block, word, bit);
1127                 } else {
1128                         /*
1129                          * FIXME: We have allocated destination, but
1130                          * we cannot use it.  Give it back to the
1131                          * allocator.
1132                          */
1133                         *(void**)destination = NULL;
1134
1135                         vtable_word = *(mword*)obj;
1136                         g_assert (vtable_word & SGEN_FORWARDED_BIT);
1137
1138                         obj = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1139
1140                         *ptr = obj;
1141
1142                         ++stat_slots_allocated_in_vain;
1143                 }
1144         } else {
1145 #ifdef FIXED_HEAP
1146                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1147 #else
1148                 mword vtable_word = *(mword*)obj;
1149                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1150
1151                 /* see comment in the non-parallel version below */
1152                 if (vtable_word & SGEN_FORWARDED_BIT) {
1153                         *ptr = (void*)vt;
1154                         return;
1155                 }
1156                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1157
1158                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1159 #endif
1160                 {
1161                         int size_index;
1162
1163                         block = MS_BLOCK_FOR_OBJ (obj);
1164                         size_index = block->obj_size_index;
1165
1166                         if (!block->has_pinned && evacuate_block_obj_sizes [size_index]) {
1167                                 if (block->is_to_space)
1168                                         return;
1169
1170 #ifdef FIXED_HEAP
1171                                 {
1172                                         mword vtable_word = *(mword*)obj;
1173                                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1174
1175                                         if (vtable_word & SGEN_FORWARDED_BIT) {
1176                                                 *ptr = (void*)vt;
1177                                                 return;
1178                                         }
1179                                 }
1180 #endif
1181
1182                                 HEAVY_STAT (++stat_major_objects_evacuated);
1183                                 goto do_copy_object;
1184                         }
1185
1186                         MS_PAR_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1187                 } else {
1188 #ifdef FIXED_HEAP
1189                         mword vtable_word = *(mword*)obj;
1190                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1191 #endif
1192
1193                         if (vtable_word & SGEN_PINNED_BIT)
1194                                 return;
1195                         binary_protocol_pin (obj, vt, mono_sgen_safe_object_get_size ((MonoObject*)obj));
1196                         if (SGEN_CAS_PTR (obj, (void*)(vtable_word | SGEN_PINNED_BIT), (void*)vtable_word) == (void*)vtable_word) {
1197                                 if (SGEN_VTABLE_HAS_REFERENCES (vt))
1198                                         GRAY_OBJECT_ENQUEUE (queue, obj);
1199                         } else {
1200                                 g_assert (SGEN_OBJECT_IS_PINNED (obj));
1201                         }
1202                 }
1203         }
1204 }
1205 #else
1206 static void
1207 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1208 {
1209         void *obj = *ptr;
1210         MSBlockInfo *block;
1211
1212         HEAVY_STAT (++stat_copy_object_called_major);
1213
1214         DEBUG (9, g_assert (obj));
1215         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1216
1217         if (ptr_in_nursery (obj)) {
1218                 int word, bit;
1219                 char *forwarded, *old_obj;
1220
1221                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1222                         *ptr = forwarded;
1223                         return;
1224                 }
1225                 if (SGEN_OBJECT_IS_PINNED (obj))
1226                         return;
1227
1228                 HEAVY_STAT (++stat_objects_copied_major);
1229
1230         do_copy_object:
1231                 old_obj = obj;
1232                 obj = copy_object_no_checks (obj, queue);
1233                 if (G_UNLIKELY (old_obj == obj)) {
1234                         /*If we fail to evacuate an object we just stop doing it for a given block size as all other will surely fail too.*/
1235                         if (!ptr_in_nursery (obj)) {
1236                                 int size_index;
1237                                 block = MS_BLOCK_FOR_OBJ (obj);
1238                                 size_index = block->obj_size_index;
1239                                 evacuate_block_obj_sizes [size_index] = FALSE;
1240                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1241                         }
1242                         return;
1243                 }
1244                 *ptr = obj;
1245
1246                 /*
1247                  * FIXME: See comment for copy_object_no_checks().  If
1248                  * we have that, we can let the allocation function
1249                  * give us the block info, too, and we won't have to
1250                  * re-fetch it.
1251                  */
1252                 block = MS_BLOCK_FOR_OBJ (obj);
1253                 MS_CALC_MARK_BIT (word, bit, obj);
1254                 DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1255                 MS_SET_MARK_BIT (block, word, bit);
1256         } else {
1257                 char *forwarded;
1258 #ifdef FIXED_HEAP
1259                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1260 #else
1261                 mword objsize;
1262
1263                 /*
1264                  * If we have don't have a fixed heap we cannot know
1265                  * whether an object is in the LOS or in the small
1266                  * object major heap without checking its size.  To do
1267                  * that, however, we need to know that we actually
1268                  * have a valid object, not a forwarding pointer, so
1269                  * we have to do this check first.
1270                  */
1271                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1272                         *ptr = forwarded;
1273                         return;
1274                 }
1275
1276                 objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
1277
1278                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1279 #endif
1280                 {
1281                         int size_index;
1282                         gboolean evacuate;
1283
1284                         block = MS_BLOCK_FOR_OBJ (obj);
1285                         size_index = block->obj_size_index;
1286                         evacuate = evacuate_block_obj_sizes [size_index];
1287
1288 #ifdef FIXED_HEAP
1289                         /*
1290                          * We could also check for !block->has_pinned
1291                          * here, but it would only make an uncommon case
1292                          * faster, namely objects that are in blocks
1293                          * whose slot sizes are evacuated but which have
1294                          * pinned objects.
1295                          */
1296                         if (evacuate && (forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1297                                 *ptr = forwarded;
1298                                 return;
1299                         }
1300 #endif
1301
1302                         if (evacuate && !block->has_pinned) {
1303                                 g_assert (!SGEN_OBJECT_IS_PINNED (obj));
1304                                 if (block->is_to_space)
1305                                         return;
1306                                 HEAVY_STAT (++stat_major_objects_evacuated);
1307                                 goto do_copy_object;
1308                         } else {
1309                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1310                         }
1311                 } else {
1312                         if (SGEN_OBJECT_IS_PINNED (obj))
1313                                 return;
1314                         binary_protocol_pin (obj, (gpointer)SGEN_LOAD_VTABLE (obj), mono_sgen_safe_object_get_size ((MonoObject*)obj));
1315                         SGEN_PIN_OBJECT (obj);
1316                         /* FIXME: only enqueue if object has references */
1317                         GRAY_OBJECT_ENQUEUE (queue, obj);
1318                 }
1319         }
1320 }
1321 #endif
1322
1323 #include "sgen-major-scan-object.h"
1324
1325 static void
1326 mark_pinned_objects_in_block (MSBlockInfo *block, SgenGrayQueue *queue)
1327 {
1328         int i;
1329         int last_index = -1;
1330
1331         if (!block->pin_queue_num_entries)
1332                 return;
1333
1334         block->has_pinned = TRUE;
1335
1336         for (i = 0; i < block->pin_queue_num_entries; ++i) {
1337                 int index = MS_BLOCK_OBJ_INDEX (block->pin_queue_start [i], block);
1338                 DEBUG (9, g_assert (index >= 0 && index < MS_BLOCK_FREE / block->obj_size));
1339                 if (index == last_index)
1340                         continue;
1341                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (MS_BLOCK_OBJ (block, index), block, queue);
1342                 last_index = index;
1343         }
1344 }
1345
1346 static void
1347 ms_sweep (void)
1348 {
1349         int i;
1350         MSBlockInfo **iter;
1351
1352         /* statistics for evacuation */
1353         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1354         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1355         int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1356
1357         for (i = 0; i < num_block_obj_sizes; ++i)
1358                 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1359
1360         /* clear all the free lists */
1361         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1362                 MSBlockInfo **free_blocks = free_block_lists [i];
1363                 int j;
1364                 for (j = 0; j < num_block_obj_sizes; ++j)
1365                         free_blocks [j] = NULL;
1366         }
1367
1368         /* traverse all blocks, free and zero unmarked objects */
1369         iter = &all_blocks;
1370         while (*iter) {
1371                 MSBlockInfo *block = *iter;
1372                 int count;
1373                 gboolean have_live = FALSE;
1374                 gboolean has_pinned;
1375                 int obj_index;
1376                 int obj_size_index;
1377
1378                 obj_size_index = block->obj_size_index;
1379
1380                 has_pinned = block->has_pinned;
1381                 block->has_pinned = block->pinned;
1382
1383                 block->is_to_space = FALSE;
1384
1385                 count = MS_BLOCK_FREE / block->obj_size;
1386                 block->free_list = NULL;
1387
1388                 for (obj_index = 0; obj_index < count; ++obj_index) {
1389                         int word, bit;
1390                         void *obj = MS_BLOCK_OBJ (block, obj_index);
1391
1392                         MS_CALC_MARK_BIT (word, bit, obj);
1393                         if (MS_MARK_BIT (block, word, bit)) {
1394                                 DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
1395                                 have_live = TRUE;
1396                                 if (!has_pinned)
1397                                         ++slots_used [obj_size_index];
1398                         } else {
1399                                 /* an unmarked object */
1400                                 if (MS_OBJ_ALLOCED (obj, block)) {
1401                                         binary_protocol_empty (obj, block->obj_size);
1402                                         memset (obj, 0, block->obj_size);
1403                                 }
1404                                 *(void**)obj = block->free_list;
1405                                 block->free_list = obj;
1406                         }
1407                 }
1408
1409                 /* reset mark bits */
1410                 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1411
1412                 /*
1413                  * FIXME: reverse free list so that it's in address
1414                  * order
1415                  */
1416
1417                 if (have_live) {
1418                         if (!has_pinned) {
1419                                 ++num_blocks [obj_size_index];
1420                                 slots_available [obj_size_index] += count;
1421                         }
1422
1423                         iter = &block->next;
1424
1425                         /*
1426                          * If there are free slots in the block, add
1427                          * the block to the corresponding free list.
1428                          */
1429                         if (block->free_list) {
1430                                 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1431                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1432                                 block->next_free = free_blocks [index];
1433                                 free_blocks [index] = block;
1434                         }
1435
1436                         update_heap_boundaries_for_block (block);
1437                 } else {
1438                         /*
1439                          * Blocks without live objects are removed from the
1440                          * block list and freed.
1441                          */
1442                         *iter = block->next;
1443
1444 #ifdef FIXED_HEAP
1445                         ms_free_block (block);
1446 #else
1447                         ms_free_block (block->block);
1448
1449                         mono_sgen_free_internal (block, INTERNAL_MEM_MS_BLOCK_INFO);
1450 #endif
1451
1452                         --num_major_sections;
1453                 }
1454         }
1455
1456         for (i = 0; i < num_block_obj_sizes; ++i) {
1457                 float usage = (float)slots_used [i] / (float)slots_available [i];
1458                 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1459                         evacuate_block_obj_sizes [i] = TRUE;
1460                         /*
1461                         g_print ("slot size %d - %d of %d used\n",
1462                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1463                         */
1464                 } else {
1465                         evacuate_block_obj_sizes [i] = FALSE;
1466                 }
1467         }
1468
1469         have_swept = TRUE;
1470 }
1471
1472 static void*
1473 ms_sweep_thread_func (void *dummy)
1474 {
1475         g_assert (concurrent_sweep);
1476
1477         for (;;) {
1478                 int result;
1479
1480                 while ((result = MONO_SEM_WAIT (&ms_sweep_cmd_semaphore)) != 0) {
1481                         if (errno != EINTR)
1482                                 g_error ("MONO_SEM_WAIT");
1483                 }
1484
1485                 ms_sweep ();
1486
1487                 ms_signal_sweep_done ();
1488         }
1489
1490         return NULL;
1491 }
1492
1493 static void
1494 major_sweep (void)
1495 {
1496         if (concurrent_sweep) {
1497                 g_assert (ms_sweep_thread);
1498                 ms_signal_sweep_command ();
1499         } else {
1500                 ms_sweep ();
1501         }
1502 }
1503
1504 static int count_pinned_ref;
1505 static int count_pinned_nonref;
1506 static int count_nonpinned_ref;
1507 static int count_nonpinned_nonref;
1508
1509 static void
1510 count_nonpinned_callback (char *obj, size_t size, void *data)
1511 {
1512         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1513
1514         if (vtable->klass->has_references)
1515                 ++count_nonpinned_ref;
1516         else
1517                 ++count_nonpinned_nonref;
1518 }
1519
1520 static void
1521 count_pinned_callback (char *obj, size_t size, void *data)
1522 {
1523         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1524
1525         if (vtable->klass->has_references)
1526                 ++count_pinned_ref;
1527         else
1528                 ++count_pinned_nonref;
1529 }
1530
1531 static void __attribute__ ((unused))
1532 count_ref_nonref_objs (void)
1533 {
1534         int total;
1535
1536         count_pinned_ref = 0;
1537         count_pinned_nonref = 0;
1538         count_nonpinned_ref = 0;
1539         count_nonpinned_nonref = 0;
1540
1541         major_iterate_objects (TRUE, FALSE, count_nonpinned_callback, NULL);
1542         major_iterate_objects (FALSE, TRUE, count_pinned_callback, NULL);
1543
1544         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1545
1546         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1547                         count_pinned_ref, count_nonpinned_ref,
1548                         count_pinned_nonref, count_nonpinned_nonref,
1549                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1550 }
1551
1552 static int
1553 ms_calculate_block_obj_sizes (double factor, int *arr)
1554 {
1555         double target_size = sizeof (MonoObject);
1556         int num_sizes = 0;
1557         int last_size = 0;
1558
1559         do {
1560                 int target_count = ceil (MS_BLOCK_FREE / target_size);
1561                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1562
1563                 if (size != last_size) {
1564                         if (arr)
1565                                 arr [num_sizes] = size;
1566                         ++num_sizes;
1567                         last_size = size;
1568                 }
1569
1570                 target_size *= factor;
1571         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1572
1573         return num_sizes;
1574 }
1575
1576 /* only valid during minor collections */
1577 static int old_num_major_sections;
1578
1579 static void
1580 major_start_nursery_collection (void)
1581 {
1582         ms_wait_for_sweep_done ();
1583
1584 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1585         consistency_check ();
1586 #endif
1587
1588         old_num_major_sections = num_major_sections;
1589 }
1590
1591 static void
1592 major_finish_nursery_collection (void)
1593 {
1594 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1595         consistency_check ();
1596 #endif
1597         mono_sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1598 }
1599
1600 static void
1601 major_start_major_collection (void)
1602 {
1603         int i;
1604
1605         ms_wait_for_sweep_done ();
1606
1607         /* clear the free lists */
1608         for (i = 0; i < num_block_obj_sizes; ++i) {
1609                 if (!evacuate_block_obj_sizes [i])
1610                         continue;
1611
1612                 free_block_lists [0][i] = NULL;
1613                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1614         }
1615 }
1616
1617 static void
1618 major_finish_major_collection (void)
1619 {
1620 }
1621
1622 static void
1623 major_have_computer_minor_collection_allowance (void)
1624 {
1625 #ifndef FIXED_HEAP
1626         int section_reserve = mono_sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1627
1628         g_assert (have_swept);
1629         ms_wait_for_sweep_done ();
1630         g_assert (!ms_sweep_in_progress);
1631
1632         /*
1633          * FIXME: We don't free blocks on 32 bit platforms because it
1634          * can lead to address space fragmentation, since we're
1635          * allocating blocks in larger contingents.
1636          */
1637         if (sizeof (mword) < 8)
1638                 return;
1639
1640         while (num_empty_blocks > section_reserve) {
1641                 void *next = *(void**)empty_blocks;
1642                 mono_sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE);
1643                 empty_blocks = next;
1644                 /*
1645                  * Needs not be atomic because this is running
1646                  * single-threaded.
1647                  */
1648                 --num_empty_blocks;
1649
1650                 ++stat_major_blocks_freed;
1651         }
1652 #endif
1653 }
1654
1655 static void
1656 major_find_pin_queue_start_ends (SgenGrayQueue *queue)
1657 {
1658         MSBlockInfo *block;
1659
1660         FOREACH_BLOCK (block) {
1661                 block->pin_queue_start = mono_sgen_find_optimized_pin_queue_area (block->block + MS_BLOCK_SKIP, block->block + MS_BLOCK_SIZE,
1662                                 &block->pin_queue_num_entries);
1663         } END_FOREACH_BLOCK;
1664 }
1665
1666 static void
1667 major_pin_objects (SgenGrayQueue *queue)
1668 {
1669         MSBlockInfo *block;
1670
1671         FOREACH_BLOCK (block) {
1672                 mark_pinned_objects_in_block (block, queue);
1673         } END_FOREACH_BLOCK;
1674 }
1675
1676 static void
1677 major_init_to_space (void)
1678 {
1679 }
1680
1681 static void
1682 major_report_pinned_memory_usage (void)
1683 {
1684         g_assert_not_reached ();
1685 }
1686
1687 static gint64
1688 major_get_used_size (void)
1689 {
1690         gint64 size = 0;
1691         MSBlockInfo *block;
1692
1693         FOREACH_BLOCK (block) {
1694                 int count = MS_BLOCK_FREE / block->obj_size;
1695                 void **iter;
1696                 size += count * block->obj_size;
1697                 for (iter = block->free_list; iter; iter = (void**)*iter)
1698                         size -= block->obj_size;
1699         } END_FOREACH_BLOCK;
1700
1701         return size;
1702 }
1703
1704 static int
1705 get_num_major_sections (void)
1706 {
1707         return num_major_sections;
1708 }
1709
1710 static gboolean
1711 major_handle_gc_param (const char *opt)
1712 {
1713 #ifdef FIXED_HEAP
1714         if (g_str_has_prefix (opt, "major-heap-size=")) {
1715                 const char *arg = strchr (opt, '=') + 1;
1716                 glong size;
1717                 if (!mono_gc_parse_environment_string_extract_number (arg, &size))
1718                         return FALSE;
1719                 ms_heap_num_blocks = (size + MS_BLOCK_SIZE - 1) / MS_BLOCK_SIZE;
1720                 g_assert (ms_heap_num_blocks > 0);
1721                 return TRUE;
1722         } else
1723 #endif
1724         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1725                 const char *arg = strchr (opt, '=') + 1;
1726                 int percentage = atoi (arg);
1727                 if (percentage < 0 || percentage > 100) {
1728                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1729                         exit (1);
1730                 }
1731                 evacuation_threshold = (float)percentage / 100.0;
1732                 return TRUE;
1733         } else if (!strcmp (opt, "concurrent-sweep")) {
1734                 concurrent_sweep = TRUE;
1735                 return TRUE;
1736         } else if (!strcmp (opt, "no-concurrent-sweep")) {
1737                 concurrent_sweep = FALSE;
1738                 return TRUE;
1739         }
1740
1741         return FALSE;
1742 }
1743
1744 static void
1745 major_print_gc_param_usage (void)
1746 {
1747         fprintf (stderr,
1748                         ""
1749 #ifdef FIXED_HEAP
1750                         "  major-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n"
1751 #endif
1752                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1753                         "  (no-)concurrent-sweep\n"
1754                         );
1755 }
1756
1757 #ifdef SGEN_HAVE_CARDTABLE
1758 static void
1759 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1760 {
1761         MSBlockInfo *block;
1762
1763         FOREACH_BLOCK (block) {
1764                 if (block->has_references)
1765                         callback ((mword)block->block, MS_BLOCK_SIZE);
1766         } END_FOREACH_BLOCK;
1767 }
1768
1769 #ifdef HEAVY_STATISTICS
1770 extern long long marked_cards;
1771 extern long long scanned_cards;
1772 extern long long scanned_objects;
1773
1774 #endif
1775
1776 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1777 /*
1778  * MS blocks are 16K aligned.
1779  * Cardtables are 4K aligned, at least.
1780  * This means that the cardtable of a given block is 32 bytes aligned.
1781  */
1782 static guint8*
1783 initial_skip_card (guint8 *card_data)
1784 {
1785         mword *cards = (mword*)card_data;
1786         mword card;
1787         int i;
1788         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1789                 card = cards [i];
1790                 if (card)
1791                         break;
1792         }
1793
1794         if (i == CARD_WORDS_PER_BLOCK)
1795                 return card_data + CARDS_PER_BLOCK;
1796
1797 #if defined(__i386__) && defined(__GNUC__)
1798         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1799 #elif defined(__x86_64__) && defined(__GNUC__)
1800         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1801 #elif defined(__s390x__) && defined(__GNUC__)
1802         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1803 #else
1804         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1805                 if (card_data [i])
1806                         return &card_data [i];
1807         }
1808         return card_data;
1809 #endif
1810 }
1811
1812
1813 static G_GNUC_UNUSED guint8*
1814 skip_card (guint8 *card_data, guint8 *card_data_end)
1815 {
1816         while (card_data < card_data_end && !*card_data)
1817                 ++card_data;
1818         return card_data;
1819 }
1820
1821 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1822 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1823 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1824
1825 static void
1826 major_scan_card_table (SgenGrayQueue *queue)
1827 {
1828         MSBlockInfo *block;
1829
1830         FOREACH_BLOCK (block) {
1831                 int block_obj_size;
1832                 char *block_start;
1833
1834                 if (!block->has_references)
1835                         continue;
1836
1837                 block_obj_size = block->obj_size;
1838                 block_start = block->block;
1839
1840                 if (block_obj_size >= CARD_SIZE_IN_BYTES) {
1841                         guint8 *cards;
1842 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1843                         guint8 cards_data [CARDS_PER_BLOCK];
1844 #endif
1845                         char *obj, *end, *base;
1846
1847                         /*We can avoid the extra copy since the remark cardtable was cleaned before */
1848 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1849                         cards = sgen_card_table_get_card_scan_address ((mword)block_start);
1850 #else
1851                         cards = cards_data;
1852                         if (!sgen_card_table_get_card_data (cards_data, (mword)block_start, CARDS_PER_BLOCK))
1853                                 continue;
1854 #endif
1855
1856                         obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, 0);
1857                         end = block_start + MS_BLOCK_SIZE;
1858                         base = sgen_card_table_align_pointer (obj);
1859
1860                         while (obj < end) {
1861                                 if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1862                                         int card_offset = (obj - base) >> CARD_BITS;
1863                                         sgen_cardtable_scan_object (obj, block_obj_size, cards + card_offset, queue);
1864                                 }
1865                                 obj += block_obj_size;
1866                         }
1867                 } else {
1868                         ScanObjectFunc scan_func = mono_sgen_get_minor_scan_object ();
1869                         guint8 *card_data, *card_base;
1870                         guint8 *card_data_end;
1871
1872                         /*
1873                          * This is safe in face of card aliasing for the following reason:
1874                          *
1875                          * Major blocks are 16k aligned, or 32 cards aligned.
1876                          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1877                          * sizes, they won't overflow the cardtable overlap modulus.
1878                          */
1879                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1880                         card_data_end = card_data + CARDS_PER_BLOCK;
1881
1882                         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)) {
1883                                 int index;
1884                                 int idx = card_data - card_base;
1885                                 char *start = (char*)(block_start + idx * CARD_SIZE_IN_BYTES);
1886                                 char *end = start + CARD_SIZE_IN_BYTES;
1887                                 char *obj;
1888
1889                                 HEAVY_STAT (++scanned_cards);
1890
1891                                 if (!*card_data)
1892                                         continue;
1893
1894                                 HEAVY_STAT (++marked_cards);
1895
1896                                 sgen_card_table_prepare_card_for_scanning (card_data);
1897
1898                                 if (idx == 0)
1899                                         index = 0;
1900                                 else
1901                                         index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1902
1903                                 obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, index);
1904                                 while (obj < end) {
1905                                         if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1906                                                 HEAVY_STAT (++scanned_objects);
1907                                                 scan_func (obj, queue);
1908                                         }
1909                                         obj += block_obj_size;
1910                                 }
1911                         }
1912                 }
1913         } END_FOREACH_BLOCK;
1914 }
1915 #endif
1916
1917 static gboolean
1918 major_is_worker_thread (pthread_t thread)
1919 {
1920         if (concurrent_sweep)
1921                 return thread == ms_sweep_thread;
1922         else
1923                 return FALSE;
1924 }
1925
1926 static void
1927 alloc_free_block_lists (MSBlockInfo ***lists)
1928 {
1929         int i;
1930         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1931                 lists [i] = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1932 }
1933
1934 #ifdef SGEN_PARALLEL_MARK
1935 static void*
1936 major_alloc_worker_data (void)
1937 {
1938         /* FIXME: free this when the workers come down */
1939         MSBlockInfo ***lists = malloc (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX);
1940         alloc_free_block_lists (lists);
1941         return lists;
1942 }
1943
1944 static void
1945 major_init_worker_thread (void *data)
1946 {
1947         MSBlockInfo ***lists = data;
1948         int i;
1949
1950         g_assert (lists && lists != free_block_lists);
1951         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1952                 int j;
1953                 for (j = 0; j < num_block_obj_sizes; ++j)
1954                         g_assert (!lists [i][j]);
1955         }
1956
1957 #ifdef HAVE_KW_THREAD
1958         workers_free_block_lists = data;
1959 #else
1960         pthread_setspecific (workers_free_block_lists_key, data);
1961 #endif
1962 }
1963
1964 static void
1965 major_reset_worker_data (void *data)
1966 {
1967         MSBlockInfo ***lists = data;
1968         int i;
1969         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1970                 int j;
1971                 for (j = 0; j < num_block_obj_sizes; ++j)
1972                         lists [i][j] = NULL;
1973         }
1974 }
1975 #endif
1976
1977 #undef pthread_create
1978
1979 static void
1980 post_param_init (void)
1981 {
1982         if (concurrent_sweep) {
1983                 if (pthread_create (&ms_sweep_thread, NULL, ms_sweep_thread_func, NULL)) {
1984                         fprintf (stderr, "Error: Could not create sweep thread.\n");
1985                         exit (1);
1986                 }
1987         }
1988 }
1989
1990 void
1991 #ifdef SGEN_PARALLEL_MARK
1992 #ifdef FIXED_HEAP
1993 mono_sgen_marksweep_fixed_par_init
1994 #else
1995 mono_sgen_marksweep_par_init
1996 #endif
1997 #else
1998 #ifdef FIXED_HEAP
1999 mono_sgen_marksweep_fixed_init
2000 #else
2001 mono_sgen_marksweep_init
2002 #endif
2003 #endif
2004         (SgenMajorCollector *collector)
2005 {
2006         int i;
2007
2008 #ifndef FIXED_HEAP
2009         mono_sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2010 #endif
2011
2012         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2013         block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
2014         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2015
2016         evacuate_block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
2017         for (i = 0; i < num_block_obj_sizes; ++i)
2018                 evacuate_block_obj_sizes [i] = FALSE;
2019
2020         /*
2021         {
2022                 int i;
2023                 g_print ("block object sizes:\n");
2024                 for (i = 0; i < num_block_obj_sizes; ++i)
2025                         g_print ("%d\n", block_obj_sizes [i]);
2026         }
2027         */
2028
2029         alloc_free_block_lists (free_block_lists);
2030
2031         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2032                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2033         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2034                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2035
2036         LOCK_INIT (ms_block_list_mutex);
2037
2038         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_alloced);
2039         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_freed);
2040         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_objects_evacuated);
2041         mono_counters_register ("Wait for sweep time", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_time_wait_for_sweep);
2042 #ifdef SGEN_PARALLEL_MARK
2043         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
2044
2045 #ifndef HAVE_KW_THREAD
2046         pthread_key_create (&workers_free_block_lists_key, NULL);
2047 #endif
2048 #endif
2049
2050         /*
2051          * FIXME: These are superfluous if concurrent sweep is
2052          * disabled.  We might want to create them lazily.
2053          */
2054         MONO_SEM_INIT (&ms_sweep_cmd_semaphore, 0);
2055         MONO_SEM_INIT (&ms_sweep_done_semaphore, 0);
2056
2057         collector->section_size = MAJOR_SECTION_SIZE;
2058 #ifdef SGEN_PARALLEL_MARK
2059         collector->is_parallel = TRUE;
2060         collector->alloc_worker_data = major_alloc_worker_data;
2061         collector->init_worker_thread = major_init_worker_thread;
2062         collector->reset_worker_data = major_reset_worker_data;
2063 #else
2064         collector->is_parallel = FALSE;
2065 #endif
2066         collector->supports_cardtable = TRUE;
2067
2068         collector->have_swept = &have_swept;
2069
2070         collector->alloc_heap = major_alloc_heap;
2071         collector->is_object_live = major_is_object_live;
2072         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2073         collector->alloc_degraded = major_alloc_degraded;
2074         collector->copy_or_mark_object = major_copy_or_mark_object;
2075         collector->alloc_object = major_alloc_object;
2076         collector->free_pinned_object = free_pinned_object;
2077         collector->iterate_objects = major_iterate_objects;
2078         collector->free_non_pinned_object = major_free_non_pinned_object;
2079         collector->find_pin_queue_start_ends = major_find_pin_queue_start_ends;
2080         collector->pin_objects = major_pin_objects;
2081 #ifdef SGEN_HAVE_CARDTABLE
2082         collector->scan_card_table = major_scan_card_table;
2083         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2084 #endif
2085         collector->init_to_space = major_init_to_space;
2086         collector->sweep = major_sweep;
2087         collector->check_scan_starts = major_check_scan_starts;
2088         collector->dump_heap = major_dump_heap;
2089         collector->get_used_size = major_get_used_size;
2090         collector->start_nursery_collection = major_start_nursery_collection;
2091         collector->finish_nursery_collection = major_finish_nursery_collection;
2092         collector->start_major_collection = major_start_major_collection;
2093         collector->finish_major_collection = major_finish_major_collection;
2094         collector->have_computed_minor_collection_allowance = major_have_computer_minor_collection_allowance;
2095         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2096         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2097         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2098         collector->get_num_major_sections = get_num_major_sections;
2099         collector->handle_gc_param = major_handle_gc_param;
2100         collector->print_gc_param_usage = major_print_gc_param_usage;
2101         collector->is_worker_thread = major_is_worker_thread;
2102         collector->post_param_init = post_param_init;
2103
2104         FILL_COLLECTOR_COPY_OBJECT (collector);
2105         FILL_COLLECTOR_SCAN_OBJECT (collector);
2106
2107 #ifdef SGEN_HAVE_CARDTABLE
2108         /*cardtable requires major pages to be 8 cards aligned*/
2109         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2110 #endif
2111 }
2112
2113 #endif