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