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