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