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