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