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