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