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