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 = FALSE;
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;
197 #define FOREACH_BLOCK_NO_LOCK(bl) { \
198 volatile gpointer *slot; \
199 SGEN_ASSERT (0, !sweep_in_progress (), "Can't iterate blocks while sweep is in progress."); \
200 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
201 (bl) = BLOCK_UNTAG (*slot);
202 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
203 volatile gpointer *slot; \
204 SGEN_ASSERT (0, !sweep_in_progress (), "Can't iterate blocks while sweep is in progress."); \
205 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
206 (bl) = (MSBlockInfo *) (*slot); \
207 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
208 (bl) = BLOCK_UNTAG ((bl));
209 #define END_FOREACH_BLOCK_NO_LOCK } SGEN_ARRAY_LIST_END_FOREACH_SLOT; }
211 static volatile size_t num_major_sections = 0;
213 * One free block list for each block object size. We add and remove blocks from these
214 * lists lock-free via CAS.
216 * Blocks accessed/removed from `free_block_lists`:
217 * from the mutator (with GC lock held)
218 * in nursery collections
219 * in non-concurrent major collections
220 * in the finishing pause of concurrent major collections (whole list is cleared)
222 * Blocks added to `free_block_lists`:
223 * in the sweeping thread
224 * during nursery collections
225 * from domain clearing (with the world stopped and no sweeping happening)
227 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
228 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
230 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
232 static guint64 stat_major_blocks_alloced = 0;
233 static guint64 stat_major_blocks_freed = 0;
234 static guint64 stat_major_blocks_lazy_swept = 0;
236 #if SIZEOF_VOID_P != 8
237 static guint64 stat_major_blocks_freed_ideal = 0;
238 static guint64 stat_major_blocks_freed_less_ideal = 0;
239 static guint64 stat_major_blocks_freed_individual = 0;
240 static guint64 stat_major_blocks_alloced_less_ideal = 0;
243 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
244 static guint64 num_major_objects_marked = 0;
245 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
247 #define INC_NUM_MAJOR_OBJECTS_MARKED()
250 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
251 static mono_mutex_t scanned_objects_list_lock;
252 static SgenPointerQueue scanned_objects_list;
255 add_scanned_object (void *ptr)
257 if (!binary_protocol_is_enabled ())
260 mono_os_mutex_lock (&scanned_objects_list_lock);
261 sgen_pointer_queue_add (&scanned_objects_list, ptr);
262 mono_os_mutex_unlock (&scanned_objects_list_lock);
266 static gboolean sweep_block (MSBlockInfo *block);
269 ms_find_block_obj_size_index (size_t size)
272 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);
273 for (i = 0; i < num_block_obj_sizes; ++i)
274 if (block_obj_sizes [i] >= size)
276 g_error ("no object of size %zd\n", size);
280 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
281 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
283 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
284 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
285 fast_block_obj_size_indexes [((s)+7)>>3] : \
286 ms_find_block_obj_size_index ((s)))
289 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
293 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
295 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
301 update_heap_boundaries_for_block (MSBlockInfo *block)
303 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
310 ms_get_empty_block (void)
314 void *block, *empty, *next;
319 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
320 * unsuccessful, we halve the number of blocks and try again, until we're at
321 * 1. If that doesn't work, either, we assert.
323 int alloc_num = MS_BLOCK_ALLOC_NUM;
325 p = (char *)sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE,
326 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
327 alloc_num == 1 ? "major heap section" : NULL);
333 for (i = 0; i < alloc_num; ++i) {
336 * We do the free list update one after the
337 * other so that other threads can use the new
338 * blocks as quickly as possible.
341 empty = empty_blocks;
342 *(void**)block = empty;
343 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
347 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
349 stat_major_blocks_alloced += alloc_num;
350 #if SIZEOF_VOID_P != 8
351 if (alloc_num != MS_BLOCK_ALLOC_NUM)
352 stat_major_blocks_alloced_less_ideal += alloc_num;
357 empty = empty_blocks;
361 next = *(void**)block;
362 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
364 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
366 *(void**)block = NULL;
368 g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
374 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
375 * list, where it will either be freed later on, or reused in nursery collections.
378 ms_free_block (void *block)
382 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
383 memset (block, 0, MS_BLOCK_SIZE);
386 empty = empty_blocks;
387 *(void**)block = empty;
388 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
390 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
392 binary_protocol_block_free (block, MS_BLOCK_SIZE);
396 sweep_in_progress (void)
398 int state = sweep_state;
399 return state == SWEEP_STATE_SWEEPING ||
400 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
401 state == SWEEP_STATE_COMPACTING;
404 static inline gboolean
405 block_is_swept_or_marking (MSBlockInfo *block)
407 gint32 state = block->state;
408 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
411 //#define MARKSWEEP_CONSISTENCY_CHECK
413 #ifdef MARKSWEEP_CONSISTENCY_CHECK
415 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
417 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
418 for (; block; block = block->next_free) {
419 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
420 g_assert (block->obj_size == size);
421 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
423 /* blocks in the free lists must have at least
425 g_assert (block->free_list);
427 /* the block must be in the allocated_blocks array */
428 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
433 check_empty_blocks (void)
437 for (p = empty_blocks; p; p = *(void**)p)
439 g_assert (i == num_empty_blocks);
443 consistency_check (void)
448 /* check all blocks */
449 FOREACH_BLOCK_NO_LOCK (block) {
450 int count = MS_BLOCK_FREE / block->obj_size;
454 /* count number of free slots */
455 for (i = 0; i < count; ++i) {
456 void **obj = (void**) MS_BLOCK_OBJ (block, i);
457 if (!MS_OBJ_ALLOCED (obj, block))
461 /* check free list */
462 for (free = block->free_list; free; free = (void**)*free) {
463 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
466 g_assert (num_free == 0);
468 /* check all mark words are zero */
469 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
470 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
471 g_assert (block->mark_words [i] == 0);
473 } END_FOREACH_BLOCK_NO_LOCK;
475 /* check free blocks */
476 for (i = 0; i < num_block_obj_sizes; ++i) {
478 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
479 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
482 check_empty_blocks ();
487 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
491 block->next_free = old = free_blocks [size_index];
492 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
495 static void major_finish_sweep_checking (void);
498 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
500 int size = block_obj_sizes [size_index];
501 int count = MS_BLOCK_FREE / size;
503 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
507 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
510 info = (MSBlockInfo*)ms_get_empty_block ();
512 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
514 info->obj_size = size;
515 info->obj_size_index = size_index;
516 info->pinned = pinned;
517 info->has_references = has_references;
518 info->has_pinned = pinned;
520 * Blocks that are to-space are not evacuated from. During an major collection
521 * blocks are allocated for two reasons: evacuating objects from the nursery and
522 * evacuating them from major blocks marked for evacuation. In both cases we don't
523 * want further evacuation. We also don't want to evacuate objects allocated during
524 * the concurrent mark since it would add pointless stress on the finishing pause.
526 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
527 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
528 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
529 info->cardtable_mod_union = NULL;
531 update_heap_boundaries_for_block (info);
533 binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
535 /* build free list */
536 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
537 info->free_list = (void**)obj_start;
538 /* we're skipping the last one - it must be nulled */
539 for (i = 0; i < count - 1; ++i) {
540 char *next_obj_start = obj_start + size;
541 *(void**)obj_start = next_obj_start;
542 obj_start = next_obj_start;
545 *(void**)obj_start = NULL;
547 add_free_block (free_blocks, size_index, info);
550 * Adding to the allocated_blocks array is racy with the removal of nulls when
551 * sweeping. We wait for sweep to finish to avoid that.
553 * The memory barrier here and in `sweep_job_func()` are required because we need
554 * `allocated_blocks` synchronized between this and the sweep thread.
556 major_finish_sweep_checking ();
557 mono_memory_barrier ();
559 sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
561 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
566 ptr_is_from_pinned_alloc (char *ptr)
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 return block->pinned;
573 } END_FOREACH_BLOCK_NO_LOCK;
578 ensure_can_access_block_free_list (MSBlockInfo *block)
582 switch (block->state) {
583 case BLOCK_STATE_SWEPT:
584 case BLOCK_STATE_MARKING:
586 case BLOCK_STATE_CHECKING:
587 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
589 case BLOCK_STATE_NEED_SWEEPING:
590 if (sweep_block (block))
591 ++stat_major_blocks_lazy_swept;
593 case BLOCK_STATE_SWEEPING:
594 /* FIXME: do this more elegantly */
598 SGEN_ASSERT (0, FALSE, "Illegal block state");
605 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
607 MSBlockInfo *block, *next_free_block;
608 void *obj, *next_free_slot;
611 block = free_blocks [size_index];
612 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
614 ensure_can_access_block_free_list (block);
616 obj = block->free_list;
617 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
619 next_free_slot = *(void**)obj;
620 if (next_free_slot) {
621 block->free_list = (gpointer *)next_free_slot;
625 next_free_block = block->next_free;
626 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
629 block->free_list = NULL;
630 block->next_free = NULL;
636 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
638 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
639 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
642 if (!free_blocks [size_index]) {
643 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
647 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
649 /* FIXME: assumes object layout */
650 *(GCVTable*)obj = vtable;
652 return (GCObject *)obj;
656 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
658 return alloc_obj (vtable, size, FALSE, has_references);
662 * We're not freeing the block if it's empty. We leave that work for
663 * the next major collection.
665 * This is just called from the domain clearing code, which runs in a
666 * single thread and has the GC lock, so we don't need an extra lock.
669 free_object (GCObject *obj, size_t size, gboolean pinned)
671 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
673 gboolean in_free_list;
675 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
677 ensure_can_access_block_free_list (block);
678 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);
679 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
680 MS_CALC_MARK_BIT (word, bit, obj);
681 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
683 memset (obj, 0, size);
685 in_free_list = !!block->free_list;
686 *(void**)obj = block->free_list;
687 block->free_list = (void**)obj;
690 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
691 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
692 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);
693 add_free_block (free_blocks, size_index, block);
698 major_free_non_pinned_object (GCObject *obj, size_t size)
700 free_object (obj, size, FALSE);
703 /* size is a multiple of SGEN_ALLOC_ALIGN */
705 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
709 res = alloc_obj (vtable, size, TRUE, has_references);
710 /*If we failed to alloc memory, we better try releasing memory
711 *as pinned alloc is requested by the runtime.
714 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
715 res = alloc_obj (vtable, size, TRUE, has_references);
717 return (GCObject *)res;
721 free_pinned_object (GCObject *obj, size_t size)
723 free_object (obj, size, TRUE);
727 * size is already rounded up and we hold the GC lock.
730 major_alloc_degraded (GCVTable vtable, size_t size)
734 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
735 if (G_LIKELY (obj)) {
736 HEAVY_STAT (++stat_objects_alloced_degraded);
737 HEAVY_STAT (stat_bytes_alloced_degraded += size);
743 * obj is some object. If it's not in the major heap (i.e. if it's in
744 * the nursery or LOS), return FALSE. Otherwise return whether it's
745 * been marked or copied.
748 major_is_object_live (GCObject *obj)
754 if (sgen_ptr_in_nursery (obj))
757 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
760 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
763 /* now we know it's in a major block */
764 block = MS_BLOCK_FOR_OBJ (obj);
765 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
766 MS_CALC_MARK_BIT (word, bit, obj);
767 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
771 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
775 FOREACH_BLOCK_NO_LOCK (block) {
776 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
777 int count = MS_BLOCK_FREE / block->obj_size;
781 for (i = 0; i <= count; ++i) {
782 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
783 *start = (char *)MS_BLOCK_OBJ (block, i);
787 return !block->pinned;
789 } END_FOREACH_BLOCK_NO_LOCK;
794 try_set_sweep_state (int new_, int expected)
796 int old = SGEN_CAS (&sweep_state, new_, expected);
797 return old == expected;
801 set_sweep_state (int new_, int expected)
803 gboolean success = try_set_sweep_state (new_, expected);
804 SGEN_ASSERT (0, success, "Could not set sweep state.");
807 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
809 static SgenThreadPoolJob * volatile sweep_job;
812 major_finish_sweep_checking (void)
815 SgenThreadPoolJob *job;
818 switch (sweep_state) {
819 case SWEEP_STATE_SWEPT:
820 case SWEEP_STATE_NEED_SWEEPING:
822 case SWEEP_STATE_SWEEPING:
823 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
826 case SWEEP_STATE_SWEEPING_AND_ITERATING:
827 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
829 case SWEEP_STATE_COMPACTING:
832 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
837 * We're running with the world stopped and the only other thread doing work is the
838 * sweep thread, which doesn't add blocks to the array, so we can safely access
841 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
842 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
844 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
849 sgen_thread_pool_job_wait (job);
850 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
851 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
855 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
857 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
858 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
859 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
862 major_finish_sweep_checking ();
863 FOREACH_BLOCK_NO_LOCK (block) {
864 int count = MS_BLOCK_FREE / block->obj_size;
867 if (block->pinned && !pinned)
869 if (!block->pinned && !non_pinned)
871 if (sweep && lazy_sweep) {
873 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
876 for (i = 0; i < count; ++i) {
877 void **obj = (void**) MS_BLOCK_OBJ (block, i);
879 * We've finished sweep checking, but if we're sweeping lazily and
880 * the flags don't require us to sweep, the block might still need
881 * sweeping. In that case, we need to consult the mark bits to tell
882 * us whether an object slot is live.
884 if (!block_is_swept_or_marking (block)) {
886 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
887 MS_CALC_MARK_BIT (word, bit, obj);
888 if (!MS_MARK_BIT (block, word, bit))
891 if (MS_OBJ_ALLOCED (obj, block))
892 callback ((GCObject*)obj, block->obj_size, data);
894 } END_FOREACH_BLOCK_NO_LOCK;
898 major_is_valid_object (char *object)
902 FOREACH_BLOCK_NO_LOCK (block) {
906 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
909 idx = MS_BLOCK_OBJ_INDEX (object, block);
910 obj = (char*)MS_BLOCK_OBJ (block, idx);
913 return MS_OBJ_ALLOCED (obj, block);
914 } END_FOREACH_BLOCK_NO_LOCK;
921 major_describe_pointer (char *ptr)
925 FOREACH_BLOCK_NO_LOCK (block) {
933 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
936 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
937 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
939 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
940 obj = (char*)MS_BLOCK_OBJ (block, idx);
941 live = MS_OBJ_ALLOCED (obj, block);
942 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
944 MS_CALC_MARK_BIT (w, b, obj);
945 marked = MS_MARK_BIT (block, w, b);
950 SGEN_LOG (0, "object");
952 SGEN_LOG (0, "dead-object");
955 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
957 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
960 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
963 } END_FOREACH_BLOCK_NO_LOCK;
969 major_check_scan_starts (void)
974 major_dump_heap (FILE *heap_dump_file)
977 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
978 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
981 for (i = 0; i < num_block_obj_sizes; ++i)
982 slots_available [i] = slots_used [i] = 0;
984 FOREACH_BLOCK_NO_LOCK (block) {
985 int index = ms_find_block_obj_size_index (block->obj_size);
986 int count = MS_BLOCK_FREE / block->obj_size;
988 slots_available [index] += count;
989 for (i = 0; i < count; ++i) {
990 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
991 ++slots_used [index];
993 } END_FOREACH_BLOCK_NO_LOCK;
995 fprintf (heap_dump_file, "<occupancies>\n");
996 for (i = 0; i < num_block_obj_sizes; ++i) {
997 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
998 block_obj_sizes [i], slots_available [i], slots_used [i]);
1000 fprintf (heap_dump_file, "</occupancies>\n");
1002 FOREACH_BLOCK_NO_LOCK (block) {
1003 int count = MS_BLOCK_FREE / block->obj_size;
1007 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1009 for (i = 0; i <= count; ++i) {
1010 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1015 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1021 fprintf (heap_dump_file, "</section>\n");
1022 } END_FOREACH_BLOCK_NO_LOCK;
1026 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1028 guint8 *mod_union = block->cardtable_mod_union;
1034 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1035 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1037 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1040 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1044 static inline guint8*
1045 major_get_cardtable_mod_union_for_reference (char *ptr)
1047 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1048 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1049 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1050 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1051 return &mod_union [offset];
1055 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1058 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1060 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1061 if (sgen_safe_object_is_small (obj, type)) {
1062 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1063 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?");
1066 sgen_los_mark_mod_union_card (obj, ptr);
1068 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1071 static inline gboolean
1072 major_block_is_evacuating (MSBlockInfo *block)
1074 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1075 !block->has_pinned &&
1076 !block->is_to_space)
1081 #define LOAD_VTABLE SGEN_LOAD_VTABLE
1083 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do { \
1084 int __word, __bit; \
1085 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1086 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
1087 MS_SET_MARK_BIT ((block), __word, __bit); \
1088 if (sgen_gc_descr_has_references (desc)) \
1089 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1090 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1091 INC_NUM_MAJOR_OBJECTS_MARKED (); \
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)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 #define GCC_VERSION (__GNUC__ * 10000 \
1142 + __GNUC_MINOR__ * 100 \
1143 + __GNUC_PATCHLEVEL__)
1144 #if GCC_VERSION <= 40300
1145 #undef PREFETCH_CARDS
1149 #ifdef HEAVY_STATISTICS
1150 static guint64 stat_optimized_copy;
1151 static guint64 stat_optimized_copy_nursery;
1152 static guint64 stat_optimized_copy_nursery_forwarded;
1153 static guint64 stat_optimized_copy_nursery_pinned;
1154 static guint64 stat_optimized_copy_major;
1155 static guint64 stat_optimized_copy_major_small_fast;
1156 static guint64 stat_optimized_copy_major_small_slow;
1157 static guint64 stat_optimized_copy_major_large;
1158 static guint64 stat_optimized_copy_major_forwarded;
1159 static guint64 stat_optimized_copy_major_small_evacuate;
1160 static guint64 stat_optimized_major_scan;
1161 static guint64 stat_optimized_major_scan_no_refs;
1163 static guint64 stat_drain_prefetch_fills;
1164 static guint64 stat_drain_prefetch_fill_failures;
1165 static guint64 stat_drain_loops;
1168 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1169 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1170 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1171 #include "sgen-marksweep-drain-gray-stack.h"
1173 #define COPY_OR_MARK_WITH_EVACUATION
1174 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1175 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1176 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_with_evacuation
1177 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1178 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_with_evacuation
1179 #include "sgen-marksweep-drain-gray-stack.h"
1181 #define COPY_OR_MARK_CONCURRENT
1182 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1183 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1184 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1185 #include "sgen-marksweep-drain-gray-stack.h"
1187 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1188 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1189 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1190 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_with_evacuation
1191 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_with_evacuation
1192 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1193 #include "sgen-marksweep-drain-gray-stack.h"
1195 static inline gboolean
1196 major_is_evacuating (void)
1199 for (i = 0; i < num_block_obj_sizes; ++i) {
1200 if (evacuate_block_obj_sizes [i]) {
1209 drain_gray_stack (SgenGrayQueue *queue)
1211 if (major_is_evacuating ())
1212 return drain_gray_stack_with_evacuation (queue);
1214 return drain_gray_stack_no_evacuation (queue);
1218 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1220 if (major_is_evacuating ())
1221 return drain_gray_stack_concurrent_with_evacuation (queue);
1223 return drain_gray_stack_concurrent_no_evacuation (queue);
1227 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1229 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1233 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1235 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1239 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1241 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1245 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1247 void **entry, **end;
1248 int last_index = -1;
1250 if (first_entry == last_entry)
1253 block->has_pinned = TRUE;
1255 entry = sgen_pinning_get_entry (first_entry);
1256 end = sgen_pinning_get_entry (last_entry);
1258 for (; entry < end; ++entry) {
1259 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1261 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));
1262 if (index == last_index)
1264 obj = MS_BLOCK_OBJ (block, index);
1265 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1271 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1275 for (obj_index = 0; obj_index < count; ++obj_index) {
1277 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1279 MS_CALC_MARK_BIT (word, bit, obj);
1280 if (MS_MARK_BIT (block, word, bit)) {
1281 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1283 /* an unmarked object */
1284 if (MS_OBJ_ALLOCED (obj, block)) {
1286 * FIXME: Merge consecutive
1287 * slots for lower reporting
1288 * overhead. Maybe memset
1289 * will also benefit?
1291 binary_protocol_empty (obj, obj_size);
1292 memset (obj, 0, obj_size);
1294 *(void**)obj = block->free_list;
1295 block->free_list = (void **)obj;
1300 static inline gboolean
1301 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1303 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1304 gboolean success = old_state == expected_state;
1306 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1311 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1313 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1314 block->state = new_state;
1318 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1320 * Sweeping means iterating through the block's slots and building the free-list from the
1321 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1324 sweep_block (MSBlockInfo *block)
1327 void *reversed = NULL;
1330 switch (block->state) {
1331 case BLOCK_STATE_SWEPT:
1333 case BLOCK_STATE_MARKING:
1334 case BLOCK_STATE_CHECKING:
1335 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1337 case BLOCK_STATE_SWEEPING:
1338 /* FIXME: Do this more elegantly */
1341 case BLOCK_STATE_NEED_SWEEPING:
1342 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1346 SGEN_ASSERT (0, FALSE, "Illegal block state");
1349 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1351 count = MS_BLOCK_FREE / block->obj_size;
1353 block->free_list = NULL;
1355 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1356 // FIXME: Add more sizes
1357 switch (block->obj_size) {
1359 sweep_block_for_size (block, count, 16);
1362 sweep_block_for_size (block, count, block->obj_size);
1366 /* reset mark bits */
1367 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1369 /* Reverse free list so that it's in address order */
1371 while (block->free_list) {
1372 void *next = *(void**)block->free_list;
1373 *(void**)block->free_list = reversed;
1374 reversed = block->free_list;
1375 block->free_list = (void **)next;
1377 block->free_list = (void **)reversed;
1379 mono_memory_write_barrier ();
1381 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1392 if (sizeof (mword) == 8)
1393 count += __builtin_popcountll (d);
1395 count += __builtin_popcount (d);
1405 /* statistics for evacuation */
1406 static size_t *sweep_slots_available;
1407 static size_t *sweep_slots_used;
1408 static size_t *sweep_num_blocks;
1410 static volatile size_t num_major_sections_before_sweep;
1411 static volatile size_t num_major_sections_freed_in_sweep;
1418 for (i = 0; i < num_block_obj_sizes; ++i)
1419 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1421 /* clear all the free lists */
1422 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1423 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1425 for (j = 0; j < num_block_obj_sizes; ++j)
1426 free_blocks [j] = NULL;
1430 static void sweep_finish (void);
1433 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1434 * the checking has finished.
1436 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1437 * be correct, i.e. must not be used.
1440 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1443 gboolean have_live = FALSE;
1444 gboolean have_free = FALSE;
1450 volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1452 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1455 *have_checked = FALSE;
1458 tagged_block = *(void * volatile *)block_slot;
1462 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1465 /* FIXME: do this more elegantly */
1470 if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1473 block = BLOCK_UNTAG (tagged_block);
1474 block_state = block->state;
1476 if (!sweep_in_progress ()) {
1477 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1479 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1482 switch (block_state) {
1483 case BLOCK_STATE_SWEPT:
1484 case BLOCK_STATE_NEED_SWEEPING:
1485 case BLOCK_STATE_SWEEPING:
1487 case BLOCK_STATE_MARKING:
1489 case BLOCK_STATE_CHECKING:
1490 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1493 SGEN_ASSERT (0, FALSE, "Illegal block state");
1497 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1498 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1501 *have_checked = TRUE;
1503 block->has_pinned = block->pinned;
1505 block->is_to_space = FALSE;
1507 count = MS_BLOCK_FREE / block->obj_size;
1509 if (block->cardtable_mod_union) {
1510 sgen_card_table_free_mod_union (block->cardtable_mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1511 block->cardtable_mod_union = NULL;
1514 /* Count marked objects in the block */
1515 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1516 nused += bitcount (block->mark_words [i]);
1518 block->nused = nused;
1525 int obj_size_index = block->obj_size_index;
1526 gboolean has_pinned = block->has_pinned;
1528 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1531 * FIXME: Go straight to SWEPT if there are no free slots. We need
1532 * to set the free slot list to NULL, though, and maybe update some
1536 sweep_block (block);
1539 ++sweep_num_blocks [obj_size_index];
1540 sweep_slots_used [obj_size_index] += nused;
1541 sweep_slots_available [obj_size_index] += count;
1545 * If there are free slots in the block, add
1546 * the block to the corresponding free list.
1549 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1552 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1554 add_free_block (free_blocks, obj_size_index, block);
1557 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1558 update_heap_boundaries_for_block (block);
1561 * Blocks without live objects are removed from the
1562 * block list and freed.
1564 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1565 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1567 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1568 ms_free_block (block);
1570 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1572 tagged_block = NULL;
1576 *block_slot = tagged_block;
1577 return !!tagged_block;
1581 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1583 guint32 block_index;
1584 guint32 num_blocks = num_major_sections_before_sweep;
1586 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1587 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1590 * We traverse the block array from high to low. Nursery collections will have to
1591 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1592 * low to high, to avoid constantly colliding on the same blocks.
1594 for (block_index = num_blocks; block_index-- > 0;) {
1596 * The block might have been freed by another thread doing some checking
1599 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL))
1600 ++num_major_sections_freed_in_sweep;
1603 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1605 * The main GC thread is currently iterating over the block array to help us
1606 * finish the sweep. We have already finished, but we don't want to mess up
1607 * that iteration, so we just wait for it.
1612 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1613 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1614 MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1615 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1619 sgen_array_list_remove_nulls (&allocated_blocks);
1631 for (i = 0; i < num_block_obj_sizes; ++i) {
1632 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1633 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1634 evacuate_block_obj_sizes [i] = TRUE;
1636 g_print ("slot size %d - %d of %d used\n",
1637 block_obj_sizes [i], slots_used [i], slots_available [i]);
1640 evacuate_block_obj_sizes [i] = FALSE;
1644 sgen_memgov_major_post_sweep ();
1646 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1652 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1656 SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1658 num_major_sections_before_sweep = num_major_sections;
1659 num_major_sections_freed_in_sweep = 0;
1661 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1662 if (concurrent_sweep) {
1663 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1664 sgen_thread_pool_job_enqueue (sweep_job);
1666 sweep_job_func (NULL, NULL);
1671 major_have_swept (void)
1673 return sweep_state == SWEEP_STATE_SWEPT;
1676 static int count_pinned_ref;
1677 static int count_pinned_nonref;
1678 static int count_nonpinned_ref;
1679 static int count_nonpinned_nonref;
1682 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1684 GCVTable vtable = LOAD_VTABLE (obj);
1686 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1687 ++count_nonpinned_ref;
1689 ++count_nonpinned_nonref;
1693 count_pinned_callback (GCObject *obj, size_t size, void *data)
1695 GCVTable vtable = LOAD_VTABLE (obj);
1697 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1700 ++count_pinned_nonref;
1703 static G_GNUC_UNUSED void
1704 count_ref_nonref_objs (void)
1708 count_pinned_ref = 0;
1709 count_pinned_nonref = 0;
1710 count_nonpinned_ref = 0;
1711 count_nonpinned_nonref = 0;
1713 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1714 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1716 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1718 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1719 count_pinned_ref, count_nonpinned_ref,
1720 count_pinned_nonref, count_nonpinned_nonref,
1721 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1725 ms_calculate_block_obj_sizes (double factor, int *arr)
1732 * Have every possible slot size starting with the minimal
1733 * object size up to and including four times that size. Then
1734 * proceed by increasing geometrically with the given factor.
1737 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1739 arr [num_sizes] = size;
1743 target_size = (double)last_size;
1746 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1747 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1749 if (size != last_size) {
1751 arr [num_sizes] = size;
1756 target_size *= factor;
1757 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1762 /* only valid during minor collections */
1763 static mword old_num_major_sections;
1766 major_start_nursery_collection (void)
1768 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1769 consistency_check ();
1772 old_num_major_sections = num_major_sections;
1776 major_finish_nursery_collection (void)
1778 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1779 consistency_check ();
1784 block_usage_comparer (const void *bl1, const void *bl2)
1786 const gint16 nused1 = ((MSBlockInfo*)bl1)->nused;
1787 const gint16 nused2 = ((MSBlockInfo*)bl2)->nused;
1789 return nused2 - nused1;
1793 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1795 MSBlockInfo **evacuated_blocks;
1796 size_t index = 0, count, num_blocks = 0, num_used = 0;
1798 MSBlockInfo * volatile *prev;
1800 for (info = *block_list; info != NULL; info = info->next_free) {
1802 num_used += info->nused;
1806 * We have a set of blocks in the freelist which will be evacuated. Instead
1807 * of evacuating all of the blocks into new ones, we traverse the freelist
1808 * sorting it by the number of occupied slots, evacuating the objects from
1809 * blocks with fewer used slots into fuller blocks.
1811 * The number of used slots is set at the end of the previous sweep. Since
1812 * we sequentially unlink slots from blocks, except for the head of the
1813 * freelist, for blocks on the freelist, the number of used slots is the same
1814 * as at the end of the previous sweep.
1816 evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
1818 for (info = *block_list; info != NULL; info = info->next_free) {
1819 evacuated_blocks [index++] = info;
1822 SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
1824 qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
1827 * Form a new freelist with the fullest blocks. These blocks will also be
1828 * marked as to_space so we don't evacuate from them.
1830 count = MS_BLOCK_FREE / block_obj_sizes [size_index];
1832 for (index = 0; index < (num_used + count - 1) / count; index++) {
1833 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
1834 info = evacuated_blocks [index];
1835 info->is_to_space = TRUE;
1837 prev = &info->next_free;
1841 sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
1845 major_start_major_collection (void)
1850 major_finish_sweep_checking ();
1853 * Clear the free lists for block sizes where we do evacuation. For those block
1854 * sizes we will have to allocate new blocks.
1856 for (i = 0; i < num_block_obj_sizes; ++i) {
1857 if (!evacuate_block_obj_sizes [i])
1860 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
1862 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
1863 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
1867 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
1869 /* Sweep all unswept blocks and set them to MARKING */
1870 FOREACH_BLOCK_NO_LOCK (block) {
1872 sweep_block (block);
1873 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1874 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1876 * Swept blocks that have a null free_list are full. Evacuation is not
1877 * effective on these blocks since we expect them to have high usage anyway,
1878 * given that the survival rate for majors is relatively high.
1880 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
1881 block->is_to_space = TRUE;
1882 } END_FOREACH_BLOCK_NO_LOCK;
1885 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
1887 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1891 major_finish_major_collection (ScannedObjectCounts *counts)
1893 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1894 if (binary_protocol_is_enabled ()) {
1895 counts->num_scanned_objects = scanned_objects_list.next_slot;
1897 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1898 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1900 sgen_pointer_queue_clear (&scanned_objects_list);
1905 #if SIZEOF_VOID_P != 8
1907 compare_pointers (const void *va, const void *vb) {
1908 char *a = *(char**)va, *b = *(char**)vb;
1918 * This is called with sweep completed and the world stopped.
1921 major_free_swept_blocks (size_t allowance)
1923 /* FIXME: This is probably too much. It's assuming all objects are small. */
1924 size_t section_reserve = allowance / MS_BLOCK_SIZE;
1926 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1930 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1931 * a VirtualAlloc ()-ed block.
1936 #if SIZEOF_VOID_P != 8
1938 int i, num_empty_blocks_orig, num_blocks, arr_length;
1940 void **empty_block_arr;
1941 void **rebuild_next;
1943 if (num_empty_blocks <= section_reserve)
1945 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1947 num_empty_blocks_orig = num_empty_blocks;
1948 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1949 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1950 if (!empty_block_arr)
1954 for (block = empty_blocks; block; block = *(void**)block)
1955 empty_block_arr [i++] = block;
1956 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1958 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1961 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1962 * contiguous ones. If we do, we free them. If that's not enough to get to
1963 * section_reserve, we halve the number of contiguous blocks we're looking
1964 * for and have another go, until we're done with looking for pairs of
1965 * blocks, at which point we give up and go to the fallback.
1967 arr_length = num_empty_blocks_orig;
1968 num_blocks = MS_BLOCK_ALLOC_NUM;
1969 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1974 for (i = 0; i < arr_length; ++i) {
1976 void *block = empty_block_arr [i];
1977 SGEN_ASSERT (6, block, "we're not shifting correctly");
1979 empty_block_arr [dest] = block;
1981 * This is not strictly necessary, but we're
1984 empty_block_arr [i] = NULL;
1993 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
1995 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
2000 if (d + 1 - first == num_blocks) {
2002 * We found num_blocks contiguous blocks. Free them
2003 * and null their array entries. As an optimization
2004 * we could, instead of nulling the entries, shift
2005 * the following entries over to the left, while
2009 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
2010 for (j = first; j <= d; ++j)
2011 empty_block_arr [j] = NULL;
2015 num_empty_blocks -= num_blocks;
2017 stat_major_blocks_freed += num_blocks;
2018 if (num_blocks == MS_BLOCK_ALLOC_NUM)
2019 stat_major_blocks_freed_ideal += num_blocks;
2021 stat_major_blocks_freed_less_ideal += num_blocks;
2026 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2028 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2033 /* rebuild empty_blocks free list */
2034 rebuild_next = (void**)&empty_blocks;
2035 for (i = 0; i < arr_length; ++i) {
2036 void *block = empty_block_arr [i];
2037 SGEN_ASSERT (6, block, "we're missing blocks");
2038 *rebuild_next = block;
2039 rebuild_next = (void**)block;
2041 *rebuild_next = NULL;
2044 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2047 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2051 * This is our threshold. If there's not more empty than used blocks, we won't
2052 * release uncontiguous blocks, in fear of fragmenting the address space.
2054 if (num_empty_blocks <= num_major_sections)
2058 while (num_empty_blocks > section_reserve) {
2059 void *next = *(void**)empty_blocks;
2060 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
2061 empty_blocks = next;
2063 * Needs not be atomic because this is running
2068 ++stat_major_blocks_freed;
2069 #if SIZEOF_VOID_P != 8
2070 ++stat_major_blocks_freed_individual;
2076 major_pin_objects (SgenGrayQueue *queue)
2080 FOREACH_BLOCK_NO_LOCK (block) {
2081 size_t first_entry, last_entry;
2082 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2083 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2084 &first_entry, &last_entry);
2085 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2086 } END_FOREACH_BLOCK_NO_LOCK;
2090 major_init_to_space (void)
2095 major_report_pinned_memory_usage (void)
2097 g_assert_not_reached ();
2101 major_get_used_size (void)
2107 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2108 * finished, then we can iterate over the block array.
2110 major_finish_sweep_checking ();
2112 FOREACH_BLOCK_NO_LOCK (block) {
2113 int count = MS_BLOCK_FREE / block->obj_size;
2115 size += count * block->obj_size;
2116 for (iter = block->free_list; iter; iter = (void**)*iter)
2117 size -= block->obj_size;
2118 } END_FOREACH_BLOCK_NO_LOCK;
2123 /* FIXME: return number of bytes, not of sections */
2125 get_num_major_sections (void)
2127 return num_major_sections;
2131 * Returns the number of bytes in blocks that were present when the last sweep was
2132 * initiated, and were not freed during the sweep. They are the basis for calculating the
2136 get_bytes_survived_last_sweep (void)
2138 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2139 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2143 major_handle_gc_param (const char *opt)
2145 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2146 const char *arg = strchr (opt, '=') + 1;
2147 int percentage = atoi (arg);
2148 if (percentage < 0 || percentage > 100) {
2149 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2152 evacuation_threshold = (float)percentage / 100.0f;
2154 } else if (!strcmp (opt, "lazy-sweep")) {
2157 } else if (!strcmp (opt, "no-lazy-sweep")) {
2160 } else if (!strcmp (opt, "concurrent-sweep")) {
2161 concurrent_sweep = TRUE;
2163 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2164 concurrent_sweep = FALSE;
2172 major_print_gc_param_usage (void)
2176 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2177 " (no-)lazy-sweep\n"
2178 " (no-)concurrent-sweep\n"
2183 * This callback is used to clear cards, move cards to the shadow table and do counting.
2186 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2189 gboolean has_references;
2191 major_finish_sweep_checking ();
2192 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2194 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2195 } END_FOREACH_BLOCK_NO_LOCK;
2198 #ifdef HEAVY_STATISTICS
2199 extern guint64 marked_cards;
2200 extern guint64 scanned_cards;
2201 extern guint64 scanned_objects;
2202 extern guint64 remarked_cards;
2205 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2207 * MS blocks are 16K aligned.
2208 * Cardtables are 4K aligned, at least.
2209 * This means that the cardtable of a given block is 32 bytes aligned.
2212 initial_skip_card (guint8 *card_data)
2214 mword *cards = (mword*)card_data;
2217 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2223 if (i == CARD_WORDS_PER_BLOCK)
2224 return card_data + CARDS_PER_BLOCK;
2226 #if defined(__i386__) && defined(__GNUC__)
2227 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2228 #elif defined(__x86_64__) && defined(__GNUC__)
2229 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2230 #elif defined(__s390x__) && defined(__GNUC__)
2231 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2233 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2235 return &card_data [i];
2241 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2242 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2243 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2246 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2248 SgenGrayQueue *queue = ctx.queue;
2249 ScanObjectFunc scan_func = ctx.ops->scan_object;
2250 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2251 guint8 cards_copy [CARDS_PER_BLOCK];
2253 guint8 cards_preclean [CARDS_PER_BLOCK];
2254 gboolean small_objects;
2257 guint8 *card_data, *card_base;
2258 guint8 *card_data_end;
2259 char *scan_front = NULL;
2261 /* The concurrent mark doesn't enter evacuating blocks */
2262 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2265 block_obj_size = block->obj_size;
2266 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2268 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2271 * This is safe in face of card aliasing for the following reason:
2273 * Major blocks are 16k aligned, or 32 cards aligned.
2274 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2275 * sizes, they won't overflow the cardtable overlap modulus.
2277 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2278 card_data = card_base = block->cardtable_mod_union;
2280 * This happens when the nursery collection that precedes finishing
2281 * the concurrent collection allocates new major blocks.
2286 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2287 sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2288 card_data = card_base = cards_preclean;
2291 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2292 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2294 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2296 card_data = card_base = cards_copy;
2299 card_data_end = card_data + CARDS_PER_BLOCK;
2301 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2303 card_data = initial_skip_card (card_data);
2304 while (card_data < card_data_end) {
2305 size_t card_index, first_object_index;
2308 char *first_obj, *obj;
2310 HEAVY_STAT (++scanned_cards);
2317 card_index = card_data - card_base;
2318 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2319 end = start + CARD_SIZE_IN_BYTES;
2321 if (!block_is_swept_or_marking (block))
2322 sweep_block (block);
2324 HEAVY_STAT (++marked_cards);
2327 sgen_card_table_prepare_card_for_scanning (card_data);
2330 * If the card we're looking at starts at or in the block header, we
2331 * must start at the first object in the block, without calculating
2332 * the index of the object we're hypothetically starting at, because
2333 * it would be negative.
2335 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2336 first_object_index = 0;
2338 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2340 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2342 binary_protocol_card_scan (first_obj, end - first_obj);
2345 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2348 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2349 /* FIXME: do this more efficiently */
2351 MS_CALC_MARK_BIT (w, b, obj);
2352 if (!MS_MARK_BIT (block, w, b))
2356 GCObject *object = (GCObject*)obj;
2358 if (small_objects) {
2359 HEAVY_STAT (++scanned_objects);
2360 scan_func (object, sgen_obj_get_descriptor (object), queue);
2362 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2363 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2366 obj += block_obj_size;
2367 g_assert (scan_front <= obj);
2371 HEAVY_STAT (if (*card_data) ++remarked_cards);
2376 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2381 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx)
2384 gboolean has_references;
2386 if (!concurrent_mark)
2387 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2389 major_finish_sweep_checking ();
2390 binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2391 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2392 #ifdef PREFETCH_CARDS
2393 int prefetch_index = __index + 6;
2394 if (prefetch_index < allocated_blocks.next_slot) {
2395 MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2396 PREFETCH_READ (prefetch_block);
2397 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2398 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2399 PREFETCH_WRITE (prefetch_cards);
2400 PREFETCH_WRITE (prefetch_cards + 32);
2405 if (!has_references)
2408 scan_card_table_for_block (block, scan_type, ctx);
2409 } END_FOREACH_BLOCK_NO_LOCK;
2410 binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2414 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2417 gboolean has_references;
2418 long long total_cards = 0;
2419 long long marked_cards = 0;
2421 if (sweep_in_progress ()) {
2422 *num_total_cards = -1;
2423 *num_marked_cards = -1;
2427 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2428 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2431 if (!has_references)
2434 total_cards += CARDS_PER_BLOCK;
2435 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2439 } END_FOREACH_BLOCK_NO_LOCK;
2441 *num_total_cards = total_cards;
2442 *num_marked_cards = marked_cards;
2446 update_cardtable_mod_union (void)
2450 FOREACH_BLOCK_NO_LOCK (block) {
2452 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2453 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2454 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2455 } END_FOREACH_BLOCK_NO_LOCK;
2458 #undef pthread_create
2461 post_param_init (SgenMajorCollector *collector)
2463 collector->sweeps_lazily = lazy_sweep;
2464 collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2468 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2472 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2474 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2475 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2476 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2478 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2479 for (i = 0; i < num_block_obj_sizes; ++i)
2480 evacuate_block_obj_sizes [i] = FALSE;
2482 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2483 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2484 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2489 g_print ("block object sizes:\n");
2490 for (i = 0; i < num_block_obj_sizes; ++i)
2491 g_print ("%d\n", block_obj_sizes [i]);
2495 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2496 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2498 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2499 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2500 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2501 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2503 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2504 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2505 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2506 #if SIZEOF_VOID_P != 8
2507 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2508 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2509 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2510 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2513 collector->section_size = MAJOR_SECTION_SIZE;
2515 concurrent_mark = is_concurrent;
2516 collector->is_concurrent = is_concurrent;
2517 collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2518 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2519 collector->supports_cardtable = TRUE;
2521 collector->alloc_heap = major_alloc_heap;
2522 collector->is_object_live = major_is_object_live;
2523 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2524 collector->alloc_degraded = major_alloc_degraded;
2526 collector->alloc_object = major_alloc_object;
2527 collector->free_pinned_object = free_pinned_object;
2528 collector->iterate_objects = major_iterate_objects;
2529 collector->free_non_pinned_object = major_free_non_pinned_object;
2530 collector->pin_objects = major_pin_objects;
2531 collector->pin_major_object = pin_major_object;
2532 collector->scan_card_table = major_scan_card_table;
2533 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2534 if (is_concurrent) {
2535 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2536 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2538 collector->init_to_space = major_init_to_space;
2539 collector->sweep = major_sweep;
2540 collector->have_swept = major_have_swept;
2541 collector->finish_sweeping = major_finish_sweep_checking;
2542 collector->free_swept_blocks = major_free_swept_blocks;
2543 collector->check_scan_starts = major_check_scan_starts;
2544 collector->dump_heap = major_dump_heap;
2545 collector->get_used_size = major_get_used_size;
2546 collector->start_nursery_collection = major_start_nursery_collection;
2547 collector->finish_nursery_collection = major_finish_nursery_collection;
2548 collector->start_major_collection = major_start_major_collection;
2549 collector->finish_major_collection = major_finish_major_collection;
2550 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2551 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2552 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2553 collector->get_num_major_sections = get_num_major_sections;
2554 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2555 collector->handle_gc_param = major_handle_gc_param;
2556 collector->print_gc_param_usage = major_print_gc_param_usage;
2557 collector->post_param_init = post_param_init;
2558 collector->is_valid_object = major_is_valid_object;
2559 collector->describe_pointer = major_describe_pointer;
2560 collector->count_cards = major_count_cards;
2562 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2563 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2564 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2565 if (is_concurrent) {
2566 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2567 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2568 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2569 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2570 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2572 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2573 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2574 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2575 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2576 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2579 #ifdef HEAVY_STATISTICS
2580 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2581 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2582 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2583 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2584 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2585 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2586 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2587 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2588 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2589 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2590 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2592 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2593 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2594 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2597 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2598 mono_os_mutex_init (&scanned_objects_list_lock);
2601 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2603 /*cardtable requires major pages to be 8 cards aligned*/
2604 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2608 sgen_marksweep_init (SgenMajorCollector *collector)
2610 sgen_marksweep_init_internal (collector, FALSE);
2614 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2616 sgen_marksweep_init_internal (collector, TRUE);