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