2 * sgen-marksweep.c: The Mark & Sweep major collector.
5 * Mark Probst <mark.probst@gmail.com>
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright (C) 2012 Xamarin Inc
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
22 #include "mono/sgen/sgen-gc.h"
23 #include "mono/sgen/sgen-protocol.h"
24 #include "mono/sgen/sgen-cardtable.h"
25 #include "mono/sgen/sgen-memory-governor.h"
26 #include "mono/sgen/sgen-layout-stats.h"
27 #include "mono/sgen/sgen-pointer-queue.h"
28 #include "mono/sgen/sgen-array-list.h"
29 #include "mono/sgen/sgen-pinning.h"
30 #include "mono/sgen/sgen-workers.h"
31 #include "mono/sgen/sgen-thread-pool.h"
32 #include "mono/sgen/sgen-client.h"
33 #include "mono/utils/mono-memory-model.h"
35 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
36 #define MS_BLOCK_SIZE ARCH_MIN_MS_BLOCK_SIZE
37 #define MS_BLOCK_SIZE_SHIFT ARCH_MIN_MS_BLOCK_SIZE_SHIFT
39 #define MS_BLOCK_SIZE_SHIFT 14 /* INT FASTENABLE */
40 #define MS_BLOCK_SIZE (1 << MS_BLOCK_SIZE_SHIFT)
42 #define MAJOR_SECTION_SIZE MS_BLOCK_SIZE
43 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
46 * Don't allocate single blocks, but alloc a contingent of this many
47 * blocks in one swoop. This must be a power of two.
49 #define MS_BLOCK_ALLOC_NUM 32
52 * Number of bytes before the first object in a block. At the start
53 * of a block is the MSBlockHeader, then opional padding, then come
54 * the objects, so this must be >= sizeof (MSBlockHeader).
56 #define MS_BLOCK_SKIP ((sizeof (MSBlockHeader) + 15) & ~15)
58 #define MS_BLOCK_FREE (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
60 #define MS_NUM_MARK_WORDS ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
63 * Blocks progress from one state to the next:
65 * SWEPT The block is fully swept. It might or might not be in
68 * MARKING The block might or might not contain live objects. If
69 * we're in between an initial collection pause and the
70 * finishing pause, the block might or might not be in a
73 * CHECKING The sweep thread is investigating the block to determine
74 * whether or not it contains live objects. The block is
77 * NEED_SWEEPING The block contains live objects but has not yet been
78 * swept. It also contains free slots. It is in a block
81 * SWEEPING The block is being swept. It might be in a free list.
88 BLOCK_STATE_NEED_SWEEPING,
92 typedef struct _MSBlockInfo MSBlockInfo;
96 * FIXME: Do we even need this? It's only used during sweep and might be worth
97 * recalculating to save the space.
99 guint16 obj_size_index;
100 /* FIXME: Reduce this - it only needs a byte. */
101 volatile gint32 state;
103 unsigned int pinned : 1;
104 unsigned int has_references : 1;
105 unsigned int has_pinned : 1; /* means cannot evacuate */
106 unsigned int is_to_space : 1;
107 void ** volatile free_list;
108 MSBlockInfo * volatile next_free;
109 guint8 * volatile cardtable_mod_union;
110 mword mark_words [MS_NUM_MARK_WORDS];
113 #define MS_BLOCK_FOR_BLOCK_INFO(b) ((char*)(b))
115 #define MS_BLOCK_OBJ(b,i) ((GCObject *)(MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i)))
116 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
117 #define MS_BLOCK_DATA_FOR_OBJ(o) ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
123 #define MS_BLOCK_FOR_OBJ(o) (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
125 /* object index will always be small */
126 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
128 //casting to int is fine since blocks are 32k
129 #define MS_CALC_MARK_BIT(w,b,o) do { \
130 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
131 if (sizeof (mword) == 4) { \
140 #define MS_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] & (ONE_P << (b)))
141 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
143 #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))
145 #define MS_BLOCK_OBJ_SIZE_FACTOR (pow (2.0, 1.0 / 3))
148 * This way we can lookup block object size indexes for sizes up to
149 * 256 bytes with a single load.
151 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES 32
153 static int *block_obj_sizes;
154 static int num_block_obj_sizes;
155 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
157 #define MS_BLOCK_FLAG_PINNED 1
158 #define MS_BLOCK_FLAG_REFS 2
160 #define MS_BLOCK_TYPE_MAX 4
162 static gboolean *evacuate_block_obj_sizes;
163 static float evacuation_threshold = 0.666f;
165 static gboolean lazy_sweep = TRUE;
169 SWEEP_STATE_NEED_SWEEPING,
170 SWEEP_STATE_SWEEPING,
171 SWEEP_STATE_SWEEPING_AND_ITERATING,
172 SWEEP_STATE_COMPACTING
175 static volatile int sweep_state = SWEEP_STATE_SWEPT;
177 static gboolean concurrent_mark;
178 static gboolean concurrent_sweep = TRUE;
180 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
181 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
183 #define BLOCK_IS_TAGGED_CHECKING(bl) SGEN_POINTER_IS_TAGGED_2 ((bl))
184 #define BLOCK_TAG_CHECKING(bl) SGEN_POINTER_TAG_2 ((bl))
186 #define BLOCK_UNTAG(bl) ((MSBlockInfo *)SGEN_POINTER_UNTAG_12 ((bl)))
188 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
190 /* all allocated blocks in the system */
191 static SgenArrayList allocated_blocks = SGEN_ARRAY_LIST_INIT (NULL, NULL, NULL, INTERNAL_MEM_PIN_QUEUE);
193 /* non-allocated block free-list */
194 static void *empty_blocks = NULL;
195 static size_t num_empty_blocks = 0;
198 * We can iterate the block list also while sweep is in progress but we
199 * need to account for blocks that will be checked for sweeping and even
200 * freed in the process.
202 #define FOREACH_BLOCK_NO_LOCK(bl) { \
203 volatile gpointer *slot; \
204 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
205 (bl) = BLOCK_UNTAG (*slot); \
208 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
209 volatile gpointer *slot; \
210 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
211 (bl) = (MSBlockInfo *) (*slot); \
214 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
215 (bl) = BLOCK_UNTAG ((bl));
216 #define END_FOREACH_BLOCK_NO_LOCK } SGEN_ARRAY_LIST_END_FOREACH_SLOT; }
218 static volatile size_t num_major_sections = 0;
220 * One free block list for each block object size. We add and remove blocks from these
221 * lists lock-free via CAS.
223 * Blocks accessed/removed from `free_block_lists`:
224 * from the mutator (with GC lock held)
225 * in nursery collections
226 * in non-concurrent major collections
227 * in the finishing pause of concurrent major collections (whole list is cleared)
229 * Blocks added to `free_block_lists`:
230 * in the sweeping thread
231 * during nursery collections
232 * from domain clearing (with the world stopped and no sweeping happening)
234 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
235 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
237 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
239 static guint64 stat_major_blocks_alloced = 0;
240 static guint64 stat_major_blocks_freed = 0;
241 static guint64 stat_major_blocks_lazy_swept = 0;
243 #if SIZEOF_VOID_P != 8
244 static guint64 stat_major_blocks_freed_ideal = 0;
245 static guint64 stat_major_blocks_freed_less_ideal = 0;
246 static guint64 stat_major_blocks_freed_individual = 0;
247 static guint64 stat_major_blocks_alloced_less_ideal = 0;
250 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
251 static guint64 num_major_objects_marked = 0;
252 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
254 #define INC_NUM_MAJOR_OBJECTS_MARKED()
257 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
258 static mono_mutex_t scanned_objects_list_lock;
259 static SgenPointerQueue scanned_objects_list;
262 add_scanned_object (void *ptr)
264 if (!binary_protocol_is_enabled ())
267 mono_os_mutex_lock (&scanned_objects_list_lock);
268 sgen_pointer_queue_add (&scanned_objects_list, ptr);
269 mono_os_mutex_unlock (&scanned_objects_list_lock);
273 static gboolean sweep_block (MSBlockInfo *block);
276 ms_find_block_obj_size_index (size_t size)
279 SGEN_ASSERT (9, size <= SGEN_MAX_SMALL_OBJ_SIZE, "size %zd is bigger than max small object size %d", size, SGEN_MAX_SMALL_OBJ_SIZE);
280 for (i = 0; i < num_block_obj_sizes; ++i)
281 if (block_obj_sizes [i] >= size)
283 g_error ("no object of size %zd\n", size);
287 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
288 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
290 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
291 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
292 fast_block_obj_size_indexes [((s)+7)>>3] : \
293 ms_find_block_obj_size_index ((s)))
296 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
300 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
302 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
308 update_heap_boundaries_for_block (MSBlockInfo *block)
310 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
317 ms_get_empty_block (void)
321 void *block, *empty, *next;
326 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
327 * unsuccessful, we halve the number of blocks and try again, until we're at
328 * 1. If that doesn't work, either, we assert.
330 int alloc_num = MS_BLOCK_ALLOC_NUM;
332 p = (char *)sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE,
333 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
334 alloc_num == 1 ? "major heap section" : NULL);
340 for (i = 0; i < alloc_num; ++i) {
343 * We do the free list update one after the
344 * other so that other threads can use the new
345 * blocks as quickly as possible.
348 empty = empty_blocks;
349 *(void**)block = empty;
350 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
354 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
356 stat_major_blocks_alloced += alloc_num;
357 #if SIZEOF_VOID_P != 8
358 if (alloc_num != MS_BLOCK_ALLOC_NUM)
359 stat_major_blocks_alloced_less_ideal += alloc_num;
364 empty = empty_blocks;
368 next = *(void**)block;
369 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
371 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
373 *(void**)block = NULL;
375 g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
381 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
382 * list, where it will either be freed later on, or reused in nursery collections.
385 ms_free_block (MSBlockInfo *info)
388 char *block = MS_BLOCK_FOR_BLOCK_INFO (info);
390 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
391 if (info->cardtable_mod_union)
392 sgen_card_table_free_mod_union (info->cardtable_mod_union, block, MS_BLOCK_SIZE);
393 memset (block, 0, MS_BLOCK_SIZE);
396 empty = empty_blocks;
397 *(void**)block = empty;
398 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
400 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
402 binary_protocol_block_free (block, MS_BLOCK_SIZE);
406 sweep_in_progress (void)
408 int state = sweep_state;
409 return state == SWEEP_STATE_SWEEPING ||
410 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
411 state == SWEEP_STATE_COMPACTING;
414 static inline gboolean
415 block_is_swept_or_marking (MSBlockInfo *block)
417 gint32 state = block->state;
418 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
421 //#define MARKSWEEP_CONSISTENCY_CHECK
423 #ifdef MARKSWEEP_CONSISTENCY_CHECK
425 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
427 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
428 for (; block; block = block->next_free) {
429 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
430 g_assert (block->obj_size == size);
431 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
433 /* blocks in the free lists must have at least
435 g_assert (block->free_list);
437 /* the block must be in the allocated_blocks array */
438 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
443 check_empty_blocks (void)
447 for (p = empty_blocks; p; p = *(void**)p)
449 g_assert (i == num_empty_blocks);
453 consistency_check (void)
458 /* check all blocks */
459 FOREACH_BLOCK_NO_LOCK (block) {
460 int count = MS_BLOCK_FREE / block->obj_size;
464 /* count number of free slots */
465 for (i = 0; i < count; ++i) {
466 void **obj = (void**) MS_BLOCK_OBJ (block, i);
467 if (!MS_OBJ_ALLOCED (obj, block))
471 /* check free list */
472 for (free = block->free_list; free; free = (void**)*free) {
473 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
476 g_assert (num_free == 0);
478 /* check all mark words are zero */
479 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
480 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
481 g_assert (block->mark_words [i] == 0);
483 } END_FOREACH_BLOCK_NO_LOCK;
485 /* check free blocks */
486 for (i = 0; i < num_block_obj_sizes; ++i) {
488 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
489 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
492 check_empty_blocks ();
497 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
501 block->next_free = old = free_blocks [size_index];
502 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
505 static void major_finish_sweep_checking (void);
508 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
510 int size = block_obj_sizes [size_index];
511 int count = MS_BLOCK_FREE / size;
513 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
517 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
520 info = (MSBlockInfo*)ms_get_empty_block ();
522 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
524 info->obj_size = size;
525 info->obj_size_index = size_index;
526 info->pinned = pinned;
527 info->has_references = has_references;
528 info->has_pinned = pinned;
530 * Blocks that are to-space are not evacuated from. During an major collection
531 * blocks are allocated for two reasons: evacuating objects from the nursery and
532 * evacuating them from major blocks marked for evacuation. In both cases we don't
533 * want further evacuation. We also don't want to evacuate objects allocated during
534 * the concurrent mark since it would add pointless stress on the finishing pause.
536 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
537 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
538 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
539 info->cardtable_mod_union = NULL;
541 update_heap_boundaries_for_block (info);
543 binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
545 /* build free list */
546 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
547 info->free_list = (void**)obj_start;
548 /* we're skipping the last one - it must be nulled */
549 for (i = 0; i < count - 1; ++i) {
550 char *next_obj_start = obj_start + size;
551 *(void**)obj_start = next_obj_start;
552 obj_start = next_obj_start;
555 *(void**)obj_start = NULL;
557 add_free_block (free_blocks, size_index, info);
559 sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
561 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
566 ptr_is_in_major_block (char *ptr, char **start, gboolean *pinned)
570 FOREACH_BLOCK_NO_LOCK (block) {
571 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
572 int count = MS_BLOCK_FREE / block->obj_size;
577 for (i = 0; i <= count; ++i) {
578 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
580 *start = (char *)MS_BLOCK_OBJ (block, i);
585 *pinned = block->pinned;
588 } END_FOREACH_BLOCK_NO_LOCK;
593 ptr_is_from_pinned_alloc (char *ptr)
596 if (ptr_is_in_major_block (ptr, NULL, &pinned))
602 ensure_can_access_block_free_list (MSBlockInfo *block)
606 switch (block->state) {
607 case BLOCK_STATE_SWEPT:
608 case BLOCK_STATE_MARKING:
610 case BLOCK_STATE_CHECKING:
611 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
613 case BLOCK_STATE_NEED_SWEEPING:
614 if (sweep_block (block))
615 ++stat_major_blocks_lazy_swept;
617 case BLOCK_STATE_SWEEPING:
618 /* FIXME: do this more elegantly */
622 SGEN_ASSERT (0, FALSE, "Illegal block state");
629 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
631 MSBlockInfo *block, *next_free_block;
632 void *obj, *next_free_slot;
635 block = free_blocks [size_index];
636 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
638 ensure_can_access_block_free_list (block);
640 obj = block->free_list;
641 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
643 next_free_slot = *(void**)obj;
644 if (next_free_slot) {
645 block->free_list = (gpointer *)next_free_slot;
649 next_free_block = block->next_free;
650 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
653 block->free_list = NULL;
654 block->next_free = NULL;
660 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
662 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
663 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
666 if (!free_blocks [size_index]) {
667 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
671 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
673 /* FIXME: assumes object layout */
674 *(GCVTable*)obj = vtable;
676 total_allocated_major += block_obj_sizes [size_index];
678 return (GCObject *)obj;
682 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
684 return alloc_obj (vtable, size, FALSE, has_references);
688 * We're not freeing the block if it's empty. We leave that work for
689 * the next major collection.
691 * This is just called from the domain clearing code, which runs in a
692 * single thread and has the GC lock, so we don't need an extra lock.
695 free_object (GCObject *obj, size_t size, gboolean pinned)
697 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
699 gboolean in_free_list;
701 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
703 ensure_can_access_block_free_list (block);
704 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);
705 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
706 MS_CALC_MARK_BIT (word, bit, obj);
707 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
709 memset (obj, 0, size);
711 in_free_list = !!block->free_list;
712 *(void**)obj = block->free_list;
713 block->free_list = (void**)obj;
716 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
717 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
718 SGEN_ASSERT (9, !block->next_free, "block %p doesn't have a free-list of object but belongs to a free-list of blocks", block);
719 add_free_block (free_blocks, size_index, block);
724 major_free_non_pinned_object (GCObject *obj, size_t size)
726 free_object (obj, size, FALSE);
729 /* size is a multiple of SGEN_ALLOC_ALIGN */
731 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
735 res = alloc_obj (vtable, size, TRUE, has_references);
736 /*If we failed to alloc memory, we better try releasing memory
737 *as pinned alloc is requested by the runtime.
740 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE, TRUE);
741 res = alloc_obj (vtable, size, TRUE, has_references);
743 return (GCObject *)res;
747 free_pinned_object (GCObject *obj, size_t size)
749 free_object (obj, size, TRUE);
753 * size is already rounded up and we hold the GC lock.
756 major_alloc_degraded (GCVTable vtable, size_t size)
760 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
761 if (G_LIKELY (obj)) {
762 HEAVY_STAT (++stat_objects_alloced_degraded);
763 HEAVY_STAT (stat_bytes_alloced_degraded += size);
769 * obj is some object. If it's not in the major heap (i.e. if it's in
770 * the nursery or LOS), return FALSE. Otherwise return whether it's
771 * been marked or copied.
774 major_is_object_live (GCObject *obj)
780 if (sgen_ptr_in_nursery (obj))
783 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
786 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
789 /* now we know it's in a major block */
790 block = MS_BLOCK_FOR_OBJ (obj);
791 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
792 MS_CALC_MARK_BIT (word, bit, obj);
793 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
797 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
800 if (ptr_is_in_major_block (ptr, start, &pinned))
806 try_set_sweep_state (int new_, int expected)
808 int old = SGEN_CAS (&sweep_state, new_, expected);
809 return old == expected;
813 set_sweep_state (int new_, int expected)
815 gboolean success = try_set_sweep_state (new_, expected);
816 SGEN_ASSERT (0, success, "Could not set sweep state.");
819 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
821 static SgenThreadPoolJob * volatile sweep_job;
822 static SgenThreadPoolJob * volatile sweep_blocks_job;
825 major_finish_sweep_checking (void)
828 SgenThreadPoolJob *job;
831 switch (sweep_state) {
832 case SWEEP_STATE_SWEPT:
833 case SWEEP_STATE_NEED_SWEEPING:
835 case SWEEP_STATE_SWEEPING:
836 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
839 case SWEEP_STATE_SWEEPING_AND_ITERATING:
840 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
842 case SWEEP_STATE_COMPACTING:
845 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
850 * We're running with the world stopped and the only other thread doing work is the
851 * sweep thread, which doesn't add blocks to the array, so we can safely access
854 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
855 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
857 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
862 sgen_thread_pool_job_wait (job);
863 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
864 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
868 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
870 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
871 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
872 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
875 major_finish_sweep_checking ();
876 FOREACH_BLOCK_NO_LOCK (block) {
877 int count = MS_BLOCK_FREE / block->obj_size;
880 if (block->pinned && !pinned)
882 if (!block->pinned && !non_pinned)
884 if (sweep && lazy_sweep) {
886 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
889 for (i = 0; i < count; ++i) {
890 void **obj = (void**) MS_BLOCK_OBJ (block, i);
892 * We've finished sweep checking, but if we're sweeping lazily and
893 * the flags don't require us to sweep, the block might still need
894 * sweeping. In that case, we need to consult the mark bits to tell
895 * us whether an object slot is live.
897 if (!block_is_swept_or_marking (block)) {
899 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
900 MS_CALC_MARK_BIT (word, bit, obj);
901 if (!MS_MARK_BIT (block, word, bit))
904 if (MS_OBJ_ALLOCED (obj, block))
905 callback ((GCObject*)obj, block->obj_size, data);
907 } END_FOREACH_BLOCK_NO_LOCK;
911 major_is_valid_object (char *object)
915 FOREACH_BLOCK_NO_LOCK (block) {
919 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
922 idx = MS_BLOCK_OBJ_INDEX (object, block);
923 obj = (char*)MS_BLOCK_OBJ (block, idx);
926 return MS_OBJ_ALLOCED (obj, block);
927 } END_FOREACH_BLOCK_NO_LOCK;
934 major_describe_pointer (char *ptr)
938 FOREACH_BLOCK_NO_LOCK (block) {
946 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
949 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
950 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
952 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
953 obj = (char*)MS_BLOCK_OBJ (block, idx);
954 live = MS_OBJ_ALLOCED (obj, block);
955 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
957 MS_CALC_MARK_BIT (w, b, obj);
958 marked = MS_MARK_BIT (block, w, b);
963 SGEN_LOG (0, "object");
965 SGEN_LOG (0, "dead-object");
968 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
970 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
973 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
976 } END_FOREACH_BLOCK_NO_LOCK;
982 major_check_scan_starts (void)
987 major_dump_heap (FILE *heap_dump_file)
990 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
991 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
994 for (i = 0; i < num_block_obj_sizes; ++i)
995 slots_available [i] = slots_used [i] = 0;
997 FOREACH_BLOCK_NO_LOCK (block) {
998 int index = ms_find_block_obj_size_index (block->obj_size);
999 int count = MS_BLOCK_FREE / block->obj_size;
1001 slots_available [index] += count;
1002 for (i = 0; i < count; ++i) {
1003 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1004 ++slots_used [index];
1006 } END_FOREACH_BLOCK_NO_LOCK;
1008 fprintf (heap_dump_file, "<occupancies>\n");
1009 for (i = 0; i < num_block_obj_sizes; ++i) {
1010 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1011 block_obj_sizes [i], slots_available [i], slots_used [i]);
1013 fprintf (heap_dump_file, "</occupancies>\n");
1015 FOREACH_BLOCK_NO_LOCK (block) {
1016 int count = MS_BLOCK_FREE / block->obj_size;
1020 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1022 for (i = 0; i <= count; ++i) {
1023 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1028 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1034 fprintf (heap_dump_file, "</section>\n");
1035 } END_FOREACH_BLOCK_NO_LOCK;
1039 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1041 guint8 *mod_union = block->cardtable_mod_union;
1047 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1048 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1050 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1053 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1057 static inline guint8*
1058 major_get_cardtable_mod_union_for_reference (char *ptr)
1060 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1061 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1062 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1063 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1064 return &mod_union [offset];
1068 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1071 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1073 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1074 if (sgen_safe_object_is_small (obj, type)) {
1075 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1076 SGEN_ASSERT (0, MS_BLOCK_FOR_OBJ (obj) == MS_BLOCK_FOR_OBJ (ptr), "How can an object and a reference inside it not be in the same block?");
1079 sgen_los_mark_mod_union_card (obj, ptr);
1081 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1084 static inline gboolean
1085 major_block_is_evacuating (MSBlockInfo *block)
1087 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1088 !block->has_pinned &&
1089 !block->is_to_space)
1094 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1095 int __word, __bit; \
1096 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1097 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1098 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1099 MS_SET_MARK_BIT ((block), __word, __bit); \
1100 if (sgen_gc_descr_has_references (desc)) \
1101 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1102 binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1103 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1108 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1112 if (concurrent_mark)
1113 g_assert_not_reached ();
1115 block = MS_BLOCK_FOR_OBJ (obj);
1116 block->has_pinned = TRUE;
1117 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1120 #include "sgen-major-copy-object.h"
1123 major_get_and_reset_num_major_objects_marked (void)
1125 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1126 long long num = num_major_objects_marked;
1127 num_major_objects_marked = 0;
1134 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1136 #undef PREFETCH_CARDS
1139 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1140 #if defined(PLATFORM_MACOSX)
1141 #if MONO_GNUC_VERSION <= 40300
1142 #undef PREFETCH_CARDS
1146 #ifdef HEAVY_STATISTICS
1147 static guint64 stat_optimized_copy;
1148 static guint64 stat_optimized_copy_nursery;
1149 static guint64 stat_optimized_copy_nursery_forwarded;
1150 static guint64 stat_optimized_copy_nursery_pinned;
1151 static guint64 stat_optimized_copy_major;
1152 static guint64 stat_optimized_copy_major_small_fast;
1153 static guint64 stat_optimized_copy_major_small_slow;
1154 static guint64 stat_optimized_copy_major_large;
1155 static guint64 stat_optimized_copy_major_forwarded;
1156 static guint64 stat_optimized_copy_major_small_evacuate;
1157 static guint64 stat_optimized_major_scan;
1158 static guint64 stat_optimized_major_scan_no_refs;
1160 static guint64 stat_drain_prefetch_fills;
1161 static guint64 stat_drain_prefetch_fill_failures;
1162 static guint64 stat_drain_loops;
1165 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1166 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1167 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1168 #include "sgen-marksweep-drain-gray-stack.h"
1170 #define COPY_OR_MARK_WITH_EVACUATION
1171 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1172 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1173 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_with_evacuation
1174 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1175 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_with_evacuation
1176 #include "sgen-marksweep-drain-gray-stack.h"
1178 #define COPY_OR_MARK_CONCURRENT
1179 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1180 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1181 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1182 #include "sgen-marksweep-drain-gray-stack.h"
1184 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1185 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1186 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1187 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_with_evacuation
1188 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_with_evacuation
1189 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1190 #include "sgen-marksweep-drain-gray-stack.h"
1192 static inline gboolean
1193 major_is_evacuating (void)
1196 for (i = 0; i < num_block_obj_sizes; ++i) {
1197 if (evacuate_block_obj_sizes [i]) {
1206 drain_gray_stack (SgenGrayQueue *queue)
1208 if (major_is_evacuating ())
1209 return drain_gray_stack_with_evacuation (queue);
1211 return drain_gray_stack_no_evacuation (queue);
1215 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1217 if (major_is_evacuating ())
1218 return drain_gray_stack_concurrent_with_evacuation (queue);
1220 return drain_gray_stack_concurrent_no_evacuation (queue);
1224 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1226 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1230 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1232 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1236 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1238 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1242 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1244 void **entry, **end;
1245 int last_index = -1;
1247 if (first_entry == last_entry)
1250 entry = sgen_pinning_get_entry (first_entry);
1251 end = sgen_pinning_get_entry (last_entry);
1253 for (; entry < end; ++entry) {
1254 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1256 SGEN_ASSERT (9, index >= 0 && index < MS_BLOCK_FREE / block->obj_size, "invalid object %p index %d max-index %d", *entry, index, (int)(MS_BLOCK_FREE / block->obj_size));
1257 if (index == last_index)
1259 obj = MS_BLOCK_OBJ (block, index);
1260 if (!MS_OBJ_ALLOCED (obj, block))
1262 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1263 sgen_pin_stats_register_object (obj, GENERATION_OLD);
1268 * There might have been potential pinning "pointers" into this block, but none of
1269 * them pointed to occupied slots, in which case we don't have to pin the block.
1271 if (last_index >= 0)
1272 block->has_pinned = TRUE;
1276 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1280 for (obj_index = 0; obj_index < count; ++obj_index) {
1282 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1284 MS_CALC_MARK_BIT (word, bit, obj);
1285 if (MS_MARK_BIT (block, word, bit)) {
1286 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1288 /* an unmarked object */
1289 if (MS_OBJ_ALLOCED (obj, block)) {
1291 * FIXME: Merge consecutive
1292 * slots for lower reporting
1293 * overhead. Maybe memset
1294 * will also benefit?
1296 binary_protocol_empty (obj, obj_size);
1297 memset (obj, 0, obj_size);
1299 *(void**)obj = block->free_list;
1300 block->free_list = (void **)obj;
1305 static inline gboolean
1306 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1308 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1309 gboolean success = old_state == expected_state;
1311 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1316 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1318 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1319 block->state = new_state;
1320 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, expected_state, new_state);
1324 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1326 * Sweeping means iterating through the block's slots and building the free-list from the
1327 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1330 sweep_block (MSBlockInfo *block)
1333 void *reversed = NULL;
1336 switch (block->state) {
1337 case BLOCK_STATE_SWEPT:
1339 case BLOCK_STATE_MARKING:
1340 case BLOCK_STATE_CHECKING:
1341 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1343 case BLOCK_STATE_SWEEPING:
1344 /* FIXME: Do this more elegantly */
1347 case BLOCK_STATE_NEED_SWEEPING:
1348 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1352 SGEN_ASSERT (0, FALSE, "Illegal block state");
1355 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1357 count = MS_BLOCK_FREE / block->obj_size;
1359 block->free_list = NULL;
1361 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1362 // FIXME: Add more sizes
1363 switch (block->obj_size) {
1365 sweep_block_for_size (block, count, 16);
1368 sweep_block_for_size (block, count, block->obj_size);
1372 /* reset mark bits */
1373 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1375 /* Reverse free list so that it's in address order */
1377 while (block->free_list) {
1378 void *next = *(void**)block->free_list;
1379 *(void**)block->free_list = reversed;
1380 reversed = block->free_list;
1381 block->free_list = (void **)next;
1383 block->free_list = (void **)reversed;
1385 mono_memory_write_barrier ();
1387 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1398 if (sizeof (mword) == 8)
1399 count += __builtin_popcountll (d);
1401 count += __builtin_popcount (d);
1411 /* statistics for evacuation */
1412 static size_t *sweep_slots_available;
1413 static size_t *sweep_slots_used;
1414 static size_t *sweep_num_blocks;
1416 static volatile size_t num_major_sections_before_sweep;
1417 static volatile size_t num_major_sections_freed_in_sweep;
1424 for (i = 0; i < num_block_obj_sizes; ++i)
1425 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1427 /* clear all the free lists */
1428 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1429 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1431 for (j = 0; j < num_block_obj_sizes; ++j)
1432 free_blocks [j] = NULL;
1435 sgen_array_list_remove_nulls (&allocated_blocks);
1438 static void sweep_finish (void);
1441 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1442 * the checking has finished.
1444 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1445 * be correct, i.e. must not be used.
1448 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1451 gboolean have_live = FALSE;
1452 gboolean have_free = FALSE;
1458 volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1460 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1463 *have_checked = FALSE;
1466 tagged_block = *(void * volatile *)block_slot;
1470 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1473 /* FIXME: do this more elegantly */
1478 if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1481 block = BLOCK_UNTAG (tagged_block);
1482 block_state = block->state;
1484 if (!sweep_in_progress ()) {
1485 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1487 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1490 switch (block_state) {
1491 case BLOCK_STATE_SWEPT:
1492 case BLOCK_STATE_NEED_SWEEPING:
1493 case BLOCK_STATE_SWEEPING:
1495 case BLOCK_STATE_MARKING:
1497 case BLOCK_STATE_CHECKING:
1498 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1501 SGEN_ASSERT (0, FALSE, "Illegal block state");
1505 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1506 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1509 *have_checked = TRUE;
1511 block->has_pinned = block->pinned;
1513 block->is_to_space = FALSE;
1515 count = MS_BLOCK_FREE / block->obj_size;
1517 if (block->cardtable_mod_union)
1518 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1520 /* Count marked objects in the block */
1521 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1522 nused += bitcount (block->mark_words [i]);
1524 block->nused = nused;
1531 int obj_size_index = block->obj_size_index;
1532 gboolean has_pinned = block->has_pinned;
1534 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1537 * FIXME: Go straight to SWEPT if there are no free slots. We need
1538 * to set the free slot list to NULL, though, and maybe update some
1542 sweep_block (block);
1545 ++sweep_num_blocks [obj_size_index];
1546 sweep_slots_used [obj_size_index] += nused;
1547 sweep_slots_available [obj_size_index] += count;
1551 * If there are free slots in the block, add
1552 * the block to the corresponding free list.
1555 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1558 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1560 add_free_block (free_blocks, obj_size_index, block);
1563 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1564 update_heap_boundaries_for_block (block);
1567 * Blocks without live objects are removed from the
1568 * block list and freed.
1570 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1571 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1573 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1574 ms_free_block (block);
1576 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1578 tagged_block = NULL;
1583 * Once the block is written back without the checking bit other threads are
1584 * free to access it. Make sure the block state is visible before we write it
1587 mono_memory_write_barrier ();
1588 *block_slot = tagged_block;
1589 return !!tagged_block;
1593 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1595 volatile gpointer *slot;
1598 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1599 bl = BLOCK_UNTAG (*slot);
1602 } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1604 mono_memory_write_barrier ();
1606 sweep_blocks_job = NULL;
1610 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1612 guint32 block_index;
1613 guint32 num_blocks = num_major_sections_before_sweep;
1615 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1616 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1619 * We traverse the block array from high to low. Nursery collections will have to
1620 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1621 * low to high, to avoid constantly colliding on the same blocks.
1623 for (block_index = num_blocks; block_index-- > 0;) {
1625 * The block might have been freed by another thread doing some checking
1628 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL))
1629 ++num_major_sections_freed_in_sweep;
1632 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1634 * The main GC thread is currently iterating over the block array to help us
1635 * finish the sweep. We have already finished, but we don't want to mess up
1636 * that iteration, so we just wait for it.
1641 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1642 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1643 MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1644 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1649 * Concurrently sweep all the blocks to reduce workload during minor
1650 * pauses where we need certain blocks to be swept. At the start of
1651 * the next major we need all blocks to be swept anyway.
1653 if (concurrent_sweep && lazy_sweep) {
1654 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1655 sgen_thread_pool_job_enqueue (sweep_blocks_job);
1666 mword used_slots_size = 0;
1669 for (i = 0; i < num_block_obj_sizes; ++i) {
1670 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1671 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1672 evacuate_block_obj_sizes [i] = TRUE;
1674 g_print ("slot size %d - %d of %d used\n",
1675 block_obj_sizes [i], slots_used [i], slots_available [i]);
1678 evacuate_block_obj_sizes [i] = FALSE;
1681 used_slots_size += sweep_slots_used [i] * block_obj_sizes [i];
1684 sgen_memgov_major_post_sweep (used_slots_size);
1686 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1687 if (concurrent_sweep)
1688 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1694 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1698 SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1700 num_major_sections_before_sweep = num_major_sections;
1701 num_major_sections_freed_in_sweep = 0;
1703 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1704 if (concurrent_sweep) {
1705 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1706 sgen_thread_pool_job_enqueue (sweep_job);
1708 sweep_job_func (NULL, NULL);
1713 major_have_swept (void)
1715 return sweep_state == SWEEP_STATE_SWEPT;
1718 static int count_pinned_ref;
1719 static int count_pinned_nonref;
1720 static int count_nonpinned_ref;
1721 static int count_nonpinned_nonref;
1724 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1726 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1728 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1729 ++count_nonpinned_ref;
1731 ++count_nonpinned_nonref;
1735 count_pinned_callback (GCObject *obj, size_t size, void *data)
1737 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1739 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1742 ++count_pinned_nonref;
1745 static G_GNUC_UNUSED void
1746 count_ref_nonref_objs (void)
1750 count_pinned_ref = 0;
1751 count_pinned_nonref = 0;
1752 count_nonpinned_ref = 0;
1753 count_nonpinned_nonref = 0;
1755 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1756 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1758 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1760 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1761 count_pinned_ref, count_nonpinned_ref,
1762 count_pinned_nonref, count_nonpinned_nonref,
1763 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1767 ms_calculate_block_obj_sizes (double factor, int *arr)
1774 * Have every possible slot size starting with the minimal
1775 * object size up to and including four times that size. Then
1776 * proceed by increasing geometrically with the given factor.
1779 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1781 arr [num_sizes] = size;
1785 target_size = (double)last_size;
1788 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1789 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1791 if (size != last_size) {
1793 arr [num_sizes] = size;
1798 target_size *= factor;
1799 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1804 /* only valid during minor collections */
1805 static mword old_num_major_sections;
1808 major_start_nursery_collection (void)
1810 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1811 consistency_check ();
1814 old_num_major_sections = num_major_sections;
1818 major_finish_nursery_collection (void)
1820 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1821 consistency_check ();
1826 block_usage_comparer (const void *bl1, const void *bl2)
1828 const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
1829 const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
1831 return nused2 - nused1;
1835 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1837 MSBlockInfo **evacuated_blocks;
1838 size_t index = 0, count, num_blocks = 0, num_used = 0;
1840 MSBlockInfo * volatile *prev;
1842 for (info = *block_list; info != NULL; info = info->next_free) {
1844 num_used += info->nused;
1848 * We have a set of blocks in the freelist which will be evacuated. Instead
1849 * of evacuating all of the blocks into new ones, we traverse the freelist
1850 * sorting it by the number of occupied slots, evacuating the objects from
1851 * blocks with fewer used slots into fuller blocks.
1853 * The number of used slots is set at the end of the previous sweep. Since
1854 * we sequentially unlink slots from blocks, except for the head of the
1855 * freelist, for blocks on the freelist, the number of used slots is the same
1856 * as at the end of the previous sweep.
1858 evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
1860 for (info = *block_list; info != NULL; info = info->next_free) {
1861 evacuated_blocks [index++] = info;
1864 SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
1866 sgen_qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
1869 * Form a new freelist with the fullest blocks. These blocks will also be
1870 * marked as to_space so we don't evacuate from them.
1872 count = MS_BLOCK_FREE / block_obj_sizes [size_index];
1874 for (index = 0; index < (num_used + count - 1) / count; index++) {
1875 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
1876 info = evacuated_blocks [index];
1877 info->is_to_space = TRUE;
1879 prev = &info->next_free;
1883 sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
1887 major_start_major_collection (void)
1892 major_finish_sweep_checking ();
1895 * Clear the free lists for block sizes where we do evacuation. For those block
1896 * sizes we will have to allocate new blocks.
1898 for (i = 0; i < num_block_obj_sizes; ++i) {
1899 if (!evacuate_block_obj_sizes [i])
1902 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
1904 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
1905 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
1908 if (lazy_sweep && concurrent_sweep) {
1910 * sweep_blocks_job is created before sweep_finish, which we wait for above
1911 * (major_finish_sweep_checking). After the end of sweep, if we don't have
1912 * sweep_blocks_job set, it means that it has already been run.
1914 SgenThreadPoolJob *job = sweep_blocks_job;
1916 sgen_thread_pool_job_wait (job);
1919 if (lazy_sweep && !concurrent_sweep)
1920 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
1921 /* Sweep all unswept blocks and set them to MARKING */
1922 FOREACH_BLOCK_NO_LOCK (block) {
1923 if (lazy_sweep && !concurrent_sweep)
1924 sweep_block (block);
1925 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1926 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1928 * Swept blocks that have a null free_list are full. Evacuation is not
1929 * effective on these blocks since we expect them to have high usage anyway,
1930 * given that the survival rate for majors is relatively high.
1932 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
1933 block->is_to_space = TRUE;
1934 } END_FOREACH_BLOCK_NO_LOCK;
1935 if (lazy_sweep && !concurrent_sweep)
1936 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
1938 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1942 major_finish_major_collection (ScannedObjectCounts *counts)
1944 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1945 if (binary_protocol_is_enabled ()) {
1946 counts->num_scanned_objects = scanned_objects_list.next_slot;
1948 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1949 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1951 sgen_pointer_queue_clear (&scanned_objects_list);
1956 #if SIZEOF_VOID_P != 8
1958 compare_pointers (const void *va, const void *vb) {
1959 char *a = *(char**)va, *b = *(char**)vb;
1969 * This is called with sweep completed and the world stopped.
1972 major_free_swept_blocks (size_t allowance)
1974 /* FIXME: This is probably too much. It's assuming all objects are small. */
1975 size_t section_reserve = allowance / MS_BLOCK_SIZE;
1977 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1981 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1982 * a VirtualAlloc ()-ed block.
1987 #if SIZEOF_VOID_P != 8
1989 int i, num_empty_blocks_orig, num_blocks, arr_length;
1991 void **empty_block_arr;
1992 void **rebuild_next;
1994 if (num_empty_blocks <= section_reserve)
1996 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1998 num_empty_blocks_orig = num_empty_blocks;
1999 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
2000 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
2001 if (!empty_block_arr)
2005 for (block = empty_blocks; block; block = *(void**)block)
2006 empty_block_arr [i++] = block;
2007 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
2009 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
2012 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
2013 * contiguous ones. If we do, we free them. If that's not enough to get to
2014 * section_reserve, we halve the number of contiguous blocks we're looking
2015 * for and have another go, until we're done with looking for pairs of
2016 * blocks, at which point we give up and go to the fallback.
2018 arr_length = num_empty_blocks_orig;
2019 num_blocks = MS_BLOCK_ALLOC_NUM;
2020 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2025 for (i = 0; i < arr_length; ++i) {
2027 void *block = empty_block_arr [i];
2028 SGEN_ASSERT (6, block, "we're not shifting correctly");
2030 empty_block_arr [dest] = block;
2032 * This is not strictly necessary, but we're
2035 empty_block_arr [i] = NULL;
2044 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2046 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
2051 if (d + 1 - first == num_blocks) {
2053 * We found num_blocks contiguous blocks. Free them
2054 * and null their array entries. As an optimization
2055 * we could, instead of nulling the entries, shift
2056 * the following entries over to the left, while
2060 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
2061 for (j = first; j <= d; ++j)
2062 empty_block_arr [j] = NULL;
2066 num_empty_blocks -= num_blocks;
2068 stat_major_blocks_freed += num_blocks;
2069 if (num_blocks == MS_BLOCK_ALLOC_NUM)
2070 stat_major_blocks_freed_ideal += num_blocks;
2072 stat_major_blocks_freed_less_ideal += num_blocks;
2077 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2079 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2084 /* rebuild empty_blocks free list */
2085 rebuild_next = (void**)&empty_blocks;
2086 for (i = 0; i < arr_length; ++i) {
2087 void *block = empty_block_arr [i];
2088 SGEN_ASSERT (6, block, "we're missing blocks");
2089 *rebuild_next = block;
2090 rebuild_next = (void**)block;
2092 *rebuild_next = NULL;
2095 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2098 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2102 * This is our threshold. If there's not more empty than used blocks, we won't
2103 * release uncontiguous blocks, in fear of fragmenting the address space.
2105 if (num_empty_blocks <= num_major_sections)
2109 while (num_empty_blocks > section_reserve) {
2110 void *next = *(void**)empty_blocks;
2111 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
2112 empty_blocks = next;
2114 * Needs not be atomic because this is running
2119 ++stat_major_blocks_freed;
2120 #if SIZEOF_VOID_P != 8
2121 ++stat_major_blocks_freed_individual;
2127 major_pin_objects (SgenGrayQueue *queue)
2131 FOREACH_BLOCK_NO_LOCK (block) {
2132 size_t first_entry, last_entry;
2133 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2134 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2135 &first_entry, &last_entry);
2136 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2137 } END_FOREACH_BLOCK_NO_LOCK;
2141 major_init_to_space (void)
2146 major_report_pinned_memory_usage (void)
2148 g_assert_not_reached ();
2152 major_get_used_size (void)
2158 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2159 * finished, then we can iterate over the block array.
2161 major_finish_sweep_checking ();
2163 FOREACH_BLOCK_NO_LOCK (block) {
2164 int count = MS_BLOCK_FREE / block->obj_size;
2166 size += count * block->obj_size;
2167 for (iter = block->free_list; iter; iter = (void**)*iter)
2168 size -= block->obj_size;
2169 } END_FOREACH_BLOCK_NO_LOCK;
2174 /* FIXME: return number of bytes, not of sections */
2176 get_num_major_sections (void)
2178 return num_major_sections;
2182 * Returns the number of bytes in blocks that were present when the last sweep was
2183 * initiated, and were not freed during the sweep. They are the basis for calculating the
2187 get_bytes_survived_last_sweep (void)
2189 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2190 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2194 major_handle_gc_param (const char *opt)
2196 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2197 const char *arg = strchr (opt, '=') + 1;
2198 int percentage = atoi (arg);
2199 if (percentage < 0 || percentage > 100) {
2200 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2203 evacuation_threshold = (float)percentage / 100.0f;
2205 } else if (!strcmp (opt, "lazy-sweep")) {
2208 } else if (!strcmp (opt, "no-lazy-sweep")) {
2211 } else if (!strcmp (opt, "concurrent-sweep")) {
2212 concurrent_sweep = TRUE;
2214 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2215 concurrent_sweep = FALSE;
2223 major_print_gc_param_usage (void)
2227 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2228 " (no-)lazy-sweep\n"
2229 " (no-)concurrent-sweep\n"
2234 * This callback is used to clear cards, move cards to the shadow table and do counting.
2237 major_iterate_block_ranges (sgen_cardtable_block_callback callback)
2240 gboolean has_references;
2242 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2244 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2245 } END_FOREACH_BLOCK_NO_LOCK;
2249 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2252 gboolean has_references;
2254 major_finish_sweep_checking ();
2255 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2257 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2258 } END_FOREACH_BLOCK_NO_LOCK;
2261 #ifdef HEAVY_STATISTICS
2262 extern guint64 marked_cards;
2263 extern guint64 scanned_cards;
2264 extern guint64 scanned_objects;
2265 extern guint64 remarked_cards;
2268 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2270 * MS blocks are 16K aligned.
2271 * Cardtables are 4K aligned, at least.
2272 * This means that the cardtable of a given block is 32 bytes aligned.
2275 initial_skip_card (guint8 *card_data)
2277 mword *cards = (mword*)card_data;
2280 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2286 if (i == CARD_WORDS_PER_BLOCK)
2287 return card_data + CARDS_PER_BLOCK;
2289 #if defined(__i386__) && defined(__GNUC__)
2290 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2291 #elif defined(__x86_64__) && defined(__GNUC__)
2292 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2293 #elif defined(__s390x__) && defined(__GNUC__)
2294 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2296 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2298 return &card_data [i];
2304 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2305 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2306 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2309 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2311 SgenGrayQueue *queue = ctx.queue;
2312 ScanObjectFunc scan_func = ctx.ops->scan_object;
2313 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2314 guint8 cards_copy [CARDS_PER_BLOCK];
2316 guint8 cards_preclean [CARDS_PER_BLOCK];
2317 gboolean small_objects;
2320 guint8 *card_data, *card_base;
2321 guint8 *card_data_end;
2322 char *scan_front = NULL;
2324 /* The concurrent mark doesn't enter evacuating blocks */
2325 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2328 block_obj_size = block->obj_size;
2329 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2331 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2334 * This is safe in face of card aliasing for the following reason:
2336 * Major blocks are 16k aligned, or 32 cards aligned.
2337 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2338 * sizes, they won't overflow the cardtable overlap modulus.
2340 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2341 card_data = card_base = block->cardtable_mod_union;
2343 * This happens when the nursery collection that precedes finishing
2344 * the concurrent collection allocates new major blocks.
2349 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2350 sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2351 card_data = card_base = cards_preclean;
2354 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2355 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2357 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2359 card_data = card_base = cards_copy;
2362 card_data_end = card_data + CARDS_PER_BLOCK;
2364 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2366 card_data = initial_skip_card (card_data);
2367 while (card_data < card_data_end) {
2368 size_t card_index, first_object_index;
2371 char *first_obj, *obj;
2373 HEAVY_STAT (++scanned_cards);
2380 card_index = card_data - card_base;
2381 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2382 end = start + CARD_SIZE_IN_BYTES;
2384 if (!block_is_swept_or_marking (block))
2385 sweep_block (block);
2387 HEAVY_STAT (++marked_cards);
2390 sgen_card_table_prepare_card_for_scanning (card_data);
2393 * If the card we're looking at starts at or in the block header, we
2394 * must start at the first object in the block, without calculating
2395 * the index of the object we're hypothetically starting at, because
2396 * it would be negative.
2398 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2399 first_object_index = 0;
2401 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2403 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2405 binary_protocol_card_scan (first_obj, end - first_obj);
2408 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2411 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2412 /* FIXME: do this more efficiently */
2414 MS_CALC_MARK_BIT (w, b, obj);
2415 if (!MS_MARK_BIT (block, w, b))
2419 GCObject *object = (GCObject*)obj;
2421 if (small_objects) {
2422 HEAVY_STAT (++scanned_objects);
2423 scan_func (object, sgen_obj_get_descriptor (object), queue);
2425 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2426 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2429 obj += block_obj_size;
2430 g_assert (scan_front <= obj);
2434 HEAVY_STAT (if (*card_data) ++remarked_cards);
2439 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2444 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx)
2447 gboolean has_references, was_sweeping, skip_scan;
2449 if (!concurrent_mark)
2450 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2452 if (scan_type != CARDTABLE_SCAN_GLOBAL)
2453 SGEN_ASSERT (0, !sweep_in_progress (), "Sweep should be finished when we scan mod union card table");
2454 was_sweeping = sweep_in_progress ();
2456 binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2457 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2458 #ifdef PREFETCH_CARDS
2459 int prefetch_index = __index + 6;
2460 if (prefetch_index < allocated_blocks.next_slot) {
2461 MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2462 PREFETCH_READ (prefetch_block);
2463 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2464 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2465 PREFETCH_WRITE (prefetch_cards);
2466 PREFETCH_WRITE (prefetch_cards + 32);
2471 if (!has_references)
2475 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2476 gpointer *card_start = (gpointer*) sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2477 gboolean has_dirty_cards = FALSE;
2479 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2480 if (card_start [i]) {
2481 has_dirty_cards = TRUE;
2485 if (!has_dirty_cards) {
2489 * After the start of the concurrent collections, blocks change state
2490 * to marking. We should not sweep it in that case. We can't race with
2491 * sweep start since we are in a nursery collection. Also avoid CAS-ing
2493 if (sweep_in_progress ()) {
2494 skip_scan = !ensure_block_is_checked_for_sweeping (__index, TRUE, NULL);
2495 } else if (was_sweeping) {
2496 /* Recheck in case sweep finished after dereferencing the slot */
2497 skip_scan = *sgen_array_list_get_slot (&allocated_blocks, __index) == 0;
2502 scan_card_table_for_block (block, scan_type, ctx);
2503 } END_FOREACH_BLOCK_NO_LOCK;
2504 binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2508 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2511 gboolean has_references;
2512 long long total_cards = 0;
2513 long long marked_cards = 0;
2515 if (sweep_in_progress ()) {
2516 *num_total_cards = -1;
2517 *num_marked_cards = -1;
2521 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2522 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2525 if (!has_references)
2528 total_cards += CARDS_PER_BLOCK;
2529 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2533 } END_FOREACH_BLOCK_NO_LOCK;
2535 *num_total_cards = total_cards;
2536 *num_marked_cards = marked_cards;
2540 update_cardtable_mod_union (void)
2544 FOREACH_BLOCK_NO_LOCK (block) {
2545 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2546 gboolean has_dirty_cards = FALSE;
2548 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2549 if (card_start [i]) {
2550 has_dirty_cards = TRUE;
2554 if (has_dirty_cards) {
2556 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2557 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2558 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2560 } END_FOREACH_BLOCK_NO_LOCK;
2563 #undef pthread_create
2566 post_param_init (SgenMajorCollector *collector)
2568 collector->sweeps_lazily = lazy_sweep;
2569 collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2573 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2577 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2579 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2580 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2581 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2583 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2584 for (i = 0; i < num_block_obj_sizes; ++i)
2585 evacuate_block_obj_sizes [i] = FALSE;
2587 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2588 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2589 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2594 g_print ("block object sizes:\n");
2595 for (i = 0; i < num_block_obj_sizes; ++i)
2596 g_print ("%d\n", block_obj_sizes [i]);
2600 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2601 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2603 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2604 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2605 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2606 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2608 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2609 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2610 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2611 #if SIZEOF_VOID_P != 8
2612 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2613 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2614 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2615 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2618 collector->section_size = MAJOR_SECTION_SIZE;
2620 concurrent_mark = is_concurrent;
2621 collector->is_concurrent = is_concurrent;
2622 collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2623 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2624 collector->supports_cardtable = TRUE;
2626 collector->alloc_heap = major_alloc_heap;
2627 collector->is_object_live = major_is_object_live;
2628 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2629 collector->alloc_degraded = major_alloc_degraded;
2631 collector->alloc_object = major_alloc_object;
2632 collector->free_pinned_object = free_pinned_object;
2633 collector->iterate_objects = major_iterate_objects;
2634 collector->free_non_pinned_object = major_free_non_pinned_object;
2635 collector->pin_objects = major_pin_objects;
2636 collector->pin_major_object = pin_major_object;
2637 collector->scan_card_table = major_scan_card_table;
2638 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2639 collector->iterate_block_ranges = major_iterate_block_ranges;
2640 if (is_concurrent) {
2641 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2642 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2644 collector->init_to_space = major_init_to_space;
2645 collector->sweep = major_sweep;
2646 collector->have_swept = major_have_swept;
2647 collector->finish_sweeping = major_finish_sweep_checking;
2648 collector->free_swept_blocks = major_free_swept_blocks;
2649 collector->check_scan_starts = major_check_scan_starts;
2650 collector->dump_heap = major_dump_heap;
2651 collector->get_used_size = major_get_used_size;
2652 collector->start_nursery_collection = major_start_nursery_collection;
2653 collector->finish_nursery_collection = major_finish_nursery_collection;
2654 collector->start_major_collection = major_start_major_collection;
2655 collector->finish_major_collection = major_finish_major_collection;
2656 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2657 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2658 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2659 collector->get_num_major_sections = get_num_major_sections;
2660 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2661 collector->handle_gc_param = major_handle_gc_param;
2662 collector->print_gc_param_usage = major_print_gc_param_usage;
2663 collector->post_param_init = post_param_init;
2664 collector->is_valid_object = major_is_valid_object;
2665 collector->describe_pointer = major_describe_pointer;
2666 collector->count_cards = major_count_cards;
2668 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2669 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2670 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2671 if (is_concurrent) {
2672 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2673 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2674 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2675 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2676 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2678 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2679 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2680 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2681 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2682 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2685 #ifdef HEAVY_STATISTICS
2686 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2687 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2688 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2689 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2690 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2691 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2692 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2693 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2694 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2695 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2696 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2698 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2699 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2700 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2703 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2704 mono_os_mutex_init (&scanned_objects_list_lock);
2707 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2709 /*cardtable requires major pages to be 8 cards aligned*/
2710 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2714 sgen_marksweep_init (SgenMajorCollector *collector)
2716 sgen_marksweep_init_internal (collector, FALSE);
2720 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2722 sgen_marksweep_init_internal (collector, TRUE);