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