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