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