67b422c1990c10c52989478c2331e14b0f1dfbb3
[mono.git] / mono / sgen / sgen-marksweep.c
1 /**
2  * \file
3  * The Mark & Sweep major collector.
4  *
5  * Author:
6  *      Mark Probst <mark.probst@gmail.com>
7  *
8  * Copyright 2009-2010 Novell, Inc.
9  * Copyright (C) 2012 Xamarin Inc
10  *
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #include "config.h"
15
16 #ifdef HAVE_SGEN_GC
17
18 #include <math.h>
19 #include <errno.h>
20 #include <string.h>
21 #include <stdlib.h>
22
23 #include "mono/sgen/sgen-gc.h"
24 #include "mono/sgen/sgen-protocol.h"
25 #include "mono/sgen/sgen-cardtable.h"
26 #include "mono/sgen/sgen-memory-governor.h"
27 #include "mono/sgen/sgen-layout-stats.h"
28 #include "mono/sgen/sgen-pointer-queue.h"
29 #include "mono/sgen/sgen-array-list.h"
30 #include "mono/sgen/sgen-pinning.h"
31 #include "mono/sgen/sgen-workers.h"
32 #include "mono/sgen/sgen-thread-pool.h"
33 #include "mono/sgen/sgen-client.h"
34 #include "mono/utils/mono-memory-model.h"
35
36 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
37 #define MS_BLOCK_SIZE   ARCH_MIN_MS_BLOCK_SIZE
38 #define MS_BLOCK_SIZE_SHIFT     ARCH_MIN_MS_BLOCK_SIZE_SHIFT
39 #else
40 #define MS_BLOCK_SIZE_SHIFT     14      /* INT FASTENABLE */
41 #define MS_BLOCK_SIZE           (1 << MS_BLOCK_SIZE_SHIFT)
42 #endif
43 #define MAJOR_SECTION_SIZE      MS_BLOCK_SIZE
44 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
45
46 /*
47  * Don't allocate single blocks, but alloc a contingent of this many
48  * blocks in one swoop.  This must be a power of two.
49  */
50 #define MS_BLOCK_ALLOC_NUM      32
51
52 /*
53  * Number of bytes before the first object in a block.  At the start
54  * of a block is the MSBlockHeader, then opional padding, then come
55  * the objects, so this must be >= sizeof (MSBlockHeader).
56  */
57 #define MS_BLOCK_SKIP   ((sizeof (MSBlockHeader) + 15) & ~15)
58
59 #define MS_BLOCK_FREE   (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
60
61 #define MS_NUM_MARK_WORDS       (MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (guint32) * 8 - 1) / (sizeof (guint32) * 8)
62
63 /*
64  * Blocks progress from one state to the next:
65  *
66  * SWEPT           The block is fully swept.  It might or might not be in
67  *                 a free list.
68  *
69  * MARKING         The block might or might not contain live objects.  If
70  *                 we're in between an initial collection pause and the
71  *                 finishing pause, the block might or might not be in a
72  *                 free list.
73  *
74  * CHECKING        The sweep thread is investigating the block to determine
75  *                 whether or not it contains live objects.  The block is
76  *                 not in a free list.
77  *
78  * NEED_SWEEPING   The block contains live objects but has not yet been
79  *                 swept.  It also contains free slots.  It is in a block
80  *                 free list.
81  *
82  * SWEEPING        The block is being swept.  It might be in a free list.
83  */
84
85 enum {
86         BLOCK_STATE_SWEPT,
87         BLOCK_STATE_MARKING,
88         BLOCK_STATE_CHECKING,
89         BLOCK_STATE_NEED_SWEEPING,
90         BLOCK_STATE_SWEEPING
91 };
92
93 typedef struct _MSBlockInfo MSBlockInfo;
94 struct _MSBlockInfo {
95         guint16 obj_size;
96         /*
97          * FIXME: Do we even need this? It's only used during sweep and might be worth
98          * recalculating to save the space.
99          */
100         guint16 obj_size_index;
101         /* FIXME: Reduce this - it only needs a byte. */
102         volatile gint32 state;
103         gint16 nused;
104         unsigned int pinned : 1;
105         unsigned int has_references : 1;
106         unsigned int has_pinned : 1;    /* means cannot evacuate */
107         unsigned int is_to_space : 1;
108         void ** volatile free_list;
109         MSBlockInfo * volatile next_free;
110         guint8 * volatile cardtable_mod_union;
111         guint32 mark_words [MS_NUM_MARK_WORDS];
112 };
113
114 #define MS_BLOCK_FOR_BLOCK_INFO(b)      ((char*)(b))
115
116 #define MS_BLOCK_OBJ(b,i)               ((GCObject *)(MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i)))
117 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size)             (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
118 #define MS_BLOCK_DATA_FOR_OBJ(o)        ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
119
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
126 /* object index will always be small */
127 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
128
129 //casting to int is fine since blocks are 32k
130 #define MS_CALC_MARK_BIT(w,b,o)         do {                            \
131                 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
132                 (w) = i >> 5;                                           \
133                 (b) = i & 31;                                           \
134         } while (0)
135
136 #define MS_MARK_BIT(bl,w,b)     ((bl)->mark_words [(w)] & (ONE_P << (b)))
137 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
138 #define MS_SET_MARK_BIT_PAR(bl,w,b,first)       do {                    \
139                 guint32 tmp_mark_word = (bl)->mark_words [(w)];         \
140                 guint32 old_mark_word;                                  \
141                 first = FALSE;                                          \
142                 while (!(tmp_mark_word & (ONE_P << (b)))) {             \
143                         old_mark_word = tmp_mark_word;                  \
144                         tmp_mark_word = InterlockedCompareExchange ((volatile gint32*)&(bl)->mark_words [w], old_mark_word | (ONE_P << (b)), old_mark_word); \
145                         if (tmp_mark_word == old_mark_word) {           \
146                                 first = TRUE;                           \
147                                 break;                                  \
148                         }                                               \
149                 }                                                       \
150         } while (0)
151
152
153 #define MS_OBJ_ALLOCED(o,b)     (*(void**)(o) && (*(char**)(o) < MS_BLOCK_FOR_BLOCK_INFO (b) || *(char**)(o) >= MS_BLOCK_FOR_BLOCK_INFO (b) + MS_BLOCK_SIZE))
154
155 #define MS_BLOCK_OBJ_SIZE_FACTOR        (pow (2.0, 1.0 / 3))
156
157 /*
158  * This way we can lookup block object size indexes for sizes up to
159  * 256 bytes with a single load.
160  */
161 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES      32
162
163 static int *block_obj_sizes;
164 static int num_block_obj_sizes;
165 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
166
167 #define MS_BLOCK_FLAG_PINNED    1
168 #define MS_BLOCK_FLAG_REFS      2
169
170 #define MS_BLOCK_TYPE_MAX       4
171
172 static gboolean *evacuate_block_obj_sizes;
173 static float evacuation_threshold = 0.666f;
174
175 static gboolean lazy_sweep = TRUE;
176
177 enum {
178         SWEEP_STATE_SWEPT,
179         SWEEP_STATE_NEED_SWEEPING,
180         SWEEP_STATE_SWEEPING,
181         SWEEP_STATE_SWEEPING_AND_ITERATING,
182         SWEEP_STATE_COMPACTING
183 };
184
185 static volatile int sweep_state = SWEEP_STATE_SWEPT;
186
187 static gboolean concurrent_mark;
188 static gboolean concurrent_sweep = TRUE;
189
190 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl)      SGEN_POINTER_IS_TAGGED_1 ((bl))
191 #define BLOCK_TAG_HAS_REFERENCES(bl)            SGEN_POINTER_TAG_1 ((bl))
192
193 #define BLOCK_IS_TAGGED_CHECKING(bl)            SGEN_POINTER_IS_TAGGED_2 ((bl))
194 #define BLOCK_TAG_CHECKING(bl)                  SGEN_POINTER_TAG_2 ((bl))
195
196 #define BLOCK_UNTAG(bl)                         ((MSBlockInfo *)SGEN_POINTER_UNTAG_12 ((bl)))
197
198 #define BLOCK_TAG(bl)                           ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
199
200 /* all allocated blocks in the system */
201 static SgenArrayList allocated_blocks = SGEN_ARRAY_LIST_INIT (NULL, sgen_array_list_default_is_slot_set, sgen_array_list_default_cas_setter, INTERNAL_MEM_PIN_QUEUE);
202
203 /* non-allocated block free-list */
204 static void *empty_blocks = NULL;
205 static size_t num_empty_blocks = 0;
206
207 /*
208  * We can iterate the block list also while sweep is in progress but we
209  * need to account for blocks that will be checked for sweeping and even
210  * freed in the process.
211  */
212 #define FOREACH_BLOCK_NO_LOCK(bl) {                                     \
213         volatile gpointer *slot;                                                \
214         SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {        \
215                 (bl) = BLOCK_UNTAG (*slot);                             \
216                 if (!(bl))                                              \
217                         continue;
218 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) {                   \
219         volatile gpointer *slot;                                                \
220         SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {        \
221                 (bl) = (MSBlockInfo *) (*slot);                 \
222                 if (!(bl))                                              \
223                         continue;                                       \
224                 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl));           \
225                 (bl) = BLOCK_UNTAG ((bl));
226 #define END_FOREACH_BLOCK_NO_LOCK       } SGEN_ARRAY_LIST_END_FOREACH_SLOT; }
227
228 static volatile size_t num_major_sections = 0;
229 /*
230  * One free block list for each block object size.  We add and remove blocks from these
231  * lists lock-free via CAS.
232  *
233  * Blocks accessed/removed from `free_block_lists`:
234  *   from the mutator (with GC lock held)
235  *   in nursery collections
236  *   in non-concurrent major collections
237  *   in the finishing pause of concurrent major collections (whole list is cleared)
238  *
239  * Blocks added to `free_block_lists`:
240  *   in the sweeping thread
241  *   during nursery collections
242  *   from domain clearing (with the world stopped and no sweeping happening)
243  *
244  * The only item of those that doesn't require the GC lock is the sweep thread.  The sweep
245  * thread only ever adds blocks to the free list, so the ABA problem can't occur.
246  */
247 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
248 static MonoNativeTlsKey worker_block_free_list_key;
249
250 static guint64 stat_major_blocks_alloced = 0;
251 static guint64 stat_major_blocks_freed = 0;
252 static guint64 stat_major_blocks_lazy_swept = 0;
253
254 static guint64 stat_major_blocks_freed_ideal = 0;
255 static guint64 stat_major_blocks_freed_less_ideal = 0;
256 static guint64 stat_major_blocks_freed_individual = 0;
257 static guint64 stat_major_blocks_alloced_less_ideal = 0;
258
259 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
260 static guint64 num_major_objects_marked = 0;
261 #define INC_NUM_MAJOR_OBJECTS_MARKED()  (++num_major_objects_marked)
262 #else
263 #define INC_NUM_MAJOR_OBJECTS_MARKED()
264 #endif
265
266 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
267 static mono_mutex_t scanned_objects_list_lock;
268 static SgenPointerQueue scanned_objects_list;
269
270 static void
271 add_scanned_object (void *ptr)
272 {
273         if (!binary_protocol_is_enabled ())
274                 return;
275
276         mono_os_mutex_lock (&scanned_objects_list_lock);
277         sgen_pointer_queue_add (&scanned_objects_list, ptr);
278         mono_os_mutex_unlock (&scanned_objects_list_lock);
279 }
280 #endif
281
282 static gboolean sweep_block (MSBlockInfo *block);
283
284 static int
285 ms_find_block_obj_size_index (size_t size)
286 {
287         int i;
288         SGEN_ASSERT (9, size <= SGEN_MAX_SMALL_OBJ_SIZE, "size %zd is bigger than max small object size %d", size, SGEN_MAX_SMALL_OBJ_SIZE);
289         for (i = 0; i < num_block_obj_sizes; ++i)
290                 if (block_obj_sizes [i] >= size)
291                         return i;
292         g_error ("no object of size %zd\n", size);
293         return -1;
294 }
295
296 #define FREE_BLOCKS_FROM(lists,p,r)     (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
297 #define FREE_BLOCKS(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
298 #define FREE_BLOCKS_LOCAL(p,r)          (FREE_BLOCKS_FROM (((MSBlockInfo***)mono_native_tls_get_value (worker_block_free_list_key)), (p), (r)))
299
300 #define MS_BLOCK_OBJ_SIZE_INDEX(s)                              \
301         (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ?      \
302          fast_block_obj_size_indexes [((s)+7)>>3] :             \
303          ms_find_block_obj_size_index ((s)))
304
305 static void*
306 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
307 {
308         char *start;
309         if (nursery_align)
310                 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
311         else
312                 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
313
314         return start;
315 }
316
317 static void
318 update_heap_boundaries_for_block (MSBlockInfo *block)
319 {
320         sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
321 }
322
323 /*
324  * Thread safe
325  */
326 static void*
327 ms_get_empty_block (void)
328 {
329         char *p;
330         int i;
331         void *block, *empty, *next;
332
333  retry:
334         if (!empty_blocks) {
335                 /*
336                  * We try allocating MS_BLOCK_ALLOC_NUM blocks first.  If that's
337                  * unsuccessful, we halve the number of blocks and try again, until we're at
338                  * 1.  If that doesn't work, either, we assert.
339                  */
340                 int alloc_num = MS_BLOCK_ALLOC_NUM;
341                 for (;;) {
342                         p = (char *)sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE,
343                                 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
344                                 alloc_num == 1 ? "major heap section" : NULL, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
345                         if (p)
346                                 break;
347                         alloc_num >>= 1;
348                 }
349
350                 for (i = 0; i < alloc_num; ++i) {
351                         block = p;
352                         /*
353                          * We do the free list update one after the
354                          * other so that other threads can use the new
355                          * blocks as quickly as possible.
356                          */
357                         do {
358                                 empty = empty_blocks;
359                                 *(void**)block = empty;
360                         } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
361                         p += MS_BLOCK_SIZE;
362                 }
363
364                 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
365
366                 stat_major_blocks_alloced += alloc_num;
367 #if SIZEOF_VOID_P != 8
368                 if (alloc_num != MS_BLOCK_ALLOC_NUM)
369                         stat_major_blocks_alloced_less_ideal += alloc_num;
370 #endif
371         }
372
373         do {
374                 empty = empty_blocks;
375                 if (!empty)
376                         goto retry;
377                 block = empty;
378                 next = *(void**)block;
379         } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
380
381         SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
382
383         *(void**)block = NULL;
384
385         g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
386
387         return block;
388 }
389
390 /*
391  * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
392  * list, where it will either be freed later on, or reused in nursery collections.
393  */
394 static void
395 ms_free_block (MSBlockInfo *info)
396 {
397         void *empty;
398         char *block = MS_BLOCK_FOR_BLOCK_INFO (info);
399
400         sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
401         if (info->cardtable_mod_union)
402                 sgen_card_table_free_mod_union (info->cardtable_mod_union, block, MS_BLOCK_SIZE);
403         memset (block, 0, MS_BLOCK_SIZE);
404
405         do {
406                 empty = empty_blocks;
407                 *(void**)block = empty;
408         } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
409
410         SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
411
412         binary_protocol_block_free (block, MS_BLOCK_SIZE);
413 }
414
415 static gboolean
416 sweep_in_progress (void)
417 {
418         int state = sweep_state;
419         return state == SWEEP_STATE_SWEEPING ||
420                 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
421                 state == SWEEP_STATE_COMPACTING;
422 }
423
424 static inline gboolean
425 block_is_swept_or_marking (MSBlockInfo *block)
426 {
427         gint32 state = block->state;
428         return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
429 }
430
431 //#define MARKSWEEP_CONSISTENCY_CHECK
432
433 #ifdef MARKSWEEP_CONSISTENCY_CHECK
434 static void
435 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
436 {
437         SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
438         for (; block; block = block->next_free) {
439                 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
440                 g_assert (block->obj_size == size);
441                 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
442
443                 /* blocks in the free lists must have at least
444                    one free slot */
445                 g_assert (block->free_list);
446
447                 /* the block must be in the allocated_blocks array */
448                 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
449         }
450 }
451
452 static void
453 check_empty_blocks (void)
454 {
455         void *p;
456         size_t i = 0;
457         for (p = empty_blocks; p; p = *(void**)p)
458                 ++i;
459         g_assert (i == num_empty_blocks);
460 }
461
462 static void
463 consistency_check (void)
464 {
465         MSBlockInfo *block;
466         int i;
467
468         /* check all blocks */
469         FOREACH_BLOCK_NO_LOCK (block) {
470                 int count = MS_BLOCK_FREE / block->obj_size;
471                 int num_free = 0;
472                 void **free;
473
474                 /* count number of free slots */
475                 for (i = 0; i < count; ++i) {
476                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
477                         if (!MS_OBJ_ALLOCED (obj, block))
478                                 ++num_free;
479                 }
480
481                 /* check free list */
482                 for (free = block->free_list; free; free = (void**)*free) {
483                         g_assert (MS_BLOCK_FOR_OBJ (free) == block);
484                         --num_free;
485                 }
486                 g_assert (num_free == 0);
487
488                 /* check all mark words are zero */
489                 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
490                         for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
491                                 g_assert (block->mark_words [i] == 0);
492                 }
493         } END_FOREACH_BLOCK_NO_LOCK;
494
495         /* check free blocks */
496         for (i = 0; i < num_block_obj_sizes; ++i) {
497                 int j;
498                 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
499                         check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
500         }
501
502         check_empty_blocks ();
503 }
504 #endif
505
506 static void
507 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
508 {
509         MSBlockInfo *old;
510         do {
511                 block->next_free = old = free_blocks [size_index];
512         } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
513 }
514
515 static void major_finish_sweep_checking (void);
516
517 static gboolean
518 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
519 {
520         int size = block_obj_sizes [size_index];
521         int count = MS_BLOCK_FREE / size;
522         MSBlockInfo *info;
523         MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
524         char *obj_start;
525         int i;
526
527         if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
528                 return FALSE;
529
530         info = (MSBlockInfo*)ms_get_empty_block ();
531
532         SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
533
534         info->obj_size = size;
535         info->obj_size_index = size_index;
536         info->pinned = pinned;
537         info->has_references = has_references;
538         info->has_pinned = pinned;
539         /*
540          * Blocks that are to-space are not evacuated from.  During an major collection
541          * blocks are allocated for two reasons: evacuating objects from the nursery and
542          * evacuating them from major blocks marked for evacuation.  In both cases we don't
543          * want further evacuation. We also don't want to evacuate objects allocated during
544          * the concurrent mark since it would add pointless stress on the finishing pause.
545          */
546         info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
547         info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
548         SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
549         info->cardtable_mod_union = NULL;
550
551         update_heap_boundaries_for_block (info);
552
553         binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
554
555         /* build free list */
556         obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
557         info->free_list = (void**)obj_start;
558         /* we're skipping the last one - it must be nulled */
559         for (i = 0; i < count - 1; ++i) {
560                 char *next_obj_start = obj_start + size;
561                 *(void**)obj_start = next_obj_start;
562                 obj_start = next_obj_start;
563         }
564         /* the last one */
565         *(void**)obj_start = NULL;
566
567         add_free_block (free_blocks, size_index, info);
568
569         sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
570
571         SGEN_ATOMIC_ADD_P (num_major_sections, 1);
572         return TRUE;
573 }
574
575 static gboolean
576 ptr_is_in_major_block (char *ptr, char **start, gboolean *pinned)
577 {
578         MSBlockInfo *block;
579
580         FOREACH_BLOCK_NO_LOCK (block) {
581                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
582                         int count = MS_BLOCK_FREE / block->obj_size;
583                         int i;
584
585                         if (start)
586                                 *start = NULL;
587                         for (i = 0; i <= count; ++i) {
588                                 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
589                                         if (start)
590                                                 *start = (char *)MS_BLOCK_OBJ (block, i);
591                                         break;
592                                 }
593                         }
594                         if (pinned)
595                                 *pinned = block->pinned;
596                         return TRUE;
597                 }
598         } END_FOREACH_BLOCK_NO_LOCK;
599         return FALSE;
600 }
601
602 static gboolean
603 ptr_is_from_pinned_alloc (char *ptr)
604 {
605         gboolean pinned;
606         if (ptr_is_in_major_block (ptr, NULL, &pinned))
607                 return pinned;
608         return FALSE;
609 }
610
611 static void
612 ensure_can_access_block_free_list (MSBlockInfo *block)
613 {
614  retry:
615         for (;;) {
616                 switch (block->state) {
617                 case BLOCK_STATE_SWEPT:
618                 case BLOCK_STATE_MARKING:
619                         return;
620                 case BLOCK_STATE_CHECKING:
621                         SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
622                         break;
623                 case BLOCK_STATE_NEED_SWEEPING:
624                         if (sweep_block (block))
625                                 ++stat_major_blocks_lazy_swept;
626                         break;
627                 case BLOCK_STATE_SWEEPING:
628                         /* FIXME: do this more elegantly */
629                         g_usleep (100);
630                         goto retry;
631                 default:
632                         SGEN_ASSERT (0, FALSE, "Illegal block state");
633                         break;
634                 }
635         }
636 }
637
638 static void*
639 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
640 {
641         MSBlockInfo *block, *next_free_block;
642         void *obj, *next_free_slot;
643
644  retry:
645         block = free_blocks [size_index];
646         SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
647
648         ensure_can_access_block_free_list (block);
649
650         obj = block->free_list;
651         SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
652
653         next_free_slot = *(void**)obj;
654         if (next_free_slot) {
655                 block->free_list = (gpointer *)next_free_slot;
656                 return obj;
657         }
658
659         next_free_block = block->next_free;
660         if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
661                 goto retry;
662
663         block->free_list = NULL;
664         block->next_free = NULL;
665
666         return obj;
667 }
668
669 static GCObject*
670 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
671 {
672         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
673         MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
674         void *obj;
675
676         if (!free_blocks [size_index]) {
677                 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
678                         return NULL;
679         }
680
681         obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
682
683         /* FIXME: assumes object layout */
684         *(GCVTable*)obj = vtable;
685
686         total_allocated_major += block_obj_sizes [size_index]; 
687
688         return (GCObject *)obj;
689 }
690
691 static GCObject*
692 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
693 {
694         return alloc_obj (vtable, size, FALSE, has_references);
695 }
696
697 /*
698  * This can only be called by sgen workers. While this is called we assume
699  * that no other thread is accessing the block free lists. The world should
700  * be stopped and the gc thread should be waiting for workers to finish.
701  */
702 static GCObject*
703 major_alloc_object_par (GCVTable vtable, size_t size, gboolean has_references)
704 {
705         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
706         MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (FALSE, has_references);
707         MSBlockInfo **free_blocks_local = FREE_BLOCKS_LOCAL (FALSE, has_references);
708         void *obj;
709
710         if (free_blocks_local [size_index]) {
711 get_slot:
712                 obj = unlink_slot_from_free_list_uncontested (free_blocks_local, size_index);
713         } else {
714                 MSBlockInfo *block;
715 get_block:
716                 block = free_blocks [size_index];
717                 if (!block) {
718                         if (G_UNLIKELY (!ms_alloc_block (size_index, FALSE, has_references)))
719                                 return NULL;
720                         goto get_block;
721                 } else {
722                         MSBlockInfo *next_free = block->next_free;
723                         /*
724                          * Once a block is removed from the main list, it cannot return on the list until
725                          * all the workers are finished and sweep is starting. This means we don't need
726                          * to account for ABA problems.
727                          */
728                         if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free, block) != block)
729                                 goto get_block;
730                         g_assert (block->free_list);
731                         block->next_free = free_blocks_local [size_index];
732                         free_blocks_local [size_index] = block;
733
734                         goto get_slot;
735                 }
736         }
737
738         /* FIXME: assumes object layout */
739         *(GCVTable*)obj = vtable;
740
741         /* FIXME is it worth CAS-ing here */
742         total_allocated_major += block_obj_sizes [size_index]; 
743
744         return (GCObject *)obj;
745 }
746
747 /*
748  * We're not freeing the block if it's empty.  We leave that work for
749  * the next major collection.
750  *
751  * This is just called from the domain clearing code, which runs in a
752  * single thread and has the GC lock, so we don't need an extra lock.
753  */
754 static void
755 free_object (GCObject *obj, size_t size, gboolean pinned)
756 {
757         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
758         int word, bit;
759         gboolean in_free_list;
760
761         SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
762
763         ensure_can_access_block_free_list (block);
764         SGEN_ASSERT (9, (pinned && block->pinned) || (!pinned && !block->pinned), "free-object pinning mixup object %p pinned %d block %p pinned %d", obj, pinned, block, block->pinned);
765         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
766         MS_CALC_MARK_BIT (word, bit, obj);
767         SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
768
769         memset (obj, 0, size);
770
771         in_free_list = !!block->free_list;
772         *(void**)obj = block->free_list;
773         block->free_list = (void**)obj;
774
775         if (!in_free_list) {
776                 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
777                 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
778                 SGEN_ASSERT (9, !block->next_free, "block %p doesn't have a free-list of object but belongs to a free-list of blocks", block);
779                 add_free_block (free_blocks, size_index, block);
780         }
781 }
782
783 static void
784 major_free_non_pinned_object (GCObject *obj, size_t size)
785 {
786         free_object (obj, size, FALSE);
787 }
788
789 /* size is a multiple of SGEN_ALLOC_ALIGN */
790 static GCObject*
791 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
792 {
793         void *res;
794
795         res = alloc_obj (vtable, size, TRUE, has_references);
796          /*If we failed to alloc memory, we better try releasing memory
797           *as pinned alloc is requested by the runtime.
798           */
799          if (!res) {
800                 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE, TRUE);
801                 res = alloc_obj (vtable, size, TRUE, has_references);
802          }
803          return (GCObject *)res;
804 }
805
806 static void
807 free_pinned_object (GCObject *obj, size_t size)
808 {
809         free_object (obj, size, TRUE);
810 }
811
812 /*
813  * size is already rounded up and we hold the GC lock.
814  */
815 static GCObject*
816 major_alloc_degraded (GCVTable vtable, size_t size)
817 {
818         GCObject *obj;
819
820         obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
821         if (G_LIKELY (obj)) {
822                 HEAVY_STAT (++stat_objects_alloced_degraded);
823                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
824         }
825         return obj;
826 }
827
828 /*
829  * obj is some object.  If it's not in the major heap (i.e. if it's in
830  * the nursery or LOS), return FALSE.  Otherwise return whether it's
831  * been marked or copied.
832  */
833 static gboolean
834 major_is_object_live (GCObject *obj)
835 {
836         MSBlockInfo *block;
837         int word, bit;
838         mword objsize;
839
840         if (sgen_ptr_in_nursery (obj))
841                 return FALSE;
842
843         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
844
845         /* LOS */
846         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
847                 return FALSE;
848
849         /* now we know it's in a major block */
850         block = MS_BLOCK_FOR_OBJ (obj);
851         SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
852         MS_CALC_MARK_BIT (word, bit, obj);
853         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
854 }
855
856 static gboolean
857 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
858 {
859         gboolean pinned;
860         if (ptr_is_in_major_block (ptr, start, &pinned))
861                 return !pinned;
862         return FALSE;
863 }
864
865 static gboolean
866 try_set_sweep_state (int new_, int expected)
867 {
868         int old = SGEN_CAS (&sweep_state, new_, expected);
869         return old == expected;
870 }
871
872 static void
873 set_sweep_state (int new_, int expected)
874 {
875         gboolean success = try_set_sweep_state (new_, expected);
876         SGEN_ASSERT (0, success, "Could not set sweep state.");
877 }
878
879 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
880
881 static SgenThreadPoolJob * volatile sweep_job;
882 static SgenThreadPoolJob * volatile sweep_blocks_job;
883
884 static void
885 major_finish_sweep_checking (void)
886 {
887         guint32 block_index;
888         SgenThreadPoolJob *job;
889
890  retry:
891         switch (sweep_state) {
892         case SWEEP_STATE_SWEPT:
893         case SWEEP_STATE_NEED_SWEEPING:
894                 return;
895         case SWEEP_STATE_SWEEPING:
896                 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
897                         break;
898                 goto retry;
899         case SWEEP_STATE_SWEEPING_AND_ITERATING:
900                 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
901                 goto retry;
902         case SWEEP_STATE_COMPACTING:
903                 goto wait;
904         default:
905                 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
906                 break;
907         }
908
909         /*
910          * We're running with the world stopped and the only other thread doing work is the
911          * sweep thread, which doesn't add blocks to the array, so we can safely access
912          * `next_slot`.
913          */
914         for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
915                 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
916
917         set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
918
919  wait:
920         job = sweep_job;
921         if (job)
922                 sgen_thread_pool_job_wait (job);
923         SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
924         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
925 }
926
927 static void
928 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
929 {
930         gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
931         gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
932         gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
933         MSBlockInfo *block;
934
935         /* No actual sweeping will take place if we are in the middle of a major collection. */
936         major_finish_sweep_checking ();
937         FOREACH_BLOCK_NO_LOCK (block) {
938                 int count = MS_BLOCK_FREE / block->obj_size;
939                 int i;
940
941                 if (block->pinned && !pinned)
942                         continue;
943                 if (!block->pinned && !non_pinned)
944                         continue;
945                 if (sweep && lazy_sweep && !block_is_swept_or_marking (block)) {
946                         sweep_block (block);
947                         SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
948                 }
949
950                 for (i = 0; i < count; ++i) {
951                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
952                         if (MS_OBJ_ALLOCED (obj, block))
953                                 callback ((GCObject*)obj, block->obj_size, data);
954                 }
955         } END_FOREACH_BLOCK_NO_LOCK;
956 }
957
958 static gboolean
959 major_is_valid_object (char *object)
960 {
961         MSBlockInfo *block;
962
963         FOREACH_BLOCK_NO_LOCK (block) {
964                 int idx;
965                 char *obj;
966
967                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
968                         continue;
969
970                 idx = MS_BLOCK_OBJ_INDEX (object, block);
971                 obj = (char*)MS_BLOCK_OBJ (block, idx);
972                 if (obj != object)
973                         return FALSE;
974                 return MS_OBJ_ALLOCED (obj, block);
975         } END_FOREACH_BLOCK_NO_LOCK;
976
977         return FALSE;
978 }
979
980
981 static GCVTable
982 major_describe_pointer (char *ptr)
983 {
984         MSBlockInfo *block;
985
986         FOREACH_BLOCK_NO_LOCK (block) {
987                 int idx;
988                 char *obj;
989                 gboolean live;
990                 GCVTable vtable;
991                 int w, b;
992                 gboolean marked;
993
994                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
995                         continue;
996
997                 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
998                         MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
999
1000                 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
1001                 obj = (char*)MS_BLOCK_OBJ (block, idx);
1002                 live = MS_OBJ_ALLOCED (obj, block);
1003                 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
1004
1005                 MS_CALC_MARK_BIT (w, b, obj);
1006                 marked = MS_MARK_BIT (block, w, b);
1007
1008                 if (obj == ptr) {
1009                         SGEN_LOG (0, "\t(");
1010                         if (live)
1011                                 SGEN_LOG (0, "object");
1012                         else
1013                                 SGEN_LOG (0, "dead-object");
1014                 } else {
1015                         if (live)
1016                                 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
1017                         else
1018                                 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
1019                 }
1020
1021                 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
1022
1023                 return vtable;
1024         } END_FOREACH_BLOCK_NO_LOCK;
1025
1026         return NULL;
1027 }
1028
1029 static void
1030 major_check_scan_starts (void)
1031 {
1032 }
1033
1034 static void
1035 major_dump_heap (FILE *heap_dump_file)
1036 {
1037         MSBlockInfo *block;
1038         int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1039         int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1040         int i;
1041
1042         for (i = 0; i < num_block_obj_sizes; ++i)
1043                 slots_available [i] = slots_used [i] = 0;
1044
1045         FOREACH_BLOCK_NO_LOCK (block) {
1046                 int index = ms_find_block_obj_size_index (block->obj_size);
1047                 int count = MS_BLOCK_FREE / block->obj_size;
1048
1049                 slots_available [index] += count;
1050                 for (i = 0; i < count; ++i) {
1051                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1052                                 ++slots_used [index];
1053                 }
1054         } END_FOREACH_BLOCK_NO_LOCK;
1055
1056         fprintf (heap_dump_file, "<occupancies>\n");
1057         for (i = 0; i < num_block_obj_sizes; ++i) {
1058                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1059                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
1060         }
1061         fprintf (heap_dump_file, "</occupancies>\n");
1062
1063         FOREACH_BLOCK_NO_LOCK (block) {
1064                 int count = MS_BLOCK_FREE / block->obj_size;
1065                 int i;
1066                 int start = -1;
1067
1068                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1069
1070                 for (i = 0; i <= count; ++i) {
1071                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1072                                 if (start < 0)
1073                                         start = i;
1074                         } else {
1075                                 if (start >= 0) {
1076                                         sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1077                                         start = -1;
1078                                 }
1079                         }
1080                 }
1081
1082                 fprintf (heap_dump_file, "</section>\n");
1083         } END_FOREACH_BLOCK_NO_LOCK;
1084 }
1085
1086 static guint8*
1087 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1088 {
1089         guint8 *mod_union = block->cardtable_mod_union;
1090         guint8 *other;
1091         if (mod_union)
1092                 return mod_union;
1093         else if (!allocate)
1094                 return NULL;
1095         mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1096         other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1097         if (!other) {
1098                 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1099                 return mod_union;
1100         }
1101         sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1102         return other;
1103 }
1104
1105 static inline guint8*
1106 major_get_cardtable_mod_union_for_reference (char *ptr)
1107 {
1108         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1109         size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1110         guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1111         SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1112         return &mod_union [offset];
1113 }
1114
1115 /*
1116  * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1117  */
1118 static void
1119 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1120 {
1121         int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1122         if (sgen_safe_object_is_small (obj, type)) {
1123                 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1124                 SGEN_ASSERT (0, MS_BLOCK_FOR_OBJ (obj) == MS_BLOCK_FOR_OBJ (ptr), "How can an object and a reference inside it not be in the same block?");
1125                 *card_byte = 1;
1126         } else {
1127                 sgen_los_mark_mod_union_card (obj, ptr);
1128         }
1129         binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1130 }
1131
1132 static inline gboolean
1133 major_block_is_evacuating (MSBlockInfo *block)
1134 {
1135         if (evacuate_block_obj_sizes [block->obj_size_index] &&
1136                         !block->has_pinned &&
1137                         !block->is_to_space)
1138                 return TRUE;
1139         return FALSE;
1140 }
1141
1142 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do {           \
1143                 int __word, __bit;                                      \
1144                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1145                 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1146                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
1147                         MS_SET_MARK_BIT ((block), __word, __bit);       \
1148                         if (sgen_gc_descr_has_references (desc))                        \
1149                                 GRAY_OBJECT_ENQUEUE_SERIAL ((queue), (obj), (desc)); \
1150                         binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1151                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
1152                 }                                                       \
1153         } while (0)
1154 #define MS_MARK_OBJECT_AND_ENQUEUE_PAR(obj,desc,block,queue) do {       \
1155                 int __word, __bit;                                      \
1156                 gboolean first;                                         \
1157                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1158                 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1159                 MS_SET_MARK_BIT_PAR ((block), __word, __bit, first);    \
1160                 if (first) {                                            \
1161                         if (sgen_gc_descr_has_references (desc))        \
1162                                 GRAY_OBJECT_ENQUEUE_PARALLEL ((queue), (obj), (desc)); \
1163                         binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1164                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
1165                 }                                                       \
1166         } while (0)
1167
1168
1169
1170 static void
1171 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1172 {
1173         MSBlockInfo *block;
1174
1175         if (concurrent_mark)
1176                 g_assert_not_reached ();
1177
1178         block = MS_BLOCK_FOR_OBJ (obj);
1179         block->has_pinned = TRUE;
1180         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1181 }
1182
1183 #define COPY_OR_MARK_PARALLEL
1184 #include "sgen-major-copy-object.h"
1185
1186 static long long
1187 major_get_and_reset_num_major_objects_marked (void)
1188 {
1189 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1190         long long num = num_major_objects_marked;
1191         num_major_objects_marked = 0;
1192         return num;
1193 #else
1194         return 0;
1195 #endif
1196 }
1197
1198 #define PREFETCH_CARDS          1       /* BOOL FASTENABLE */
1199 #if !PREFETCH_CARDS
1200 #undef PREFETCH_CARDS
1201 #endif
1202
1203 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1204 #if defined(PLATFORM_MACOSX)
1205 #if MONO_GNUC_VERSION <= 40300
1206 #undef PREFETCH_CARDS
1207 #endif
1208 #endif
1209
1210 #ifdef HEAVY_STATISTICS
1211 static guint64 stat_optimized_copy;
1212 static guint64 stat_optimized_copy_nursery;
1213 static guint64 stat_optimized_copy_nursery_forwarded;
1214 static guint64 stat_optimized_copy_nursery_pinned;
1215 static guint64 stat_optimized_copy_major;
1216 static guint64 stat_optimized_copy_major_small_fast;
1217 static guint64 stat_optimized_copy_major_small_slow;
1218 static guint64 stat_optimized_copy_major_large;
1219 static guint64 stat_optimized_copy_major_forwarded;
1220 static guint64 stat_optimized_copy_major_small_evacuate;
1221 static guint64 stat_optimized_major_scan;
1222 static guint64 stat_optimized_major_scan_no_refs;
1223
1224 static guint64 stat_drain_prefetch_fills;
1225 static guint64 stat_drain_prefetch_fill_failures;
1226 static guint64 stat_drain_loops;
1227 #endif
1228
1229 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_no_evacuation
1230 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_no_evacuation
1231 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_no_evacuation
1232 #include "sgen-marksweep-drain-gray-stack.h"
1233
1234 #define COPY_OR_MARK_PARALLEL
1235 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_par_no_evacuation
1236 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_par_no_evacuation
1237 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_par_no_evacuation
1238 #include "sgen-marksweep-drain-gray-stack.h"
1239
1240 #define COPY_OR_MARK_WITH_EVACUATION
1241 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_with_evacuation
1242 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_with_evacuation
1243 #define SCAN_VTYPE_FUNCTION_NAME        major_scan_vtype_with_evacuation
1244 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_with_evacuation
1245 #define SCAN_PTR_FIELD_FUNCTION_NAME    major_scan_ptr_field_with_evacuation
1246 #include "sgen-marksweep-drain-gray-stack.h"
1247
1248 #define COPY_OR_MARK_PARALLEL
1249 #define COPY_OR_MARK_WITH_EVACUATION
1250 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_par_with_evacuation
1251 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_par_with_evacuation
1252 #define SCAN_VTYPE_FUNCTION_NAME        major_scan_vtype_par_with_evacuation
1253 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_par_with_evacuation
1254 #define SCAN_PTR_FIELD_FUNCTION_NAME    major_scan_ptr_field_par_with_evacuation
1255 #include "sgen-marksweep-drain-gray-stack.h"
1256
1257 #define COPY_OR_MARK_CONCURRENT
1258 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_concurrent_no_evacuation
1259 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_concurrent_no_evacuation
1260 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_concurrent_no_evacuation
1261 #include "sgen-marksweep-drain-gray-stack.h"
1262
1263 #define COPY_OR_MARK_PARALLEL
1264 #define COPY_OR_MARK_CONCURRENT
1265 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_concurrent_par_no_evacuation
1266 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_concurrent_par_no_evacuation
1267 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_concurrent_par_no_evacuation
1268 #include "sgen-marksweep-drain-gray-stack.h"
1269
1270 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1271 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_concurrent_with_evacuation
1272 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_concurrent_with_evacuation
1273 #define SCAN_VTYPE_FUNCTION_NAME        major_scan_vtype_concurrent_with_evacuation
1274 #define SCAN_PTR_FIELD_FUNCTION_NAME    major_scan_ptr_field_concurrent_with_evacuation
1275 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_concurrent_with_evacuation
1276 #include "sgen-marksweep-drain-gray-stack.h"
1277
1278 #define COPY_OR_MARK_PARALLEL
1279 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1280 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_concurrent_par_with_evacuation
1281 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_concurrent_par_with_evacuation
1282 #define SCAN_VTYPE_FUNCTION_NAME        major_scan_vtype_concurrent_par_with_evacuation
1283 #define SCAN_PTR_FIELD_FUNCTION_NAME    major_scan_ptr_field_concurrent_par_with_evacuation
1284 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_concurrent_par_with_evacuation
1285 #include "sgen-marksweep-drain-gray-stack.h"
1286
1287 static inline gboolean
1288 major_is_evacuating (void)
1289 {
1290         int i;
1291         for (i = 0; i < num_block_obj_sizes; ++i) {
1292                 if (evacuate_block_obj_sizes [i]) {
1293                         return TRUE;
1294                 }
1295         }
1296
1297         return FALSE;
1298 }
1299
1300 static gboolean
1301 drain_gray_stack (SgenGrayQueue *queue)
1302 {
1303         if (major_is_evacuating ())
1304                 return drain_gray_stack_with_evacuation (queue);
1305         else
1306                 return drain_gray_stack_no_evacuation (queue);
1307 }
1308
1309 static gboolean
1310 drain_gray_stack_par (SgenGrayQueue *queue)
1311 {
1312         if (major_is_evacuating ())
1313                 return drain_gray_stack_par_with_evacuation (queue);
1314         else
1315                 return drain_gray_stack_par_no_evacuation (queue);
1316 }
1317
1318 static gboolean
1319 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1320 {
1321         if (major_is_evacuating ())
1322                 return drain_gray_stack_concurrent_with_evacuation (queue);
1323         else
1324                 return drain_gray_stack_concurrent_no_evacuation (queue);
1325 }
1326
1327 static gboolean
1328 drain_gray_stack_concurrent_par (SgenGrayQueue *queue)
1329 {
1330         if (major_is_evacuating ())
1331                 return drain_gray_stack_concurrent_par_with_evacuation (queue);
1332         else
1333                 return drain_gray_stack_concurrent_par_no_evacuation (queue);
1334 }
1335
1336 static void
1337 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1338 {
1339         major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1340 }
1341
1342 static void
1343 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1344 {
1345         major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1346 }
1347
1348 static void
1349 major_copy_or_mark_object_concurrent_par_canonical (GCObject **ptr, SgenGrayQueue *queue)
1350 {
1351         major_copy_or_mark_object_concurrent_par_with_evacuation (ptr, *ptr, queue);
1352 }
1353
1354 static void
1355 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1356 {
1357         major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1358 }
1359
1360 static void
1361 major_copy_or_mark_object_concurrent_par_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1362 {
1363         major_copy_or_mark_object_par_with_evacuation (ptr, *ptr, queue);
1364 }
1365
1366 static void
1367 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1368 {
1369         void **entry, **end;
1370         int last_index = -1;
1371
1372         if (first_entry == last_entry)
1373                 return;
1374
1375         entry = sgen_pinning_get_entry (first_entry);
1376         end = sgen_pinning_get_entry (last_entry);
1377
1378         for (; entry < end; ++entry) {
1379                 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1380                 GCObject *obj;
1381                 SGEN_ASSERT (9, index >= 0 && index < MS_BLOCK_FREE / block->obj_size, "invalid object %p index %d max-index %d", *entry, index, (int)(MS_BLOCK_FREE / block->obj_size));
1382                 if (index == last_index)
1383                         continue;
1384                 obj = MS_BLOCK_OBJ (block, index);
1385                 if (!MS_OBJ_ALLOCED (obj, block))
1386                         continue;
1387                 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1388                 sgen_pin_stats_register_object (obj, GENERATION_OLD);
1389                 last_index = index;
1390         }
1391
1392         /*
1393          * There might have been potential pinning "pointers" into this block, but none of
1394          * them pointed to occupied slots, in which case we don't have to pin the block.
1395          */
1396         if (last_index >= 0)
1397                 block->has_pinned = TRUE;
1398 }
1399
1400 static inline void
1401 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1402 {
1403         int obj_index;
1404
1405         for (obj_index = 0; obj_index < count; ++obj_index) {
1406                 int word, bit;
1407                 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1408
1409                 MS_CALC_MARK_BIT (word, bit, obj);
1410                 if (MS_MARK_BIT (block, word, bit)) {
1411                         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1412                 } else {
1413                         /* an unmarked object */
1414                         if (MS_OBJ_ALLOCED (obj, block)) {
1415                                 /*
1416                                  * FIXME: Merge consecutive
1417                                  * slots for lower reporting
1418                                  * overhead.  Maybe memset
1419                                  * will also benefit?
1420                                  */
1421                                 binary_protocol_empty (obj, obj_size);
1422                                 memset (obj, 0, obj_size);
1423                         }
1424                         *(void**)obj = block->free_list;
1425                         block->free_list = (void **)obj;
1426                 }
1427         }
1428 }
1429
1430 static inline gboolean
1431 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1432 {
1433         gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1434         gboolean success = old_state == expected_state;
1435         if (success)
1436                 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1437         return success;
1438 }
1439
1440 static inline void
1441 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1442 {
1443         SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1444         block->state = new_state;
1445         binary_protocol_block_set_state (block, MS_BLOCK_SIZE, expected_state, new_state);
1446 }
1447
1448 /*
1449  * If `block` needs sweeping, sweep it and return TRUE.  Otherwise return FALSE.
1450  *
1451  * Sweeping means iterating through the block's slots and building the free-list from the
1452  * unmarked ones.  They will also be zeroed.  The mark bits will be reset.
1453  */
1454 static gboolean
1455 sweep_block (MSBlockInfo *block)
1456 {
1457         int count;
1458         void *reversed = NULL;
1459
1460  retry:
1461         switch (block->state) {
1462         case BLOCK_STATE_SWEPT:
1463                 return FALSE;
1464         case BLOCK_STATE_MARKING:
1465         case BLOCK_STATE_CHECKING:
1466                 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1467                 goto retry;
1468         case BLOCK_STATE_SWEEPING:
1469                 /* FIXME: Do this more elegantly */
1470                 g_usleep (100);
1471                 goto retry;
1472         case BLOCK_STATE_NEED_SWEEPING:
1473                 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1474                         goto retry;
1475                 break;
1476         default:
1477                 SGEN_ASSERT (0, FALSE, "Illegal block state");
1478         }
1479
1480         SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1481
1482         count = MS_BLOCK_FREE / block->obj_size;
1483
1484         block->free_list = NULL;
1485
1486         /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1487         // FIXME: Add more sizes
1488         switch (block->obj_size) {
1489         case 16:
1490                 sweep_block_for_size (block, count, 16);
1491                 break;
1492         default:
1493                 sweep_block_for_size (block, count, block->obj_size);
1494                 break;
1495         }
1496
1497         /* reset mark bits */
1498         memset (block->mark_words, 0, sizeof (guint32) * MS_NUM_MARK_WORDS);
1499
1500         /* Reverse free list so that it's in address order */
1501         reversed = NULL;
1502         while (block->free_list) {
1503                 void *next = *(void**)block->free_list;
1504                 *(void**)block->free_list = reversed;
1505                 reversed = block->free_list;
1506                 block->free_list = (void **)next;
1507         }
1508         block->free_list = (void **)reversed;
1509
1510         mono_memory_write_barrier ();
1511
1512         set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1513
1514         return TRUE;
1515 }
1516
1517 static inline int
1518 bitcount (mword d)
1519 {
1520         int count = 0;
1521
1522 #ifdef __GNUC__
1523         if (sizeof (mword) == 8)
1524                 count += __builtin_popcountll (d);
1525         else
1526                 count += __builtin_popcount (d);
1527 #else
1528         while (d) {
1529                 count ++;
1530                 d &= (d - 1);
1531         }
1532 #endif
1533         return count;
1534 }
1535
1536 /* statistics for evacuation */
1537 static size_t *sweep_slots_available;
1538 static size_t *sweep_slots_used;
1539 static size_t *sweep_num_blocks;
1540
1541 static volatile size_t num_major_sections_before_sweep;
1542 static volatile size_t num_major_sections_freed_in_sweep;
1543
1544 static void
1545 sgen_worker_clear_free_block_lists (WorkerData *worker)
1546 {
1547         int i, j;
1548
1549         if (!worker->free_block_lists)
1550                 return;
1551
1552         for (i = 0; i < MS_BLOCK_TYPE_MAX; i++) {
1553                 for (j = 0; j < num_block_obj_sizes; j++) {
1554                         ((MSBlockInfo***) worker->free_block_lists) [i][j] = NULL;
1555                 }
1556         }
1557 }
1558
1559 static void
1560 sweep_start (void)
1561 {
1562         int i;
1563
1564         for (i = 0; i < num_block_obj_sizes; ++i)
1565                 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1566
1567         /* clear all the free lists */
1568         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1569                 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1570                 int j;
1571                 for (j = 0; j < num_block_obj_sizes; ++j)
1572                         free_blocks [j] = NULL;
1573         }
1574
1575         sgen_workers_foreach (sgen_worker_clear_free_block_lists);
1576 }
1577
1578 static void sweep_finish (void);
1579
1580 /*
1581  * If `wait` is TRUE and the block is currently being checked, this function will wait until
1582  * the checking has finished.
1583  *
1584  * Returns whether the block is still there.  If `wait` is FALSE, the return value will not
1585  * be correct, i.e. must not be used.
1586  */
1587 static gboolean
1588 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1589 {
1590         int count;
1591         gboolean have_live = FALSE;
1592         gboolean have_free = FALSE;
1593         int nused = 0;
1594         int block_state;
1595         int i;
1596         void *tagged_block;
1597         MSBlockInfo *block;
1598         volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1599
1600         SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1601
1602         if (have_checked)
1603                 *have_checked = FALSE;
1604
1605  retry:
1606         tagged_block = *(void * volatile *)block_slot;
1607         if (!tagged_block)
1608                 return FALSE;
1609
1610         if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1611                 if (!wait)
1612                         return FALSE;
1613                 /* FIXME: do this more elegantly */
1614                 g_usleep (100);
1615                 goto retry;
1616         }
1617
1618         if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1619                 goto retry;
1620
1621         block = BLOCK_UNTAG (tagged_block);
1622         block_state = block->state;
1623
1624         if (!sweep_in_progress ()) {
1625                 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1626                 if (!lazy_sweep)
1627                         SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1628         }
1629
1630         switch (block_state) {
1631         case BLOCK_STATE_SWEPT:
1632         case BLOCK_STATE_NEED_SWEEPING:
1633         case BLOCK_STATE_SWEEPING:
1634                 goto done;
1635         case BLOCK_STATE_MARKING:
1636                 break;
1637         case BLOCK_STATE_CHECKING:
1638                 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1639                 goto done;
1640         default:
1641                 SGEN_ASSERT (0, FALSE, "Illegal block state");
1642                 break;
1643         }
1644
1645         SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1646         set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1647
1648         if (have_checked)
1649                 *have_checked = TRUE;
1650
1651         block->has_pinned = block->pinned;
1652
1653         block->is_to_space = FALSE;
1654
1655         count = MS_BLOCK_FREE / block->obj_size;
1656
1657         if (block->cardtable_mod_union)
1658                 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1659
1660         /* Count marked objects in the block */
1661         for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1662                 nused += bitcount (block->mark_words [i]);
1663
1664         block->nused = nused;
1665         if (nused)
1666                 have_live = TRUE;
1667         if (nused < count)
1668                 have_free = TRUE;
1669
1670         if (have_live) {
1671                 int obj_size_index = block->obj_size_index;
1672                 gboolean has_pinned = block->has_pinned;
1673
1674                 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1675
1676                 /*
1677                  * FIXME: Go straight to SWEPT if there are no free slots.  We need
1678                  * to set the free slot list to NULL, though, and maybe update some
1679                  * statistics.
1680                  */
1681                 if (!lazy_sweep)
1682                         sweep_block (block);
1683
1684                 if (!has_pinned) {
1685                         ++sweep_num_blocks [obj_size_index];
1686                         sweep_slots_used [obj_size_index] += nused;
1687                         sweep_slots_available [obj_size_index] += count;
1688                 }
1689
1690                 /*
1691                  * If there are free slots in the block, add
1692                  * the block to the corresponding free list.
1693                  */
1694                 if (have_free) {
1695                         MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1696
1697                         if (!lazy_sweep)
1698                                 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1699
1700                         add_free_block (free_blocks, obj_size_index, block);
1701                 }
1702
1703                 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1704                 update_heap_boundaries_for_block (block);
1705         } else {
1706                 /*
1707                  * Blocks without live objects are removed from the
1708                  * block list and freed.
1709                  */
1710                 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1711                 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1712
1713                 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1714                 ms_free_block (block);
1715
1716                 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1717                 SGEN_ATOMIC_ADD_P (num_major_sections_freed_in_sweep, 1);
1718
1719                 tagged_block = NULL;
1720         }
1721
1722  done:
1723         /*
1724          * Once the block is written back without the checking bit other threads are
1725          * free to access it. Make sure the block state is visible before we write it
1726          * back.
1727          */
1728         mono_memory_write_barrier ();
1729         *block_slot = tagged_block;
1730         return !!tagged_block;
1731 }
1732
1733 static void
1734 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1735 {
1736         volatile gpointer *slot;
1737         MSBlockInfo *bl;
1738
1739         SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1740                 bl = BLOCK_UNTAG (*slot);
1741                 if (bl)
1742                         sweep_block (bl);
1743         } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1744
1745         mono_memory_write_barrier ();
1746
1747         sweep_blocks_job = NULL;
1748 }
1749
1750 static void
1751 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1752 {
1753         guint32 block_index;
1754         guint32 num_blocks = num_major_sections_before_sweep;
1755
1756         SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1757         SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1758
1759         /*
1760          * We traverse the block array from high to low.  Nursery collections will have to
1761          * cooperate with the sweep thread to finish sweeping, and they will traverse from
1762          * low to high, to avoid constantly colliding on the same blocks.
1763          */
1764         for (block_index = allocated_blocks.next_slot; block_index-- > 0;) {
1765                 ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL);
1766         }
1767
1768         while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1769                 /*
1770                  * The main GC thread is currently iterating over the block array to help us
1771                  * finish the sweep.  We have already finished, but we don't want to mess up
1772                  * that iteration, so we just wait for it.
1773                  */
1774                 g_usleep (100);
1775         }
1776
1777         if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1778                 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1779                         MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1780                         SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1781                 }
1782         }
1783
1784         /*
1785          * Concurrently sweep all the blocks to reduce workload during minor
1786          * pauses where we need certain blocks to be swept. At the start of
1787          * the next major we need all blocks to be swept anyway.
1788          */
1789         if (concurrent_sweep && lazy_sweep) {
1790                 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1791                 sgen_thread_pool_job_enqueue (sweep_blocks_job);
1792         }
1793
1794         sweep_finish ();
1795
1796         sweep_job = NULL;
1797 }
1798
1799 static void
1800 sweep_finish (void)
1801 {
1802         mword used_slots_size = 0;
1803         int i;
1804
1805         for (i = 0; i < num_block_obj_sizes; ++i) {
1806                 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1807                 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1808                         evacuate_block_obj_sizes [i] = TRUE;
1809                         /*
1810                         g_print ("slot size %d - %d of %d used\n",
1811                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1812                         */
1813                 } else {
1814                         evacuate_block_obj_sizes [i] = FALSE;
1815                 }
1816
1817                 used_slots_size += sweep_slots_used [i] * block_obj_sizes [i];
1818         }
1819
1820         sgen_memgov_major_post_sweep (used_slots_size);
1821
1822         set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1823         if (concurrent_sweep)
1824                 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1825 }
1826
1827 static void
1828 major_sweep (void)
1829 {
1830         set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1831
1832         sweep_start ();
1833
1834         num_major_sections_before_sweep = num_major_sections;
1835         num_major_sections_freed_in_sweep = 0;
1836
1837         SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1838         if (concurrent_sweep) {
1839                 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1840                 sgen_thread_pool_job_enqueue (sweep_job);
1841         } else {
1842                 sweep_job_func (NULL, NULL);
1843         }
1844 }
1845
1846 static gboolean
1847 major_have_swept (void)
1848 {
1849         return sweep_state == SWEEP_STATE_SWEPT;
1850 }
1851
1852 static int count_pinned_ref;
1853 static int count_pinned_nonref;
1854 static int count_nonpinned_ref;
1855 static int count_nonpinned_nonref;
1856
1857 static void
1858 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1859 {
1860         GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1861
1862         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1863                 ++count_nonpinned_ref;
1864         else
1865                 ++count_nonpinned_nonref;
1866 }
1867
1868 static void
1869 count_pinned_callback (GCObject *obj, size_t size, void *data)
1870 {
1871         GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1872
1873         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1874                 ++count_pinned_ref;
1875         else
1876                 ++count_pinned_nonref;
1877 }
1878
1879 static G_GNUC_UNUSED void
1880 count_ref_nonref_objs (void)
1881 {
1882         int total;
1883
1884         count_pinned_ref = 0;
1885         count_pinned_nonref = 0;
1886         count_nonpinned_ref = 0;
1887         count_nonpinned_nonref = 0;
1888
1889         major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1890         major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1891
1892         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1893
1894         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1895                         count_pinned_ref, count_nonpinned_ref,
1896                         count_pinned_nonref, count_nonpinned_nonref,
1897                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1898 }
1899
1900 static int
1901 ms_calculate_block_obj_sizes (double factor, int *arr)
1902 {
1903         double target_size;
1904         int num_sizes = 0;
1905         int last_size = 0;
1906
1907         /*
1908          * Have every possible slot size starting with the minimal
1909          * object size up to and including four times that size.  Then
1910          * proceed by increasing geometrically with the given factor.
1911          */
1912
1913         for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1914                 if (arr)
1915                         arr [num_sizes] = size;
1916                 ++num_sizes;
1917                 last_size = size;
1918         }
1919         target_size = (double)last_size;
1920
1921         do {
1922                 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1923                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1924
1925                 if (size != last_size) {
1926                         if (arr)
1927                                 arr [num_sizes] = size;
1928                         ++num_sizes;
1929                         last_size = size;
1930                 }
1931
1932                 target_size *= factor;
1933         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1934
1935         return num_sizes;
1936 }
1937
1938 /* only valid during minor collections */
1939 static mword old_num_major_sections;
1940
1941 static void
1942 major_start_nursery_collection (void)
1943 {
1944 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1945         consistency_check ();
1946 #endif
1947
1948         old_num_major_sections = num_major_sections;
1949 }
1950
1951 static void
1952 major_finish_nursery_collection (void)
1953 {
1954 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1955         consistency_check ();
1956 #endif
1957 }
1958
1959 static int
1960 block_usage_comparer (const void *bl1, const void *bl2)
1961 {
1962         const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
1963         const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
1964
1965         return nused2 - nused1;
1966 }
1967
1968 static void
1969 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1970 {
1971         MSBlockInfo **evacuated_blocks;
1972         size_t index = 0, count, num_blocks = 0, num_used = 0;
1973         MSBlockInfo *info;
1974         MSBlockInfo * volatile *prev;
1975
1976         for (info = *block_list; info != NULL; info = info->next_free) {
1977                 num_blocks++;
1978                 num_used += info->nused;
1979         }
1980
1981         /*
1982          * We have a set of blocks in the freelist which will be evacuated. Instead
1983          * of evacuating all of the blocks into new ones, we traverse the freelist
1984          * sorting it by the number of occupied slots, evacuating the objects from
1985          * blocks with fewer used slots into fuller blocks.
1986          *
1987          * The number of used slots is set at the end of the previous sweep. Since
1988          * we sequentially unlink slots from blocks, except for the head of the
1989          * freelist, for blocks on the freelist, the number of used slots is the same
1990          * as at the end of the previous sweep.
1991          */
1992         evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
1993
1994         for (info = *block_list; info != NULL; info = info->next_free) {
1995                 evacuated_blocks [index++] = info;
1996         }
1997
1998         SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
1999
2000         sgen_qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
2001
2002         /*
2003          * Form a new freelist with the fullest blocks. These blocks will also be
2004          * marked as to_space so we don't evacuate from them.
2005          */
2006         count = MS_BLOCK_FREE / block_obj_sizes [size_index];
2007         prev = block_list;
2008         for (index = 0; index < (num_used + count - 1) / count; index++) {
2009                 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
2010                 info = evacuated_blocks [index];
2011                 info->is_to_space = TRUE;
2012                 *prev = info;
2013                 prev = &info->next_free;
2014         }
2015         *prev = NULL;
2016
2017         sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
2018 }
2019
2020 static void
2021 major_start_major_collection (void)
2022 {
2023         MSBlockInfo *block;
2024         int i;
2025
2026         major_finish_sweep_checking ();
2027
2028         /*
2029          * Clear the free lists for block sizes where we do evacuation.  For those block
2030          * sizes we will have to allocate new blocks.
2031          */
2032         for (i = 0; i < num_block_obj_sizes; ++i) {
2033                 if (!evacuate_block_obj_sizes [i])
2034                         continue;
2035
2036                 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
2037
2038                 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
2039                 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
2040         }
2041
2042         if (lazy_sweep && concurrent_sweep) {
2043                 /*
2044                  * sweep_blocks_job is created before sweep_finish, which we wait for above
2045                  * (major_finish_sweep_checking). After the end of sweep, if we don't have
2046                  * sweep_blocks_job set, it means that it has already been run.
2047                  */
2048                 SgenThreadPoolJob *job = sweep_blocks_job;
2049                 if (job)
2050                         sgen_thread_pool_job_wait (job);
2051         }
2052
2053         if (lazy_sweep && !concurrent_sweep)
2054                 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
2055         /* Sweep all unswept blocks and set them to MARKING */
2056         FOREACH_BLOCK_NO_LOCK (block) {
2057                 if (lazy_sweep && !concurrent_sweep)
2058                         sweep_block (block);
2059                 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
2060                 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
2061                 /*
2062                  * Swept blocks that have a null free_list are full. Evacuation is not
2063                  * effective on these blocks since we expect them to have high usage anyway,
2064                  * given that the survival rate for majors is relatively high.
2065                  */
2066                 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
2067                         block->is_to_space = TRUE;
2068         } END_FOREACH_BLOCK_NO_LOCK;
2069         if (lazy_sweep && !concurrent_sweep)
2070                 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
2071
2072         set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
2073 }
2074
2075 static void
2076 major_finish_major_collection (ScannedObjectCounts *counts)
2077 {
2078 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2079         if (binary_protocol_is_enabled ()) {
2080                 counts->num_scanned_objects = scanned_objects_list.next_slot;
2081
2082                 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
2083                 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
2084
2085                 sgen_pointer_queue_clear (&scanned_objects_list);
2086         }
2087 #endif
2088 }
2089
2090 static int
2091 compare_pointers (const void *va, const void *vb) {
2092         char *a = *(char**)va, *b = *(char**)vb;
2093         if (a < b)
2094                 return -1;
2095         if (a > b)
2096                 return 1;
2097         return 0;
2098 }
2099
2100 /*
2101  * This is called with sweep completed and the world stopped.
2102  */
2103 static void
2104 major_free_swept_blocks (size_t section_reserve)
2105 {
2106         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
2107
2108 #ifdef TARGET_WIN32
2109                 /*
2110                  * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
2111                  * a VirtualAlloc ()-ed block.
2112                  */
2113                 return;
2114 #endif
2115
2116         {
2117                 int i, num_empty_blocks_orig, num_blocks, arr_length;
2118                 void *block;
2119                 void **empty_block_arr;
2120                 void **rebuild_next;
2121
2122                 if (num_empty_blocks <= section_reserve)
2123                         return;
2124                 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
2125
2126                 num_empty_blocks_orig = num_empty_blocks;
2127                 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
2128                                 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
2129                 if (!empty_block_arr)
2130                         goto fallback;
2131
2132                 i = 0;
2133                 for (block = empty_blocks; block; block = *(void**)block)
2134                         empty_block_arr [i++] = block;
2135                 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
2136
2137                 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
2138
2139                 /*
2140                  * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
2141                  * contiguous ones.  If we do, we free them.  If that's not enough to get to
2142                  * section_reserve, we halve the number of contiguous blocks we're looking
2143                  * for and have another go, until we're done with looking for pairs of
2144                  * blocks, at which point we give up and go to the fallback.
2145                  */
2146                 arr_length = num_empty_blocks_orig;
2147                 num_blocks = MS_BLOCK_ALLOC_NUM;
2148                 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2149                         int first = -1;
2150                         int dest = 0;
2151
2152                         dest = 0;
2153                         for (i = 0; i < arr_length; ++i) {
2154                                 int d = dest;
2155                                 void *block = empty_block_arr [i];
2156                                 SGEN_ASSERT (6, block, "we're not shifting correctly");
2157                                 if (i != dest) {
2158                                         empty_block_arr [dest] = block;
2159                                         /*
2160                                          * This is not strictly necessary, but we're
2161                                          * cautious.
2162                                          */
2163                                         empty_block_arr [i] = NULL;
2164                                 }
2165                                 ++dest;
2166
2167                                 if (first < 0) {
2168                                         first = d;
2169                                         continue;
2170                                 }
2171
2172                                 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2173
2174                                 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
2175                                         first = d;
2176                                         continue;
2177                                 }
2178
2179                                 if (d + 1 - first == num_blocks) {
2180                                         /*
2181                                          * We found num_blocks contiguous blocks.  Free them
2182                                          * and null their array entries.  As an optimization
2183                                          * we could, instead of nulling the entries, shift
2184                                          * the following entries over to the left, while
2185                                          * we're iterating.
2186                                          */
2187                                         int j;
2188                                         sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2189                                         for (j = first; j <= d; ++j)
2190                                                 empty_block_arr [j] = NULL;
2191                                         dest = first;
2192                                         first = -1;
2193
2194                                         num_empty_blocks -= num_blocks;
2195
2196                                         stat_major_blocks_freed += num_blocks;
2197                                         if (num_blocks == MS_BLOCK_ALLOC_NUM)
2198                                                 stat_major_blocks_freed_ideal += num_blocks;
2199                                         else
2200                                                 stat_major_blocks_freed_less_ideal += num_blocks;
2201
2202                                 }
2203                         }
2204
2205                         SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2206                         arr_length = dest;
2207                         SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2208
2209                         num_blocks >>= 1;
2210                 }
2211
2212                 /* rebuild empty_blocks free list */
2213                 rebuild_next = (void**)&empty_blocks;
2214                 for (i = 0; i < arr_length; ++i) {
2215                         void *block = empty_block_arr [i];
2216                         SGEN_ASSERT (6, block, "we're missing blocks");
2217                         *rebuild_next = block;
2218                         rebuild_next = (void**)block;
2219                 }
2220                 *rebuild_next = NULL;
2221
2222                 /* free array */
2223                 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2224         }
2225
2226         SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2227
2228  fallback:
2229         /*
2230          * This is our threshold.  If there's not more empty than used blocks, we won't
2231          * release uncontiguous blocks, in fear of fragmenting the address space.
2232          */
2233         if (num_empty_blocks <= num_major_sections)
2234                 return;
2235
2236         while (num_empty_blocks > section_reserve) {
2237                 void *next = *(void**)empty_blocks;
2238                 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2239                 empty_blocks = next;
2240                 /*
2241                  * Needs not be atomic because this is running
2242                  * single-threaded.
2243                  */
2244                 --num_empty_blocks;
2245
2246                 ++stat_major_blocks_freed;
2247                 ++stat_major_blocks_freed_individual;
2248         }
2249 }
2250
2251 static void
2252 major_pin_objects (SgenGrayQueue *queue)
2253 {
2254         MSBlockInfo *block;
2255
2256         FOREACH_BLOCK_NO_LOCK (block) {
2257                 size_t first_entry, last_entry;
2258                 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2259                 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2260                                 &first_entry, &last_entry);
2261                 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2262         } END_FOREACH_BLOCK_NO_LOCK;
2263 }
2264
2265 static void
2266 major_init_to_space (void)
2267 {
2268 }
2269
2270 static void
2271 major_report_pinned_memory_usage (void)
2272 {
2273         g_assert_not_reached ();
2274 }
2275
2276 static gint64
2277 major_get_used_size (void)
2278 {
2279         gint64 size = 0;
2280         MSBlockInfo *block;
2281
2282         /*
2283          * We're holding the GC lock, but the sweep thread might be running.  Make sure it's
2284          * finished, then we can iterate over the block array.
2285          */
2286         major_finish_sweep_checking ();
2287
2288         FOREACH_BLOCK_NO_LOCK (block) {
2289                 int count = MS_BLOCK_FREE / block->obj_size;
2290                 void **iter;
2291                 size += count * block->obj_size;
2292                 for (iter = block->free_list; iter; iter = (void**)*iter)
2293                         size -= block->obj_size;
2294         } END_FOREACH_BLOCK_NO_LOCK;
2295
2296         return size;
2297 }
2298
2299 /* FIXME: return number of bytes, not of sections */
2300 static size_t
2301 get_num_major_sections (void)
2302 {
2303         return num_major_sections;
2304 }
2305
2306 /*
2307  * Returns the number of bytes in blocks that were present when the last sweep was
2308  * initiated, and were not freed during the sweep.  They are the basis for calculating the
2309  * allowance.
2310  */
2311 static size_t
2312 get_bytes_survived_last_sweep (void)
2313 {
2314         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2315         return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2316 }
2317
2318 static gboolean
2319 major_handle_gc_param (const char *opt)
2320 {
2321         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2322                 const char *arg = strchr (opt, '=') + 1;
2323                 int percentage = atoi (arg);
2324                 if (percentage < 0 || percentage > 100) {
2325                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2326                         exit (1);
2327                 }
2328                 evacuation_threshold = (float)percentage / 100.0f;
2329                 return TRUE;
2330         } else if (!strcmp (opt, "lazy-sweep")) {
2331                 lazy_sweep = TRUE;
2332                 return TRUE;
2333         } else if (!strcmp (opt, "no-lazy-sweep")) {
2334                 lazy_sweep = FALSE;
2335                 return TRUE;
2336         } else if (!strcmp (opt, "concurrent-sweep")) {
2337                 concurrent_sweep = TRUE;
2338                 return TRUE;
2339         } else if (!strcmp (opt, "no-concurrent-sweep")) {
2340                 concurrent_sweep = FALSE;
2341                 return TRUE;
2342         }
2343
2344         return FALSE;
2345 }
2346
2347 static void
2348 major_print_gc_param_usage (void)
2349 {
2350         fprintf (stderr,
2351                         ""
2352                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2353                         "  (no-)lazy-sweep\n"
2354                         "  (no-)concurrent-sweep\n"
2355                         );
2356 }
2357
2358 /*
2359  * This callback is used to clear cards, move cards to the shadow table and do counting.
2360  */
2361 static void
2362 major_iterate_block_ranges (sgen_cardtable_block_callback callback)
2363 {
2364         MSBlockInfo *block;
2365         gboolean has_references;
2366
2367         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2368                 if (has_references)
2369                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2370         } END_FOREACH_BLOCK_NO_LOCK;
2371 }
2372
2373 static void
2374 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2375 {
2376         MSBlockInfo *block;
2377         gboolean has_references;
2378
2379         major_finish_sweep_checking ();
2380         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2381                 if (has_references)
2382                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2383         } END_FOREACH_BLOCK_NO_LOCK;
2384 }
2385
2386 #ifdef HEAVY_STATISTICS
2387 extern guint64 marked_cards;
2388 extern guint64 scanned_cards;
2389 extern guint64 scanned_objects;
2390 extern guint64 remarked_cards;
2391 #endif
2392
2393 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2394 /*
2395  * MS blocks are 16K aligned.
2396  * Cardtables are 4K aligned, at least.
2397  * This means that the cardtable of a given block is 32 bytes aligned.
2398  */
2399 static guint8*
2400 initial_skip_card (guint8 *card_data)
2401 {
2402         mword *cards = (mword*)card_data;
2403         mword card;
2404         int i;
2405         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2406                 card = cards [i];
2407                 if (card)
2408                         break;
2409         }
2410
2411         if (i == CARD_WORDS_PER_BLOCK)
2412                 return card_data + CARDS_PER_BLOCK;
2413
2414 #if defined(__i386__) && defined(__GNUC__)
2415         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
2416 #elif defined(__x86_64__) && defined(__GNUC__)
2417         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
2418 #elif defined(__s390x__) && defined(__GNUC__)
2419         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2420 #else
2421         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2422                 if (card_data [i])
2423                         return &card_data [i];
2424         }
2425         return card_data;
2426 #endif
2427 }
2428
2429 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2430 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
2431 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2432
2433 static void
2434 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2435 {
2436         SgenGrayQueue *queue = ctx.queue;
2437         ScanObjectFunc scan_func = ctx.ops->scan_object;
2438 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2439         guint8 cards_copy [CARDS_PER_BLOCK];
2440 #endif
2441         guint8 cards_preclean [CARDS_PER_BLOCK];
2442         gboolean small_objects;
2443         int block_obj_size;
2444         char *block_start;
2445         guint8 *card_data, *card_base;
2446         guint8 *card_data_end;
2447         char *scan_front = NULL;
2448
2449         /* The concurrent mark doesn't enter evacuating blocks */
2450         if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2451                 return;
2452
2453         block_obj_size = block->obj_size;
2454         small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2455
2456         block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2457
2458         /*
2459          * This is safe in face of card aliasing for the following reason:
2460          *
2461          * Major blocks are 16k aligned, or 32 cards aligned.
2462          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2463          * sizes, they won't overflow the cardtable overlap modulus.
2464          */
2465         if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2466                 card_data = card_base = block->cardtable_mod_union;
2467                 /*
2468                  * This happens when the nursery collection that precedes finishing
2469                  * the concurrent collection allocates new major blocks.
2470                  */
2471                 if (!card_data)
2472                         return;
2473
2474                 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2475                         sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2476                         card_data = card_base = cards_preclean;
2477                 }
2478         } else {
2479 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2480                 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2481 #else
2482                 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2483                         return;
2484                 card_data = card_base = cards_copy;
2485 #endif
2486         }
2487         card_data_end = card_data + CARDS_PER_BLOCK;
2488
2489         card_data += MS_BLOCK_SKIP >> CARD_BITS;
2490
2491         card_data = initial_skip_card (card_data);
2492         while (card_data < card_data_end) {
2493                 size_t card_index, first_object_index;
2494                 char *start;
2495                 char *end;
2496                 char *first_obj, *obj;
2497
2498                 HEAVY_STAT (++scanned_cards);
2499
2500                 if (!*card_data) {
2501                         ++card_data;
2502                         continue;
2503                 }
2504
2505                 card_index = card_data - card_base;
2506                 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2507                 end = start + CARD_SIZE_IN_BYTES;
2508
2509                 if (!block_is_swept_or_marking (block))
2510                         sweep_block (block);
2511
2512                 HEAVY_STAT (++marked_cards);
2513
2514                 if (small_objects)
2515                         sgen_card_table_prepare_card_for_scanning (card_data);
2516
2517                 /*
2518                  * If the card we're looking at starts at or in the block header, we
2519                  * must start at the first object in the block, without calculating
2520                  * the index of the object we're hypothetically starting at, because
2521                  * it would be negative.
2522                  */
2523                 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2524                         first_object_index = 0;
2525                 else
2526                         first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2527
2528                 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2529
2530                 binary_protocol_card_scan (first_obj, end - first_obj);
2531
2532                 while (obj < end) {
2533                         if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2534                                 goto next_object;
2535
2536                         if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2537                                 /* FIXME: do this more efficiently */
2538                                 int w, b;
2539                                 MS_CALC_MARK_BIT (w, b, obj);
2540                                 if (!MS_MARK_BIT (block, w, b))
2541                                         goto next_object;
2542                         }
2543
2544                         GCObject *object = (GCObject*)obj;
2545
2546                         if (small_objects) {
2547                                 HEAVY_STAT (++scanned_objects);
2548                                 scan_func (object, sgen_obj_get_descriptor (object), queue);
2549                         } else {
2550                                 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2551                                 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2552                         }
2553                 next_object:
2554                         obj += block_obj_size;
2555                         g_assert (scan_front <= obj);
2556                         scan_front = obj;
2557                 }
2558
2559                 HEAVY_STAT (if (*card_data) ++remarked_cards);
2560
2561                 if (small_objects)
2562                         ++card_data;
2563                 else
2564                         card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2565         }
2566 }
2567
2568 static void
2569 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count)
2570 {
2571         MSBlockInfo *block;
2572         gboolean has_references, was_sweeping, skip_scan;
2573
2574         if (!concurrent_mark)
2575                 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2576
2577         if (scan_type != CARDTABLE_SCAN_GLOBAL)
2578                 SGEN_ASSERT (0, !sweep_in_progress (), "Sweep should be finished when we scan mod union card table");
2579         was_sweeping = sweep_in_progress ();
2580
2581         binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2582         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2583                 if (__index % job_split_count != job_index)
2584                         continue;
2585 #ifdef PREFETCH_CARDS
2586                 int prefetch_index = __index + 6 * job_split_count;
2587                 if (prefetch_index < allocated_blocks.next_slot) {
2588                         MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2589                         PREFETCH_READ (prefetch_block);
2590                         if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2591                                 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2592                                 PREFETCH_WRITE (prefetch_cards);
2593                                 PREFETCH_WRITE (prefetch_cards + 32);
2594                         }
2595                 }
2596 #endif
2597
2598                 if (!has_references)
2599                         continue;
2600                 skip_scan = FALSE;
2601
2602                 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2603                         gpointer *card_start = (gpointer*) sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2604                         gboolean has_dirty_cards = FALSE;
2605                         int i;
2606                         for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2607                                 if (card_start [i]) {
2608                                         has_dirty_cards = TRUE;
2609                                         break;
2610                                 }
2611                         }
2612                         if (!has_dirty_cards) {
2613                                 skip_scan = TRUE;
2614                         } else {
2615                                 /*
2616                                  * After the start of the concurrent collections, blocks change state
2617                                  * to marking. We should not sweep it in that case. We can't race with
2618                                  * sweep start since we are in a nursery collection. Also avoid CAS-ing
2619                                  */
2620                                 if (sweep_in_progress ()) {
2621                                         skip_scan = !ensure_block_is_checked_for_sweeping (__index, TRUE, NULL);
2622                                 } else if (was_sweeping) {
2623                                         /* Recheck in case sweep finished after dereferencing the slot */
2624                                         skip_scan = *sgen_array_list_get_slot (&allocated_blocks, __index) == 0;
2625                                 }
2626                         }
2627                 }
2628                 if (!skip_scan)
2629                         scan_card_table_for_block (block, scan_type, ctx);
2630         } END_FOREACH_BLOCK_NO_LOCK;
2631         binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2632 }
2633
2634 static void
2635 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2636 {
2637         MSBlockInfo *block;
2638         gboolean has_references;
2639         long long total_cards = 0;
2640         long long marked_cards = 0;
2641
2642         if (sweep_in_progress ()) {
2643                 *num_total_cards = -1;
2644                 *num_marked_cards = -1;
2645                 return;
2646         }
2647
2648         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2649                 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2650                 int i;
2651
2652                 if (!has_references)
2653                         continue;
2654
2655                 total_cards += CARDS_PER_BLOCK;
2656                 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2657                         if (cards [i])
2658                                 ++marked_cards;
2659                 }
2660         } END_FOREACH_BLOCK_NO_LOCK;
2661
2662         *num_total_cards = total_cards;
2663         *num_marked_cards = marked_cards;
2664 }
2665
2666 static void
2667 update_cardtable_mod_union (void)
2668 {
2669         MSBlockInfo *block;
2670
2671         FOREACH_BLOCK_NO_LOCK (block) {
2672                 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2673                 gboolean has_dirty_cards = FALSE;
2674                 int i;
2675                 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2676                         if (card_start [i]) {
2677                                 has_dirty_cards = TRUE;
2678                                 break;
2679                         }
2680                 }
2681                 if (has_dirty_cards) {
2682                         size_t num_cards;
2683                         guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2684                         sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2685                         SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2686                 }
2687         } END_FOREACH_BLOCK_NO_LOCK;
2688 }
2689
2690 #undef pthread_create
2691
2692 static void
2693 post_param_init (SgenMajorCollector *collector)
2694 {
2695         collector->sweeps_lazily = lazy_sweep;
2696         collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2697 }
2698
2699 /* We are guaranteed to be called by the worker in question */
2700 static void
2701 sgen_worker_init_callback (gpointer worker_untyped)
2702 {
2703         int i;
2704         WorkerData *worker = (WorkerData*) worker_untyped;
2705         MSBlockInfo ***worker_free_blocks = (MSBlockInfo ***) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX, INTERNAL_MEM_MS_TABLES, TRUE);
2706
2707         for (i = 0; i < MS_BLOCK_TYPE_MAX; i++)
2708                 worker_free_blocks [i] = (MSBlockInfo **) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2709
2710         worker->free_block_lists = worker_free_blocks;
2711
2712         mono_native_tls_set_value (worker_block_free_list_key, worker_free_blocks);
2713 }
2714
2715 static void
2716 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent, gboolean is_parallel)
2717 {
2718         int i;
2719
2720         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2721
2722         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2723         block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2724         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2725
2726         evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2727         for (i = 0; i < num_block_obj_sizes; ++i)
2728                 evacuate_block_obj_sizes [i] = FALSE;
2729
2730         sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2731         sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2732         sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2733
2734         /*
2735         {
2736                 int i;
2737                 g_print ("block object sizes:\n");
2738                 for (i = 0; i < num_block_obj_sizes; ++i)
2739                         g_print ("%d\n", block_obj_sizes [i]);
2740         }
2741         */
2742
2743         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2744                 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2745
2746         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2747                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2748         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2749                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2750
2751         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2752         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2753         mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2754         mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2755         mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2756         mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2757         mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2758
2759         collector->section_size = MAJOR_SECTION_SIZE;
2760
2761         concurrent_mark = is_concurrent;
2762         collector->is_concurrent = is_concurrent;
2763         collector->is_parallel = is_parallel;
2764         collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2765         collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2766         collector->supports_cardtable = TRUE;
2767
2768         collector->alloc_heap = major_alloc_heap;
2769         collector->is_object_live = major_is_object_live;
2770         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2771         collector->alloc_degraded = major_alloc_degraded;
2772
2773         collector->alloc_object = major_alloc_object;
2774         collector->alloc_object_par = major_alloc_object_par;
2775         collector->free_pinned_object = free_pinned_object;
2776         collector->iterate_objects = major_iterate_objects;
2777         collector->free_non_pinned_object = major_free_non_pinned_object;
2778         collector->pin_objects = major_pin_objects;
2779         collector->pin_major_object = pin_major_object;
2780         collector->scan_card_table = major_scan_card_table;
2781         collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2782         collector->iterate_block_ranges = major_iterate_block_ranges;
2783         if (is_concurrent) {
2784                 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2785                 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2786         }
2787         collector->init_to_space = major_init_to_space;
2788         collector->sweep = major_sweep;
2789         collector->have_swept = major_have_swept;
2790         collector->finish_sweeping = major_finish_sweep_checking;
2791         collector->free_swept_blocks = major_free_swept_blocks;
2792         collector->check_scan_starts = major_check_scan_starts;
2793         collector->dump_heap = major_dump_heap;
2794         collector->get_used_size = major_get_used_size;
2795         collector->start_nursery_collection = major_start_nursery_collection;
2796         collector->finish_nursery_collection = major_finish_nursery_collection;
2797         collector->start_major_collection = major_start_major_collection;
2798         collector->finish_major_collection = major_finish_major_collection;
2799         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2800         collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2801         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2802         collector->get_num_major_sections = get_num_major_sections;
2803         collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2804         collector->handle_gc_param = major_handle_gc_param;
2805         collector->print_gc_param_usage = major_print_gc_param_usage;
2806         collector->post_param_init = post_param_init;
2807         collector->is_valid_object = major_is_valid_object;
2808         collector->describe_pointer = major_describe_pointer;
2809         collector->count_cards = major_count_cards;
2810
2811         collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2812         collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2813         collector->major_ops_serial.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2814         collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2815         if (is_concurrent) {
2816                 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2817                 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2818                 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2819                 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2820                 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2821
2822                 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2823                 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2824                 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2825                 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2826                 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2827
2828                 if (is_parallel) {
2829                         collector->major_ops_conc_par_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_canonical;
2830                         collector->major_ops_conc_par_start.scan_object = major_scan_object_concurrent_par_with_evacuation;
2831                         collector->major_ops_conc_par_start.scan_vtype = major_scan_vtype_concurrent_par_with_evacuation;
2832                         collector->major_ops_conc_par_start.scan_ptr_field = major_scan_ptr_field_concurrent_par_with_evacuation;
2833                         collector->major_ops_conc_par_start.drain_gray_stack = drain_gray_stack_concurrent_par;
2834
2835                         collector->major_ops_conc_par_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_finish_canonical;
2836                         collector->major_ops_conc_par_finish.scan_object = major_scan_object_par_with_evacuation;
2837                         collector->major_ops_conc_par_finish.scan_vtype = major_scan_vtype_par_with_evacuation;
2838                         collector->major_ops_conc_par_finish.scan_ptr_field = major_scan_ptr_field_par_with_evacuation;
2839                         collector->major_ops_conc_par_finish.drain_gray_stack = drain_gray_stack_par;
2840
2841                         collector->worker_init_cb = sgen_worker_init_callback;
2842
2843                         mono_native_tls_alloc (&worker_block_free_list_key, NULL);
2844                 }
2845         }
2846
2847 #ifdef HEAVY_STATISTICS
2848         mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2849         mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2850         mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2851         mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2852         mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2853         mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2854         mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2855         mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2856         mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2857         mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2858         mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2859
2860         mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2861         mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2862         mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2863 #endif
2864
2865 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2866         mono_os_mutex_init (&scanned_objects_list_lock);
2867 #endif
2868
2869         SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2870
2871         /*cardtable requires major pages to be 8 cards aligned*/
2872         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2873 }
2874
2875 void
2876 sgen_marksweep_init (SgenMajorCollector *collector)
2877 {
2878         sgen_marksweep_init_internal (collector, FALSE, FALSE);
2879 }
2880
2881 void
2882 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2883 {
2884         sgen_marksweep_init_internal (collector, TRUE, FALSE);
2885 }
2886
2887 void
2888 sgen_marksweep_conc_par_init (SgenMajorCollector *collector)
2889 {
2890         sgen_marksweep_init_internal (collector, TRUE, TRUE);
2891 }
2892
2893 #endif