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