[sgen] Implement work context for thread pool threads
[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 #include "mono/utils/mono-proclib.h"
36
37 static int ms_block_size;
38
39 /*
40  * Blocks must be at least this size, meaning that if we detect a
41  * page size lower than this, we'll use this instead.
42  */
43 #define MS_BLOCK_SIZE_MIN (1024 * 16)
44
45 #define CARDS_PER_BLOCK (ms_block_size / CARD_SIZE_IN_BYTES)
46
47 /*
48  * Don't allocate single blocks, but alloc a contingent of this many
49  * blocks in one swoop.  This must be a power of two.
50  */
51 #define MS_BLOCK_ALLOC_NUM      32
52
53 #define MS_NUM_MARK_WORDS       ((ms_block_size / SGEN_ALLOC_ALIGN + sizeof (guint32) * 8 - 1) / (sizeof (guint32) * 8))
54
55 /*
56  * Use this instead of sizeof (MSBlockInfo) since the mark_words
57  * array size depends on page size at runtime.
58  */
59 #define SIZEOF_MS_BLOCK_INFO (sizeof (MSBlockInfo) + sizeof (guint32) * (MS_NUM_MARK_WORDS - MONO_ZERO_LEN_ARRAY))
60
61 /*
62  * Number of bytes before the first object in a block.  At the start
63  * of a block is the MSBlockHeader, then opional padding, then come
64  * the objects, so this must be >= SIZEOF_MS_BLOCK_INFO.
65  */
66 #define MS_BLOCK_SKIP   ((SIZEOF_MS_BLOCK_INFO + 15) & ~15)
67
68 #define MS_BLOCK_FREE   (ms_block_size - MS_BLOCK_SKIP)
69
70 /*
71  * Blocks progress from one state to the next:
72  *
73  * SWEPT           The block is fully swept.  It might or might not be in
74  *                 a free list.
75  *
76  * MARKING         The block might or might not contain live objects.  If
77  *                 we're in between an initial collection pause and the
78  *                 finishing pause, the block might or might not be in a
79  *                 free list.
80  *
81  * CHECKING        The sweep thread is investigating the block to determine
82  *                 whether or not it contains live objects.  The block is
83  *                 not in a free list.
84  *
85  * NEED_SWEEPING   The block contains live objects but has not yet been
86  *                 swept.  It also contains free slots.  It is in a block
87  *                 free list.
88  *
89  * SWEEPING        The block is being swept.  It might be in a free list.
90  */
91
92 enum {
93         BLOCK_STATE_SWEPT,
94         BLOCK_STATE_MARKING,
95         BLOCK_STATE_CHECKING,
96         BLOCK_STATE_NEED_SWEEPING,
97         BLOCK_STATE_SWEEPING
98 };
99
100 typedef struct _MSBlockInfo MSBlockInfo;
101 struct _MSBlockInfo {
102         guint16 obj_size;
103         /*
104          * FIXME: Do we even need this? It's only used during sweep and might be worth
105          * recalculating to save the space.
106          */
107         guint16 obj_size_index;
108         /* FIXME: Reduce this - it only needs a byte. */
109         volatile gint32 state;
110         gint16 nused;
111         unsigned int pinned : 1;
112         unsigned int has_references : 1;
113         unsigned int has_pinned : 1;    /* means cannot evacuate */
114         unsigned int is_to_space : 1;
115         void ** volatile free_list;
116         MSBlockInfo * volatile next_free;
117         guint8 * volatile cardtable_mod_union;
118         guint32 mark_words [MONO_ZERO_LEN_ARRAY];
119 };
120
121 #define MS_BLOCK_FOR_BLOCK_INFO(b)      ((char*)(b))
122
123 #define MS_BLOCK_OBJ(b,i)               ((GCObject *)(MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i)))
124 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size)             (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
125 #define MS_BLOCK_DATA_FOR_OBJ(o)        ((char*)((mword)(o) & ~(mword)(ms_block_size - 1)))
126
127 typedef struct {
128         MSBlockInfo info;
129 } MSBlockHeader;
130
131 #define MS_BLOCK_FOR_OBJ(o)             (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
132
133 /* object index will always be small */
134 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
135
136 //casting to int is fine since blocks are 32k
137 #define MS_CALC_MARK_BIT(w,b,o)         do {                            \
138                 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
139                 (w) = i >> 5;                                           \
140                 (b) = i & 31;                                           \
141         } while (0)
142
143 #define MS_MARK_BIT(bl,w,b)     ((bl)->mark_words [(w)] & (ONE_P << (b)))
144 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
145 #define MS_SET_MARK_BIT_PAR(bl,w,b,first)       do {                    \
146                 guint32 tmp_mark_word = (bl)->mark_words [(w)];         \
147                 guint32 old_mark_word;                                  \
148                 first = FALSE;                                          \
149                 while (!(tmp_mark_word & (ONE_P << (b)))) {             \
150                         old_mark_word = tmp_mark_word;                  \
151                         tmp_mark_word = InterlockedCompareExchange ((volatile gint32*)&(bl)->mark_words [w], old_mark_word | (ONE_P << (b)), old_mark_word); \
152                         if (tmp_mark_word == old_mark_word) {           \
153                                 first = TRUE;                           \
154                                 break;                                  \
155                         }                                               \
156                 }                                                       \
157         } while (0)
158
159
160 #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))
161
162 #define MS_BLOCK_OBJ_SIZE_FACTOR        (pow (2.0, 1.0 / 3))
163
164 /*
165  * This way we can lookup block object size indexes for sizes up to
166  * 256 bytes with a single load.
167  */
168 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES      32
169
170 static int *block_obj_sizes;
171 static int num_block_obj_sizes;
172 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
173
174 #define MS_BLOCK_FLAG_PINNED    1
175 #define MS_BLOCK_FLAG_REFS      2
176
177 #define MS_BLOCK_TYPE_MAX       4
178
179 static gboolean *evacuate_block_obj_sizes;
180 static float evacuation_threshold = 0.666f;
181
182 static gboolean lazy_sweep = TRUE;
183
184 enum {
185         SWEEP_STATE_SWEPT,
186         SWEEP_STATE_NEED_SWEEPING,
187         SWEEP_STATE_SWEEPING,
188         SWEEP_STATE_SWEEPING_AND_ITERATING,
189         SWEEP_STATE_COMPACTING
190 };
191
192 static volatile int sweep_state = SWEEP_STATE_SWEPT;
193
194 static gboolean concurrent_mark;
195 static gboolean concurrent_sweep = TRUE;
196
197 int sweep_pool_context = -1;
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_context, 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 (GENERATION_NURSERY, sgen_worker_clear_free_block_lists);
1603         sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists);
1604 }
1605
1606 static void sweep_finish (void);
1607
1608 /*
1609  * If `wait` is TRUE and the block is currently being checked, this function will wait until
1610  * the checking has finished.
1611  *
1612  * Returns whether the block is still there.  If `wait` is FALSE, the return value will not
1613  * be correct, i.e. must not be used.
1614  */
1615 static gboolean
1616 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1617 {
1618         int count;
1619         gboolean have_live = FALSE;
1620         gboolean have_free = FALSE;
1621         int nused = 0;
1622         int block_state;
1623         int i;
1624         void *tagged_block;
1625         MSBlockInfo *block;
1626         volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1627
1628         SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1629
1630         if (have_checked)
1631                 *have_checked = FALSE;
1632
1633  retry:
1634         tagged_block = *(void * volatile *)block_slot;
1635         if (!tagged_block)
1636                 return FALSE;
1637
1638         if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1639                 if (!wait)
1640                         return FALSE;
1641                 /* FIXME: do this more elegantly */
1642                 g_usleep (100);
1643                 goto retry;
1644         }
1645
1646         if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1647                 goto retry;
1648
1649         block = BLOCK_UNTAG (tagged_block);
1650         block_state = block->state;
1651
1652         if (!sweep_in_progress ()) {
1653                 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1654                 if (!lazy_sweep)
1655                         SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1656         }
1657
1658         switch (block_state) {
1659         case BLOCK_STATE_SWEPT:
1660         case BLOCK_STATE_NEED_SWEEPING:
1661         case BLOCK_STATE_SWEEPING:
1662                 goto done;
1663         case BLOCK_STATE_MARKING:
1664                 break;
1665         case BLOCK_STATE_CHECKING:
1666                 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1667                 goto done;
1668         default:
1669                 SGEN_ASSERT (0, FALSE, "Illegal block state");
1670                 break;
1671         }
1672
1673         SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1674         set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1675
1676         if (have_checked)
1677                 *have_checked = TRUE;
1678
1679         block->has_pinned = block->pinned;
1680
1681         block->is_to_space = FALSE;
1682
1683         count = MS_BLOCK_FREE / block->obj_size;
1684
1685         if (block->cardtable_mod_union)
1686                 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1687
1688         /* Count marked objects in the block */
1689         for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1690                 nused += bitcount (block->mark_words [i]);
1691
1692         block->nused = nused;
1693         if (nused)
1694                 have_live = TRUE;
1695         if (nused < count)
1696                 have_free = TRUE;
1697
1698         if (have_live) {
1699                 int obj_size_index = block->obj_size_index;
1700                 gboolean has_pinned = block->has_pinned;
1701
1702                 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1703
1704                 /*
1705                  * FIXME: Go straight to SWEPT if there are no free slots.  We need
1706                  * to set the free slot list to NULL, though, and maybe update some
1707                  * statistics.
1708                  */
1709                 if (!lazy_sweep)
1710                         sweep_block (block);
1711
1712                 if (!has_pinned) {
1713                         ++sweep_num_blocks [obj_size_index];
1714                         sweep_slots_used [obj_size_index] += nused;
1715                         sweep_slots_available [obj_size_index] += count;
1716                 }
1717
1718                 /*
1719                  * If there are free slots in the block, add
1720                  * the block to the corresponding free list.
1721                  */
1722                 if (have_free) {
1723                         MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1724
1725                         if (!lazy_sweep)
1726                                 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1727
1728                         add_free_block (free_blocks, obj_size_index, block);
1729                 }
1730
1731                 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1732                 update_heap_boundaries_for_block (block);
1733         } else {
1734                 /*
1735                  * Blocks without live objects are removed from the
1736                  * block list and freed.
1737                  */
1738                 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1739                 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1740
1741                 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1742                 ms_free_block (block);
1743
1744                 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1745                 SGEN_ATOMIC_ADD_P (num_major_sections_freed_in_sweep, 1);
1746
1747                 tagged_block = NULL;
1748         }
1749
1750  done:
1751         /*
1752          * Once the block is written back without the checking bit other threads are
1753          * free to access it. Make sure the block state is visible before we write it
1754          * back.
1755          */
1756         mono_memory_write_barrier ();
1757         *block_slot = tagged_block;
1758         return !!tagged_block;
1759 }
1760
1761 static void
1762 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1763 {
1764         volatile gpointer *slot;
1765         MSBlockInfo *bl;
1766
1767         SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1768                 bl = BLOCK_UNTAG (*slot);
1769                 if (bl)
1770                         sweep_block (bl);
1771         } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1772
1773         mono_memory_write_barrier ();
1774
1775         sweep_blocks_job = NULL;
1776 }
1777
1778 static void
1779 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1780 {
1781         guint32 block_index;
1782         guint32 num_blocks = num_major_sections_before_sweep;
1783
1784         SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1785         SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1786
1787         /*
1788          * We traverse the block array from high to low.  Nursery collections will have to
1789          * cooperate with the sweep thread to finish sweeping, and they will traverse from
1790          * low to high, to avoid constantly colliding on the same blocks.
1791          */
1792         for (block_index = allocated_blocks.next_slot; block_index-- > 0;) {
1793                 ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL);
1794         }
1795
1796         while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1797                 /*
1798                  * The main GC thread is currently iterating over the block array to help us
1799                  * finish the sweep.  We have already finished, but we don't want to mess up
1800                  * that iteration, so we just wait for it.
1801                  */
1802                 g_usleep (100);
1803         }
1804
1805         if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1806                 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1807                         MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1808                         SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1809                 }
1810         }
1811
1812         /*
1813          * Concurrently sweep all the blocks to reduce workload during minor
1814          * pauses where we need certain blocks to be swept. At the start of
1815          * the next major we need all blocks to be swept anyway.
1816          */
1817         if (concurrent_sweep && lazy_sweep) {
1818                 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1819                 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_blocks_job);
1820         }
1821
1822         sweep_finish ();
1823
1824         sweep_job = NULL;
1825 }
1826
1827 static void
1828 sweep_finish (void)
1829 {
1830         mword used_slots_size = 0;
1831         int i;
1832
1833         for (i = 0; i < num_block_obj_sizes; ++i) {
1834                 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1835                 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1836                         evacuate_block_obj_sizes [i] = TRUE;
1837                         /*
1838                         g_print ("slot size %d - %d of %d used\n",
1839                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1840                         */
1841                 } else {
1842                         evacuate_block_obj_sizes [i] = FALSE;
1843                 }
1844
1845                 used_slots_size += sweep_slots_used [i] * block_obj_sizes [i];
1846         }
1847
1848         sgen_memgov_major_post_sweep (used_slots_size);
1849
1850         set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1851         if (concurrent_sweep)
1852                 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1853 }
1854
1855 static void
1856 major_sweep (void)
1857 {
1858         set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1859
1860         sweep_start ();
1861
1862         num_major_sections_before_sweep = num_major_sections;
1863         num_major_sections_freed_in_sweep = 0;
1864
1865         SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1866         if (concurrent_sweep) {
1867                 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1868                 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_job);
1869         } else {
1870                 sweep_job_func (NULL, NULL);
1871         }
1872 }
1873
1874 static gboolean
1875 major_have_swept (void)
1876 {
1877         return sweep_state == SWEEP_STATE_SWEPT;
1878 }
1879
1880 static int count_pinned_ref;
1881 static int count_pinned_nonref;
1882 static int count_nonpinned_ref;
1883 static int count_nonpinned_nonref;
1884
1885 static void
1886 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1887 {
1888         GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1889
1890         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1891                 ++count_nonpinned_ref;
1892         else
1893                 ++count_nonpinned_nonref;
1894 }
1895
1896 static void
1897 count_pinned_callback (GCObject *obj, size_t size, void *data)
1898 {
1899         GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1900
1901         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1902                 ++count_pinned_ref;
1903         else
1904                 ++count_pinned_nonref;
1905 }
1906
1907 static G_GNUC_UNUSED void
1908 count_ref_nonref_objs (void)
1909 {
1910         int total;
1911
1912         count_pinned_ref = 0;
1913         count_pinned_nonref = 0;
1914         count_nonpinned_ref = 0;
1915         count_nonpinned_nonref = 0;
1916
1917         major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1918         major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1919
1920         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1921
1922         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1923                         count_pinned_ref, count_nonpinned_ref,
1924                         count_pinned_nonref, count_nonpinned_nonref,
1925                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1926 }
1927
1928 static int
1929 ms_calculate_block_obj_sizes (double factor, int *arr)
1930 {
1931         double target_size;
1932         int num_sizes = 0;
1933         int last_size = 0;
1934
1935         /*
1936          * Have every possible slot size starting with the minimal
1937          * object size up to and including four times that size.  Then
1938          * proceed by increasing geometrically with the given factor.
1939          */
1940
1941         for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1942                 if (arr)
1943                         arr [num_sizes] = size;
1944                 ++num_sizes;
1945                 last_size = size;
1946         }
1947         target_size = (double)last_size;
1948
1949         do {
1950                 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1951                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1952
1953                 if (size != last_size) {
1954                         if (arr)
1955                                 arr [num_sizes] = size;
1956                         ++num_sizes;
1957                         last_size = size;
1958                 }
1959
1960                 target_size *= factor;
1961         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1962
1963         return num_sizes;
1964 }
1965
1966 /* only valid during minor collections */
1967 static mword old_num_major_sections;
1968
1969 static void
1970 major_start_nursery_collection (void)
1971 {
1972 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1973         consistency_check ();
1974 #endif
1975
1976         old_num_major_sections = num_major_sections;
1977 }
1978
1979 static void
1980 major_finish_nursery_collection (void)
1981 {
1982 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1983         consistency_check ();
1984 #endif
1985 }
1986
1987 static int
1988 block_usage_comparer (const void *bl1, const void *bl2)
1989 {
1990         const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
1991         const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
1992
1993         return nused2 - nused1;
1994 }
1995
1996 static void
1997 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1998 {
1999         MSBlockInfo **evacuated_blocks;
2000         size_t index = 0, count, num_blocks = 0, num_used = 0;
2001         MSBlockInfo *info;
2002         MSBlockInfo * volatile *prev;
2003
2004         for (info = *block_list; info != NULL; info = info->next_free) {
2005                 num_blocks++;
2006                 num_used += info->nused;
2007         }
2008
2009         /*
2010          * We have a set of blocks in the freelist which will be evacuated. Instead
2011          * of evacuating all of the blocks into new ones, we traverse the freelist
2012          * sorting it by the number of occupied slots, evacuating the objects from
2013          * blocks with fewer used slots into fuller blocks.
2014          *
2015          * The number of used slots is set at the end of the previous sweep. Since
2016          * we sequentially unlink slots from blocks, except for the head of the
2017          * freelist, for blocks on the freelist, the number of used slots is the same
2018          * as at the end of the previous sweep.
2019          */
2020         evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
2021
2022         for (info = *block_list; info != NULL; info = info->next_free) {
2023                 evacuated_blocks [index++] = info;
2024         }
2025
2026         SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
2027
2028         sgen_qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
2029
2030         /*
2031          * Form a new freelist with the fullest blocks. These blocks will also be
2032          * marked as to_space so we don't evacuate from them.
2033          */
2034         count = MS_BLOCK_FREE / block_obj_sizes [size_index];
2035         prev = block_list;
2036         for (index = 0; index < (num_used + count - 1) / count; index++) {
2037                 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
2038                 info = evacuated_blocks [index];
2039                 info->is_to_space = TRUE;
2040                 *prev = info;
2041                 prev = &info->next_free;
2042         }
2043         *prev = NULL;
2044
2045         sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
2046 }
2047
2048 static void
2049 major_start_major_collection (void)
2050 {
2051         MSBlockInfo *block;
2052         int i;
2053
2054         major_finish_sweep_checking ();
2055
2056         /*
2057          * Clear the free lists for block sizes where we do evacuation.  For those block
2058          * sizes we will have to allocate new blocks.
2059          */
2060         for (i = 0; i < num_block_obj_sizes; ++i) {
2061                 if (!evacuate_block_obj_sizes [i])
2062                         continue;
2063
2064                 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
2065
2066                 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
2067                 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
2068         }
2069
2070         /* We expect workers to have very few blocks on the freelist, just evacuate them */
2071         sgen_workers_foreach (GENERATION_NURSERY, sgen_worker_clear_free_block_lists_evac);
2072         sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists_evac);
2073
2074         if (lazy_sweep && concurrent_sweep) {
2075                 /*
2076                  * sweep_blocks_job is created before sweep_finish, which we wait for above
2077                  * (major_finish_sweep_checking). After the end of sweep, if we don't have
2078                  * sweep_blocks_job set, it means that it has already been run.
2079                  */
2080                 SgenThreadPoolJob *job = sweep_blocks_job;
2081                 if (job)
2082                         sgen_thread_pool_job_wait (sweep_pool_context, job);
2083         }
2084
2085         if (lazy_sweep && !concurrent_sweep)
2086                 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
2087         /* Sweep all unswept blocks and set them to MARKING */
2088         FOREACH_BLOCK_NO_LOCK (block) {
2089                 if (lazy_sweep && !concurrent_sweep)
2090                         sweep_block (block);
2091                 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
2092                 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
2093                 /*
2094                  * Swept blocks that have a null free_list are full. Evacuation is not
2095                  * effective on these blocks since we expect them to have high usage anyway,
2096                  * given that the survival rate for majors is relatively high.
2097                  */
2098                 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
2099                         block->is_to_space = TRUE;
2100         } END_FOREACH_BLOCK_NO_LOCK;
2101         if (lazy_sweep && !concurrent_sweep)
2102                 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
2103
2104         set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
2105 }
2106
2107 static void
2108 major_finish_major_collection (ScannedObjectCounts *counts)
2109 {
2110 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2111         if (binary_protocol_is_enabled ()) {
2112                 counts->num_scanned_objects = scanned_objects_list.next_slot;
2113
2114                 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
2115                 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
2116
2117                 sgen_pointer_queue_clear (&scanned_objects_list);
2118         }
2119 #endif
2120 }
2121
2122 static int
2123 compare_pointers (const void *va, const void *vb) {
2124         char *a = *(char**)va, *b = *(char**)vb;
2125         if (a < b)
2126                 return -1;
2127         if (a > b)
2128                 return 1;
2129         return 0;
2130 }
2131
2132 /*
2133  * This is called with sweep completed and the world stopped.
2134  */
2135 static void
2136 major_free_swept_blocks (size_t section_reserve)
2137 {
2138         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
2139
2140 #ifdef TARGET_WIN32
2141                 /*
2142                  * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
2143                  * a VirtualAlloc ()-ed block.
2144                  */
2145                 return;
2146 #endif
2147
2148         {
2149                 int i, num_empty_blocks_orig, num_blocks, arr_length;
2150                 void *block;
2151                 void **empty_block_arr;
2152                 void **rebuild_next;
2153
2154                 if (num_empty_blocks <= section_reserve)
2155                         return;
2156                 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
2157
2158                 num_empty_blocks_orig = num_empty_blocks;
2159                 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
2160                                 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
2161                 if (!empty_block_arr)
2162                         goto fallback;
2163
2164                 i = 0;
2165                 for (block = empty_blocks; block; block = *(void**)block)
2166                         empty_block_arr [i++] = block;
2167                 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
2168
2169                 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
2170
2171                 /*
2172                  * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
2173                  * contiguous ones.  If we do, we free them.  If that's not enough to get to
2174                  * section_reserve, we halve the number of contiguous blocks we're looking
2175                  * for and have another go, until we're done with looking for pairs of
2176                  * blocks, at which point we give up and go to the fallback.
2177                  */
2178                 arr_length = num_empty_blocks_orig;
2179                 num_blocks = MS_BLOCK_ALLOC_NUM;
2180                 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2181                         int first = -1;
2182                         int dest = 0;
2183
2184                         dest = 0;
2185                         for (i = 0; i < arr_length; ++i) {
2186                                 int d = dest;
2187                                 void *block = empty_block_arr [i];
2188                                 SGEN_ASSERT (6, block, "we're not shifting correctly");
2189                                 if (i != dest) {
2190                                         empty_block_arr [dest] = block;
2191                                         /*
2192                                          * This is not strictly necessary, but we're
2193                                          * cautious.
2194                                          */
2195                                         empty_block_arr [i] = NULL;
2196                                 }
2197                                 ++dest;
2198
2199                                 if (first < 0) {
2200                                         first = d;
2201                                         continue;
2202                                 }
2203
2204                                 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2205
2206                                 if ((char*)block != ((char*)empty_block_arr [d-1]) + ms_block_size) {
2207                                         first = d;
2208                                         continue;
2209                                 }
2210
2211                                 if (d + 1 - first == num_blocks) {
2212                                         /*
2213                                          * We found num_blocks contiguous blocks.  Free them
2214                                          * and null their array entries.  As an optimization
2215                                          * we could, instead of nulling the entries, shift
2216                                          * the following entries over to the left, while
2217                                          * we're iterating.
2218                                          */
2219                                         int j;
2220                                         sgen_free_os_memory (empty_block_arr [first], ms_block_size * num_blocks, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2221                                         for (j = first; j <= d; ++j)
2222                                                 empty_block_arr [j] = NULL;
2223                                         dest = first;
2224                                         first = -1;
2225
2226                                         num_empty_blocks -= num_blocks;
2227
2228                                         stat_major_blocks_freed += num_blocks;
2229                                         if (num_blocks == MS_BLOCK_ALLOC_NUM)
2230                                                 stat_major_blocks_freed_ideal += num_blocks;
2231                                         else
2232                                                 stat_major_blocks_freed_less_ideal += num_blocks;
2233
2234                                 }
2235                         }
2236
2237                         SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2238                         arr_length = dest;
2239                         SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2240
2241                         num_blocks >>= 1;
2242                 }
2243
2244                 /* rebuild empty_blocks free list */
2245                 rebuild_next = (void**)&empty_blocks;
2246                 for (i = 0; i < arr_length; ++i) {
2247                         void *block = empty_block_arr [i];
2248                         SGEN_ASSERT (6, block, "we're missing blocks");
2249                         *rebuild_next = block;
2250                         rebuild_next = (void**)block;
2251                 }
2252                 *rebuild_next = NULL;
2253
2254                 /* free array */
2255                 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2256         }
2257
2258         SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2259
2260  fallback:
2261         /*
2262          * This is our threshold.  If there's not more empty than used blocks, we won't
2263          * release uncontiguous blocks, in fear of fragmenting the address space.
2264          */
2265         if (num_empty_blocks <= num_major_sections)
2266                 return;
2267
2268         while (num_empty_blocks > section_reserve) {
2269                 void *next = *(void**)empty_blocks;
2270                 sgen_free_os_memory (empty_blocks, ms_block_size, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2271                 empty_blocks = next;
2272                 /*
2273                  * Needs not be atomic because this is running
2274                  * single-threaded.
2275                  */
2276                 --num_empty_blocks;
2277
2278                 ++stat_major_blocks_freed;
2279                 ++stat_major_blocks_freed_individual;
2280         }
2281 }
2282
2283 static void
2284 major_pin_objects (SgenGrayQueue *queue)
2285 {
2286         MSBlockInfo *block;
2287
2288         FOREACH_BLOCK_NO_LOCK (block) {
2289                 size_t first_entry, last_entry;
2290                 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2291                 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size,
2292                                 &first_entry, &last_entry);
2293                 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2294         } END_FOREACH_BLOCK_NO_LOCK;
2295 }
2296
2297 static void
2298 major_init_to_space (void)
2299 {
2300 }
2301
2302 static void
2303 major_report_pinned_memory_usage (void)
2304 {
2305         g_assert_not_reached ();
2306 }
2307
2308 static gint64
2309 major_get_used_size (void)
2310 {
2311         gint64 size = 0;
2312         MSBlockInfo *block;
2313
2314         /*
2315          * We're holding the GC lock, but the sweep thread might be running.  Make sure it's
2316          * finished, then we can iterate over the block array.
2317          */
2318         major_finish_sweep_checking ();
2319
2320         FOREACH_BLOCK_NO_LOCK (block) {
2321                 int count = MS_BLOCK_FREE / block->obj_size;
2322                 void **iter;
2323                 size += count * block->obj_size;
2324                 for (iter = block->free_list; iter; iter = (void**)*iter)
2325                         size -= block->obj_size;
2326         } END_FOREACH_BLOCK_NO_LOCK;
2327
2328         return size;
2329 }
2330
2331 /* FIXME: return number of bytes, not of sections */
2332 static size_t
2333 get_num_major_sections (void)
2334 {
2335         return num_major_sections;
2336 }
2337
2338 /*
2339  * Returns the number of bytes in blocks that were present when the last sweep was
2340  * initiated, and were not freed during the sweep.  They are the basis for calculating the
2341  * allowance.
2342  */
2343 static size_t
2344 get_bytes_survived_last_sweep (void)
2345 {
2346         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2347         return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * ms_block_size;
2348 }
2349
2350 static gboolean
2351 major_handle_gc_param (const char *opt)
2352 {
2353         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2354                 const char *arg = strchr (opt, '=') + 1;
2355                 int percentage = atoi (arg);
2356                 if (percentage < 0 || percentage > 100) {
2357                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2358                         exit (1);
2359                 }
2360                 evacuation_threshold = (float)percentage / 100.0f;
2361                 return TRUE;
2362         } else if (!strcmp (opt, "lazy-sweep")) {
2363                 lazy_sweep = TRUE;
2364                 return TRUE;
2365         } else if (!strcmp (opt, "no-lazy-sweep")) {
2366                 lazy_sweep = FALSE;
2367                 return TRUE;
2368         } else if (!strcmp (opt, "concurrent-sweep")) {
2369                 concurrent_sweep = TRUE;
2370                 return TRUE;
2371         } else if (!strcmp (opt, "no-concurrent-sweep")) {
2372                 concurrent_sweep = FALSE;
2373                 return TRUE;
2374         }
2375
2376         return FALSE;
2377 }
2378
2379 static void
2380 major_print_gc_param_usage (void)
2381 {
2382         fprintf (stderr,
2383                         ""
2384                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2385                         "  (no-)lazy-sweep\n"
2386                         "  (no-)concurrent-sweep\n"
2387                         );
2388 }
2389
2390 /*
2391  * This callback is used to clear cards, move cards to the shadow table and do counting.
2392  */
2393 static void
2394 major_iterate_block_ranges (sgen_cardtable_block_callback callback)
2395 {
2396         MSBlockInfo *block;
2397         gboolean has_references;
2398
2399         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2400                 if (has_references)
2401                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2402         } END_FOREACH_BLOCK_NO_LOCK;
2403 }
2404
2405 static void
2406 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2407 {
2408         MSBlockInfo *block;
2409         gboolean has_references;
2410
2411         major_finish_sweep_checking ();
2412         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2413                 if (has_references)
2414                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2415         } END_FOREACH_BLOCK_NO_LOCK;
2416 }
2417
2418 #ifdef HEAVY_STATISTICS
2419 extern guint64 marked_cards;
2420 extern guint64 scanned_cards;
2421 extern guint64 scanned_objects;
2422 extern guint64 remarked_cards;
2423 #endif
2424
2425 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2426 /*
2427  * MS blocks are 16K aligned.
2428  * Cardtables are 4K aligned, at least.
2429  * This means that the cardtable of a given block is 32 bytes aligned.
2430  */
2431 static guint8*
2432 initial_skip_card (guint8 *card_data)
2433 {
2434         mword *cards = (mword*)card_data;
2435         mword card = 0;
2436         int i;
2437         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2438                 card = cards [i];
2439                 if (card)
2440                         break;
2441         }
2442
2443         if (i == CARD_WORDS_PER_BLOCK)
2444                 return card_data + CARDS_PER_BLOCK;
2445
2446 #if defined(__i386__) && defined(__GNUC__)
2447         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
2448 #elif defined(__x86_64__) && defined(__GNUC__)
2449         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
2450 #elif defined(__s390x__) && defined(__GNUC__)
2451         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2452 #else
2453         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2454                 if (card_data [i])
2455                         return &card_data [i];
2456         }
2457         return card_data;
2458 #endif
2459 }
2460
2461 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2462 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
2463 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + ms_block_size))
2464
2465 static void
2466 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2467 {
2468         SgenGrayQueue *queue = ctx.queue;
2469         ScanObjectFunc scan_func = ctx.ops->scan_object;
2470         /*
2471          * FIXME: On systems with very large pages, we allocate fairly large
2472          * arrays on the stack here. This shouldn't be a problem once block
2473          * size is no longer required to be a multiple of the system page size.
2474          */
2475 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2476         guint8 *cards_copy = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2477 #endif
2478         guint8 *cards_preclean = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2479         gboolean small_objects;
2480         int block_obj_size;
2481         char *block_start;
2482         guint8 *card_data, *card_base;
2483         guint8 *card_data_end;
2484         char *scan_front = NULL;
2485
2486         /* The concurrent mark doesn't enter evacuating blocks */
2487         if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2488                 return;
2489
2490         block_obj_size = block->obj_size;
2491         small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2492
2493         block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2494
2495         /*
2496          * This is safe in face of card aliasing for the following reason:
2497          *
2498          * Major blocks are 16k aligned, or 32 cards aligned.
2499          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2500          * sizes, they won't overflow the cardtable overlap modulus.
2501          */
2502         if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2503                 card_data = card_base = block->cardtable_mod_union;
2504                 /*
2505                  * This happens when the nursery collection that precedes finishing
2506                  * the concurrent collection allocates new major blocks.
2507                  */
2508                 if (!card_data)
2509                         return;
2510
2511                 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2512                         sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2513                         card_data = card_base = cards_preclean;
2514                 }
2515         } else {
2516 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2517                 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2518 #else
2519                 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2520                         return;
2521                 card_data = card_base = cards_copy;
2522 #endif
2523         }
2524         card_data_end = card_data + CARDS_PER_BLOCK;
2525
2526         card_data += MS_BLOCK_SKIP >> CARD_BITS;
2527
2528         card_data = initial_skip_card (card_data);
2529         while (card_data < card_data_end) {
2530                 size_t card_index, first_object_index;
2531                 char *start;
2532                 char *end;
2533                 char *first_obj, *obj;
2534
2535                 HEAVY_STAT (++scanned_cards);
2536
2537                 if (!*card_data) {
2538                         ++card_data;
2539                         continue;
2540                 }
2541
2542                 card_index = card_data - card_base;
2543                 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2544                 end = start + CARD_SIZE_IN_BYTES;
2545
2546                 if (!block_is_swept_or_marking (block))
2547                         sweep_block (block);
2548
2549                 HEAVY_STAT (++marked_cards);
2550
2551                 if (small_objects)
2552                         sgen_card_table_prepare_card_for_scanning (card_data);
2553
2554                 /*
2555                  * If the card we're looking at starts at or in the block header, we
2556                  * must start at the first object in the block, without calculating
2557                  * the index of the object we're hypothetically starting at, because
2558                  * it would be negative.
2559                  */
2560                 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2561                         first_object_index = 0;
2562                 else
2563                         first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2564
2565                 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2566
2567                 binary_protocol_card_scan (first_obj, end - first_obj);
2568
2569                 while (obj < end) {
2570                         if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2571                                 goto next_object;
2572
2573                         if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2574                                 /* FIXME: do this more efficiently */
2575                                 int w, b;
2576                                 MS_CALC_MARK_BIT (w, b, obj);
2577                                 if (!MS_MARK_BIT (block, w, b))
2578                                         goto next_object;
2579                         }
2580
2581                         GCObject *object = (GCObject*)obj;
2582
2583                         if (small_objects) {
2584                                 HEAVY_STAT (++scanned_objects);
2585                                 scan_func (object, sgen_obj_get_descriptor (object), queue);
2586                         } else {
2587                                 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2588                                 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2589                         }
2590                 next_object:
2591                         obj += block_obj_size;
2592                         g_assert (scan_front <= obj);
2593                         scan_front = obj;
2594                 }
2595
2596                 HEAVY_STAT (if (*card_data) ++remarked_cards);
2597
2598                 if (small_objects)
2599                         ++card_data;
2600                 else
2601                         card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2602         }
2603 }
2604
2605 static void
2606 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count)
2607 {
2608         MSBlockInfo *block;
2609         gboolean has_references, was_sweeping, skip_scan;
2610
2611         if (!concurrent_mark)
2612                 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2613
2614         if (scan_type != CARDTABLE_SCAN_GLOBAL)
2615                 SGEN_ASSERT (0, !sweep_in_progress (), "Sweep should be finished when we scan mod union card table");
2616         was_sweeping = sweep_in_progress ();
2617
2618         binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2619         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2620                 if (__index % job_split_count != job_index)
2621                         continue;
2622 #ifdef PREFETCH_CARDS
2623                 int prefetch_index = __index + 6 * job_split_count;
2624                 if (prefetch_index < allocated_blocks.next_slot) {
2625                         MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2626                         PREFETCH_READ (prefetch_block);
2627                         if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2628                                 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2629                                 PREFETCH_WRITE (prefetch_cards);
2630                                 PREFETCH_WRITE (prefetch_cards + 32);
2631                         }
2632                 }
2633 #endif
2634
2635                 if (!has_references)
2636                         continue;
2637                 skip_scan = FALSE;
2638
2639                 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2640                         gpointer *card_start = (gpointer*) sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2641                         gboolean has_dirty_cards = FALSE;
2642                         int i;
2643                         for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2644                                 if (card_start [i]) {
2645                                         has_dirty_cards = TRUE;
2646                                         break;
2647                                 }
2648                         }
2649                         if (!has_dirty_cards) {
2650                                 skip_scan = TRUE;
2651                         } else {
2652                                 /*
2653                                  * After the start of the concurrent collections, blocks change state
2654                                  * to marking. We should not sweep it in that case. We can't race with
2655                                  * sweep start since we are in a nursery collection. Also avoid CAS-ing
2656                                  */
2657                                 if (sweep_in_progress ()) {
2658                                         skip_scan = !ensure_block_is_checked_for_sweeping (__index, TRUE, NULL);
2659                                 } else if (was_sweeping) {
2660                                         /* Recheck in case sweep finished after dereferencing the slot */
2661                                         skip_scan = *sgen_array_list_get_slot (&allocated_blocks, __index) == 0;
2662                                 }
2663                         }
2664                 }
2665                 if (!skip_scan)
2666                         scan_card_table_for_block (block, scan_type, ctx);
2667         } END_FOREACH_BLOCK_NO_LOCK;
2668         binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2669 }
2670
2671 static void
2672 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2673 {
2674         MSBlockInfo *block;
2675         gboolean has_references;
2676         long long total_cards = 0;
2677         long long marked_cards = 0;
2678
2679         if (sweep_in_progress ()) {
2680                 *num_total_cards = -1;
2681                 *num_marked_cards = -1;
2682                 return;
2683         }
2684
2685         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2686                 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2687                 int i;
2688
2689                 if (!has_references)
2690                         continue;
2691
2692                 total_cards += CARDS_PER_BLOCK;
2693                 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2694                         if (cards [i])
2695                                 ++marked_cards;
2696                 }
2697         } END_FOREACH_BLOCK_NO_LOCK;
2698
2699         *num_total_cards = total_cards;
2700         *num_marked_cards = marked_cards;
2701 }
2702
2703 static void
2704 update_cardtable_mod_union (void)
2705 {
2706         MSBlockInfo *block;
2707
2708         FOREACH_BLOCK_NO_LOCK (block) {
2709                 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2710                 gboolean has_dirty_cards = FALSE;
2711                 int i;
2712                 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2713                         if (card_start [i]) {
2714                                 has_dirty_cards = TRUE;
2715                                 break;
2716                         }
2717                 }
2718                 if (has_dirty_cards) {
2719                         size_t num_cards;
2720                         guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2721                         sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size, &num_cards);
2722                         SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2723                 }
2724         } END_FOREACH_BLOCK_NO_LOCK;
2725 }
2726
2727 #undef pthread_create
2728
2729 static void
2730 post_param_init (SgenMajorCollector *collector)
2731 {
2732         collector->sweeps_lazily = lazy_sweep;
2733 }
2734
2735 /*
2736  * We are guaranteed to be called by the worker in question.
2737  * This provides initialization for threads that plan to do
2738  * parallel object allocation. We need to store these lists
2739  * in additional data structures so we can traverse them
2740  * at major/sweep start.
2741  */
2742 static void
2743 sgen_init_block_free_lists (gpointer *list_p)
2744 {
2745         int i;
2746         MSBlockInfo ***worker_free_blocks = (MSBlockInfo ***) mono_native_tls_get_value (worker_block_free_list_key);
2747
2748         /*
2749          * For simplification, a worker thread uses the same free block lists,
2750          * regardless of the context it is part of (major/minor).
2751          */
2752         if (worker_free_blocks) {
2753                 *list_p = (gpointer)worker_free_blocks;
2754                 return;
2755         }
2756
2757         worker_free_blocks = (MSBlockInfo ***) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX, INTERNAL_MEM_MS_TABLES, TRUE);
2758
2759         for (i = 0; i < MS_BLOCK_TYPE_MAX; i++)
2760                 worker_free_blocks [i] = (MSBlockInfo **) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2761
2762         *list_p = (gpointer)worker_free_blocks;
2763
2764         mono_native_tls_set_value (worker_block_free_list_key, worker_free_blocks);
2765 }
2766
2767 static void
2768 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent, gboolean is_parallel)
2769 {
2770         int i;
2771
2772         ms_block_size = mono_pagesize ();
2773
2774         if (ms_block_size < MS_BLOCK_SIZE_MIN)
2775                 ms_block_size = MS_BLOCK_SIZE_MIN;
2776
2777         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, SIZEOF_MS_BLOCK_INFO);
2778
2779         if (mono_cpu_count () <= 1)
2780                 is_parallel = FALSE;
2781
2782         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2783         block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2784         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2785
2786         evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2787         for (i = 0; i < num_block_obj_sizes; ++i)
2788                 evacuate_block_obj_sizes [i] = FALSE;
2789
2790         sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2791         sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2792         sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2793
2794         /*
2795         {
2796                 int i;
2797                 g_print ("block object sizes:\n");
2798                 for (i = 0; i < num_block_obj_sizes; ++i)
2799                         g_print ("%d\n", block_obj_sizes [i]);
2800         }
2801         */
2802
2803         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2804                 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2805
2806         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2807                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2808         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2809                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2810
2811         /* We can do this because we always init the minor before the major */
2812         if (is_parallel || sgen_get_minor_collector ()->is_parallel)
2813                 mono_native_tls_alloc (&worker_block_free_list_key, NULL);
2814
2815         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2816         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2817         mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2818         mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2819         mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2820         mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2821         mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2822
2823         collector->section_size = ms_block_size;
2824
2825         concurrent_mark = is_concurrent;
2826         collector->is_concurrent = is_concurrent;
2827         collector->is_parallel = is_parallel;
2828         collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2829         collector->supports_cardtable = TRUE;
2830
2831         collector->alloc_heap = major_alloc_heap;
2832         collector->is_object_live = major_is_object_live;
2833         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2834         collector->alloc_degraded = major_alloc_degraded;
2835
2836         collector->alloc_object = major_alloc_object;
2837         collector->alloc_object_par = major_alloc_object_par;
2838         collector->free_pinned_object = free_pinned_object;
2839         collector->iterate_objects = major_iterate_objects;
2840         collector->free_non_pinned_object = major_free_non_pinned_object;
2841         collector->pin_objects = major_pin_objects;
2842         collector->pin_major_object = pin_major_object;
2843         collector->scan_card_table = major_scan_card_table;
2844         collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2845         collector->iterate_block_ranges = major_iterate_block_ranges;
2846         if (is_concurrent) {
2847                 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2848                 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2849         }
2850         collector->init_to_space = major_init_to_space;
2851         collector->sweep = major_sweep;
2852         collector->have_swept = major_have_swept;
2853         collector->finish_sweeping = major_finish_sweep_checking;
2854         collector->free_swept_blocks = major_free_swept_blocks;
2855         collector->check_scan_starts = major_check_scan_starts;
2856         collector->dump_heap = major_dump_heap;
2857         collector->get_used_size = major_get_used_size;
2858         collector->start_nursery_collection = major_start_nursery_collection;
2859         collector->finish_nursery_collection = major_finish_nursery_collection;
2860         collector->start_major_collection = major_start_major_collection;
2861         collector->finish_major_collection = major_finish_major_collection;
2862         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2863         collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2864         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2865         collector->get_num_major_sections = get_num_major_sections;
2866         collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2867         collector->handle_gc_param = major_handle_gc_param;
2868         collector->print_gc_param_usage = major_print_gc_param_usage;
2869         collector->post_param_init = post_param_init;
2870         collector->is_valid_object = major_is_valid_object;
2871         collector->describe_pointer = major_describe_pointer;
2872         collector->count_cards = major_count_cards;
2873         collector->init_block_free_lists = sgen_init_block_free_lists;
2874
2875         collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2876         collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2877         collector->major_ops_serial.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2878         collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2879         if (is_concurrent) {
2880                 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2881                 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2882                 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2883                 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2884                 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2885
2886                 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2887                 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2888                 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2889                 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2890                 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2891
2892                 if (is_parallel) {
2893                         collector->major_ops_conc_par_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_canonical;
2894                         collector->major_ops_conc_par_start.scan_object = major_scan_object_concurrent_par_with_evacuation;
2895                         collector->major_ops_conc_par_start.scan_vtype = major_scan_vtype_concurrent_par_with_evacuation;
2896                         collector->major_ops_conc_par_start.scan_ptr_field = major_scan_ptr_field_concurrent_par_with_evacuation;
2897                         collector->major_ops_conc_par_start.drain_gray_stack = drain_gray_stack_concurrent_par;
2898
2899                         collector->major_ops_conc_par_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_finish_canonical;
2900                         collector->major_ops_conc_par_finish.scan_object = major_scan_object_par_with_evacuation;
2901                         collector->major_ops_conc_par_finish.scan_vtype = major_scan_vtype_par_with_evacuation;
2902                         collector->major_ops_conc_par_finish.scan_ptr_field = major_scan_ptr_field_par_with_evacuation;
2903                         collector->major_ops_conc_par_finish.drain_gray_stack = drain_gray_stack_par;
2904                 }
2905         }
2906
2907 #ifdef HEAVY_STATISTICS
2908         mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2909         mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2910         mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2911         mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2912         mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2913         mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2914         mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2915         mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2916         mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2917         mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2918         mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2919
2920         mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2921         mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2922         mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2923 #endif
2924
2925 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2926         mono_os_mutex_init (&scanned_objects_list_lock);
2927 #endif
2928
2929         SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2930
2931         /*cardtable requires major pages to be 8 cards aligned*/
2932         g_assert ((ms_block_size % (8 * CARD_SIZE_IN_BYTES)) == 0);
2933
2934         if (is_concurrent && is_parallel)
2935                 sgen_workers_create_context (GENERATION_OLD, mono_cpu_count ());
2936         else if (is_concurrent)
2937                 sgen_workers_create_context (GENERATION_OLD, 1);
2938
2939         if (concurrent_sweep)
2940                 sweep_pool_context = sgen_thread_pool_create_context (1, NULL, NULL, NULL, NULL, NULL);
2941 }
2942
2943 void
2944 sgen_marksweep_init (SgenMajorCollector *collector)
2945 {
2946         sgen_marksweep_init_internal (collector, FALSE, FALSE);
2947 }
2948
2949 void
2950 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2951 {
2952         sgen_marksweep_init_internal (collector, TRUE, FALSE);
2953 }
2954
2955 void
2956 sgen_marksweep_conc_par_init (SgenMajorCollector *collector)
2957 {
2958         sgen_marksweep_init_internal (collector, TRUE, TRUE);
2959 }
2960
2961 #endif