[System] Process.WaitForExit now triggers event Exited.
[mono.git] / mono / metadata / 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
31 #include "utils/mono-counters.h"
32 #include "utils/mono-semaphore.h"
33 #include "utils/mono-time.h"
34 #include "metadata/object-internals.h"
35 #include "metadata/profiler-private.h"
36
37 #include "metadata/sgen-gc.h"
38 #include "metadata/sgen-protocol.h"
39 #include "metadata/sgen-cardtable.h"
40 #include "metadata/sgen-memory-governor.h"
41 #include "metadata/sgen-layout-stats.h"
42 #include "metadata/gc-internal.h"
43 #include "metadata/sgen-pointer-queue.h"
44 #include "metadata/sgen-pinning.h"
45 #include "metadata/sgen-workers.h"
46
47 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
48 #define MS_BLOCK_SIZE   ARCH_MIN_MS_BLOCK_SIZE
49 #define MS_BLOCK_SIZE_SHIFT     ARCH_MIN_MS_BLOCK_SIZE_SHIFT
50 #else
51 #define MS_BLOCK_SIZE_SHIFT     14      /* INT FASTENABLE */
52 #define MS_BLOCK_SIZE           (1 << MS_BLOCK_SIZE_SHIFT)
53 #endif
54 #define MAJOR_SECTION_SIZE      MS_BLOCK_SIZE
55 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
56
57 /*
58  * Don't allocate single blocks, but alloc a contingent of this many
59  * blocks in one swoop.  This must be a power of two.
60  */
61 #define MS_BLOCK_ALLOC_NUM      32
62
63 /*
64  * Number of bytes before the first object in a block.  At the start
65  * of a block is the MSBlockHeader, then opional padding, then come
66  * the objects, so this must be >= sizeof (MSBlockHeader).
67  */
68 #define MS_BLOCK_SKIP   ((sizeof (MSBlockHeader) + 15) & ~15)
69
70 #define MS_BLOCK_FREE   (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
71
72 #define MS_NUM_MARK_WORDS       ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
73
74 typedef struct _MSBlockInfo MSBlockInfo;
75 struct _MSBlockInfo {
76         guint16 obj_size;
77         /*
78          * FIXME: Do we even need this? It's only used during sweep and might be worth
79          * recalculating to save the space.
80          */
81         guint16 obj_size_index;
82         unsigned int pinned : 1;
83         unsigned int has_references : 1;
84         unsigned int has_pinned : 1;    /* means cannot evacuate */
85         unsigned int is_to_space : 1;
86         unsigned int swept : 1;
87         void ** volatile free_list;
88         MSBlockInfo * volatile next_free;
89         guint8 *cardtable_mod_union;
90         mword mark_words [MS_NUM_MARK_WORDS];
91 };
92
93 #define MS_BLOCK_FOR_BLOCK_INFO(b)      ((char*)(b))
94
95 #define MS_BLOCK_OBJ(b,i)               (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i))
96 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size)             (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
97 #define MS_BLOCK_DATA_FOR_OBJ(o)        ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
98
99 typedef struct {
100         MSBlockInfo info;
101 } MSBlockHeader;
102
103 #define MS_BLOCK_FOR_OBJ(o)             (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
104
105 /* object index will always be small */
106 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
107
108 //casting to int is fine since blocks are 32k
109 #define MS_CALC_MARK_BIT(w,b,o)         do {                            \
110                 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
111                 if (sizeof (mword) == 4) {                              \
112                         (w) = i >> 5;                                   \
113                         (b) = i & 31;                                   \
114                 } else {                                                \
115                         (w) = i >> 6;                                   \
116                         (b) = i & 63;                                   \
117                 }                                                       \
118         } while (0)
119
120 #define MS_MARK_BIT(bl,w,b)     ((bl)->mark_words [(w)] & (ONE_P << (b)))
121 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
122
123 #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))
124
125 #define MS_BLOCK_OBJ_SIZE_FACTOR        (pow (2.0, 1.0 / 3))
126
127 /*
128  * This way we can lookup block object size indexes for sizes up to
129  * 256 bytes with a single load.
130  */
131 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES      32
132
133 static int *block_obj_sizes;
134 static int num_block_obj_sizes;
135 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
136
137 #define MS_BLOCK_FLAG_PINNED    1
138 #define MS_BLOCK_FLAG_REFS      2
139
140 #define MS_BLOCK_TYPE_MAX       4
141
142 static gboolean *evacuate_block_obj_sizes;
143 static float evacuation_threshold = 0.666f;
144 static float concurrent_evacuation_threshold = 0.666f;
145 static gboolean want_evacuation = FALSE;
146
147 static gboolean lazy_sweep = TRUE;
148 static gboolean have_swept = TRUE;
149
150 static gboolean concurrent_mark;
151
152 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl)      SGEN_POINTER_IS_TAGGED_1 ((bl))
153 #define BLOCK_TAG_HAS_REFERENCES(bl)            SGEN_POINTER_TAG_1 ((bl))
154 #define BLOCK_UNTAG_HAS_REFERENCES(bl)          SGEN_POINTER_UNTAG_1 ((bl))
155
156 #define BLOCK_TAG(bl)   ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
157
158 /* all allocated blocks in the system */
159 static SgenPointerQueue allocated_blocks;
160
161 /* non-allocated block free-list */
162 static void *empty_blocks = NULL;
163 static size_t num_empty_blocks = 0;
164
165 #define FOREACH_BLOCK(bl)       { size_t __index; for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { (bl) = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [__index]);
166 #define FOREACH_BLOCK_HAS_REFERENCES(bl,hr)     { size_t __index; for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { (bl) = allocated_blocks.data [__index]; (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); (bl) = BLOCK_UNTAG_HAS_REFERENCES ((bl));
167 #define END_FOREACH_BLOCK       } }
168 #define DELETE_BLOCK_IN_FOREACH()       (allocated_blocks.data [__index] = NULL)
169
170 static size_t num_major_sections = 0;
171 /* one free block list for each block object size */
172 static MSBlockInfo **free_block_lists [MS_BLOCK_TYPE_MAX];
173
174 static guint64 stat_major_blocks_alloced = 0;
175 static guint64 stat_major_blocks_freed = 0;
176 static guint64 stat_major_blocks_lazy_swept = 0;
177 static guint64 stat_major_objects_evacuated = 0;
178
179 #if SIZEOF_VOID_P != 8
180 static guint64 stat_major_blocks_freed_ideal = 0;
181 static guint64 stat_major_blocks_freed_less_ideal = 0;
182 static guint64 stat_major_blocks_freed_individual = 0;
183 static guint64 stat_major_blocks_alloced_less_ideal = 0;
184 #endif
185
186 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
187 static guint64 num_major_objects_marked = 0;
188 #define INC_NUM_MAJOR_OBJECTS_MARKED()  (++num_major_objects_marked)
189 #else
190 #define INC_NUM_MAJOR_OBJECTS_MARKED()
191 #endif
192
193 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
194 static mono_mutex_t scanned_objects_list_lock;
195 static SgenPointerQueue scanned_objects_list;
196
197 static void
198 add_scanned_object (void *ptr)
199 {
200         if (!binary_protocol_is_enabled ())
201                 return;
202
203         mono_mutex_lock (&scanned_objects_list_lock);
204         sgen_pointer_queue_add (&scanned_objects_list, ptr);
205         mono_mutex_unlock (&scanned_objects_list_lock);
206 }
207 #endif
208
209 static void
210 sweep_block (MSBlockInfo *block, gboolean during_major_collection);
211
212 static int
213 ms_find_block_obj_size_index (size_t size)
214 {
215         int i;
216         SGEN_ASSERT (9, size <= SGEN_MAX_SMALL_OBJ_SIZE, "size %d is bigger than max small object size %d", size, SGEN_MAX_SMALL_OBJ_SIZE);
217         for (i = 0; i < num_block_obj_sizes; ++i)
218                 if (block_obj_sizes [i] >= size)
219                         return i;
220         g_error ("no object of size %d\n", size);
221 }
222
223 #define FREE_BLOCKS_FROM(lists,p,r)     (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
224 #define FREE_BLOCKS(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
225
226 #define MS_BLOCK_OBJ_SIZE_INDEX(s)                              \
227         (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ?      \
228          fast_block_obj_size_indexes [((s)+7)>>3] :             \
229          ms_find_block_obj_size_index ((s)))
230
231 static void*
232 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
233 {
234         char *start;
235         if (nursery_align)
236                 start = sgen_alloc_os_memory_aligned (nursery_size, nursery_align, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
237         else
238                 start = sgen_alloc_os_memory (nursery_size, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
239
240         return start;
241 }
242
243 static void
244 update_heap_boundaries_for_block (MSBlockInfo *block)
245 {
246         sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
247 }
248
249 static void*
250 ms_get_empty_block (void)
251 {
252         char *p;
253         int i;
254         void *block, *empty, *next;
255
256  retry:
257         if (!empty_blocks) {
258                 /*
259                  * We try allocating MS_BLOCK_ALLOC_NUM blocks first.  If that's
260                  * unsuccessful, we halve the number of blocks and try again, until we're at
261                  * 1.  If that doesn't work, either, we assert.
262                  */
263                 int alloc_num = MS_BLOCK_ALLOC_NUM;
264                 for (;;) {
265                         p = sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE,
266                                         alloc_num == 1 ? "major heap section" : NULL);
267                         if (p)
268                                 break;
269                         alloc_num >>= 1;
270                 }
271
272                 for (i = 0; i < alloc_num; ++i) {
273                         block = p;
274                         /*
275                          * We do the free list update one after the
276                          * other so that other threads can use the new
277                          * blocks as quickly as possible.
278                          */
279                         do {
280                                 empty = empty_blocks;
281                                 *(void**)block = empty;
282                         } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
283                         p += MS_BLOCK_SIZE;
284                 }
285
286                 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
287
288                 stat_major_blocks_alloced += alloc_num;
289 #if SIZEOF_VOID_P != 8
290                 if (alloc_num != MS_BLOCK_ALLOC_NUM)
291                         stat_major_blocks_alloced_less_ideal += alloc_num;
292 #endif
293         }
294
295         do {
296                 empty = empty_blocks;
297                 if (!empty)
298                         goto retry;
299                 block = empty;
300                 next = *(void**)block;
301         } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
302
303         SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
304
305         *(void**)block = NULL;
306
307         g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
308
309         return block;
310 }
311
312 /*
313  * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
314  * list, where it will either be freed later on, or reused in nursery collections.
315  */
316 static void
317 ms_free_block (void *block)
318 {
319         void *empty;
320
321         sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
322         memset (block, 0, MS_BLOCK_SIZE);
323
324         do {
325                 empty = empty_blocks;
326                 *(void**)block = empty;
327         } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
328
329         SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
330 }
331
332 //#define MARKSWEEP_CONSISTENCY_CHECK
333
334 #ifdef MARKSWEEP_CONSISTENCY_CHECK
335 static void
336 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
337 {
338         MSBlockInfo *b;
339
340         for (; block; block = block->next_free) {
341                 g_assert (block->obj_size == size);
342                 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
343
344                 /* blocks in the free lists must have at least
345                    one free slot */
346                 if (block->swept)
347                         g_assert (block->free_list);
348
349                 /* the block must be in the allocated_blocks array */
350                 g_assert (sgen_pointer_queue_find (&allocated_blocks, BLOCK_TAG (block)) != (size_t)-1);
351         }
352 }
353
354 static void
355 check_empty_blocks (void)
356 {
357         void *p;
358         size_t i = 0;
359         for (p = empty_blocks; p; p = *(void**)p)
360                 ++i;
361         g_assert (i == num_empty_blocks);
362 }
363
364 static void
365 consistency_check (void)
366 {
367         MSBlockInfo *block;
368         int i;
369
370         /* check all blocks */
371         FOREACH_BLOCK (block) {
372                 int count = MS_BLOCK_FREE / block->obj_size;
373                 int num_free = 0;
374                 void **free;
375
376                 /* check block header */
377                 g_assert (((MSBlockHeader*)block->block)->info == block);
378
379                 /* count number of free slots */
380                 for (i = 0; i < count; ++i) {
381                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
382                         if (!MS_OBJ_ALLOCED (obj, block))
383                                 ++num_free;
384                 }
385
386                 /* check free list */
387                 for (free = block->free_list; free; free = (void**)*free) {
388                         g_assert (MS_BLOCK_FOR_OBJ (free) == block);
389                         --num_free;
390                 }
391                 g_assert (num_free == 0);
392
393                 /* check all mark words are zero */
394                 if (block->swept) {
395                         for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
396                                 g_assert (block->mark_words [i] == 0);
397                 }
398         } END_FOREACH_BLOCK;
399
400         /* check free blocks */
401         for (i = 0; i < num_block_obj_sizes; ++i) {
402                 int j;
403                 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
404                         check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
405         }
406
407         check_empty_blocks ();
408 }
409 #endif
410
411 static gboolean
412 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
413 {
414         int size = block_obj_sizes [size_index];
415         int count = MS_BLOCK_FREE / size;
416         MSBlockInfo *info;
417         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
418         char *obj_start;
419         int i;
420
421         if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
422                 return FALSE;
423
424         info = (MSBlockInfo*)ms_get_empty_block ();
425
426         SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
427
428         info->obj_size = size;
429         info->obj_size_index = size_index;
430         info->pinned = pinned;
431         info->has_references = has_references;
432         info->has_pinned = pinned;
433         /*
434          * Blocks that are to-space are not evacuated from.  During an major collection
435          * blocks are allocated for two reasons: evacuating objects from the nursery and
436          * evacuating them from major blocks marked for evacuation.  In both cases we don't
437          * want further evacuation.
438          */
439         info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD);
440         info->swept = 1;
441         info->cardtable_mod_union = NULL;
442
443         update_heap_boundaries_for_block (info);
444
445         /* build free list */
446         obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
447         info->free_list = (void**)obj_start;
448         /* we're skipping the last one - it must be nulled */
449         for (i = 0; i < count - 1; ++i) {
450                 char *next_obj_start = obj_start + size;
451                 *(void**)obj_start = next_obj_start;
452                 obj_start = next_obj_start;
453         }
454         /* the last one */
455         *(void**)obj_start = NULL;
456
457         info->next_free = free_blocks [size_index];
458         free_blocks [size_index] = info;
459
460         sgen_pointer_queue_add (&allocated_blocks, BLOCK_TAG (info));
461
462         ++num_major_sections;
463         return TRUE;
464 }
465
466 static gboolean
467 obj_is_from_pinned_alloc (char *ptr)
468 {
469         MSBlockInfo *block;
470
471         FOREACH_BLOCK (block) {
472                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
473                         return block->pinned;
474         } END_FOREACH_BLOCK;
475         return FALSE;
476 }
477
478 static void*
479 unlink_slot_from_free_list_uncontested (MSBlockInfo **free_blocks, int size_index)
480 {
481         MSBlockInfo *block;
482         void *obj;
483
484         block = free_blocks [size_index];
485         SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
486
487         if (G_UNLIKELY (!block->swept)) {
488                 stat_major_blocks_lazy_swept ++;
489                 sweep_block (block, FALSE);
490         }
491
492         obj = block->free_list;
493         SGEN_ASSERT (9, obj, "block %p in free list had no available object to alloc from", block);
494
495         block->free_list = *(void**)obj;
496         if (!block->free_list) {
497                 free_blocks [size_index] = block->next_free;
498                 block->next_free = NULL;
499         }
500
501         return obj;
502 }
503
504 static void*
505 alloc_obj (MonoVTable *vtable, size_t size, gboolean pinned, gboolean has_references)
506 {
507         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
508         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
509         void *obj;
510
511         if (!free_blocks [size_index]) {
512                 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
513                         return NULL;
514         }
515
516         obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
517
518         *(MonoVTable**)obj = vtable;
519
520         return obj;
521 }
522
523 static void*
524 major_alloc_object (MonoVTable *vtable, size_t size, gboolean has_references)
525 {
526         return alloc_obj (vtable, size, FALSE, has_references);
527 }
528
529 /*
530  * We're not freeing the block if it's empty.  We leave that work for
531  * the next major collection.
532  *
533  * This is just called from the domain clearing code, which runs in a
534  * single thread and has the GC lock, so we don't need an extra lock.
535  */
536 static void
537 free_object (char *obj, size_t size, gboolean pinned)
538 {
539         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
540         int word, bit;
541
542         if (!block->swept)
543                 sweep_block (block, FALSE);
544         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);
545         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
546         MS_CALC_MARK_BIT (word, bit, obj);
547         SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set");
548         if (!block->free_list) {
549                 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, block->has_references);
550                 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
551                 SGEN_ASSERT (9, !block->next_free, "block %p doesn't have a free-list of object but belongs to a free-list of blocks");
552                 block->next_free = free_blocks [size_index];
553                 free_blocks [size_index] = block;
554         }
555         memset (obj, 0, size);
556         *(void**)obj = block->free_list;
557         block->free_list = (void**)obj;
558 }
559
560 static void
561 major_free_non_pinned_object (char *obj, size_t size)
562 {
563         free_object (obj, size, FALSE);
564 }
565
566 /* size is a multiple of SGEN_ALLOC_ALIGN */
567 static void*
568 major_alloc_small_pinned_obj (MonoVTable *vtable, size_t size, gboolean has_references)
569 {
570         void *res;
571
572         res = alloc_obj (vtable, size, TRUE, has_references);
573          /*If we failed to alloc memory, we better try releasing memory
574           *as pinned alloc is requested by the runtime.
575           */
576          if (!res) {
577                 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
578                 res = alloc_obj (vtable, size, TRUE, has_references);
579          }
580          return res;
581 }
582
583 static void
584 free_pinned_object (char *obj, size_t size)
585 {
586         free_object (obj, size, TRUE);
587 }
588
589 /*
590  * size is already rounded up and we hold the GC lock.
591  */
592 static void*
593 major_alloc_degraded (MonoVTable *vtable, size_t size)
594 {
595         void *obj;
596         size_t old_num_sections;
597
598         old_num_sections = num_major_sections;
599
600         obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
601         if (G_LIKELY (obj)) {
602                 HEAVY_STAT (++stat_objects_alloced_degraded);
603                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
604                 g_assert (num_major_sections >= old_num_sections);
605                 sgen_register_major_sections_alloced (num_major_sections - old_num_sections);
606         }
607         return obj;
608 }
609
610 /*
611  * obj is some object.  If it's not in the major heap (i.e. if it's in
612  * the nursery or LOS), return FALSE.  Otherwise return whether it's
613  * been marked or copied.
614  */
615 static gboolean
616 major_is_object_live (char *obj)
617 {
618         MSBlockInfo *block;
619         int word, bit;
620         mword objsize;
621
622         if (sgen_ptr_in_nursery (obj))
623                 return FALSE;
624
625         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
626
627         /* LOS */
628         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
629                 return FALSE;
630
631         /* now we know it's in a major block */
632         block = MS_BLOCK_FOR_OBJ (obj);
633         SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?");
634         MS_CALC_MARK_BIT (word, bit, obj);
635         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
636 }
637
638 static gboolean
639 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
640 {
641         MSBlockInfo *block;
642
643         FOREACH_BLOCK (block) {
644                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
645                         int count = MS_BLOCK_FREE / block->obj_size;
646                         int i;
647
648                         *start = NULL;
649                         for (i = 0; i <= count; ++i) {
650                                 if (ptr >= MS_BLOCK_OBJ (block, i) && ptr < MS_BLOCK_OBJ (block, i + 1)) {
651                                         *start = MS_BLOCK_OBJ (block, i);
652                                         break;
653                                 }
654                         }
655                         return !block->pinned;
656                 }
657         } END_FOREACH_BLOCK;
658         return FALSE;
659 }
660
661 static void
662 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
663 {
664         gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
665         gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
666         gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
667         MSBlockInfo *block;
668
669         FOREACH_BLOCK (block) {
670                 int count = MS_BLOCK_FREE / block->obj_size;
671                 int i;
672
673                 if (block->pinned && !pinned)
674                         continue;
675                 if (!block->pinned && !non_pinned)
676                         continue;
677                 if (sweep && lazy_sweep) {
678                         sweep_block (block, FALSE);
679                         SGEN_ASSERT (0, block->swept, "Block must be swept after sweeping");
680                 }
681
682                 for (i = 0; i < count; ++i) {
683                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
684                         if (!block->swept) {
685                                 int word, bit;
686                                 MS_CALC_MARK_BIT (word, bit, obj);
687                                 if (!MS_MARK_BIT (block, word, bit))
688                                         continue;
689                         }
690                         if (MS_OBJ_ALLOCED (obj, block))
691                                 callback ((char*)obj, block->obj_size, data);
692                 }
693         } END_FOREACH_BLOCK;
694 }
695
696 static gboolean
697 major_is_valid_object (char *object)
698 {
699         MSBlockInfo *block;
700
701         FOREACH_BLOCK (block) {
702                 int idx;
703                 char *obj;
704
705                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
706                         continue;
707
708                 idx = MS_BLOCK_OBJ_INDEX (object, block);
709                 obj = (char*)MS_BLOCK_OBJ (block, idx);
710                 if (obj != object)
711                         return FALSE;
712                 return MS_OBJ_ALLOCED (obj, block);
713         } END_FOREACH_BLOCK;
714
715         return FALSE;
716 }
717
718
719 static MonoVTable*
720 major_describe_pointer (char *ptr)
721 {
722         MSBlockInfo *block;
723
724         FOREACH_BLOCK (block) {
725                 int idx;
726                 char *obj;
727                 gboolean live;
728                 MonoVTable *vtable;
729                 int w, b;
730                 gboolean marked;
731
732                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
733                         continue;
734
735                 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
736                         MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
737
738                 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
739                 obj = (char*)MS_BLOCK_OBJ (block, idx);
740                 live = MS_OBJ_ALLOCED (obj, block);
741                 vtable = live ? (MonoVTable*)SGEN_LOAD_VTABLE (obj) : NULL;
742
743                 MS_CALC_MARK_BIT (w, b, obj);
744                 marked = MS_MARK_BIT (block, w, b);
745
746                 if (obj == ptr) {
747                         SGEN_LOG (0, "\t(");
748                         if (live)
749                                 SGEN_LOG (0, "object");
750                         else
751                                 SGEN_LOG (0, "dead-object");
752                 } else {
753                         if (live)
754                                 SGEN_LOG (0, "interior-ptr offset %td", ptr - obj);
755                         else
756                                 SGEN_LOG (0, "dead-interior-ptr offset %td", ptr - obj);
757                 }
758
759                 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
760
761                 return vtable;
762         } END_FOREACH_BLOCK;
763
764         return NULL;
765 }
766
767 static void
768 major_check_scan_starts (void)
769 {
770 }
771
772 static void
773 major_dump_heap (FILE *heap_dump_file)
774 {
775         MSBlockInfo *block;
776         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
777         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
778         int i;
779
780         for (i = 0; i < num_block_obj_sizes; ++i)
781                 slots_available [i] = slots_used [i] = 0;
782
783         FOREACH_BLOCK (block) {
784                 int index = ms_find_block_obj_size_index (block->obj_size);
785                 int count = MS_BLOCK_FREE / block->obj_size;
786
787                 slots_available [index] += count;
788                 for (i = 0; i < count; ++i) {
789                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
790                                 ++slots_used [index];
791                 }
792         } END_FOREACH_BLOCK;
793
794         fprintf (heap_dump_file, "<occupancies>\n");
795         for (i = 0; i < num_block_obj_sizes; ++i) {
796                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
797                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
798         }
799         fprintf (heap_dump_file, "</occupancies>\n");
800
801         FOREACH_BLOCK (block) {
802                 int count = MS_BLOCK_FREE / block->obj_size;
803                 int i;
804                 int start = -1;
805
806                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
807
808                 for (i = 0; i <= count; ++i) {
809                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
810                                 if (start < 0)
811                                         start = i;
812                         } else {
813                                 if (start >= 0) {
814                                         sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
815                                         start = -1;
816                                 }
817                         }
818                 }
819
820                 fprintf (heap_dump_file, "</section>\n");
821         } END_FOREACH_BLOCK;
822 }
823
824 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
825
826 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do {   \
827                 int __word, __bit;                                      \
828                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
829                 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
830                         MS_SET_MARK_BIT ((block), __word, __bit);       \
831                         if (sgen_gc_descr_has_references (desc))                        \
832                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
833                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
834                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
835                 }                                                       \
836         } while (0)
837 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do {           \
838                 int __word, __bit;                                      \
839                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
840                 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
841                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
842                         MS_SET_MARK_BIT ((block), __word, __bit);       \
843                         if (sgen_gc_descr_has_references (desc))                        \
844                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
845                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
846                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
847                 }                                                       \
848         } while (0)
849
850 static void
851 pin_major_object (char *obj, SgenGrayQueue *queue)
852 {
853         MSBlockInfo *block;
854
855         if (concurrent_mark)
856                 g_assert_not_reached ();
857
858         block = MS_BLOCK_FOR_OBJ (obj);
859         block->has_pinned = TRUE;
860         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
861 }
862
863 #include "sgen-major-copy-object.h"
864
865 static void
866 major_copy_or_mark_object_with_evacuation_concurrent (void **ptr, void *obj, SgenGrayQueue *queue)
867 {
868         SGEN_ASSERT (9, sgen_concurrent_collection_in_progress (), "Why are we scanning concurrently when there's no concurrent collection on?");
869         SGEN_ASSERT (9, !sgen_workers_are_working () || sgen_is_worker_thread (mono_native_thread_id_get ()), "We must not scan from two threads at the same time!");
870
871         g_assert (!SGEN_OBJECT_IS_FORWARDED (obj));
872
873         if (!sgen_ptr_in_nursery (obj)) {
874                 mword objsize;
875
876                 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
877
878                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE) {
879                         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
880                         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
881                 } else {
882                         if (sgen_los_object_is_pinned (obj))
883                                 return;
884
885 #ifdef ENABLE_DTRACE
886                         if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
887                                 MonoVTable *vt = (MonoVTable*)SGEN_LOAD_VTABLE (obj);
888                                 MONO_GC_OBJ_PINNED ((mword)obj, sgen_safe_object_get_size (obj), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
889                         }
890 #endif
891
892                         sgen_los_pin_object (obj);
893                         if (SGEN_OBJECT_HAS_REFERENCES (obj))
894                                 GRAY_OBJECT_ENQUEUE (queue, obj, sgen_obj_get_descriptor (obj));
895                         INC_NUM_MAJOR_OBJECTS_MARKED ();
896                 }
897         }
898 }
899
900 static long long
901 major_get_and_reset_num_major_objects_marked (void)
902 {
903 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
904         long long num = num_major_objects_marked;
905         num_major_objects_marked = 0;
906         return num;
907 #else
908         return 0;
909 #endif
910 }
911
912 #define PREFETCH_CARDS          1       /* BOOL FASTENABLE */
913 #if !PREFETCH_CARDS
914 #undef PREFETCH_CARDS
915 #endif
916
917 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
918 #if defined(PLATFORM_MACOSX)
919 #define GCC_VERSION (__GNUC__ * 10000 \
920                                + __GNUC_MINOR__ * 100 \
921                                + __GNUC_PATCHLEVEL__)
922 #if GCC_VERSION <= 40300
923 #undef PREFETCH_CARDS
924 #endif
925 #endif
926
927 #ifdef HEAVY_STATISTICS
928 static guint64 stat_optimized_copy;
929 static guint64 stat_optimized_copy_nursery;
930 static guint64 stat_optimized_copy_nursery_forwarded;
931 static guint64 stat_optimized_copy_nursery_pinned;
932 static guint64 stat_optimized_copy_major;
933 static guint64 stat_optimized_copy_major_small_fast;
934 static guint64 stat_optimized_copy_major_small_slow;
935 static guint64 stat_optimized_copy_major_large;
936 static guint64 stat_optimized_copy_major_forwarded;
937 static guint64 stat_optimized_copy_major_small_evacuate;
938 static guint64 stat_optimized_major_scan;
939 static guint64 stat_optimized_major_scan_no_refs;
940
941 static guint64 stat_drain_prefetch_fills;
942 static guint64 stat_drain_prefetch_fill_failures;
943 static guint64 stat_drain_loops;
944 #endif
945
946 static void major_scan_object_with_evacuation (char *start, mword desc, SgenGrayQueue *queue);
947
948 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_no_evacuation
949 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_no_evacuation
950 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_no_evacuation
951 #include "sgen-marksweep-drain-gray-stack.h"
952
953 #define COPY_OR_MARK_WITH_EVACUATION
954 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_with_evacuation
955 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_with_evacuation
956 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_with_evacuation
957 #include "sgen-marksweep-drain-gray-stack.h"
958
959 static gboolean
960 drain_gray_stack (ScanCopyContext ctx)
961 {
962         gboolean evacuation = FALSE;
963         int i;
964         for (i = 0; i < num_block_obj_sizes; ++i) {
965                 if (evacuate_block_obj_sizes [i]) {
966                         evacuation = TRUE;
967                         break;
968                 }
969         }
970
971         if (evacuation)
972                 return drain_gray_stack_with_evacuation (ctx);
973         else
974                 return drain_gray_stack_no_evacuation (ctx);
975 }
976
977 #include "sgen-marksweep-scan-object-concurrent.h"
978
979 static void
980 major_copy_or_mark_object_canonical (void **ptr, SgenGrayQueue *queue)
981 {
982         major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
983 }
984
985 static void
986 major_copy_or_mark_object_concurrent_canonical (void **ptr, SgenGrayQueue *queue)
987 {
988         major_copy_or_mark_object_with_evacuation_concurrent (ptr, *ptr, queue);
989 }
990
991 static void
992 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
993 {
994         void **entry, **end;
995         int last_index = -1;
996
997         if (first_entry == last_entry)
998                 return;
999
1000         block->has_pinned = TRUE;
1001
1002         entry = sgen_pinning_get_entry (first_entry);
1003         end = sgen_pinning_get_entry (last_entry);
1004
1005         for (; entry < end; ++entry) {
1006                 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1007                 char *obj;
1008                 SGEN_ASSERT (9, index >= 0 && index < MS_BLOCK_FREE / block->obj_size, "invalid object %p index %d max-index %d", *entry, index, MS_BLOCK_FREE / block->obj_size);
1009                 if (index == last_index)
1010                         continue;
1011                 obj = MS_BLOCK_OBJ (block, index);
1012                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1013                 last_index = index;
1014         }
1015 }
1016
1017 static inline void
1018 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1019 {
1020         int obj_index;
1021
1022         for (obj_index = 0; obj_index < count; ++obj_index) {
1023                 int word, bit;
1024                 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1025
1026                 MS_CALC_MARK_BIT (word, bit, obj);
1027                 if (MS_MARK_BIT (block, word, bit)) {
1028                         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1029                 } else {
1030                         /* an unmarked object */
1031                         if (MS_OBJ_ALLOCED (obj, block)) {
1032                                 /*
1033                                  * FIXME: Merge consecutive
1034                                  * slots for lower reporting
1035                                  * overhead.  Maybe memset
1036                                  * will also benefit?
1037                                  */
1038                                 binary_protocol_empty (obj, obj_size);
1039                                 MONO_GC_MAJOR_SWEPT ((mword)obj, obj_size);
1040                                 memset (obj, 0, obj_size);
1041                         }
1042                         *(void**)obj = block->free_list;
1043                         block->free_list = obj;
1044                 }
1045         }
1046 }
1047
1048 /*
1049  * sweep_block:
1050  *
1051  *   Traverse BLOCK, freeing and zeroing unused objects.
1052  */
1053 static void
1054 sweep_block (MSBlockInfo *block, gboolean during_major_collection)
1055 {
1056         int count;
1057         void *reversed = NULL;
1058
1059         if (!during_major_collection)
1060                 g_assert (!sgen_concurrent_collection_in_progress ());
1061
1062         if (block->swept)
1063                 return;
1064
1065         count = MS_BLOCK_FREE / block->obj_size;
1066
1067         block->free_list = NULL;
1068
1069         /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1070         // FIXME: Add more sizes
1071         switch (block->obj_size) {
1072         case 16:
1073                 sweep_block_for_size (block, count, 16);
1074                 break;
1075         default:
1076                 sweep_block_for_size (block, count, block->obj_size);
1077                 break;
1078         }
1079
1080         /* reset mark bits */
1081         memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1082
1083         /* Reverse free list so that it's in address order */
1084         reversed = NULL;
1085         while (block->free_list) {
1086                 void *next = *(void**)block->free_list;
1087                 *(void**)block->free_list = reversed;
1088                 reversed = block->free_list;
1089                 block->free_list = next;
1090         }
1091         block->free_list = reversed;
1092
1093         block->swept = 1;
1094 }
1095
1096 static inline int
1097 bitcount (mword d)
1098 {
1099         int count = 0;
1100
1101 #ifdef __GNUC__
1102         if (sizeof (mword) == sizeof (unsigned long))
1103                 count += __builtin_popcountl (d);
1104         else
1105                 count += __builtin_popcount (d);
1106 #else
1107         while (d) {
1108                 count ++;
1109                 d &= (d - 1);
1110         }
1111 #endif
1112         return count;
1113 }
1114
1115 static void
1116 major_sweep (void)
1117 {
1118         int i;
1119         MSBlockInfo *block;
1120
1121         /* statistics for evacuation */
1122         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1123         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1124         int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1125
1126         mword total_evacuate_heap = 0;
1127         mword total_evacuate_saved = 0;
1128
1129         for (i = 0; i < num_block_obj_sizes; ++i)
1130                 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1131
1132         /* clear all the free lists */
1133         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1134                 MSBlockInfo **free_blocks = free_block_lists [i];
1135                 int j;
1136                 for (j = 0; j < num_block_obj_sizes; ++j)
1137                         free_blocks [j] = NULL;
1138         }
1139
1140         /* traverse all blocks, free and zero unmarked objects */
1141         FOREACH_BLOCK (block) {
1142                 int count;
1143                 gboolean have_live = FALSE;
1144                 gboolean has_pinned;
1145                 gboolean have_free = FALSE;
1146                 int obj_size_index;
1147                 int nused = 0;
1148
1149                 obj_size_index = block->obj_size_index;
1150
1151                 has_pinned = block->has_pinned;
1152                 block->has_pinned = block->pinned;
1153
1154                 block->is_to_space = FALSE;
1155                 block->swept = 0;
1156
1157                 count = MS_BLOCK_FREE / block->obj_size;
1158
1159                 if (block->cardtable_mod_union) {
1160                         sgen_free_internal_dynamic (block->cardtable_mod_union, CARDS_PER_BLOCK, INTERNAL_MEM_CARDTABLE_MOD_UNION);
1161                         block->cardtable_mod_union = NULL;
1162                 }
1163
1164                 /* Count marked objects in the block */
1165                 for (i = 0; i < MS_NUM_MARK_WORDS; ++i) {
1166                         nused += bitcount (block->mark_words [i]);
1167                 }
1168                 if (nused) {
1169                         have_live = TRUE;
1170                 }
1171                 if (nused < count)
1172                         have_free = TRUE;
1173
1174                 if (!lazy_sweep)
1175                         sweep_block (block, TRUE);
1176
1177                 if (have_live) {
1178                         if (!has_pinned) {
1179                                 ++num_blocks [obj_size_index];
1180                                 slots_used [obj_size_index] += nused;
1181                                 slots_available [obj_size_index] += count;
1182                         }
1183
1184                         /*
1185                          * If there are free slots in the block, add
1186                          * the block to the corresponding free list.
1187                          */
1188                         if (have_free) {
1189                                 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1190                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1191                                 block->next_free = free_blocks [index];
1192                                 free_blocks [index] = block;
1193                         }
1194
1195                         update_heap_boundaries_for_block (block);
1196                 } else {
1197                         /*
1198                          * Blocks without live objects are removed from the
1199                          * block list and freed.
1200                          */
1201                         DELETE_BLOCK_IN_FOREACH ();
1202
1203                         binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1204                         ms_free_block (block);
1205
1206                         --num_major_sections;
1207                 }
1208         } END_FOREACH_BLOCK;
1209         sgen_pointer_queue_remove_nulls (&allocated_blocks);
1210
1211         for (i = 0; i < num_block_obj_sizes; ++i) {
1212                 float usage = (float)slots_used [i] / (float)slots_available [i];
1213                 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1214                         evacuate_block_obj_sizes [i] = TRUE;
1215                         /*
1216                         g_print ("slot size %d - %d of %d used\n",
1217                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1218                         */
1219                 } else {
1220                         evacuate_block_obj_sizes [i] = FALSE;
1221                 }
1222                 {
1223                         mword total_bytes = block_obj_sizes [i] * slots_available [i];
1224                         total_evacuate_heap += total_bytes;
1225                         if (evacuate_block_obj_sizes [i])
1226                                 total_evacuate_saved += total_bytes - block_obj_sizes [i] * slots_used [i];
1227                 }
1228         }
1229
1230         want_evacuation = (float)total_evacuate_saved / (float)total_evacuate_heap > (1 - concurrent_evacuation_threshold);
1231
1232         have_swept = TRUE;
1233 }
1234
1235 static gboolean
1236 major_have_finished_sweeping (void)
1237 {
1238         return have_swept;
1239 }
1240
1241 static int count_pinned_ref;
1242 static int count_pinned_nonref;
1243 static int count_nonpinned_ref;
1244 static int count_nonpinned_nonref;
1245
1246 static void
1247 count_nonpinned_callback (char *obj, size_t size, void *data)
1248 {
1249         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1250
1251         if (vtable->klass->has_references)
1252                 ++count_nonpinned_ref;
1253         else
1254                 ++count_nonpinned_nonref;
1255 }
1256
1257 static void
1258 count_pinned_callback (char *obj, size_t size, void *data)
1259 {
1260         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1261
1262         if (vtable->klass->has_references)
1263                 ++count_pinned_ref;
1264         else
1265                 ++count_pinned_nonref;
1266 }
1267
1268 static G_GNUC_UNUSED void
1269 count_ref_nonref_objs (void)
1270 {
1271         int total;
1272
1273         count_pinned_ref = 0;
1274         count_pinned_nonref = 0;
1275         count_nonpinned_ref = 0;
1276         count_nonpinned_nonref = 0;
1277
1278         major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1279         major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1280
1281         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1282
1283         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1284                         count_pinned_ref, count_nonpinned_ref,
1285                         count_pinned_nonref, count_nonpinned_nonref,
1286                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1287 }
1288
1289 static int
1290 ms_calculate_block_obj_sizes (double factor, int *arr)
1291 {
1292         double target_size;
1293         int num_sizes = 0;
1294         int last_size = 0;
1295
1296         /*
1297          * Have every possible slot size starting with the minimal
1298          * object size up to and including four times that size.  Then
1299          * proceed by increasing geometrically with the given factor.
1300          */
1301
1302         for (int size = sizeof (MonoObject); size <= 4 * sizeof (MonoObject); size += SGEN_ALLOC_ALIGN) {
1303                 if (arr)
1304                         arr [num_sizes] = size;
1305                 ++num_sizes;
1306                 last_size = size;
1307         }
1308         target_size = (double)last_size;
1309
1310         do {
1311                 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1312                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1313
1314                 if (size != last_size) {
1315                         if (arr)
1316                                 arr [num_sizes] = size;
1317                         ++num_sizes;
1318                         last_size = size;
1319                 }
1320
1321                 target_size *= factor;
1322         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1323
1324         return num_sizes;
1325 }
1326
1327 /* only valid during minor collections */
1328 static mword old_num_major_sections;
1329
1330 static void
1331 major_start_nursery_collection (void)
1332 {
1333 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1334         consistency_check ();
1335 #endif
1336
1337         old_num_major_sections = num_major_sections;
1338 }
1339
1340 static void
1341 major_finish_nursery_collection (void)
1342 {
1343 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1344         consistency_check ();
1345 #endif
1346         sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1347 }
1348
1349 static void
1350 major_start_major_collection (void)
1351 {
1352         int i;
1353
1354         /* clear the free lists */
1355         for (i = 0; i < num_block_obj_sizes; ++i) {
1356                 if (!evacuate_block_obj_sizes [i])
1357                         continue;
1358
1359                 free_block_lists [0][i] = NULL;
1360                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1361         }
1362
1363         // Sweep all unswept blocks
1364         if (lazy_sweep) {
1365                 MSBlockInfo *block;
1366
1367                 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, TRUE);
1368
1369                 FOREACH_BLOCK (block) {
1370                         sweep_block (block, TRUE);
1371                 } END_FOREACH_BLOCK;
1372
1373                 MONO_GC_SWEEP_END (GENERATION_OLD, TRUE);
1374         }
1375
1376         SGEN_ASSERT (0, have_swept, "Cannot start major collection without having finished sweeping");
1377         have_swept = FALSE;
1378 }
1379
1380 static void
1381 major_finish_major_collection (ScannedObjectCounts *counts)
1382 {
1383 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1384         if (binary_protocol_is_enabled ()) {
1385                 counts->num_scanned_objects = scanned_objects_list.next_slot;
1386
1387                 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1388                 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1389
1390                 sgen_pointer_queue_clear (&scanned_objects_list);
1391         }
1392 #endif
1393 }
1394
1395 #if SIZEOF_VOID_P != 8
1396 static int
1397 compare_pointers (const void *va, const void *vb) {
1398         char *a = *(char**)va, *b = *(char**)vb;
1399         if (a < b)
1400                 return -1;
1401         if (a > b)
1402                 return 1;
1403         return 0;
1404 }
1405 #endif
1406
1407 static void
1408 major_free_swept_blocks (void)
1409 {
1410         size_t section_reserve = sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1411
1412         g_assert (have_swept);
1413
1414 #if SIZEOF_VOID_P != 8
1415         {
1416                 int i, num_empty_blocks_orig, num_blocks, arr_length;
1417                 void *block;
1418                 void **empty_block_arr;
1419                 void **rebuild_next;
1420
1421 #ifdef TARGET_WIN32
1422                 /*
1423                  * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1424                  * a VirtualAlloc ()-ed block.
1425                  */
1426                 return;
1427 #endif
1428
1429                 if (num_empty_blocks <= section_reserve)
1430                         return;
1431                 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1432
1433                 num_empty_blocks_orig = num_empty_blocks;
1434                 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1435                                 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1436                 if (!empty_block_arr)
1437                         goto fallback;
1438
1439                 i = 0;
1440                 for (block = empty_blocks; block; block = *(void**)block)
1441                         empty_block_arr [i++] = block;
1442                 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1443
1444                 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1445
1446                 /*
1447                  * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1448                  * contiguous ones.  If we do, we free them.  If that's not enough to get to
1449                  * section_reserve, we halve the number of contiguous blocks we're looking
1450                  * for and have another go, until we're done with looking for pairs of
1451                  * blocks, at which point we give up and go to the fallback.
1452                  */
1453                 arr_length = num_empty_blocks_orig;
1454                 num_blocks = MS_BLOCK_ALLOC_NUM;
1455                 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1456                         int first = -1;
1457                         int dest = 0;
1458
1459                         dest = 0;
1460                         for (i = 0; i < arr_length; ++i) {
1461                                 int d = dest;
1462                                 void *block = empty_block_arr [i];
1463                                 SGEN_ASSERT (0, block, "we're not shifting correctly");
1464                                 if (i != dest) {
1465                                         empty_block_arr [dest] = block;
1466                                         /*
1467                                          * This is not strictly necessary, but we're
1468                                          * cautious.
1469                                          */
1470                                         empty_block_arr [i] = NULL;
1471                                 }
1472                                 ++dest;
1473
1474                                 if (first < 0) {
1475                                         first = d;
1476                                         continue;
1477                                 }
1478
1479                                 SGEN_ASSERT (0, first >= 0 && d > first, "algorithm is wrong");
1480
1481                                 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1482                                         first = d;
1483                                         continue;
1484                                 }
1485
1486                                 if (d + 1 - first == num_blocks) {
1487                                         /*
1488                                          * We found num_blocks contiguous blocks.  Free them
1489                                          * and null their array entries.  As an optimization
1490                                          * we could, instead of nulling the entries, shift
1491                                          * the following entries over to the left, while
1492                                          * we're iterating.
1493                                          */
1494                                         int j;
1495                                         sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1496                                         for (j = first; j <= d; ++j)
1497                                                 empty_block_arr [j] = NULL;
1498                                         dest = first;
1499                                         first = -1;
1500
1501                                         num_empty_blocks -= num_blocks;
1502
1503                                         stat_major_blocks_freed += num_blocks;
1504                                         if (num_blocks == MS_BLOCK_ALLOC_NUM)
1505                                                 stat_major_blocks_freed_ideal += num_blocks;
1506                                         else
1507                                                 stat_major_blocks_freed_less_ideal += num_blocks;
1508
1509                                 }
1510                         }
1511
1512                         SGEN_ASSERT (0, dest <= i && dest <= arr_length, "array length is off");
1513                         arr_length = dest;
1514                         SGEN_ASSERT (0, arr_length == num_empty_blocks, "array length is off");
1515
1516                         num_blocks >>= 1;
1517                 }
1518
1519                 /* rebuild empty_blocks free list */
1520                 rebuild_next = (void**)&empty_blocks;
1521                 for (i = 0; i < arr_length; ++i) {
1522                         void *block = empty_block_arr [i];
1523                         SGEN_ASSERT (0, block, "we're missing blocks");
1524                         *rebuild_next = block;
1525                         rebuild_next = (void**)block;
1526                 }
1527                 *rebuild_next = NULL;
1528
1529                 /* free array */
1530                 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1531         }
1532
1533         SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1534
1535  fallback:
1536         /*
1537          * This is our threshold.  If there's not more empty than used blocks, we won't
1538          * release uncontiguous blocks, in fear of fragmenting the address space.
1539          */
1540         if (num_empty_blocks <= num_major_sections)
1541                 return;
1542 #endif
1543
1544         while (num_empty_blocks > section_reserve) {
1545                 void *next = *(void**)empty_blocks;
1546                 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
1547                 empty_blocks = next;
1548                 /*
1549                  * Needs not be atomic because this is running
1550                  * single-threaded.
1551                  */
1552                 --num_empty_blocks;
1553
1554                 ++stat_major_blocks_freed;
1555 #if SIZEOF_VOID_P != 8
1556                 ++stat_major_blocks_freed_individual;
1557 #endif
1558         }
1559 }
1560
1561 static void
1562 major_pin_objects (SgenGrayQueue *queue)
1563 {
1564         MSBlockInfo *block;
1565
1566         FOREACH_BLOCK (block) {
1567                 size_t first_entry, last_entry;
1568                 SGEN_ASSERT (0, block->swept, "All blocks must be swept when we're pinning.");
1569                 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
1570                                 &first_entry, &last_entry);
1571                 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
1572         } END_FOREACH_BLOCK;
1573 }
1574
1575 static void
1576 major_init_to_space (void)
1577 {
1578 }
1579
1580 static void
1581 major_report_pinned_memory_usage (void)
1582 {
1583         g_assert_not_reached ();
1584 }
1585
1586 static gint64
1587 major_get_used_size (void)
1588 {
1589         gint64 size = 0;
1590         MSBlockInfo *block;
1591
1592         FOREACH_BLOCK (block) {
1593                 int count = MS_BLOCK_FREE / block->obj_size;
1594                 void **iter;
1595                 size += count * block->obj_size;
1596                 for (iter = block->free_list; iter; iter = (void**)*iter)
1597                         size -= block->obj_size;
1598         } END_FOREACH_BLOCK;
1599
1600         return size;
1601 }
1602
1603 static size_t
1604 get_num_major_sections (void)
1605 {
1606         return num_major_sections;
1607 }
1608
1609 static gboolean
1610 major_handle_gc_param (const char *opt)
1611 {
1612         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1613                 const char *arg = strchr (opt, '=') + 1;
1614                 int percentage = atoi (arg);
1615                 if (percentage < 0 || percentage > 100) {
1616                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1617                         exit (1);
1618                 }
1619                 evacuation_threshold = (float)percentage / 100.0f;
1620                 return TRUE;
1621         } else if (!strcmp (opt, "lazy-sweep")) {
1622                 lazy_sweep = TRUE;
1623                 return TRUE;
1624         } else if (!strcmp (opt, "no-lazy-sweep")) {
1625                 lazy_sweep = FALSE;
1626                 return TRUE;
1627         }
1628
1629         return FALSE;
1630 }
1631
1632 static void
1633 major_print_gc_param_usage (void)
1634 {
1635         fprintf (stderr,
1636                         ""
1637                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1638                         "  (no-)lazy-sweep\n"
1639                         );
1640 }
1641
1642 static void
1643 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1644 {
1645         MSBlockInfo *block;
1646         gboolean has_references;
1647
1648         FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1649                 if (has_references)
1650                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1651         } END_FOREACH_BLOCK;
1652 }
1653
1654 #ifdef HEAVY_STATISTICS
1655 extern guint64 marked_cards;
1656 extern guint64 scanned_cards;
1657 extern guint64 scanned_objects;
1658 extern guint64 remarked_cards;
1659 #endif
1660
1661 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1662 /*
1663  * MS blocks are 16K aligned.
1664  * Cardtables are 4K aligned, at least.
1665  * This means that the cardtable of a given block is 32 bytes aligned.
1666  */
1667 static guint8*
1668 initial_skip_card (guint8 *card_data)
1669 {
1670         mword *cards = (mword*)card_data;
1671         mword card;
1672         int i;
1673         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1674                 card = cards [i];
1675                 if (card)
1676                         break;
1677         }
1678
1679         if (i == CARD_WORDS_PER_BLOCK)
1680                 return card_data + CARDS_PER_BLOCK;
1681
1682 #if defined(__i386__) && defined(__GNUC__)
1683         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1684 #elif defined(__x86_64__) && defined(__GNUC__)
1685         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1686 #elif defined(__s390x__) && defined(__GNUC__)
1687         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1688 #else
1689         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1690                 if (card_data [i])
1691                         return &card_data [i];
1692         }
1693         return card_data;
1694 #endif
1695 }
1696
1697 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1698 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1699 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1700
1701 static size_t
1702 card_offset (char *obj, char *base)
1703 {
1704         return (obj - base) >> CARD_BITS;
1705 }
1706
1707 static void
1708 major_scan_card_table (gboolean mod_union, SgenGrayQueue *queue)
1709 {
1710         MSBlockInfo *block;
1711         gboolean has_references;
1712         ScanObjectFunc scan_func = sgen_get_current_object_ops ()->scan_object;
1713
1714         if (!concurrent_mark)
1715                 g_assert (!mod_union);
1716
1717         FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1718 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1719                 guint8 cards_copy [CARDS_PER_BLOCK];
1720 #endif
1721                 gboolean small_objects;
1722                 int block_obj_size;
1723                 char *block_start;
1724                 guint8 *card_data, *card_base;
1725                 guint8 *card_data_end;
1726                 char *scan_front = NULL;
1727
1728 #ifdef PREFETCH_CARDS
1729                 int prefetch_index = __index + 6;
1730                 if (prefetch_index < allocated_blocks.next_slot) {
1731                         MSBlockInfo *prefetch_block = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [prefetch_index]);
1732                         guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
1733                         PREFETCH_READ (prefetch_block);
1734                         PREFETCH_WRITE (prefetch_cards);
1735                         PREFETCH_WRITE (prefetch_cards + 32);
1736                 }
1737 #endif
1738
1739                 if (!has_references)
1740                         continue;
1741
1742                 block_obj_size = block->obj_size;
1743                 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
1744
1745                 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
1746
1747                 /*
1748                  * This is safe in face of card aliasing for the following reason:
1749                  *
1750                  * Major blocks are 16k aligned, or 32 cards aligned.
1751                  * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1752                  * sizes, they won't overflow the cardtable overlap modulus.
1753                  */
1754                 if (mod_union) {
1755                         card_data = card_base = block->cardtable_mod_union;
1756                         /*
1757                          * This happens when the nursery collection that precedes finishing
1758                          * the concurrent collection allocates new major blocks.
1759                          */
1760                         if (!card_data)
1761                                 continue;
1762                 } else {
1763 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1764                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1765 #else
1766                         if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
1767                                 continue;
1768                         card_data = card_base = cards_copy;
1769 #endif
1770                 }
1771                 card_data_end = card_data + CARDS_PER_BLOCK;
1772
1773                 card_data += MS_BLOCK_SKIP >> CARD_BITS;
1774
1775                 card_data = initial_skip_card (card_data);
1776                 while (card_data < card_data_end) {
1777                         size_t card_index, first_object_index;
1778                         char *start;
1779                         char *end;
1780                         char *first_obj, *obj;
1781
1782                         HEAVY_STAT (++scanned_cards);
1783
1784                         if (!*card_data) {
1785                                 ++card_data;
1786                                 continue;
1787                         }
1788
1789                         card_index = card_data - card_base;
1790                         start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
1791                         end = start + CARD_SIZE_IN_BYTES;
1792
1793                         if (!block->swept)
1794                                 sweep_block (block, FALSE);
1795
1796                         HEAVY_STAT (++marked_cards);
1797
1798                         if (small_objects)
1799                                 sgen_card_table_prepare_card_for_scanning (card_data);
1800
1801                         /*
1802                          * If the card we're looking at starts at or in the block header, we
1803                          * must start at the first object in the block, without calculating
1804                          * the index of the object we're hypothetically starting at, because
1805                          * it would be negative.
1806                          */
1807                         if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
1808                                 first_object_index = 0;
1809                         else
1810                                 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1811
1812                         obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
1813
1814                         while (obj < end) {
1815                                 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
1816                                         goto next_object;
1817
1818                                 if (mod_union) {
1819                                         /* FIXME: do this more efficiently */
1820                                         int w, b;
1821                                         MS_CALC_MARK_BIT (w, b, obj);
1822                                         if (!MS_MARK_BIT (block, w, b))
1823                                                 goto next_object;
1824                                 }
1825
1826                                 if (small_objects) {
1827                                         HEAVY_STAT (++scanned_objects);
1828                                         scan_func (obj, sgen_obj_get_descriptor (obj), queue);
1829                                 } else {
1830                                         size_t offset = card_offset (obj, block_start);
1831                                         sgen_cardtable_scan_object (obj, block_obj_size, card_base + offset, mod_union, queue);
1832                                 }
1833                         next_object:
1834                                 obj += block_obj_size;
1835                                 g_assert (scan_front <= obj);
1836                                 scan_front = obj;
1837                         }
1838
1839                         HEAVY_STAT (if (*card_data) ++remarked_cards);
1840                         binary_protocol_card_scan (first_obj, obj - first_obj);
1841
1842                         if (small_objects)
1843                                 ++card_data;
1844                         else
1845                                 card_data = card_base + card_offset (obj, block_start);
1846                 }
1847         } END_FOREACH_BLOCK;
1848 }
1849
1850 static void
1851 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
1852 {
1853         MSBlockInfo *block;
1854         gboolean has_references;
1855         long long total_cards = 0;
1856         long long marked_cards = 0;
1857
1858         FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1859                 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
1860                 int i;
1861
1862                 if (!has_references)
1863                         continue;
1864
1865                 total_cards += CARDS_PER_BLOCK;
1866                 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
1867                         if (cards [i])
1868                                 ++marked_cards;
1869                 }
1870         } END_FOREACH_BLOCK;
1871
1872         *num_total_cards = total_cards;
1873         *num_marked_cards = marked_cards;
1874 }
1875
1876 static void
1877 update_cardtable_mod_union (void)
1878 {
1879         MSBlockInfo *block;
1880
1881         FOREACH_BLOCK (block) {
1882                 size_t num_cards;
1883
1884                 block->cardtable_mod_union = sgen_card_table_update_mod_union (block->cardtable_mod_union,
1885                                 MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
1886
1887                 SGEN_ASSERT (0, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
1888         } END_FOREACH_BLOCK;
1889 }
1890
1891 static guint8*
1892 major_get_cardtable_mod_union_for_object (char *obj)
1893 {
1894         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
1895         size_t offset = card_offset (obj, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1896         return &block->cardtable_mod_union [offset];
1897 }
1898
1899 static void
1900 alloc_free_block_lists (MSBlockInfo ***lists)
1901 {
1902         int i;
1903         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1904                 lists [i] = sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1905 }
1906
1907 #undef pthread_create
1908
1909 static void
1910 post_param_init (SgenMajorCollector *collector)
1911 {
1912         collector->sweeps_lazily = lazy_sweep;
1913 }
1914
1915 static void
1916 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
1917 {
1918         int i;
1919
1920         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
1921
1922         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
1923         block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1924         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
1925
1926         evacuate_block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1927         for (i = 0; i < num_block_obj_sizes; ++i)
1928                 evacuate_block_obj_sizes [i] = FALSE;
1929
1930         /*
1931         {
1932                 int i;
1933                 g_print ("block object sizes:\n");
1934                 for (i = 0; i < num_block_obj_sizes; ++i)
1935                         g_print ("%d\n", block_obj_sizes [i]);
1936         }
1937         */
1938
1939         alloc_free_block_lists (free_block_lists);
1940
1941         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
1942                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
1943         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
1944                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
1945
1946         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
1947         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
1948         mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
1949         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_objects_evacuated);
1950 #if SIZEOF_VOID_P != 8
1951         mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
1952         mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
1953         mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
1954         mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
1955 #endif
1956
1957         collector->section_size = MAJOR_SECTION_SIZE;
1958
1959         concurrent_mark = is_concurrent;
1960         if (is_concurrent) {
1961                 collector->is_concurrent = TRUE;
1962                 collector->want_synchronous_collection = &want_evacuation;
1963         } else {
1964                 collector->is_concurrent = FALSE;
1965                 collector->want_synchronous_collection = NULL;
1966         }
1967         collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
1968         collector->supports_cardtable = TRUE;
1969
1970         collector->alloc_heap = major_alloc_heap;
1971         collector->is_object_live = major_is_object_live;
1972         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
1973         collector->alloc_degraded = major_alloc_degraded;
1974
1975         collector->alloc_object = major_alloc_object;
1976         collector->free_pinned_object = free_pinned_object;
1977         collector->iterate_objects = major_iterate_objects;
1978         collector->free_non_pinned_object = major_free_non_pinned_object;
1979         collector->pin_objects = major_pin_objects;
1980         collector->pin_major_object = pin_major_object;
1981         collector->scan_card_table = major_scan_card_table;
1982         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
1983         if (is_concurrent) {
1984                 collector->update_cardtable_mod_union = update_cardtable_mod_union;
1985                 collector->get_cardtable_mod_union_for_object = major_get_cardtable_mod_union_for_object;
1986         }
1987         collector->init_to_space = major_init_to_space;
1988         collector->sweep = major_sweep;
1989         collector->have_finished_sweeping = major_have_finished_sweeping;
1990         collector->free_swept_blocks = major_free_swept_blocks;
1991         collector->check_scan_starts = major_check_scan_starts;
1992         collector->dump_heap = major_dump_heap;
1993         collector->get_used_size = major_get_used_size;
1994         collector->start_nursery_collection = major_start_nursery_collection;
1995         collector->finish_nursery_collection = major_finish_nursery_collection;
1996         collector->start_major_collection = major_start_major_collection;
1997         collector->finish_major_collection = major_finish_major_collection;
1998         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
1999         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2000         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2001         collector->get_num_major_sections = get_num_major_sections;
2002         collector->handle_gc_param = major_handle_gc_param;
2003         collector->print_gc_param_usage = major_print_gc_param_usage;
2004         collector->post_param_init = post_param_init;
2005         collector->is_valid_object = major_is_valid_object;
2006         collector->describe_pointer = major_describe_pointer;
2007         collector->count_cards = major_count_cards;
2008
2009         collector->major_ops.copy_or_mark_object = major_copy_or_mark_object_canonical;
2010         collector->major_ops.scan_object = major_scan_object_with_evacuation;
2011         if (is_concurrent) {
2012                 collector->major_concurrent_ops.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2013                 collector->major_concurrent_ops.scan_object = major_scan_object_no_mark_concurrent;
2014                 collector->major_concurrent_ops.scan_vtype = major_scan_vtype_concurrent;
2015         }
2016
2017 #if !defined (FIXED_HEAP) && !defined (SGEN_PARALLEL_MARK)
2018         /* FIXME: this will not work with evacuation or the split nursery. */
2019         if (!is_concurrent)
2020                 collector->drain_gray_stack = drain_gray_stack;
2021
2022 #ifdef HEAVY_STATISTICS
2023         mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2024         mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2025         mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2026         mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2027         mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2028         mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2029         mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2030         mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2031         mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2032         mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2033
2034         mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2035         mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2036         mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2037 #endif
2038 #endif
2039
2040 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2041         mono_mutex_init (&scanned_objects_list_lock);
2042 #endif
2043
2044         SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2045
2046         /*cardtable requires major pages to be 8 cards aligned*/
2047         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2048 }
2049
2050 void
2051 sgen_marksweep_init (SgenMajorCollector *collector)
2052 {
2053         sgen_marksweep_init_internal (collector, FALSE);
2054 }
2055
2056 void
2057 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2058 {
2059         sgen_marksweep_init_internal (collector, TRUE);
2060 }
2061
2062 #endif