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