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