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