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