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