[sgen] Sweep state instead of `have_swept`.
[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;
635         size_t old_num_sections;
636
637         old_num_sections = num_major_sections;
638
639         obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
640         if (G_LIKELY (obj)) {
641                 HEAVY_STAT (++stat_objects_alloced_degraded);
642                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
643                 g_assert (num_major_sections >= old_num_sections);
644                 sgen_register_major_sections_alloced (num_major_sections - old_num_sections);
645         }
646         return obj;
647 }
648
649 /*
650  * obj is some object.  If it's not in the major heap (i.e. if it's in
651  * the nursery or LOS), return FALSE.  Otherwise return whether it's
652  * been marked or copied.
653  */
654 static gboolean
655 major_is_object_live (char *obj)
656 {
657         MSBlockInfo *block;
658         int word, bit;
659         mword objsize;
660
661         if (sgen_ptr_in_nursery (obj))
662                 return FALSE;
663
664         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
665
666         /* LOS */
667         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
668                 return FALSE;
669
670         /* now we know it's in a major block */
671         block = MS_BLOCK_FOR_OBJ (obj);
672         SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?");
673         MS_CALC_MARK_BIT (word, bit, obj);
674         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
675 }
676
677 static gboolean
678 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
679 {
680         MSBlockInfo *block;
681
682         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Can't examine allocated blocks during sweep");
683         FOREACH_BLOCK_NO_LOCK (block) {
684                 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
685                         int count = MS_BLOCK_FREE / block->obj_size;
686                         int i;
687
688                         *start = NULL;
689                         for (i = 0; i <= count; ++i) {
690                                 if (ptr >= MS_BLOCK_OBJ (block, i) && ptr < MS_BLOCK_OBJ (block, i + 1)) {
691                                         *start = MS_BLOCK_OBJ (block, i);
692                                         break;
693                                 }
694                         }
695                         return !block->pinned;
696                 }
697         } END_FOREACH_BLOCK_NO_LOCK;
698         return FALSE;
699 }
700
701 static void
702 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
703 {
704         gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
705         gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
706         gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
707         MSBlockInfo *block;
708
709         FOREACH_BLOCK (block) {
710                 int count = MS_BLOCK_FREE / block->obj_size;
711                 int i;
712
713                 if (block->pinned && !pinned)
714                         continue;
715                 if (!block->pinned && !non_pinned)
716                         continue;
717                 if (sweep && lazy_sweep) {
718                         sweep_block (block, FALSE);
719                         SGEN_ASSERT (0, block->swept, "Block must be swept after sweeping");
720                 }
721
722                 for (i = 0; i < count; ++i) {
723                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
724                         if (!block->swept) {
725                                 int word, bit;
726                                 MS_CALC_MARK_BIT (word, bit, obj);
727                                 if (!MS_MARK_BIT (block, word, bit))
728                                         continue;
729                         }
730                         if (MS_OBJ_ALLOCED (obj, block))
731                                 callback ((char*)obj, block->obj_size, data);
732                 }
733         } END_FOREACH_BLOCK;
734 }
735
736 static gboolean
737 major_is_valid_object (char *object)
738 {
739         MSBlockInfo *block;
740
741         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Can't iterate blocks during sweep");
742         FOREACH_BLOCK_NO_LOCK (block) {
743                 int idx;
744                 char *obj;
745
746                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
747                         continue;
748
749                 idx = MS_BLOCK_OBJ_INDEX (object, block);
750                 obj = (char*)MS_BLOCK_OBJ (block, idx);
751                 if (obj != object)
752                         return FALSE;
753                 return MS_OBJ_ALLOCED (obj, block);
754         } END_FOREACH_BLOCK_NO_LOCK;
755
756         return FALSE;
757 }
758
759
760 static MonoVTable*
761 major_describe_pointer (char *ptr)
762 {
763         MSBlockInfo *block;
764
765         FOREACH_BLOCK_NO_LOCK (block) {
766                 int idx;
767                 char *obj;
768                 gboolean live;
769                 MonoVTable *vtable;
770                 int w, b;
771                 gboolean marked;
772
773                 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
774                         continue;
775
776                 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
777                         MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
778
779                 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
780                 obj = (char*)MS_BLOCK_OBJ (block, idx);
781                 live = MS_OBJ_ALLOCED (obj, block);
782                 vtable = live ? (MonoVTable*)SGEN_LOAD_VTABLE (obj) : NULL;
783
784                 MS_CALC_MARK_BIT (w, b, obj);
785                 marked = MS_MARK_BIT (block, w, b);
786
787                 if (obj == ptr) {
788                         SGEN_LOG (0, "\t(");
789                         if (live)
790                                 SGEN_LOG (0, "object");
791                         else
792                                 SGEN_LOG (0, "dead-object");
793                 } else {
794                         if (live)
795                                 SGEN_LOG (0, "interior-ptr offset %td", ptr - obj);
796                         else
797                                 SGEN_LOG (0, "dead-interior-ptr offset %td", ptr - obj);
798                 }
799
800                 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
801
802                 return vtable;
803         } END_FOREACH_BLOCK_NO_LOCK;
804
805         return NULL;
806 }
807
808 static void
809 major_check_scan_starts (void)
810 {
811 }
812
813 static void
814 major_dump_heap (FILE *heap_dump_file)
815 {
816         MSBlockInfo *block;
817         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
818         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
819         int i;
820
821         for (i = 0; i < num_block_obj_sizes; ++i)
822                 slots_available [i] = slots_used [i] = 0;
823
824         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Can't iterate blocks during sweep");
825         FOREACH_BLOCK (block) {
826                 int index = ms_find_block_obj_size_index (block->obj_size);
827                 int count = MS_BLOCK_FREE / block->obj_size;
828
829                 slots_available [index] += count;
830                 for (i = 0; i < count; ++i) {
831                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
832                                 ++slots_used [index];
833                 }
834         } END_FOREACH_BLOCK;
835
836         fprintf (heap_dump_file, "<occupancies>\n");
837         for (i = 0; i < num_block_obj_sizes; ++i) {
838                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
839                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
840         }
841         fprintf (heap_dump_file, "</occupancies>\n");
842
843         FOREACH_BLOCK (block) {
844                 int count = MS_BLOCK_FREE / block->obj_size;
845                 int i;
846                 int start = -1;
847
848                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
849
850                 for (i = 0; i <= count; ++i) {
851                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
852                                 if (start < 0)
853                                         start = i;
854                         } else {
855                                 if (start >= 0) {
856                                         sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
857                                         start = -1;
858                                 }
859                         }
860                 }
861
862                 fprintf (heap_dump_file, "</section>\n");
863         } END_FOREACH_BLOCK;
864 }
865
866 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
867
868 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do {   \
869                 int __word, __bit;                                      \
870                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
871                 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
872                         MS_SET_MARK_BIT ((block), __word, __bit);       \
873                         if (sgen_gc_descr_has_references (desc))                        \
874                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
875                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
876                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
877                 }                                                       \
878         } while (0)
879 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do {           \
880                 int __word, __bit;                                      \
881                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
882                 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
883                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
884                         MS_SET_MARK_BIT ((block), __word, __bit);       \
885                         if (sgen_gc_descr_has_references (desc))                        \
886                                 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
887                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
888                         INC_NUM_MAJOR_OBJECTS_MARKED ();                \
889                 }                                                       \
890         } while (0)
891
892 static void
893 pin_major_object (char *obj, SgenGrayQueue *queue)
894 {
895         MSBlockInfo *block;
896
897         if (concurrent_mark)
898                 g_assert_not_reached ();
899
900         block = MS_BLOCK_FOR_OBJ (obj);
901         block->has_pinned = TRUE;
902         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
903 }
904
905 #include "sgen-major-copy-object.h"
906
907 static void
908 major_copy_or_mark_object_with_evacuation_concurrent (void **ptr, void *obj, SgenGrayQueue *queue)
909 {
910         SGEN_ASSERT (9, sgen_concurrent_collection_in_progress (), "Why are we scanning concurrently when there's no concurrent collection on?");
911         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!");
912
913         g_assert (!SGEN_OBJECT_IS_FORWARDED (obj));
914
915         if (!sgen_ptr_in_nursery (obj)) {
916                 mword objsize;
917
918                 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
919
920                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE) {
921                         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
922                         MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
923                 } else {
924                         if (sgen_los_object_is_pinned (obj))
925                                 return;
926
927 #ifdef ENABLE_DTRACE
928                         if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
929                                 MonoVTable *vt = (MonoVTable*)SGEN_LOAD_VTABLE (obj);
930                                 MONO_GC_OBJ_PINNED ((mword)obj, sgen_safe_object_get_size (obj), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
931                         }
932 #endif
933
934                         sgen_los_pin_object (obj);
935                         if (SGEN_OBJECT_HAS_REFERENCES (obj))
936                                 GRAY_OBJECT_ENQUEUE (queue, obj, sgen_obj_get_descriptor (obj));
937                         INC_NUM_MAJOR_OBJECTS_MARKED ();
938                 }
939         }
940 }
941
942 static long long
943 major_get_and_reset_num_major_objects_marked (void)
944 {
945 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
946         long long num = num_major_objects_marked;
947         num_major_objects_marked = 0;
948         return num;
949 #else
950         return 0;
951 #endif
952 }
953
954 #define PREFETCH_CARDS          1       /* BOOL FASTENABLE */
955 #if !PREFETCH_CARDS
956 #undef PREFETCH_CARDS
957 #endif
958
959 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
960 #if defined(PLATFORM_MACOSX)
961 #define GCC_VERSION (__GNUC__ * 10000 \
962                                + __GNUC_MINOR__ * 100 \
963                                + __GNUC_PATCHLEVEL__)
964 #if GCC_VERSION <= 40300
965 #undef PREFETCH_CARDS
966 #endif
967 #endif
968
969 #ifdef HEAVY_STATISTICS
970 static guint64 stat_optimized_copy;
971 static guint64 stat_optimized_copy_nursery;
972 static guint64 stat_optimized_copy_nursery_forwarded;
973 static guint64 stat_optimized_copy_nursery_pinned;
974 static guint64 stat_optimized_copy_major;
975 static guint64 stat_optimized_copy_major_small_fast;
976 static guint64 stat_optimized_copy_major_small_slow;
977 static guint64 stat_optimized_copy_major_large;
978 static guint64 stat_optimized_copy_major_forwarded;
979 static guint64 stat_optimized_copy_major_small_evacuate;
980 static guint64 stat_optimized_major_scan;
981 static guint64 stat_optimized_major_scan_no_refs;
982
983 static guint64 stat_drain_prefetch_fills;
984 static guint64 stat_drain_prefetch_fill_failures;
985 static guint64 stat_drain_loops;
986 #endif
987
988 static void major_scan_object_with_evacuation (char *start, mword desc, SgenGrayQueue *queue);
989
990 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_no_evacuation
991 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_no_evacuation
992 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_no_evacuation
993 #include "sgen-marksweep-drain-gray-stack.h"
994
995 #define COPY_OR_MARK_WITH_EVACUATION
996 #define COPY_OR_MARK_FUNCTION_NAME      major_copy_or_mark_object_with_evacuation
997 #define SCAN_OBJECT_FUNCTION_NAME       major_scan_object_with_evacuation
998 #define DRAIN_GRAY_STACK_FUNCTION_NAME  drain_gray_stack_with_evacuation
999 #include "sgen-marksweep-drain-gray-stack.h"
1000
1001 static gboolean
1002 drain_gray_stack (ScanCopyContext ctx)
1003 {
1004         gboolean evacuation = FALSE;
1005         int i;
1006         for (i = 0; i < num_block_obj_sizes; ++i) {
1007                 if (evacuate_block_obj_sizes [i]) {
1008                         evacuation = TRUE;
1009                         break;
1010                 }
1011         }
1012
1013         if (evacuation)
1014                 return drain_gray_stack_with_evacuation (ctx);
1015         else
1016                 return drain_gray_stack_no_evacuation (ctx);
1017 }
1018
1019 #include "sgen-marksweep-scan-object-concurrent.h"
1020
1021 static void
1022 major_copy_or_mark_object_canonical (void **ptr, SgenGrayQueue *queue)
1023 {
1024         major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1025 }
1026
1027 static void
1028 major_copy_or_mark_object_concurrent_canonical (void **ptr, SgenGrayQueue *queue)
1029 {
1030         major_copy_or_mark_object_with_evacuation_concurrent (ptr, *ptr, queue);
1031 }
1032
1033 static void
1034 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1035 {
1036         void **entry, **end;
1037         int last_index = -1;
1038
1039         if (first_entry == last_entry)
1040                 return;
1041
1042         block->has_pinned = TRUE;
1043
1044         entry = sgen_pinning_get_entry (first_entry);
1045         end = sgen_pinning_get_entry (last_entry);
1046
1047         for (; entry < end; ++entry) {
1048                 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1049                 char *obj;
1050                 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);
1051                 if (index == last_index)
1052                         continue;
1053                 obj = MS_BLOCK_OBJ (block, index);
1054                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1055                 last_index = index;
1056         }
1057 }
1058
1059 static inline void
1060 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1061 {
1062         int obj_index;
1063
1064         for (obj_index = 0; obj_index < count; ++obj_index) {
1065                 int word, bit;
1066                 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1067
1068                 MS_CALC_MARK_BIT (word, bit, obj);
1069                 if (MS_MARK_BIT (block, word, bit)) {
1070                         SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1071                 } else {
1072                         /* an unmarked object */
1073                         if (MS_OBJ_ALLOCED (obj, block)) {
1074                                 /*
1075                                  * FIXME: Merge consecutive
1076                                  * slots for lower reporting
1077                                  * overhead.  Maybe memset
1078                                  * will also benefit?
1079                                  */
1080                                 binary_protocol_empty (obj, obj_size);
1081                                 MONO_GC_MAJOR_SWEPT ((mword)obj, obj_size);
1082                                 memset (obj, 0, obj_size);
1083                         }
1084                         *(void**)obj = block->free_list;
1085                         block->free_list = obj;
1086                 }
1087         }
1088 }
1089
1090 /*
1091  * sweep_block:
1092  *
1093  *   Traverse BLOCK, freeing and zeroing unused objects.
1094  */
1095 static void
1096 sweep_block (MSBlockInfo *block, gboolean during_major_collection)
1097 {
1098         int count;
1099         void *reversed = NULL;
1100
1101         if (!during_major_collection)
1102                 g_assert (!sgen_concurrent_collection_in_progress ());
1103
1104         if (block->swept)
1105                 return;
1106
1107         count = MS_BLOCK_FREE / block->obj_size;
1108
1109         block->free_list = NULL;
1110
1111         /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1112         // FIXME: Add more sizes
1113         switch (block->obj_size) {
1114         case 16:
1115                 sweep_block_for_size (block, count, 16);
1116                 break;
1117         default:
1118                 sweep_block_for_size (block, count, block->obj_size);
1119                 break;
1120         }
1121
1122         /* reset mark bits */
1123         memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1124
1125         /* Reverse free list so that it's in address order */
1126         reversed = NULL;
1127         while (block->free_list) {
1128                 void *next = *(void**)block->free_list;
1129                 *(void**)block->free_list = reversed;
1130                 reversed = block->free_list;
1131                 block->free_list = next;
1132         }
1133         block->free_list = reversed;
1134
1135         block->swept = 1;
1136 }
1137
1138 static inline int
1139 bitcount (mword d)
1140 {
1141         int count = 0;
1142
1143 #ifdef __GNUC__
1144         if (sizeof (mword) == sizeof (unsigned long))
1145                 count += __builtin_popcountl (d);
1146         else
1147                 count += __builtin_popcount (d);
1148 #else
1149         while (d) {
1150                 count ++;
1151                 d &= (d - 1);
1152         }
1153 #endif
1154         return count;
1155 }
1156
1157 /* statistics for evacuation */
1158 static size_t *sweep_slots_available;
1159 static size_t *sweep_slots_used;
1160 static size_t *sweep_num_blocks;
1161
1162 static void
1163 sweep_start (void)
1164 {
1165         int i;
1166
1167         for (i = 0; i < num_block_obj_sizes; ++i)
1168                 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1169
1170         /* clear all the free lists */
1171         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1172                 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1173                 int j;
1174                 for (j = 0; j < num_block_obj_sizes; ++j)
1175                         free_blocks [j] = NULL;
1176         }
1177 }
1178
1179 static mono_native_thread_return_t
1180 sweep_loop_thread_func (void *dummy)
1181 {
1182         int block_index;
1183
1184         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEEPING, "Sweep thread called with wrong state");
1185
1186         /* traverse all blocks, free and zero unmarked objects */
1187         block_index = 0;
1188
1189         for (;;) {
1190                 MSBlockInfo *block;
1191                 int count;
1192                 gboolean have_live = FALSE;
1193                 gboolean has_pinned;
1194                 gboolean have_free = FALSE;
1195                 int obj_size_index;
1196                 int nused = 0;
1197                 int i;
1198
1199                 LOCK_ALLOCATED_BLOCKS;
1200                 if (block_index >= allocated_blocks.next_slot) {
1201                         UNLOCK_ALLOCATED_BLOCKS;
1202                         break;
1203                 }
1204                 block = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [block_index]);
1205                 UNLOCK_ALLOCATED_BLOCKS;
1206
1207                 obj_size_index = block->obj_size_index;
1208
1209                 has_pinned = block->has_pinned;
1210                 block->has_pinned = block->pinned;
1211
1212                 block->is_to_space = FALSE;
1213                 block->swept = 0;
1214
1215                 count = MS_BLOCK_FREE / block->obj_size;
1216
1217                 if (block->cardtable_mod_union) {
1218                         sgen_free_internal_dynamic (block->cardtable_mod_union, CARDS_PER_BLOCK, INTERNAL_MEM_CARDTABLE_MOD_UNION);
1219                         block->cardtable_mod_union = NULL;
1220                 }
1221
1222                 /* Count marked objects in the block */
1223                 for (i = 0; i < MS_NUM_MARK_WORDS; ++i) {
1224                         nused += bitcount (block->mark_words [i]);
1225                 }
1226                 if (nused) {
1227                         have_live = TRUE;
1228                 }
1229                 if (nused < count)
1230                         have_free = TRUE;
1231
1232                 if (!lazy_sweep)
1233                         sweep_block (block, TRUE);
1234
1235                 if (have_live) {
1236                         if (!has_pinned) {
1237                                 ++sweep_num_blocks [obj_size_index];
1238                                 sweep_slots_used [obj_size_index] += nused;
1239                                 sweep_slots_available [obj_size_index] += count;
1240                         }
1241
1242                         /*
1243                          * If there are free slots in the block, add
1244                          * the block to the corresponding free list.
1245                          */
1246                         if (have_free) {
1247                                 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1248                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1249                                 add_free_block (free_blocks, index, block);
1250                         }
1251
1252                         update_heap_boundaries_for_block (block);
1253                 } else {
1254                         /*
1255                          * Blocks without live objects are removed from the
1256                          * block list and freed.
1257                          */
1258                         LOCK_ALLOCATED_BLOCKS;
1259                         SGEN_ASSERT (0, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1260                         SGEN_ASSERT (0, BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [block_index]) == block, "How did the block move?");
1261                         allocated_blocks.data [block_index] = NULL;
1262                         UNLOCK_ALLOCATED_BLOCKS;
1263
1264                         binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1265                         ms_free_block (block);
1266
1267                         --num_major_sections;
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_finished_sweeping (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         sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1437 }
1438
1439 static void
1440 major_start_major_collection (void)
1441 {
1442         int i;
1443
1444         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Major collection on unswept heap");
1445
1446         /* clear the free lists */
1447         for (i = 0; i < num_block_obj_sizes; ++i) {
1448                 if (!evacuate_block_obj_sizes [i])
1449                         continue;
1450
1451                 free_block_lists [0][i] = NULL;
1452                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1453         }
1454
1455         // Sweep all unswept blocks
1456         if (lazy_sweep) {
1457                 MSBlockInfo *block;
1458
1459                 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, TRUE);
1460
1461                 FOREACH_BLOCK (block) {
1462                         sweep_block (block, TRUE);
1463                 } END_FOREACH_BLOCK;
1464
1465                 MONO_GC_SWEEP_END (GENERATION_OLD, TRUE);
1466         }
1467
1468         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Cannot start major collection without having finished sweeping");
1469         sweep_state = SWEEP_STATE_NEED_SWEEPING;
1470 }
1471
1472 static void
1473 major_finish_major_collection (ScannedObjectCounts *counts)
1474 {
1475 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1476         if (binary_protocol_is_enabled ()) {
1477                 counts->num_scanned_objects = scanned_objects_list.next_slot;
1478
1479                 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1480                 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1481
1482                 sgen_pointer_queue_clear (&scanned_objects_list);
1483         }
1484 #endif
1485 }
1486
1487 #if SIZEOF_VOID_P != 8
1488 static int
1489 compare_pointers (const void *va, const void *vb) {
1490         char *a = *(char**)va, *b = *(char**)vb;
1491         if (a < b)
1492                 return -1;
1493         if (a > b)
1494                 return 1;
1495         return 0;
1496 }
1497 #endif
1498
1499 /*
1500  * This is called with sweep completed and the world stopped.
1501  */
1502 static void
1503 major_free_swept_blocks (void)
1504 {
1505         size_t section_reserve = sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1506
1507         SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1508
1509 #if SIZEOF_VOID_P != 8
1510         {
1511                 int i, num_empty_blocks_orig, num_blocks, arr_length;
1512                 void *block;
1513                 void **empty_block_arr;
1514                 void **rebuild_next;
1515
1516 #ifdef TARGET_WIN32
1517                 /*
1518                  * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1519                  * a VirtualAlloc ()-ed block.
1520                  */
1521                 return;
1522 #endif
1523
1524                 if (num_empty_blocks <= section_reserve)
1525                         return;
1526                 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1527
1528                 num_empty_blocks_orig = num_empty_blocks;
1529                 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1530                                 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1531                 if (!empty_block_arr)
1532                         goto fallback;
1533
1534                 i = 0;
1535                 for (block = empty_blocks; block; block = *(void**)block)
1536                         empty_block_arr [i++] = block;
1537                 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1538
1539                 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1540
1541                 /*
1542                  * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1543                  * contiguous ones.  If we do, we free them.  If that's not enough to get to
1544                  * section_reserve, we halve the number of contiguous blocks we're looking
1545                  * for and have another go, until we're done with looking for pairs of
1546                  * blocks, at which point we give up and go to the fallback.
1547                  */
1548                 arr_length = num_empty_blocks_orig;
1549                 num_blocks = MS_BLOCK_ALLOC_NUM;
1550                 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1551                         int first = -1;
1552                         int dest = 0;
1553
1554                         dest = 0;
1555                         for (i = 0; i < arr_length; ++i) {
1556                                 int d = dest;
1557                                 void *block = empty_block_arr [i];
1558                                 SGEN_ASSERT (0, block, "we're not shifting correctly");
1559                                 if (i != dest) {
1560                                         empty_block_arr [dest] = block;
1561                                         /*
1562                                          * This is not strictly necessary, but we're
1563                                          * cautious.
1564                                          */
1565                                         empty_block_arr [i] = NULL;
1566                                 }
1567                                 ++dest;
1568
1569                                 if (first < 0) {
1570                                         first = d;
1571                                         continue;
1572                                 }
1573
1574                                 SGEN_ASSERT (0, first >= 0 && d > first, "algorithm is wrong");
1575
1576                                 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1577                                         first = d;
1578                                         continue;
1579                                 }
1580
1581                                 if (d + 1 - first == num_blocks) {
1582                                         /*
1583                                          * We found num_blocks contiguous blocks.  Free them
1584                                          * and null their array entries.  As an optimization
1585                                          * we could, instead of nulling the entries, shift
1586                                          * the following entries over to the left, while
1587                                          * we're iterating.
1588                                          */
1589                                         int j;
1590                                         sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1591                                         for (j = first; j <= d; ++j)
1592                                                 empty_block_arr [j] = NULL;
1593                                         dest = first;
1594                                         first = -1;
1595
1596                                         num_empty_blocks -= num_blocks;
1597
1598                                         stat_major_blocks_freed += num_blocks;
1599                                         if (num_blocks == MS_BLOCK_ALLOC_NUM)
1600                                                 stat_major_blocks_freed_ideal += num_blocks;
1601                                         else
1602                                                 stat_major_blocks_freed_less_ideal += num_blocks;
1603
1604                                 }
1605                         }
1606
1607                         SGEN_ASSERT (0, dest <= i && dest <= arr_length, "array length is off");
1608                         arr_length = dest;
1609                         SGEN_ASSERT (0, arr_length == num_empty_blocks, "array length is off");
1610
1611                         num_blocks >>= 1;
1612                 }
1613
1614                 /* rebuild empty_blocks free list */
1615                 rebuild_next = (void**)&empty_blocks;
1616                 for (i = 0; i < arr_length; ++i) {
1617                         void *block = empty_block_arr [i];
1618                         SGEN_ASSERT (0, block, "we're missing blocks");
1619                         *rebuild_next = block;
1620                         rebuild_next = (void**)block;
1621                 }
1622                 *rebuild_next = NULL;
1623
1624                 /* free array */
1625                 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1626         }
1627
1628         SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1629
1630  fallback:
1631         /*
1632          * This is our threshold.  If there's not more empty than used blocks, we won't
1633          * release uncontiguous blocks, in fear of fragmenting the address space.
1634          */
1635         if (num_empty_blocks <= num_major_sections)
1636                 return;
1637 #endif
1638
1639         while (num_empty_blocks > section_reserve) {
1640                 void *next = *(void**)empty_blocks;
1641                 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
1642                 empty_blocks = next;
1643                 /*
1644                  * Needs not be atomic because this is running
1645                  * single-threaded.
1646                  */
1647                 --num_empty_blocks;
1648
1649                 ++stat_major_blocks_freed;
1650 #if SIZEOF_VOID_P != 8
1651                 ++stat_major_blocks_freed_individual;
1652 #endif
1653         }
1654 }
1655
1656 static void
1657 major_pin_objects (SgenGrayQueue *queue)
1658 {
1659         MSBlockInfo *block;
1660
1661         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Cannot iterate blocks during sweep");
1662         FOREACH_BLOCK (block) {
1663                 size_t first_entry, last_entry;
1664                 SGEN_ASSERT (0, block->swept, "All blocks must be swept when we're pinning.");
1665                 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
1666                                 &first_entry, &last_entry);
1667                 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
1668         } END_FOREACH_BLOCK;
1669 }
1670
1671 static void
1672 major_init_to_space (void)
1673 {
1674 }
1675
1676 static void
1677 major_report_pinned_memory_usage (void)
1678 {
1679         g_assert_not_reached ();
1680 }
1681
1682 static gint64
1683 major_get_used_size (void)
1684 {
1685         gint64 size = 0;
1686         MSBlockInfo *block;
1687
1688         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Cannot iterate blocks during sweep");
1689         FOREACH_BLOCK (block) {
1690                 int count = MS_BLOCK_FREE / block->obj_size;
1691                 void **iter;
1692                 size += count * block->obj_size;
1693                 for (iter = block->free_list; iter; iter = (void**)*iter)
1694                         size -= block->obj_size;
1695         } END_FOREACH_BLOCK;
1696
1697         return size;
1698 }
1699
1700 static size_t
1701 get_num_major_sections (void)
1702 {
1703         return num_major_sections;
1704 }
1705
1706 static gboolean
1707 major_handle_gc_param (const char *opt)
1708 {
1709         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1710                 const char *arg = strchr (opt, '=') + 1;
1711                 int percentage = atoi (arg);
1712                 if (percentage < 0 || percentage > 100) {
1713                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1714                         exit (1);
1715                 }
1716                 evacuation_threshold = (float)percentage / 100.0f;
1717                 return TRUE;
1718         } else if (!strcmp (opt, "lazy-sweep")) {
1719                 lazy_sweep = TRUE;
1720                 return TRUE;
1721         } else if (!strcmp (opt, "no-lazy-sweep")) {
1722                 lazy_sweep = FALSE;
1723                 return TRUE;
1724         }
1725
1726         return FALSE;
1727 }
1728
1729 static void
1730 major_print_gc_param_usage (void)
1731 {
1732         fprintf (stderr,
1733                         ""
1734                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1735                         "  (no-)lazy-sweep\n"
1736                         );
1737 }
1738
1739 static void
1740 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1741 {
1742         MSBlockInfo *block;
1743         gboolean has_references;
1744
1745         FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1746                 if (has_references)
1747                         callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1748         } END_FOREACH_BLOCK;
1749 }
1750
1751 #ifdef HEAVY_STATISTICS
1752 extern guint64 marked_cards;
1753 extern guint64 scanned_cards;
1754 extern guint64 scanned_objects;
1755 extern guint64 remarked_cards;
1756 #endif
1757
1758 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1759 /*
1760  * MS blocks are 16K aligned.
1761  * Cardtables are 4K aligned, at least.
1762  * This means that the cardtable of a given block is 32 bytes aligned.
1763  */
1764 static guint8*
1765 initial_skip_card (guint8 *card_data)
1766 {
1767         mword *cards = (mword*)card_data;
1768         mword card;
1769         int i;
1770         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1771                 card = cards [i];
1772                 if (card)
1773                         break;
1774         }
1775
1776         if (i == CARD_WORDS_PER_BLOCK)
1777                 return card_data + CARDS_PER_BLOCK;
1778
1779 #if defined(__i386__) && defined(__GNUC__)
1780         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1781 #elif defined(__x86_64__) && defined(__GNUC__)
1782         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1783 #elif defined(__s390x__) && defined(__GNUC__)
1784         return card_data + i * 8 +  (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1785 #else
1786         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1787                 if (card_data [i])
1788                         return &card_data [i];
1789         }
1790         return card_data;
1791 #endif
1792 }
1793
1794 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1795 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1796 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1797
1798 static size_t
1799 card_offset (char *obj, char *base)
1800 {
1801         return (obj - base) >> CARD_BITS;
1802 }
1803
1804 static void
1805 major_scan_card_table (gboolean mod_union, SgenGrayQueue *queue)
1806 {
1807         MSBlockInfo *block;
1808         gboolean has_references;
1809         ScanObjectFunc scan_func = sgen_get_current_object_ops ()->scan_object;
1810
1811         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Can't scan card table during sweep");
1812
1813         if (!concurrent_mark)
1814                 g_assert (!mod_union);
1815
1816         FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
1817 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1818                 guint8 cards_copy [CARDS_PER_BLOCK];
1819 #endif
1820                 gboolean small_objects;
1821                 int block_obj_size;
1822                 char *block_start;
1823                 guint8 *card_data, *card_base;
1824                 guint8 *card_data_end;
1825                 char *scan_front = NULL;
1826
1827 #ifdef PREFETCH_CARDS
1828                 int prefetch_index = __index + 6;
1829                 if (prefetch_index < allocated_blocks.next_slot) {
1830                         MSBlockInfo *prefetch_block = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [prefetch_index]);
1831                         guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
1832                         PREFETCH_READ (prefetch_block);
1833                         PREFETCH_WRITE (prefetch_cards);
1834                         PREFETCH_WRITE (prefetch_cards + 32);
1835                 }
1836 #endif
1837
1838                 if (!has_references)
1839                         continue;
1840
1841                 block_obj_size = block->obj_size;
1842                 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
1843
1844                 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
1845
1846                 /*
1847                  * This is safe in face of card aliasing for the following reason:
1848                  *
1849                  * Major blocks are 16k aligned, or 32 cards aligned.
1850                  * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1851                  * sizes, they won't overflow the cardtable overlap modulus.
1852                  */
1853                 if (mod_union) {
1854                         card_data = card_base = block->cardtable_mod_union;
1855                         /*
1856                          * This happens when the nursery collection that precedes finishing
1857                          * the concurrent collection allocates new major blocks.
1858                          */
1859                         if (!card_data)
1860                                 continue;
1861                 } else {
1862 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1863                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1864 #else
1865                         if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
1866                                 continue;
1867                         card_data = card_base = cards_copy;
1868 #endif
1869                 }
1870                 card_data_end = card_data + CARDS_PER_BLOCK;
1871
1872                 card_data += MS_BLOCK_SKIP >> CARD_BITS;
1873
1874                 card_data = initial_skip_card (card_data);
1875                 while (card_data < card_data_end) {
1876                         size_t card_index, first_object_index;
1877                         char *start;
1878                         char *end;
1879                         char *first_obj, *obj;
1880
1881                         HEAVY_STAT (++scanned_cards);
1882
1883                         if (!*card_data) {
1884                                 ++card_data;
1885                                 continue;
1886                         }
1887
1888                         card_index = card_data - card_base;
1889                         start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
1890                         end = start + CARD_SIZE_IN_BYTES;
1891
1892                         if (!block->swept)
1893                                 sweep_block (block, FALSE);
1894
1895                         HEAVY_STAT (++marked_cards);
1896
1897                         if (small_objects)
1898                                 sgen_card_table_prepare_card_for_scanning (card_data);
1899
1900                         /*
1901                          * If the card we're looking at starts at or in the block header, we
1902                          * must start at the first object in the block, without calculating
1903                          * the index of the object we're hypothetically starting at, because
1904                          * it would be negative.
1905                          */
1906                         if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
1907                                 first_object_index = 0;
1908                         else
1909                                 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1910
1911                         obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
1912
1913                         while (obj < end) {
1914                                 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
1915                                         goto next_object;
1916
1917                                 if (mod_union) {
1918                                         /* FIXME: do this more efficiently */
1919                                         int w, b;
1920                                         MS_CALC_MARK_BIT (w, b, obj);
1921                                         if (!MS_MARK_BIT (block, w, b))
1922                                                 goto next_object;
1923                                 }
1924
1925                                 if (small_objects) {
1926                                         HEAVY_STAT (++scanned_objects);
1927                                         scan_func (obj, sgen_obj_get_descriptor (obj), queue);
1928                                 } else {
1929                                         size_t offset = card_offset (obj, block_start);
1930                                         sgen_cardtable_scan_object (obj, block_obj_size, card_base + offset, mod_union, queue);
1931                                 }
1932                         next_object:
1933                                 obj += block_obj_size;
1934                                 g_assert (scan_front <= obj);
1935                                 scan_front = obj;
1936                         }
1937
1938                         HEAVY_STAT (if (*card_data) ++remarked_cards);
1939                         binary_protocol_card_scan (first_obj, obj - first_obj);
1940
1941                         if (small_objects)
1942                                 ++card_data;
1943                         else
1944                                 card_data = card_base + card_offset (obj, block_start);
1945                 }
1946         } END_FOREACH_BLOCK_NO_LOCK;
1947 }
1948
1949 static void
1950 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
1951 {
1952         MSBlockInfo *block;
1953         gboolean has_references;
1954         long long total_cards = 0;
1955         long long marked_cards = 0;
1956
1957         FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1958                 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
1959                 int i;
1960
1961                 if (!has_references)
1962                         continue;
1963
1964                 total_cards += CARDS_PER_BLOCK;
1965                 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
1966                         if (cards [i])
1967                                 ++marked_cards;
1968                 }
1969         } END_FOREACH_BLOCK;
1970
1971         *num_total_cards = total_cards;
1972         *num_marked_cards = marked_cards;
1973 }
1974
1975 static void
1976 update_cardtable_mod_union (void)
1977 {
1978         MSBlockInfo *block;
1979
1980         SGEN_ASSERT (0, sweep_state != SWEEP_STATE_SWEEPING, "Cannot iterate blocks during sweep");
1981         FOREACH_BLOCK (block) {
1982                 size_t num_cards;
1983
1984                 block->cardtable_mod_union = sgen_card_table_update_mod_union (block->cardtable_mod_union,
1985                                 MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
1986
1987                 SGEN_ASSERT (0, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
1988         } END_FOREACH_BLOCK;
1989 }
1990
1991 static guint8*
1992 major_get_cardtable_mod_union_for_object (char *obj)
1993 {
1994         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
1995         size_t offset = card_offset (obj, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1996         return &block->cardtable_mod_union [offset];
1997 }
1998
1999 #undef pthread_create
2000
2001 static void
2002 post_param_init (SgenMajorCollector *collector)
2003 {
2004         collector->sweeps_lazily = lazy_sweep;
2005 }
2006
2007 static void
2008 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2009 {
2010         int i;
2011
2012         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2013
2014         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2015         block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2016         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2017
2018         evacuate_block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2019         for (i = 0; i < num_block_obj_sizes; ++i)
2020                 evacuate_block_obj_sizes [i] = FALSE;
2021
2022         sweep_slots_available = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2023         sweep_slots_used = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2024         sweep_num_blocks = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2025
2026         /*
2027         {
2028                 int i;
2029                 g_print ("block object sizes:\n");
2030                 for (i = 0; i < num_block_obj_sizes; ++i)
2031                         g_print ("%d\n", block_obj_sizes [i]);
2032         }
2033         */
2034
2035         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2036                 free_block_lists [i] = sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2037
2038         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2039                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2040         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2041                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2042
2043         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2044         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2045         mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2046         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_objects_evacuated);
2047 #if SIZEOF_VOID_P != 8
2048         mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2049         mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2050         mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2051         mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2052 #endif
2053
2054         collector->section_size = MAJOR_SECTION_SIZE;
2055
2056         concurrent_mark = is_concurrent;
2057         if (is_concurrent) {
2058                 collector->is_concurrent = TRUE;
2059                 collector->want_synchronous_collection = &want_evacuation;
2060         } else {
2061                 collector->is_concurrent = FALSE;
2062                 collector->want_synchronous_collection = NULL;
2063         }
2064         collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2065         collector->supports_cardtable = TRUE;
2066
2067         collector->alloc_heap = major_alloc_heap;
2068         collector->is_object_live = major_is_object_live;
2069         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2070         collector->alloc_degraded = major_alloc_degraded;
2071
2072         collector->alloc_object = major_alloc_object;
2073         collector->free_pinned_object = free_pinned_object;
2074         collector->iterate_objects = major_iterate_objects;
2075         collector->free_non_pinned_object = major_free_non_pinned_object;
2076         collector->pin_objects = major_pin_objects;
2077         collector->pin_major_object = pin_major_object;
2078         collector->scan_card_table = major_scan_card_table;
2079         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2080         if (is_concurrent) {
2081                 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2082                 collector->get_cardtable_mod_union_for_object = major_get_cardtable_mod_union_for_object;
2083         }
2084         collector->init_to_space = major_init_to_space;
2085         collector->sweep = major_sweep;
2086         collector->have_finished_sweeping = major_have_finished_sweeping;
2087         collector->free_swept_blocks = major_free_swept_blocks;
2088         collector->check_scan_starts = major_check_scan_starts;
2089         collector->dump_heap = major_dump_heap;
2090         collector->get_used_size = major_get_used_size;
2091         collector->start_nursery_collection = major_start_nursery_collection;
2092         collector->finish_nursery_collection = major_finish_nursery_collection;
2093         collector->start_major_collection = major_start_major_collection;
2094         collector->finish_major_collection = major_finish_major_collection;
2095         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2096         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2097         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2098         collector->get_num_major_sections = get_num_major_sections;
2099         collector->handle_gc_param = major_handle_gc_param;
2100         collector->print_gc_param_usage = major_print_gc_param_usage;
2101         collector->post_param_init = post_param_init;
2102         collector->is_valid_object = major_is_valid_object;
2103         collector->describe_pointer = major_describe_pointer;
2104         collector->count_cards = major_count_cards;
2105
2106         collector->major_ops.copy_or_mark_object = major_copy_or_mark_object_canonical;
2107         collector->major_ops.scan_object = major_scan_object_with_evacuation;
2108         if (is_concurrent) {
2109                 collector->major_concurrent_ops.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2110                 collector->major_concurrent_ops.scan_object = major_scan_object_no_mark_concurrent;
2111                 collector->major_concurrent_ops.scan_vtype = major_scan_vtype_concurrent;
2112         }
2113
2114 #if !defined (FIXED_HEAP) && !defined (SGEN_PARALLEL_MARK)
2115         /* FIXME: this will not work with evacuation or the split nursery. */
2116         if (!is_concurrent)
2117                 collector->drain_gray_stack = drain_gray_stack;
2118
2119 #ifdef HEAVY_STATISTICS
2120         mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2121         mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2122         mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2123         mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2124         mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2125         mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2126         mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2127         mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2128         mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2129         mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2130
2131         mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2132         mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2133         mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2134 #endif
2135 #endif
2136
2137         mono_mutex_init (&allocated_blocks_lock);
2138
2139 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2140         mono_mutex_init (&scanned_objects_list_lock);
2141 #endif
2142
2143         SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2144
2145         /*cardtable requires major pages to be 8 cards aligned*/
2146         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2147 }
2148
2149 void
2150 sgen_marksweep_init (SgenMajorCollector *collector)
2151 {
2152         sgen_marksweep_init_internal (collector, FALSE);
2153 }
2154
2155 void
2156 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2157 {
2158         sgen_marksweep_init_internal (collector, TRUE);
2159 }
2160
2161 #endif