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