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