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