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