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