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