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