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