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