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