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