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