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