[aot] Fix the encoding/decoding of generic parameters after 835cc6eda9fb6edc6e5177444...
[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_os_mutex_lock (&scanned_objects_list_lock);
275         sgen_pointer_queue_add (&scanned_objects_list, ptr);
276         mono_os_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          * Adding to the allocated_blocks array is racy with the removal of nulls when
563          * sweeping. We wait for sweep to finish to avoid that.
564          *
565          * The memory barrier here and in `sweep_job_func()` are required because we need
566          * `allocated_blocks` synchronized between this and the sweep thread.
567          */
568         major_finish_sweep_checking ();
569         mono_memory_barrier ();
570
571         sgen_pointer_queue_add (&allocated_blocks, BLOCK_TAG (info));
572
573         SGEN_ATOMIC_ADD_P (num_major_sections, 1);
574         return TRUE;
575 }
576
577 static gboolean
578 ptr_is_from_pinned_alloc (char *ptr)
579 {
580         MSBlockInfo *block;
581
582         FOREACH_BLOCK_NO_LOCK (block) {
583                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
584                         return block->pinned;
585         } END_FOREACH_BLOCK_NO_LOCK;
586         return FALSE;
587 }
588
589 static void
590 ensure_can_access_block_free_list (MSBlockInfo *block)
591 {
592  retry:
593         for (;;) {
594                 switch (block->state) {
595                 case BLOCK_STATE_SWEPT:
596                 case BLOCK_STATE_MARKING:
597                         return;
598                 case BLOCK_STATE_CHECKING:
599                         SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
600                         break;
601                 case BLOCK_STATE_NEED_SWEEPING:
602                         if (sweep_block (block))
603                                 ++stat_major_blocks_lazy_swept;
604                         break;
605                 case BLOCK_STATE_SWEEPING:
606                         /* FIXME: do this more elegantly */
607                         g_usleep (100);
608                         goto retry;
609                 default:
610                         SGEN_ASSERT (0, FALSE, "Illegal block state");
611                         break;
612                 }
613         }
614 }
615
616 static void*
617 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
618 {
619         MSBlockInfo *block, *next_free_block;
620         void *obj, *next_free_slot;
621
622  retry:
623         block = free_blocks [size_index];
624         SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
625
626         ensure_can_access_block_free_list (block);
627
628         obj = block->free_list;
629         SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
630
631         next_free_slot = *(void**)obj;
632         if (next_free_slot) {
633                 block->free_list = next_free_slot;
634                 return obj;
635         }
636
637         next_free_block = block->next_free;
638         if (SGEN_CAS_PTR ((gpointer)&free_blocks [size_index], next_free_block, block) != block)
639                 goto retry;
640
641         block->free_list = NULL;
642         block->next_free = NULL;
643
644         return obj;
645 }
646
647 static GCObject*
648 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
649 {
650         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
651         MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
652         void *obj;
653
654         if (!free_blocks [size_index]) {
655                 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
656                         return NULL;
657         }
658
659         obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
660
661         /* FIXME: assumes object layout */
662         *(GCVTable*)obj = vtable;
663
664         return obj;
665 }
666
667 static GCObject*
668 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
669 {
670         return alloc_obj (vtable, size, FALSE, has_references);
671 }
672
673 /*
674  * We're not freeing the block if it's empty.  We leave that work for
675  * the next major collection.
676  *
677  * This is just called from the domain clearing code, which runs in a
678  * single thread and has the GC lock, so we don't need an extra lock.
679  */
680 static void
681 free_object (GCObject *obj, size_t size, gboolean pinned)
682 {
683         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
684         int word, bit;
685         gboolean in_free_list;
686
687         SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
688
689         ensure_can_access_block_free_list (block);
690         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);
691         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
692         MS_CALC_MARK_BIT (word, bit, obj);
693         SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
694
695         memset (obj, 0, size);
696
697         in_free_list = !!block->free_list;
698         *(void**)obj = block->free_list;
699         block->free_list = (void**)obj;
700
701         if (!in_free_list) {
702                 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
703                 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
704                 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);
705                 add_free_block (free_blocks, size_index, block);
706         }
707 }
708
709 static void
710 major_free_non_pinned_object (GCObject *obj, size_t size)
711 {
712         free_object (obj, size, FALSE);
713 }
714
715 /* size is a multiple of SGEN_ALLOC_ALIGN */
716 static GCObject*
717 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
718 {
719         void *res;
720
721         res = alloc_obj (vtable, size, TRUE, has_references);
722          /*If we failed to alloc memory, we better try releasing memory
723           *as pinned alloc is requested by the runtime.
724           */
725          if (!res) {
726                 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
727                 res = alloc_obj (vtable, size, TRUE, has_references);
728          }
729          return res;
730 }
731
732 static void
733 free_pinned_object (GCObject *obj, size_t size)
734 {
735         free_object (obj, size, TRUE);
736 }
737
738 /*
739  * size is already rounded up and we hold the GC lock.
740  */
741 static GCObject*
742 major_alloc_degraded (GCVTable vtable, size_t size)
743 {
744         GCObject *obj;
745
746         obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
747         if (G_LIKELY (obj)) {
748                 HEAVY_STAT (++stat_objects_alloced_degraded);
749                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
750         }
751         return obj;
752 }
753
754 /*
755  * obj is some object.  If it's not in the major heap (i.e. if it's in
756  * the nursery or LOS), return FALSE.  Otherwise return whether it's
757  * been marked or copied.
758  */
759 static gboolean
760 major_is_object_live (GCObject *obj)
761 {
762         MSBlockInfo *block;
763         int word, bit;
764         mword objsize;
765
766         if (sgen_ptr_in_nursery (obj))
767                 return FALSE;
768
769         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
770
771         /* LOS */
772         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
773                 return FALSE;
774
775         /* now we know it's in a major block */
776         block = MS_BLOCK_FOR_OBJ (obj);
777         SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
778         MS_CALC_MARK_BIT (word, bit, obj);
779         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
780 }
781
782 static gboolean
783 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
784 {
785         MSBlockInfo *block;
786
787         FOREACH_BLOCK_NO_LOCK (block) {
788                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
789                         int count = MS_BLOCK_FREE / block->obj_size;
790                         int i;
791
792                         *start = NULL;
793                         for (i = 0; i <= count; ++i) {
794                                 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
795                                         *start = MS_BLOCK_OBJ (block, i);
796                                         break;
797                                 }
798                         }
799                         return !block->pinned;
800                 }
801         } END_FOREACH_BLOCK_NO_LOCK;
802         return FALSE;
803 }
804
805 static gboolean
806 try_set_sweep_state (int new, int expected)
807 {
808         int old = SGEN_CAS (&sweep_state, new, expected);
809         return old == expected;
810 }
811
812 static void
813 set_sweep_state (int new, int expected)
814 {
815         gboolean success = try_set_sweep_state (new, expected);
816         SGEN_ASSERT (0, success, "Could not set sweep state.");
817 }
818
819 static gboolean ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked);
820
821 static SgenThreadPoolJob * volatile sweep_job;
822
823 static void
824 major_finish_sweep_checking (void)
825 {
826         int block_index;
827         SgenThreadPoolJob *job;
828
829  retry:
830         switch (sweep_state) {
831         case SWEEP_STATE_SWEPT:
832         case SWEEP_STATE_NEED_SWEEPING:
833                 return;
834         case SWEEP_STATE_SWEEPING:
835                 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
836                         break;
837                 goto retry;
838         case SWEEP_STATE_SWEEPING_AND_ITERATING:
839                 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
840                 goto retry;
841         case SWEEP_STATE_COMPACTING:
842                 goto wait;
843         default:
844                 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
845                 break;
846         }
847
848         /*
849          * We're running with the world stopped and the only other thread doing work is the
850          * sweep thread, which doesn't add blocks to the array, so we can safely access
851          * `next_slot`.
852          */
853         for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
854                 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
855
856         set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
857
858  wait:
859         job = sweep_job;
860         if (job)
861                 sgen_thread_pool_job_wait (job);
862         SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
863         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
864 }
865
866 static void
867 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
868 {
869         gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
870         gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
871         gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
872         MSBlockInfo *block;
873
874         major_finish_sweep_checking ();
875         FOREACH_BLOCK_NO_LOCK (block) {
876                 int count = MS_BLOCK_FREE / block->obj_size;
877                 int i;
878
879                 if (block->pinned && !pinned)
880                         continue;
881                 if (!block->pinned && !non_pinned)
882                         continue;
883                 if (sweep && lazy_sweep) {
884                         sweep_block (block);
885                         SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
886                 }
887
888                 for (i = 0; i < count; ++i) {
889                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
890                         /*
891                          * We've finished sweep checking, but if we're sweeping lazily and
892                          * the flags don't require us to sweep, the block might still need
893                          * sweeping.  In that case, we need to consult the mark bits to tell
894                          * us whether an object slot is live.
895                          */
896                         if (!block_is_swept_or_marking (block)) {
897                                 int word, bit;
898                                 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
899                                 MS_CALC_MARK_BIT (word, bit, obj);
900                                 if (!MS_MARK_BIT (block, word, bit))
901                                         continue;
902                         }
903                         if (MS_OBJ_ALLOCED (obj, block))
904                                 callback ((GCObject*)obj, block->obj_size, data);
905                 }
906         } END_FOREACH_BLOCK_NO_LOCK;
907 }
908
909 static gboolean
910 major_is_valid_object (char *object)
911 {
912         MSBlockInfo *block;
913
914         FOREACH_BLOCK_NO_LOCK (block) {
915                 int idx;
916                 char *obj;
917
918                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
919                         continue;
920
921                 idx = MS_BLOCK_OBJ_INDEX (object, block);
922                 obj = (char*)MS_BLOCK_OBJ (block, idx);
923                 if (obj != object)
924                         return FALSE;
925                 return MS_OBJ_ALLOCED (obj, block);
926         } END_FOREACH_BLOCK_NO_LOCK;
927
928         return FALSE;
929 }
930
931
932 static GCVTable
933 major_describe_pointer (char *ptr)
934 {
935         MSBlockInfo *block;
936
937         FOREACH_BLOCK_NO_LOCK (block) {
938                 int idx;
939                 char *obj;
940                 gboolean live;
941                 GCVTable vtable;
942                 int w, b;
943                 gboolean marked;
944
945                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
946                         continue;
947
948                 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
949                         MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
950
951                 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
952                 obj = (char*)MS_BLOCK_OBJ (block, idx);
953                 live = MS_OBJ_ALLOCED (obj, block);
954                 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
955
956                 MS_CALC_MARK_BIT (w, b, obj);
957                 marked = MS_MARK_BIT (block, w, b);
958
959                 if (obj == ptr) {
960                         SGEN_LOG (0, "\t(");
961                         if (live)
962                                 SGEN_LOG (0, "object");
963                         else
964                                 SGEN_LOG (0, "dead-object");
965                 } else {
966                         if (live)
967                                 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
968                         else
969                                 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
970                 }
971
972                 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
973
974                 return vtable;
975         } END_FOREACH_BLOCK_NO_LOCK;
976
977         return NULL;
978 }
979
980 static void
981 major_check_scan_starts (void)
982 {
983 }
984
985 static void
986 major_dump_heap (FILE *heap_dump_file)
987 {
988         MSBlockInfo *block;
989         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
990         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
991         int i;
992
993         for (i = 0; i < num_block_obj_sizes; ++i)
994                 slots_available [i] = slots_used [i] = 0;
995
996         FOREACH_BLOCK_NO_LOCK (block) {
997                 int index = ms_find_block_obj_size_index (block->obj_size);
998                 int count = MS_BLOCK_FREE / block->obj_size;
999
1000                 slots_available [index] += count;
1001                 for (i = 0; i < count; ++i) {
1002                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1003                                 ++slots_used [index];
1004                 }
1005         } END_FOREACH_BLOCK_NO_LOCK;
1006
1007         fprintf (heap_dump_file, "<occupancies>\n");
1008         for (i = 0; i < num_block_obj_sizes; ++i) {
1009                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1010                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
1011         }
1012         fprintf (heap_dump_file, "</occupancies>\n");
1013
1014         FOREACH_BLOCK_NO_LOCK (block) {
1015                 int count = MS_BLOCK_FREE / block->obj_size;
1016                 int i;
1017                 int start = -1;
1018
1019                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1020
1021                 for (i = 0; i <= count; ++i) {
1022                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1023                                 if (start < 0)
1024                                         start = i;
1025                         } else {
1026                                 if (start >= 0) {
1027                                         sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1028                                         start = -1;
1029                                 }
1030                         }
1031                 }
1032
1033                 fprintf (heap_dump_file, "</section>\n");
1034         } END_FOREACH_BLOCK_NO_LOCK;
1035 }
1036
1037 static guint8*
1038 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1039 {
1040         guint8 *mod_union = block->cardtable_mod_union;
1041         guint8 *other;
1042         if (mod_union)
1043                 return mod_union;
1044         else if (!allocate)
1045                 return NULL;
1046         mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1047         other = SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1048         if (!other) {
1049                 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1050                 return mod_union;
1051         }
1052         sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1053         return other;
1054 }
1055
1056 static inline guint8*
1057 major_get_cardtable_mod_union_for_reference (char *ptr)
1058 {
1059         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1060         size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1061         guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1062         SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1063         return &mod_union [offset];
1064 }
1065
1066 /*
1067  * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1068  */
1069 static void
1070 mark_mod_union_card (GCObject *obj, void **ptr)
1071 {
1072         int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1073         if (sgen_safe_object_is_small (obj, type)) {
1074                 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1075                 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?");
1076                 *card_byte = 1;
1077         } else {
1078                 sgen_los_mark_mod_union_card (obj, ptr);
1079         }
1080 }
1081
1082 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
1083
1084 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do {   \
1085                 int __word, __bit;                                      \
1086                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1087                 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
1088                         MS_SET_MARK_BIT ((block), __word, __bit);       \
1089                         if (sgen_gc_descr_has_references (desc))                        \
1090                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1091                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1092                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
1093                 }                                                       \
1094         } while (0)
1095 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do {           \
1096                 int __word, __bit;                                      \
1097                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1098                 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1099                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
1100                         MS_SET_MARK_BIT ((block), __word, __bit);       \
1101                         if (sgen_gc_descr_has_references (desc))                        \
1102                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1103                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1104                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
1105                 }                                                       \
1106         } while (0)
1107
1108 static void
1109 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1110 {
1111         MSBlockInfo *block;
1112
1113         if (concurrent_mark)
1114                 g_assert_not_reached ();
1115
1116         block = MS_BLOCK_FOR_OBJ (obj);
1117         block->has_pinned = TRUE;
1118         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1119 }
1120
1121 #include "sgen-major-copy-object.h"
1122
1123 static long long
1124 major_get_and_reset_num_major_objects_marked (void)
1125 {
1126 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1127         long long num = num_major_objects_marked;
1128         num_major_objects_marked = 0;
1129         return num;
1130 #else
1131         return 0;
1132 #endif
1133 }
1134
1135 #define PREFETCH_CARDS          1       /* BOOL FASTENABLE */
1136 #if !PREFETCH_CARDS
1137 #undef PREFETCH_CARDS
1138 #endif
1139
1140 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1141 #if defined(PLATFORM_MACOSX)
1142 #define GCC_VERSION (__GNUC__ * 10000 \
1143                                + __GNUC_MINOR__ * 100 \
1144                                + __GNUC_PATCHLEVEL__)
1145 #if GCC_VERSION <= 40300
1146 #undef PREFETCH_CARDS
1147 #endif
1148 #endif
1149
1150 #ifdef HEAVY_STATISTICS
1151 static guint64 stat_optimized_copy;
1152 static guint64 stat_optimized_copy_nursery;
1153 static guint64 stat_optimized_copy_nursery_forwarded;
1154 static guint64 stat_optimized_copy_nursery_pinned;
1155 static guint64 stat_optimized_copy_major;
1156 static guint64 stat_optimized_copy_major_small_fast;
1157 static guint64 stat_optimized_copy_major_small_slow;
1158 static guint64 stat_optimized_copy_major_large;
1159 static guint64 stat_optimized_copy_major_forwarded;
1160 static guint64 stat_optimized_copy_major_small_evacuate;
1161 static guint64 stat_optimized_major_scan;
1162 static guint64 stat_optimized_major_scan_no_refs;
1163
1164 static guint64 stat_drain_prefetch_fills;
1165 static guint64 stat_drain_prefetch_fill_failures;
1166 static guint64 stat_drain_loops;
1167 #endif
1168
1169 static void major_scan_object_with_evacuation (GCObject *start, mword desc, SgenGrayQueue *queue);
1170
1171 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_no_evacuation
1172 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_no_evacuation
1173 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_no_evacuation
1174 #include "sgen-marksweep-drain-gray-stack.h"
1175
1176 #define COPY_OR_MARK_WITH_EVACUATION
1177 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_with_evacuation
1178 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_with_evacuation
1179 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_with_evacuation
1180 #include "sgen-marksweep-drain-gray-stack.h"
1181
1182 #undef COPY_OR_MARK_WITH_EVACUATION
1183 #define COPY_OR_MARK_CONCURRENT
1184 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_concurrent
1185 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_concurrent
1186 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_concurrent
1187 #include "sgen-marksweep-drain-gray-stack.h"
1188
1189 static gboolean
1190 drain_gray_stack (SgenGrayQueue *queue)
1191 {
1192         gboolean evacuation = FALSE;
1193         int i;
1194         for (i = 0; i < num_block_obj_sizes; ++i) {
1195                 if (evacuate_block_obj_sizes [i]) {
1196                         evacuation = TRUE;
1197                         break;
1198                 }
1199         }
1200
1201         if (evacuation)
1202                 return drain_gray_stack_with_evacuation (queue);
1203         else
1204                 return drain_gray_stack_no_evacuation (queue);
1205 }
1206
1207 #include "sgen-marksweep-scan-object-concurrent.h"
1208
1209 static void
1210 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1211 {
1212         major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1213 }
1214
1215 static void
1216 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1217 {
1218         major_copy_or_mark_object_concurrent (ptr, *ptr, queue);
1219 }
1220
1221 static void
1222 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1223 {
1224         major_copy_or_mark_object_no_evacuation (ptr, *ptr, queue);
1225 }
1226
1227 static void
1228 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1229 {
1230         void **entry, **end;
1231         int last_index = -1;
1232
1233         if (first_entry == last_entry)
1234                 return;
1235
1236         block->has_pinned = TRUE;
1237
1238         entry = sgen_pinning_get_entry (first_entry);
1239         end = sgen_pinning_get_entry (last_entry);
1240
1241         for (; entry < end; ++entry) {
1242                 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1243                 GCObject *obj;
1244                 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));
1245                 if (index == last_index)
1246                         continue;
1247                 obj = MS_BLOCK_OBJ (block, index);
1248                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1249                 last_index = index;
1250         }
1251 }
1252
1253 static inline void
1254 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1255 {
1256         int obj_index;
1257
1258         for (obj_index = 0; obj_index < count; ++obj_index) {
1259                 int word, bit;
1260                 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1261
1262                 MS_CALC_MARK_BIT (word, bit, obj);
1263                 if (MS_MARK_BIT (block, word, bit)) {
1264                         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1265                 } else {
1266                         /* an unmarked object */
1267                         if (MS_OBJ_ALLOCED (obj, block)) {
1268                                 /*
1269                                  * FIXME: Merge consecutive
1270                                  * slots for lower reporting
1271                                  * overhead.  Maybe memset
1272                                  * will also benefit?
1273                                  */
1274                                 binary_protocol_empty (obj, obj_size);
1275                                 memset (obj, 0, obj_size);
1276                         }
1277                         *(void**)obj = block->free_list;
1278                         block->free_list = obj;
1279                 }
1280         }
1281 }
1282
1283 static inline gboolean
1284 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1285 {
1286         gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1287         gboolean success = old_state == expected_state;
1288         if (success)
1289                 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1290         return success;
1291 }
1292
1293 static inline void
1294 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1295 {
1296         SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1297         block->state = new_state;
1298 }
1299
1300 /*
1301  * If `block` needs sweeping, sweep it and return TRUE.  Otherwise return FALSE.
1302  *
1303  * Sweeping means iterating through the block's slots and building the free-list from the
1304  * unmarked ones.  They will also be zeroed.  The mark bits will be reset.
1305  */
1306 static gboolean
1307 sweep_block (MSBlockInfo *block)
1308 {
1309         int count;
1310         void *reversed = NULL;
1311
1312  retry:
1313         switch (block->state) {
1314         case BLOCK_STATE_SWEPT:
1315                 return FALSE;
1316         case BLOCK_STATE_MARKING:
1317         case BLOCK_STATE_CHECKING:
1318                 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1319                 goto retry;
1320         case BLOCK_STATE_SWEEPING:
1321                 /* FIXME: Do this more elegantly */
1322                 g_usleep (100);
1323                 goto retry;
1324         case BLOCK_STATE_NEED_SWEEPING:
1325                 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1326                         goto retry;
1327                 break;
1328         default:
1329                 SGEN_ASSERT (0, FALSE, "Illegal block state");
1330         }
1331
1332         SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1333
1334         count = MS_BLOCK_FREE / block->obj_size;
1335
1336         block->free_list = NULL;
1337
1338         /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1339         // FIXME: Add more sizes
1340         switch (block->obj_size) {
1341         case 16:
1342                 sweep_block_for_size (block, count, 16);
1343                 break;
1344         default:
1345                 sweep_block_for_size (block, count, block->obj_size);
1346                 break;
1347         }
1348
1349         /* reset mark bits */
1350         memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1351
1352         /* Reverse free list so that it's in address order */
1353         reversed = NULL;
1354         while (block->free_list) {
1355                 void *next = *(void**)block->free_list;
1356                 *(void**)block->free_list = reversed;
1357                 reversed = block->free_list;
1358                 block->free_list = next;
1359         }
1360         block->free_list = reversed;
1361
1362         mono_memory_write_barrier ();
1363
1364         set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1365
1366         return TRUE;
1367 }
1368
1369 static inline int
1370 bitcount (mword d)
1371 {
1372         int count = 0;
1373
1374 #ifdef __GNUC__
1375         if (sizeof (mword) == sizeof (unsigned long))
1376                 count += __builtin_popcountl (d);
1377         else
1378                 count += __builtin_popcount (d);
1379 #else
1380         while (d) {
1381                 count ++;
1382                 d &= (d - 1);
1383         }
1384 #endif
1385         return count;
1386 }
1387
1388 /* statistics for evacuation */
1389 static size_t *sweep_slots_available;
1390 static size_t *sweep_slots_used;
1391 static size_t *sweep_num_blocks;
1392
1393 static volatile size_t num_major_sections_before_sweep;
1394 static volatile size_t num_major_sections_freed_in_sweep;
1395
1396 static void
1397 sweep_start (void)
1398 {
1399         int i;
1400
1401         for (i = 0; i < num_block_obj_sizes; ++i)
1402                 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1403
1404         /* clear all the free lists */
1405         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1406                 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1407                 int j;
1408                 for (j = 0; j < num_block_obj_sizes; ++j)
1409                         free_blocks [j] = NULL;
1410         }
1411 }
1412
1413 static void sweep_finish (void);
1414
1415 /*
1416  * If `wait` is TRUE and the block is currently being checked, this function will wait until
1417  * the checking has finished.
1418  *
1419  * Returns whether the block is still there.  If `wait` is FALSE, the return value will not
1420  * be correct, i.e. must not be used.
1421  */
1422 static gboolean
1423 ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked)
1424 {
1425         int count;
1426         gboolean have_live = FALSE;
1427         gboolean have_free = FALSE;
1428         int nused = 0;
1429         int block_state;
1430         int i;
1431         void *tagged_block;
1432         MSBlockInfo *block;
1433
1434         SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1435
1436         if (have_checked)
1437                 *have_checked = FALSE;
1438
1439  retry:
1440         tagged_block = *(void * volatile *)&allocated_blocks.data [block_index];
1441         if (!tagged_block)
1442                 return FALSE;
1443
1444         if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1445                 if (!wait)
1446                         return FALSE;
1447                 /* FIXME: do this more elegantly */
1448                 g_usleep (100);
1449                 goto retry;
1450         }
1451
1452         if (SGEN_CAS_PTR (&allocated_blocks.data [block_index], BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1453                 goto retry;
1454
1455         block = BLOCK_UNTAG (tagged_block);
1456         block_state = block->state;
1457
1458         if (!sweep_in_progress ()) {
1459                 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1460                 if (!lazy_sweep)
1461                         SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1462         }
1463
1464         switch (block_state) {
1465         case BLOCK_STATE_SWEPT:
1466         case BLOCK_STATE_NEED_SWEEPING:
1467         case BLOCK_STATE_SWEEPING:
1468                 goto done;
1469         case BLOCK_STATE_MARKING:
1470                 break;
1471         case BLOCK_STATE_CHECKING:
1472                 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1473                 goto done;
1474         default:
1475                 SGEN_ASSERT (0, FALSE, "Illegal block state");
1476                 break;
1477         }
1478
1479         SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1480         set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1481
1482         if (have_checked)
1483                 *have_checked = TRUE;
1484
1485         block->has_pinned = block->pinned;
1486
1487         block->is_to_space = FALSE;
1488
1489         count = MS_BLOCK_FREE / block->obj_size;
1490
1491         if (block->cardtable_mod_union) {
1492                 sgen_card_table_free_mod_union (block->cardtable_mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1493                 block->cardtable_mod_union = NULL;
1494         }
1495
1496         /* Count marked objects in the block */
1497         for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1498                 nused += bitcount (block->mark_words [i]);
1499
1500         if (nused)
1501                 have_live = TRUE;
1502         if (nused < count)
1503                 have_free = TRUE;
1504
1505         if (have_live) {
1506                 int obj_size_index = block->obj_size_index;
1507                 gboolean has_pinned = block->has_pinned;
1508
1509                 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1510
1511                 /*
1512                  * FIXME: Go straight to SWEPT if there are no free slots.  We need
1513                  * to set the free slot list to NULL, though, and maybe update some
1514                  * statistics.
1515                  */
1516                 if (!lazy_sweep)
1517                         sweep_block (block);
1518
1519                 if (!has_pinned) {
1520                         ++sweep_num_blocks [obj_size_index];
1521                         sweep_slots_used [obj_size_index] += nused;
1522                         sweep_slots_available [obj_size_index] += count;
1523                 }
1524
1525                 /*
1526                  * If there are free slots in the block, add
1527                  * the block to the corresponding free list.
1528                  */
1529                 if (have_free) {
1530                         MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1531
1532                         if (!lazy_sweep)
1533                                 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1534
1535                         add_free_block (free_blocks, obj_size_index, block);
1536                 }
1537
1538                 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1539                 update_heap_boundaries_for_block (block);
1540         } else {
1541                 /*
1542                  * Blocks without live objects are removed from the
1543                  * block list and freed.
1544                  */
1545                 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1546                 SGEN_ASSERT (6, allocated_blocks.data [block_index] == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1547
1548                 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1549                 ms_free_block (block);
1550
1551                 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1552
1553                 tagged_block = NULL;
1554         }
1555
1556  done:
1557         allocated_blocks.data [block_index] = tagged_block;
1558         return !!tagged_block;
1559 }
1560
1561 static void
1562 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1563 {
1564         int block_index;
1565         int num_blocks = num_major_sections_before_sweep;
1566
1567         SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1568         SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1569
1570         /*
1571          * We traverse the block array from high to low.  Nursery collections will have to
1572          * cooperate with the sweep thread to finish sweeping, and they will traverse from
1573          * low to high, to avoid constantly colliding on the same blocks.
1574          */
1575         for (block_index = num_blocks - 1; block_index >= 0; --block_index) {
1576                 gboolean have_checked;
1577
1578                 /*
1579                  * The block might have been freed by another thread doing some checking
1580                  * work.
1581                  */
1582                 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, &have_checked))
1583                         ++num_major_sections_freed_in_sweep;
1584         }
1585
1586         while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1587                 /*
1588                  * The main GC thread is currently iterating over the block array to help us
1589                  * finish the sweep.  We have already finished, but we don't want to mess up
1590                  * that iteration, so we just wait for it.
1591                  */
1592                 g_usleep (100);
1593         }
1594
1595         if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1596                 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1597                         MSBlockInfo *block = BLOCK_UNTAG (allocated_blocks.data [block_index]);
1598                         SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1599                 }
1600         }
1601
1602         sgen_pointer_queue_remove_nulls (&allocated_blocks);
1603         mono_memory_barrier ();
1604
1605         sweep_finish ();
1606
1607         sweep_job = NULL;
1608 }
1609
1610 static void
1611 sweep_finish (void)
1612 {
1613         mword total_evacuate_heap = 0;
1614         mword total_evacuate_saved = 0;
1615         int i;
1616
1617         for (i = 0; i < num_block_obj_sizes; ++i) {
1618                 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1619                 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1620                         evacuate_block_obj_sizes [i] = TRUE;
1621                         /*
1622                         g_print ("slot size %d - %d of %d used\n",
1623                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1624                         */
1625                 } else {
1626                         evacuate_block_obj_sizes [i] = FALSE;
1627                 }
1628                 {
1629                         mword total_bytes = block_obj_sizes [i] * sweep_slots_available [i];
1630                         total_evacuate_heap += total_bytes;
1631                         if (evacuate_block_obj_sizes [i])
1632                                 total_evacuate_saved += total_bytes - block_obj_sizes [i] * sweep_slots_used [i];
1633                 }
1634         }
1635
1636         want_evacuation = (float)total_evacuate_saved / (float)total_evacuate_heap > (1 - concurrent_evacuation_threshold);
1637
1638         set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1639 }
1640
1641 static void
1642 major_sweep (void)
1643 {
1644         set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1645
1646         sweep_start ();
1647
1648         SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1649
1650         num_major_sections_before_sweep = num_major_sections;
1651         num_major_sections_freed_in_sweep = 0;
1652
1653         SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1654         if (concurrent_sweep) {
1655                 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1656                 sgen_thread_pool_job_enqueue (sweep_job);
1657         } else {
1658                 sweep_job_func (NULL, NULL);
1659         }
1660 }
1661
1662 static gboolean
1663 major_have_swept (void)
1664 {
1665         return sweep_state == SWEEP_STATE_SWEPT;
1666 }
1667
1668 static int count_pinned_ref;
1669 static int count_pinned_nonref;
1670 static int count_nonpinned_ref;
1671 static int count_nonpinned_nonref;
1672
1673 static void
1674 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1675 {
1676         GCVTable vtable = LOAD_VTABLE (obj);
1677
1678         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1679                 ++count_nonpinned_ref;
1680         else
1681                 ++count_nonpinned_nonref;
1682 }
1683
1684 static void
1685 count_pinned_callback (GCObject *obj, size_t size, void *data)
1686 {
1687         GCVTable vtable = LOAD_VTABLE (obj);
1688
1689         if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1690                 ++count_pinned_ref;
1691         else
1692                 ++count_pinned_nonref;
1693 }
1694
1695 static G_GNUC_UNUSED void
1696 count_ref_nonref_objs (void)
1697 {
1698         int total;
1699
1700         count_pinned_ref = 0;
1701         count_pinned_nonref = 0;
1702         count_nonpinned_ref = 0;
1703         count_nonpinned_nonref = 0;
1704
1705         major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1706         major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1707
1708         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1709
1710         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1711                         count_pinned_ref, count_nonpinned_ref,
1712                         count_pinned_nonref, count_nonpinned_nonref,
1713                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1714 }
1715
1716 static int
1717 ms_calculate_block_obj_sizes (double factor, int *arr)
1718 {
1719         double target_size;
1720         int num_sizes = 0;
1721         int last_size = 0;
1722
1723         /*
1724          * Have every possible slot size starting with the minimal
1725          * object size up to and including four times that size.  Then
1726          * proceed by increasing geometrically with the given factor.
1727          */
1728
1729         for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1730                 if (arr)
1731                         arr [num_sizes] = size;
1732                 ++num_sizes;
1733                 last_size = size;
1734         }
1735         target_size = (double)last_size;
1736
1737         do {
1738                 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1739                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1740
1741                 if (size != last_size) {
1742                         if (arr)
1743                                 arr [num_sizes] = size;
1744                         ++num_sizes;
1745                         last_size = size;
1746                 }
1747
1748                 target_size *= factor;
1749         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1750
1751         return num_sizes;
1752 }
1753
1754 /* only valid during minor collections */
1755 static mword old_num_major_sections;
1756
1757 static void
1758 major_start_nursery_collection (void)
1759 {
1760 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1761         consistency_check ();
1762 #endif
1763
1764         old_num_major_sections = num_major_sections;
1765 }
1766
1767 static void
1768 major_finish_nursery_collection (void)
1769 {
1770 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1771         consistency_check ();
1772 #endif
1773 }
1774
1775 static void
1776 major_start_major_collection (void)
1777 {
1778         MSBlockInfo *block;
1779         int i;
1780
1781         major_finish_sweep_checking ();
1782
1783         /*
1784          * Clear the free lists for block sizes where we do evacuation.  For those block
1785          * sizes we will have to allocate new blocks.
1786          */
1787         for (i = 0; i < num_block_obj_sizes; ++i) {
1788                 if (!evacuate_block_obj_sizes [i])
1789                         continue;
1790
1791                 free_block_lists [0][i] = NULL;
1792                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1793         }
1794
1795         if (lazy_sweep)
1796                 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
1797
1798         /* Sweep all unswept blocks and set them to MARKING */
1799         FOREACH_BLOCK_NO_LOCK (block) {
1800                 if (lazy_sweep)
1801                         sweep_block (block);
1802                 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1803                 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1804         } END_FOREACH_BLOCK_NO_LOCK;
1805
1806         if (lazy_sweep)
1807                 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
1808
1809         set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1810 }
1811
1812 static void
1813 major_finish_major_collection (ScannedObjectCounts *counts)
1814 {
1815 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1816         if (binary_protocol_is_enabled ()) {
1817                 counts->num_scanned_objects = scanned_objects_list.next_slot;
1818
1819                 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1820                 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1821
1822                 sgen_pointer_queue_clear (&scanned_objects_list);
1823         }
1824 #endif
1825 }
1826
1827 #if SIZEOF_VOID_P != 8
1828 static int
1829 compare_pointers (const void *va, const void *vb) {
1830         char *a = *(char**)va, *b = *(char**)vb;
1831         if (a < b)
1832                 return -1;
1833         if (a > b)
1834                 return 1;
1835         return 0;
1836 }
1837 #endif
1838
1839 /*
1840  * This is called with sweep completed and the world stopped.
1841  */
1842 static void
1843 major_free_swept_blocks (size_t allowance)
1844 {
1845         /* FIXME: This is probably too much.  It's assuming all objects are small. */
1846         size_t section_reserve = allowance / MS_BLOCK_SIZE;
1847
1848         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1849
1850 #if SIZEOF_VOID_P != 8
1851         {
1852                 int i, num_empty_blocks_orig, num_blocks, arr_length;
1853                 void *block;
1854                 void **empty_block_arr;
1855                 void **rebuild_next;
1856
1857 #ifdef TARGET_WIN32
1858                 /*
1859                  * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1860                  * a VirtualAlloc ()-ed block.
1861                  */
1862                 return;
1863 #endif
1864
1865                 if (num_empty_blocks <= section_reserve)
1866                         return;
1867                 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1868
1869                 num_empty_blocks_orig = num_empty_blocks;
1870                 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1871                                 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1872                 if (!empty_block_arr)
1873                         goto fallback;
1874
1875                 i = 0;
1876                 for (block = empty_blocks; block; block = *(void**)block)
1877                         empty_block_arr [i++] = block;
1878                 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1879
1880                 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1881
1882                 /*
1883                  * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1884                  * contiguous ones.  If we do, we free them.  If that's not enough to get to
1885                  * section_reserve, we halve the number of contiguous blocks we're looking
1886                  * for and have another go, until we're done with looking for pairs of
1887                  * blocks, at which point we give up and go to the fallback.
1888                  */
1889                 arr_length = num_empty_blocks_orig;
1890                 num_blocks = MS_BLOCK_ALLOC_NUM;
1891                 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1892                         int first = -1;
1893                         int dest = 0;
1894
1895                         dest = 0;
1896                         for (i = 0; i < arr_length; ++i) {
1897                                 int d = dest;
1898                                 void *block = empty_block_arr [i];
1899                                 SGEN_ASSERT (6, block, "we're not shifting correctly");
1900                                 if (i != dest) {
1901                                         empty_block_arr [dest] = block;
1902                                         /*
1903                                          * This is not strictly necessary, but we're
1904                                          * cautious.
1905                                          */
1906                                         empty_block_arr [i] = NULL;
1907                                 }
1908                                 ++dest;
1909
1910                                 if (first < 0) {
1911                                         first = d;
1912                                         continue;
1913                                 }
1914
1915                                 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
1916
1917                                 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1918                                         first = d;
1919                                         continue;
1920                                 }
1921
1922                                 if (d + 1 - first == num_blocks) {
1923                                         /*
1924                                          * We found num_blocks contiguous blocks.  Free them
1925                                          * and null their array entries.  As an optimization
1926                                          * we could, instead of nulling the entries, shift
1927                                          * the following entries over to the left, while
1928                                          * we're iterating.
1929                                          */
1930                                         int j;
1931                                         sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1932                                         for (j = first; j <= d; ++j)
1933                                                 empty_block_arr [j] = NULL;
1934                                         dest = first;
1935                                         first = -1;
1936
1937                                         num_empty_blocks -= num_blocks;
1938
1939                                         stat_major_blocks_freed += num_blocks;
1940                                         if (num_blocks == MS_BLOCK_ALLOC_NUM)
1941                                                 stat_major_blocks_freed_ideal += num_blocks;
1942                                         else
1943                                                 stat_major_blocks_freed_less_ideal += num_blocks;
1944
1945                                 }
1946                         }
1947
1948                         SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
1949                         arr_length = dest;
1950                         SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
1951
1952                         num_blocks >>= 1;
1953                 }
1954
1955                 /* rebuild empty_blocks free list */
1956                 rebuild_next = (void**)&empty_blocks;
1957                 for (i = 0; i < arr_length; ++i) {
1958                         void *block = empty_block_arr [i];
1959                         SGEN_ASSERT (6, block, "we're missing blocks");
1960                         *rebuild_next = block;
1961                         rebuild_next = (void**)block;
1962                 }
1963                 *rebuild_next = NULL;
1964
1965                 /* free array */
1966                 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1967         }
1968
1969         SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1970
1971  fallback:
1972         /*
1973          * This is our threshold.  If there's not more empty than used blocks, we won't
1974          * release uncontiguous blocks, in fear of fragmenting the address space.
1975          */
1976         if (num_empty_blocks <= num_major_sections)
1977                 return;
1978 #endif
1979
1980         while (num_empty_blocks > section_reserve) {
1981                 void *next = *(void**)empty_blocks;
1982                 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
1983                 empty_blocks = next;
1984                 /*
1985                  * Needs not be atomic because this is running
1986                  * single-threaded.
1987                  */
1988                 --num_empty_blocks;
1989
1990                 ++stat_major_blocks_freed;
1991 #if SIZEOF_VOID_P != 8
1992                 ++stat_major_blocks_freed_individual;
1993 #endif
1994         }
1995 }
1996
1997 static void
1998 major_pin_objects (SgenGrayQueue *queue)
1999 {
2000         MSBlockInfo *block;
2001
2002         FOREACH_BLOCK_NO_LOCK (block) {
2003                 size_t first_entry, last_entry;
2004                 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2005                 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2006                                 &first_entry, &last_entry);
2007                 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2008         } END_FOREACH_BLOCK_NO_LOCK;
2009 }
2010
2011 static void
2012 major_init_to_space (void)
2013 {
2014 }
2015
2016 static void
2017 major_report_pinned_memory_usage (void)
2018 {
2019         g_assert_not_reached ();
2020 }
2021
2022 static gint64
2023 major_get_used_size (void)
2024 {
2025         gint64 size = 0;
2026         MSBlockInfo *block;
2027
2028         /*
2029          * We're holding the GC lock, but the sweep thread might be running.  Make sure it's
2030          * finished, then we can iterate over the block array.
2031          */
2032         major_finish_sweep_checking ();
2033
2034         FOREACH_BLOCK_NO_LOCK_CONDITION (TRUE, block) {
2035                 int count = MS_BLOCK_FREE / block->obj_size;
2036                 void **iter;
2037                 size += count * block->obj_size;
2038                 for (iter = block->free_list; iter; iter = (void**)*iter)
2039                         size -= block->obj_size;
2040         } END_FOREACH_BLOCK_NO_LOCK;
2041
2042         return size;
2043 }
2044
2045 /* FIXME: return number of bytes, not of sections */
2046 static size_t
2047 get_num_major_sections (void)
2048 {
2049         return num_major_sections;
2050 }
2051
2052 /*
2053  * Returns the number of bytes in blocks that were present when the last sweep was
2054  * initiated, and were not freed during the sweep.  They are the basis for calculating the
2055  * allowance.
2056  */
2057 static size_t
2058 get_bytes_survived_last_sweep (void)
2059 {
2060         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2061         return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2062 }
2063
2064 static gboolean
2065 major_handle_gc_param (const char *opt)
2066 {
2067         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2068                 const char *arg = strchr (opt, '=') + 1;
2069                 int percentage = atoi (arg);
2070                 if (percentage < 0 || percentage > 100) {
2071                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2072                         exit (1);
2073                 }
2074                 evacuation_threshold = (float)percentage / 100.0f;
2075                 return TRUE;
2076         } else if (!strcmp (opt, "lazy-sweep")) {
2077                 lazy_sweep = TRUE;
2078                 return TRUE;
2079         } else if (!strcmp (opt, "no-lazy-sweep")) {
2080                 lazy_sweep = FALSE;
2081                 return TRUE;
2082         } else if (!strcmp (opt, "concurrent-sweep")) {
2083                 concurrent_sweep = TRUE;
2084                 return TRUE;
2085         } else if (!strcmp (opt, "no-concurrent-sweep")) {
2086                 concurrent_sweep = FALSE;
2087                 return TRUE;
2088         }
2089
2090         return FALSE;
2091 }
2092
2093 static void
2094 major_print_gc_param_usage (void)
2095 {
2096         fprintf (stderr,
2097                         ""
2098                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2099                         "  (no-)lazy-sweep\n"
2100                         "  (no-)concurrent-sweep\n"
2101                         );
2102 }
2103
2104 /*
2105  * This callback is used to clear cards, move cards to the shadow table and do counting.
2106  */
2107 static void
2108 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2109 {
2110         MSBlockInfo *block;
2111         gboolean has_references;
2112
2113         major_finish_sweep_checking ();
2114         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2115                 if (has_references)
2116                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2117         } END_FOREACH_BLOCK_NO_LOCK;
2118 }
2119
2120 #ifdef HEAVY_STATISTICS
2121 extern guint64 marked_cards;
2122 extern guint64 scanned_cards;
2123 extern guint64 scanned_objects;
2124 extern guint64 remarked_cards;
2125 #endif
2126
2127 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2128 /*
2129  * MS blocks are 16K aligned.
2130  * Cardtables are 4K aligned, at least.
2131  * This means that the cardtable of a given block is 32 bytes aligned.
2132  */
2133 static guint8*
2134 initial_skip_card (guint8 *card_data)
2135 {
2136         mword *cards = (mword*)card_data;
2137         mword card;
2138         int i;
2139         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2140                 card = cards [i];
2141                 if (card)
2142                         break;
2143         }
2144
2145         if (i == CARD_WORDS_PER_BLOCK)
2146                 return card_data + CARDS_PER_BLOCK;
2147
2148 #if defined(__i386__) && defined(__GNUC__)
2149         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
2150 #elif defined(__x86_64__) && defined(__GNUC__)
2151         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
2152 #elif defined(__s390x__) && defined(__GNUC__)
2153         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2154 #else
2155         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2156                 if (card_data [i])
2157                         return &card_data [i];
2158         }
2159         return card_data;
2160 #endif
2161 }
2162
2163 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2164 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
2165 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2166
2167 static void
2168 scan_card_table_for_block (MSBlockInfo *block, gboolean mod_union, ScanCopyContext ctx)
2169 {
2170         SgenGrayQueue *queue = ctx.queue;
2171         ScanObjectFunc scan_func = ctx.ops->scan_object;
2172 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2173         guint8 cards_copy [CARDS_PER_BLOCK];
2174 #endif
2175         gboolean small_objects;
2176         int block_obj_size;
2177         char *block_start;
2178         guint8 *card_data, *card_base;
2179         guint8 *card_data_end;
2180         char *scan_front = NULL;
2181
2182         block_obj_size = block->obj_size;
2183         small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2184
2185         block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2186
2187         /*
2188          * This is safe in face of card aliasing for the following reason:
2189          *
2190          * Major blocks are 16k aligned, or 32 cards aligned.
2191          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2192          * sizes, they won't overflow the cardtable overlap modulus.
2193          */
2194         if (mod_union) {
2195                 card_data = card_base = block->cardtable_mod_union;
2196                 /*
2197                  * This happens when the nursery collection that precedes finishing
2198                  * the concurrent collection allocates new major blocks.
2199                  */
2200                 if (!card_data)
2201                         return;
2202         } else {
2203 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2204                 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2205 #else
2206                 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2207                         return;
2208                 card_data = card_base = cards_copy;
2209 #endif
2210         }
2211         card_data_end = card_data + CARDS_PER_BLOCK;
2212
2213         card_data += MS_BLOCK_SKIP >> CARD_BITS;
2214
2215         card_data = initial_skip_card (card_data);
2216         while (card_data < card_data_end) {
2217                 size_t card_index, first_object_index;
2218                 char *start;
2219                 char *end;
2220                 char *first_obj, *obj;
2221
2222                 HEAVY_STAT (++scanned_cards);
2223
2224                 if (!*card_data) {
2225                         ++card_data;
2226                         continue;
2227                 }
2228
2229                 card_index = card_data - card_base;
2230                 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2231                 end = start + CARD_SIZE_IN_BYTES;
2232
2233                 if (!block_is_swept_or_marking (block))
2234                         sweep_block (block);
2235
2236                 HEAVY_STAT (++marked_cards);
2237
2238                 if (small_objects)
2239                         sgen_card_table_prepare_card_for_scanning (card_data);
2240
2241                 /*
2242                  * If the card we're looking at starts at or in the block header, we
2243                  * must start at the first object in the block, without calculating
2244                  * the index of the object we're hypothetically starting at, because
2245                  * it would be negative.
2246                  */
2247                 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2248                         first_object_index = 0;
2249                 else
2250                         first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2251
2252                 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2253
2254                 binary_protocol_card_scan (first_obj, end - first_obj);
2255
2256                 while (obj < end) {
2257                         if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2258                                 goto next_object;
2259
2260                         if (mod_union) {
2261                                 /* FIXME: do this more efficiently */
2262                                 int w, b;
2263                                 MS_CALC_MARK_BIT (w, b, obj);
2264                                 if (!MS_MARK_BIT (block, w, b))
2265                                         goto next_object;
2266                         }
2267
2268                         GCObject *object = (GCObject*)obj;
2269
2270                         if (small_objects) {
2271                                 HEAVY_STAT (++scanned_objects);
2272                                 scan_func (object, sgen_obj_get_descriptor (object), queue);
2273                         } else {
2274                                 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2275                                 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, mod_union, ctx);
2276                         }
2277                 next_object:
2278                         obj += block_obj_size;
2279                         g_assert (scan_front <= obj);
2280                         scan_front = obj;
2281                 }
2282
2283                 HEAVY_STAT (if (*card_data) ++remarked_cards);
2284
2285                 if (small_objects)
2286                         ++card_data;
2287                 else
2288                         card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2289         }
2290 }
2291
2292 static void
2293 major_scan_card_table (gboolean mod_union, ScanCopyContext ctx)
2294 {
2295         MSBlockInfo *block;
2296         gboolean has_references;
2297
2298         if (!concurrent_mark)
2299                 g_assert (!mod_union);
2300
2301         major_finish_sweep_checking ();
2302         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2303 #ifdef PREFETCH_CARDS
2304                 int prefetch_index = __index + 6;
2305                 if (prefetch_index < allocated_blocks.next_slot) {
2306                         MSBlockInfo *prefetch_block = BLOCK_UNTAG (allocated_blocks.data [prefetch_index]);
2307                         guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2308                         PREFETCH_READ (prefetch_block);
2309                         PREFETCH_WRITE (prefetch_cards);
2310                         PREFETCH_WRITE (prefetch_cards + 32);
2311                 }
2312 #endif
2313
2314                 if (!has_references)
2315                         continue;
2316
2317                 scan_card_table_for_block (block, mod_union, ctx);
2318         } END_FOREACH_BLOCK_NO_LOCK;
2319 }
2320
2321 static void
2322 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2323 {
2324         MSBlockInfo *block;
2325         gboolean has_references;
2326         long long total_cards = 0;
2327         long long marked_cards = 0;
2328
2329         if (sweep_in_progress ()) {
2330                 *num_total_cards = -1;
2331                 *num_marked_cards = -1;
2332                 return;
2333         }
2334
2335         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2336                 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2337                 int i;
2338
2339                 if (!has_references)
2340                         continue;
2341
2342                 total_cards += CARDS_PER_BLOCK;
2343                 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2344                         if (cards [i])
2345                                 ++marked_cards;
2346                 }
2347         } END_FOREACH_BLOCK_NO_LOCK;
2348
2349         *num_total_cards = total_cards;
2350         *num_marked_cards = marked_cards;
2351 }
2352
2353 static void
2354 update_cardtable_mod_union (void)
2355 {
2356         MSBlockInfo *block;
2357
2358         FOREACH_BLOCK_NO_LOCK (block) {
2359                 size_t num_cards;
2360                 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2361                 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2362                 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2363         } END_FOREACH_BLOCK_NO_LOCK;
2364 }
2365
2366 #undef pthread_create
2367
2368 static void
2369 post_param_init (SgenMajorCollector *collector)
2370 {
2371         collector->sweeps_lazily = lazy_sweep;
2372         collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2373 }
2374
2375 static void
2376 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2377 {
2378         int i;
2379
2380         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2381
2382         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2383         block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2384         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2385
2386         evacuate_block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2387         for (i = 0; i < num_block_obj_sizes; ++i)
2388                 evacuate_block_obj_sizes [i] = FALSE;
2389
2390         sweep_slots_available = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2391         sweep_slots_used = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2392         sweep_num_blocks = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2393
2394         /*
2395         {
2396                 int i;
2397                 g_print ("block object sizes:\n");
2398                 for (i = 0; i < num_block_obj_sizes; ++i)
2399                         g_print ("%d\n", block_obj_sizes [i]);
2400         }
2401         */
2402
2403         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2404                 free_block_lists [i] = sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2405
2406         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2407                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2408         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2409                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2410
2411         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2412         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2413         mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2414         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_objects_evacuated);
2415 #if SIZEOF_VOID_P != 8
2416         mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2417         mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2418         mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2419         mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2420 #endif
2421
2422         collector->section_size = MAJOR_SECTION_SIZE;
2423
2424         concurrent_mark = is_concurrent;
2425         collector->is_concurrent = is_concurrent;
2426         collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2427         if (is_concurrent)
2428                 collector->want_synchronous_collection = &want_evacuation;
2429         else
2430                 collector->want_synchronous_collection = NULL;
2431         collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2432         collector->supports_cardtable = TRUE;
2433
2434         collector->alloc_heap = major_alloc_heap;
2435         collector->is_object_live = major_is_object_live;
2436         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2437         collector->alloc_degraded = major_alloc_degraded;
2438
2439         collector->alloc_object = major_alloc_object;
2440         collector->free_pinned_object = free_pinned_object;
2441         collector->iterate_objects = major_iterate_objects;
2442         collector->free_non_pinned_object = major_free_non_pinned_object;
2443         collector->pin_objects = major_pin_objects;
2444         collector->pin_major_object = pin_major_object;
2445         collector->scan_card_table = major_scan_card_table;
2446         collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2447         if (is_concurrent) {
2448                 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2449                 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2450         }
2451         collector->init_to_space = major_init_to_space;
2452         collector->sweep = major_sweep;
2453         collector->have_swept = major_have_swept;
2454         collector->finish_sweeping = major_finish_sweep_checking;
2455         collector->free_swept_blocks = major_free_swept_blocks;
2456         collector->check_scan_starts = major_check_scan_starts;
2457         collector->dump_heap = major_dump_heap;
2458         collector->get_used_size = major_get_used_size;
2459         collector->start_nursery_collection = major_start_nursery_collection;
2460         collector->finish_nursery_collection = major_finish_nursery_collection;
2461         collector->start_major_collection = major_start_major_collection;
2462         collector->finish_major_collection = major_finish_major_collection;
2463         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2464         collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2465         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2466         collector->get_num_major_sections = get_num_major_sections;
2467         collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2468         collector->handle_gc_param = major_handle_gc_param;
2469         collector->print_gc_param_usage = major_print_gc_param_usage;
2470         collector->post_param_init = post_param_init;
2471         collector->is_valid_object = major_is_valid_object;
2472         collector->describe_pointer = major_describe_pointer;
2473         collector->count_cards = major_count_cards;
2474
2475         collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2476         collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2477         collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2478         if (is_concurrent) {
2479                 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2480                 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent;
2481                 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2482
2483                 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2484                 collector->major_ops_concurrent_finish.scan_object = major_scan_object_no_evacuation;
2485                 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_concurrent_finish;
2486                 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack_no_evacuation;
2487         }
2488
2489 #ifdef HEAVY_STATISTICS
2490         mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2491         mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2492         mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2493         mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2494         mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2495         mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2496         mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2497         mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2498         mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2499         mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2500
2501         mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2502         mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2503         mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2504 #endif
2505
2506 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2507         mono_os_mutex_init (&scanned_objects_list_lock);
2508 #endif
2509
2510         SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2511
2512         /*cardtable requires major pages to be 8 cards aligned*/
2513         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2514 }
2515
2516 void
2517 sgen_marksweep_init (SgenMajorCollector *collector)
2518 {
2519         sgen_marksweep_init_internal (collector, FALSE);
2520 }
2521
2522 void
2523 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2524 {
2525         sgen_marksweep_init_internal (collector, TRUE);
2526 }
2527
2528 #endif