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