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;
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 (MSBlockInfo *info)
381 char *block = MS_BLOCK_FOR_BLOCK_INFO (info);
383 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
384 if (info->cardtable_mod_union)
385 sgen_card_table_free_mod_union (info->cardtable_mod_union, block, MS_BLOCK_SIZE);
386 memset (block, 0, MS_BLOCK_SIZE);
389 empty = empty_blocks;
390 *(void**)block = empty;
391 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
393 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
395 binary_protocol_block_free (block, MS_BLOCK_SIZE);
399 sweep_in_progress (void)
401 int state = sweep_state;
402 return state == SWEEP_STATE_SWEEPING ||
403 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
404 state == SWEEP_STATE_COMPACTING;
407 static inline gboolean
408 block_is_swept_or_marking (MSBlockInfo *block)
410 gint32 state = block->state;
411 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
414 //#define MARKSWEEP_CONSISTENCY_CHECK
416 #ifdef MARKSWEEP_CONSISTENCY_CHECK
418 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
420 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
421 for (; block; block = block->next_free) {
422 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
423 g_assert (block->obj_size == size);
424 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
426 /* blocks in the free lists must have at least
428 g_assert (block->free_list);
430 /* the block must be in the allocated_blocks array */
431 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
436 check_empty_blocks (void)
440 for (p = empty_blocks; p; p = *(void**)p)
442 g_assert (i == num_empty_blocks);
446 consistency_check (void)
451 /* check all blocks */
452 FOREACH_BLOCK_NO_LOCK (block) {
453 int count = MS_BLOCK_FREE / block->obj_size;
457 /* count number of free slots */
458 for (i = 0; i < count; ++i) {
459 void **obj = (void**) MS_BLOCK_OBJ (block, i);
460 if (!MS_OBJ_ALLOCED (obj, block))
464 /* check free list */
465 for (free = block->free_list; free; free = (void**)*free) {
466 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
469 g_assert (num_free == 0);
471 /* check all mark words are zero */
472 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
473 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
474 g_assert (block->mark_words [i] == 0);
476 } END_FOREACH_BLOCK_NO_LOCK;
478 /* check free blocks */
479 for (i = 0; i < num_block_obj_sizes; ++i) {
481 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
482 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
485 check_empty_blocks ();
490 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
494 block->next_free = old = free_blocks [size_index];
495 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
498 static void major_finish_sweep_checking (void);
501 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
503 int size = block_obj_sizes [size_index];
504 int count = MS_BLOCK_FREE / size;
506 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
510 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
513 info = (MSBlockInfo*)ms_get_empty_block ();
515 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
517 info->obj_size = size;
518 info->obj_size_index = size_index;
519 info->pinned = pinned;
520 info->has_references = has_references;
521 info->has_pinned = pinned;
523 * Blocks that are to-space are not evacuated from. During an major collection
524 * blocks are allocated for two reasons: evacuating objects from the nursery and
525 * evacuating them from major blocks marked for evacuation. In both cases we don't
526 * want further evacuation. We also don't want to evacuate objects allocated during
527 * the concurrent mark since it would add pointless stress on the finishing pause.
529 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
530 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
531 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
532 info->cardtable_mod_union = NULL;
534 update_heap_boundaries_for_block (info);
536 binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
538 /* build free list */
539 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
540 info->free_list = (void**)obj_start;
541 /* we're skipping the last one - it must be nulled */
542 for (i = 0; i < count - 1; ++i) {
543 char *next_obj_start = obj_start + size;
544 *(void**)obj_start = next_obj_start;
545 obj_start = next_obj_start;
548 *(void**)obj_start = NULL;
550 add_free_block (free_blocks, size_index, info);
553 * Adding to the allocated_blocks array is racy with the removal of nulls when
554 * sweeping. We wait for sweep to finish to avoid that.
556 * The memory barrier here and in `sweep_job_func()` are required because we need
557 * `allocated_blocks` synchronized between this and the sweep thread.
559 major_finish_sweep_checking ();
560 mono_memory_barrier ();
562 sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
564 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
569 ptr_is_from_pinned_alloc (char *ptr)
573 FOREACH_BLOCK_NO_LOCK (block) {
574 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
575 return block->pinned;
576 } END_FOREACH_BLOCK_NO_LOCK;
581 ensure_can_access_block_free_list (MSBlockInfo *block)
585 switch (block->state) {
586 case BLOCK_STATE_SWEPT:
587 case BLOCK_STATE_MARKING:
589 case BLOCK_STATE_CHECKING:
590 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
592 case BLOCK_STATE_NEED_SWEEPING:
593 if (sweep_block (block))
594 ++stat_major_blocks_lazy_swept;
596 case BLOCK_STATE_SWEEPING:
597 /* FIXME: do this more elegantly */
601 SGEN_ASSERT (0, FALSE, "Illegal block state");
608 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
610 MSBlockInfo *block, *next_free_block;
611 void *obj, *next_free_slot;
614 block = free_blocks [size_index];
615 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
617 ensure_can_access_block_free_list (block);
619 obj = block->free_list;
620 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
622 next_free_slot = *(void**)obj;
623 if (next_free_slot) {
624 block->free_list = (gpointer *)next_free_slot;
628 next_free_block = block->next_free;
629 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
632 block->free_list = NULL;
633 block->next_free = NULL;
639 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
641 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
642 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
645 if (!free_blocks [size_index]) {
646 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
650 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
652 /* FIXME: assumes object layout */
653 *(GCVTable*)obj = vtable;
655 return (GCObject *)obj;
659 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
661 return alloc_obj (vtable, size, FALSE, has_references);
665 * We're not freeing the block if it's empty. We leave that work for
666 * the next major collection.
668 * This is just called from the domain clearing code, which runs in a
669 * single thread and has the GC lock, so we don't need an extra lock.
672 free_object (GCObject *obj, size_t size, gboolean pinned)
674 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
676 gboolean in_free_list;
678 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
680 ensure_can_access_block_free_list (block);
681 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);
682 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
683 MS_CALC_MARK_BIT (word, bit, obj);
684 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
686 memset (obj, 0, size);
688 in_free_list = !!block->free_list;
689 *(void**)obj = block->free_list;
690 block->free_list = (void**)obj;
693 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
694 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
695 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);
696 add_free_block (free_blocks, size_index, block);
701 major_free_non_pinned_object (GCObject *obj, size_t size)
703 free_object (obj, size, FALSE);
706 /* size is a multiple of SGEN_ALLOC_ALIGN */
708 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
712 res = alloc_obj (vtable, size, TRUE, has_references);
713 /*If we failed to alloc memory, we better try releasing memory
714 *as pinned alloc is requested by the runtime.
717 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
718 res = alloc_obj (vtable, size, TRUE, has_references);
720 return (GCObject *)res;
724 free_pinned_object (GCObject *obj, size_t size)
726 free_object (obj, size, TRUE);
730 * size is already rounded up and we hold the GC lock.
733 major_alloc_degraded (GCVTable vtable, size_t size)
737 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
738 if (G_LIKELY (obj)) {
739 HEAVY_STAT (++stat_objects_alloced_degraded);
740 HEAVY_STAT (stat_bytes_alloced_degraded += size);
746 * obj is some object. If it's not in the major heap (i.e. if it's in
747 * the nursery or LOS), return FALSE. Otherwise return whether it's
748 * been marked or copied.
751 major_is_object_live (GCObject *obj)
757 if (sgen_ptr_in_nursery (obj))
760 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
763 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
766 /* now we know it's in a major block */
767 block = MS_BLOCK_FOR_OBJ (obj);
768 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
769 MS_CALC_MARK_BIT (word, bit, obj);
770 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
774 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
778 FOREACH_BLOCK_NO_LOCK (block) {
779 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
780 int count = MS_BLOCK_FREE / block->obj_size;
784 for (i = 0; i <= count; ++i) {
785 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
786 *start = (char *)MS_BLOCK_OBJ (block, i);
790 return !block->pinned;
792 } END_FOREACH_BLOCK_NO_LOCK;
797 try_set_sweep_state (int new_, int expected)
799 int old = SGEN_CAS (&sweep_state, new_, expected);
800 return old == expected;
804 set_sweep_state (int new_, int expected)
806 gboolean success = try_set_sweep_state (new_, expected);
807 SGEN_ASSERT (0, success, "Could not set sweep state.");
810 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
812 static SgenThreadPoolJob * volatile sweep_job;
813 static SgenThreadPoolJob * volatile sweep_blocks_job;
816 major_finish_sweep_checking (void)
819 SgenThreadPoolJob *job;
822 switch (sweep_state) {
823 case SWEEP_STATE_SWEPT:
824 case SWEEP_STATE_NEED_SWEEPING:
826 case SWEEP_STATE_SWEEPING:
827 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
830 case SWEEP_STATE_SWEEPING_AND_ITERATING:
831 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
833 case SWEEP_STATE_COMPACTING:
836 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
841 * We're running with the world stopped and the only other thread doing work is the
842 * sweep thread, which doesn't add blocks to the array, so we can safely access
845 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
846 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
848 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
853 sgen_thread_pool_job_wait (job);
854 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
855 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
859 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
861 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
862 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
863 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
866 major_finish_sweep_checking ();
867 FOREACH_BLOCK_NO_LOCK (block) {
868 int count = MS_BLOCK_FREE / block->obj_size;
871 if (block->pinned && !pinned)
873 if (!block->pinned && !non_pinned)
875 if (sweep && lazy_sweep) {
877 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
880 for (i = 0; i < count; ++i) {
881 void **obj = (void**) MS_BLOCK_OBJ (block, i);
883 * We've finished sweep checking, but if we're sweeping lazily and
884 * the flags don't require us to sweep, the block might still need
885 * sweeping. In that case, we need to consult the mark bits to tell
886 * us whether an object slot is live.
888 if (!block_is_swept_or_marking (block)) {
890 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
891 MS_CALC_MARK_BIT (word, bit, obj);
892 if (!MS_MARK_BIT (block, word, bit))
895 if (MS_OBJ_ALLOCED (obj, block))
896 callback ((GCObject*)obj, block->obj_size, data);
898 } END_FOREACH_BLOCK_NO_LOCK;
902 major_is_valid_object (char *object)
906 FOREACH_BLOCK_NO_LOCK (block) {
910 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
913 idx = MS_BLOCK_OBJ_INDEX (object, block);
914 obj = (char*)MS_BLOCK_OBJ (block, idx);
917 return MS_OBJ_ALLOCED (obj, block);
918 } END_FOREACH_BLOCK_NO_LOCK;
925 major_describe_pointer (char *ptr)
929 FOREACH_BLOCK_NO_LOCK (block) {
937 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
940 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
941 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
943 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
944 obj = (char*)MS_BLOCK_OBJ (block, idx);
945 live = MS_OBJ_ALLOCED (obj, block);
946 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
948 MS_CALC_MARK_BIT (w, b, obj);
949 marked = MS_MARK_BIT (block, w, b);
954 SGEN_LOG (0, "object");
956 SGEN_LOG (0, "dead-object");
959 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
961 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
964 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
967 } END_FOREACH_BLOCK_NO_LOCK;
973 major_check_scan_starts (void)
978 major_dump_heap (FILE *heap_dump_file)
981 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
982 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
985 for (i = 0; i < num_block_obj_sizes; ++i)
986 slots_available [i] = slots_used [i] = 0;
988 FOREACH_BLOCK_NO_LOCK (block) {
989 int index = ms_find_block_obj_size_index (block->obj_size);
990 int count = MS_BLOCK_FREE / block->obj_size;
992 slots_available [index] += count;
993 for (i = 0; i < count; ++i) {
994 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
995 ++slots_used [index];
997 } END_FOREACH_BLOCK_NO_LOCK;
999 fprintf (heap_dump_file, "<occupancies>\n");
1000 for (i = 0; i < num_block_obj_sizes; ++i) {
1001 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1002 block_obj_sizes [i], slots_available [i], slots_used [i]);
1004 fprintf (heap_dump_file, "</occupancies>\n");
1006 FOREACH_BLOCK_NO_LOCK (block) {
1007 int count = MS_BLOCK_FREE / block->obj_size;
1011 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1013 for (i = 0; i <= count; ++i) {
1014 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1019 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1025 fprintf (heap_dump_file, "</section>\n");
1026 } END_FOREACH_BLOCK_NO_LOCK;
1030 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1032 guint8 *mod_union = block->cardtable_mod_union;
1038 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1039 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1041 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1044 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1048 static inline guint8*
1049 major_get_cardtable_mod_union_for_reference (char *ptr)
1051 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1052 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1053 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1054 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1055 return &mod_union [offset];
1059 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1062 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1064 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1065 if (sgen_safe_object_is_small (obj, type)) {
1066 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1067 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?");
1070 sgen_los_mark_mod_union_card (obj, ptr);
1072 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1075 static inline gboolean
1076 major_block_is_evacuating (MSBlockInfo *block)
1078 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1079 !block->has_pinned &&
1080 !block->is_to_space)
1085 #define LOAD_VTABLE SGEN_LOAD_VTABLE
1087 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do { \
1088 int __word, __bit; \
1089 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1090 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
1091 MS_SET_MARK_BIT ((block), __word, __bit); \
1092 if (sgen_gc_descr_has_references (desc)) \
1093 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1094 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1095 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1098 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1099 int __word, __bit; \
1100 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1101 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1102 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1103 MS_SET_MARK_BIT ((block), __word, __bit); \
1104 if (sgen_gc_descr_has_references (desc)) \
1105 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1106 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1107 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1112 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1116 if (concurrent_mark)
1117 g_assert_not_reached ();
1119 block = MS_BLOCK_FOR_OBJ (obj);
1120 block->has_pinned = TRUE;
1121 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1124 #include "sgen-major-copy-object.h"
1127 major_get_and_reset_num_major_objects_marked (void)
1129 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1130 long long num = num_major_objects_marked;
1131 num_major_objects_marked = 0;
1138 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1140 #undef PREFETCH_CARDS
1143 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1144 #if defined(PLATFORM_MACOSX)
1145 #define GCC_VERSION (__GNUC__ * 10000 \
1146 + __GNUC_MINOR__ * 100 \
1147 + __GNUC_PATCHLEVEL__)
1148 #if GCC_VERSION <= 40300
1149 #undef PREFETCH_CARDS
1153 #ifdef HEAVY_STATISTICS
1154 static guint64 stat_optimized_copy;
1155 static guint64 stat_optimized_copy_nursery;
1156 static guint64 stat_optimized_copy_nursery_forwarded;
1157 static guint64 stat_optimized_copy_nursery_pinned;
1158 static guint64 stat_optimized_copy_major;
1159 static guint64 stat_optimized_copy_major_small_fast;
1160 static guint64 stat_optimized_copy_major_small_slow;
1161 static guint64 stat_optimized_copy_major_large;
1162 static guint64 stat_optimized_copy_major_forwarded;
1163 static guint64 stat_optimized_copy_major_small_evacuate;
1164 static guint64 stat_optimized_major_scan;
1165 static guint64 stat_optimized_major_scan_no_refs;
1167 static guint64 stat_drain_prefetch_fills;
1168 static guint64 stat_drain_prefetch_fill_failures;
1169 static guint64 stat_drain_loops;
1172 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1173 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1174 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1175 #include "sgen-marksweep-drain-gray-stack.h"
1177 #define COPY_OR_MARK_WITH_EVACUATION
1178 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1179 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1180 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_with_evacuation
1181 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1182 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_with_evacuation
1183 #include "sgen-marksweep-drain-gray-stack.h"
1185 #define COPY_OR_MARK_CONCURRENT
1186 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1187 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1188 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1189 #include "sgen-marksweep-drain-gray-stack.h"
1191 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1192 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1193 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1194 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_with_evacuation
1195 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_with_evacuation
1196 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1197 #include "sgen-marksweep-drain-gray-stack.h"
1199 static inline gboolean
1200 major_is_evacuating (void)
1203 for (i = 0; i < num_block_obj_sizes; ++i) {
1204 if (evacuate_block_obj_sizes [i]) {
1213 drain_gray_stack (SgenGrayQueue *queue)
1215 if (major_is_evacuating ())
1216 return drain_gray_stack_with_evacuation (queue);
1218 return drain_gray_stack_no_evacuation (queue);
1222 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1224 if (major_is_evacuating ())
1225 return drain_gray_stack_concurrent_with_evacuation (queue);
1227 return drain_gray_stack_concurrent_no_evacuation (queue);
1231 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1233 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1237 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1239 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1243 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1245 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1249 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1251 void **entry, **end;
1252 int last_index = -1;
1254 if (first_entry == last_entry)
1257 block->has_pinned = TRUE;
1259 entry = sgen_pinning_get_entry (first_entry);
1260 end = sgen_pinning_get_entry (last_entry);
1262 for (; entry < end; ++entry) {
1263 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1265 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));
1266 if (index == last_index)
1268 obj = MS_BLOCK_OBJ (block, index);
1269 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1275 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1279 for (obj_index = 0; obj_index < count; ++obj_index) {
1281 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1283 MS_CALC_MARK_BIT (word, bit, obj);
1284 if (MS_MARK_BIT (block, word, bit)) {
1285 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1287 /* an unmarked object */
1288 if (MS_OBJ_ALLOCED (obj, block)) {
1290 * FIXME: Merge consecutive
1291 * slots for lower reporting
1292 * overhead. Maybe memset
1293 * will also benefit?
1295 binary_protocol_empty (obj, obj_size);
1296 memset (obj, 0, obj_size);
1298 *(void**)obj = block->free_list;
1299 block->free_list = (void **)obj;
1304 static inline gboolean
1305 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1307 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1308 gboolean success = old_state == expected_state;
1310 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1315 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1317 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1318 block->state = new_state;
1322 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1324 * Sweeping means iterating through the block's slots and building the free-list from the
1325 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1328 sweep_block (MSBlockInfo *block)
1331 void *reversed = NULL;
1334 switch (block->state) {
1335 case BLOCK_STATE_SWEPT:
1337 case BLOCK_STATE_MARKING:
1338 case BLOCK_STATE_CHECKING:
1339 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1341 case BLOCK_STATE_SWEEPING:
1342 /* FIXME: Do this more elegantly */
1345 case BLOCK_STATE_NEED_SWEEPING:
1346 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1350 SGEN_ASSERT (0, FALSE, "Illegal block state");
1353 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1355 count = MS_BLOCK_FREE / block->obj_size;
1357 block->free_list = NULL;
1359 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1360 // FIXME: Add more sizes
1361 switch (block->obj_size) {
1363 sweep_block_for_size (block, count, 16);
1366 sweep_block_for_size (block, count, block->obj_size);
1370 /* reset mark bits */
1371 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1373 /* Reverse free list so that it's in address order */
1375 while (block->free_list) {
1376 void *next = *(void**)block->free_list;
1377 *(void**)block->free_list = reversed;
1378 reversed = block->free_list;
1379 block->free_list = (void **)next;
1381 block->free_list = (void **)reversed;
1383 mono_memory_write_barrier ();
1385 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1396 if (sizeof (mword) == 8)
1397 count += __builtin_popcountll (d);
1399 count += __builtin_popcount (d);
1409 /* statistics for evacuation */
1410 static size_t *sweep_slots_available;
1411 static size_t *sweep_slots_used;
1412 static size_t *sweep_num_blocks;
1414 static volatile size_t num_major_sections_before_sweep;
1415 static volatile size_t num_major_sections_freed_in_sweep;
1422 for (i = 0; i < num_block_obj_sizes; ++i)
1423 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1425 /* clear all the free lists */
1426 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1427 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1429 for (j = 0; j < num_block_obj_sizes; ++j)
1430 free_blocks [j] = NULL;
1434 static void sweep_finish (void);
1437 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1438 * the checking has finished.
1440 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1441 * be correct, i.e. must not be used.
1444 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1447 gboolean have_live = FALSE;
1448 gboolean have_free = FALSE;
1454 volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1456 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1459 *have_checked = FALSE;
1462 tagged_block = *(void * volatile *)block_slot;
1466 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1469 /* FIXME: do this more elegantly */
1474 if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1477 block = BLOCK_UNTAG (tagged_block);
1478 block_state = block->state;
1480 if (!sweep_in_progress ()) {
1481 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1483 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1486 switch (block_state) {
1487 case BLOCK_STATE_SWEPT:
1488 case BLOCK_STATE_NEED_SWEEPING:
1489 case BLOCK_STATE_SWEEPING:
1491 case BLOCK_STATE_MARKING:
1493 case BLOCK_STATE_CHECKING:
1494 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1497 SGEN_ASSERT (0, FALSE, "Illegal block state");
1501 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1502 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1505 *have_checked = TRUE;
1507 block->has_pinned = block->pinned;
1509 block->is_to_space = FALSE;
1511 count = MS_BLOCK_FREE / block->obj_size;
1513 if (block->cardtable_mod_union)
1514 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1516 /* Count marked objects in the block */
1517 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1518 nused += bitcount (block->mark_words [i]);
1520 block->nused = nused;
1527 int obj_size_index = block->obj_size_index;
1528 gboolean has_pinned = block->has_pinned;
1530 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1533 * FIXME: Go straight to SWEPT if there are no free slots. We need
1534 * to set the free slot list to NULL, though, and maybe update some
1538 sweep_block (block);
1541 ++sweep_num_blocks [obj_size_index];
1542 sweep_slots_used [obj_size_index] += nused;
1543 sweep_slots_available [obj_size_index] += count;
1547 * If there are free slots in the block, add
1548 * the block to the corresponding free list.
1551 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1554 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1556 add_free_block (free_blocks, obj_size_index, block);
1559 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1560 update_heap_boundaries_for_block (block);
1563 * Blocks without live objects are removed from the
1564 * block list and freed.
1566 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1567 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1569 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1570 ms_free_block (block);
1572 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1574 tagged_block = NULL;
1578 *block_slot = tagged_block;
1579 return !!tagged_block;
1583 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1585 volatile gpointer *slot;
1587 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1588 sweep_block (BLOCK_UNTAG (*slot));
1589 } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1591 mono_memory_write_barrier ();
1593 sweep_blocks_job = NULL;
1597 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1599 guint32 block_index;
1600 guint32 num_blocks = num_major_sections_before_sweep;
1602 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1603 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1606 * We traverse the block array from high to low. Nursery collections will have to
1607 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1608 * low to high, to avoid constantly colliding on the same blocks.
1610 for (block_index = num_blocks; block_index-- > 0;) {
1612 * The block might have been freed by another thread doing some checking
1615 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL))
1616 ++num_major_sections_freed_in_sweep;
1619 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1621 * The main GC thread is currently iterating over the block array to help us
1622 * finish the sweep. We have already finished, but we don't want to mess up
1623 * that iteration, so we just wait for it.
1628 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1629 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1630 MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1631 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1635 sgen_array_list_remove_nulls (&allocated_blocks);
1638 * Concurrently sweep all the blocks to reduce workload during minor
1639 * pauses where we need certain blocks to be swept. At the start of
1640 * the next major we need all blocks to be swept anyway.
1642 if (concurrent_sweep && lazy_sweep) {
1643 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1644 sgen_thread_pool_job_enqueue (sweep_blocks_job);
1657 for (i = 0; i < num_block_obj_sizes; ++i) {
1658 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1659 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1660 evacuate_block_obj_sizes [i] = TRUE;
1662 g_print ("slot size %d - %d of %d used\n",
1663 block_obj_sizes [i], slots_used [i], slots_available [i]);
1666 evacuate_block_obj_sizes [i] = FALSE;
1670 sgen_memgov_major_post_sweep ();
1672 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1673 if (concurrent_sweep)
1674 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1680 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1684 SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1686 num_major_sections_before_sweep = num_major_sections;
1687 num_major_sections_freed_in_sweep = 0;
1689 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1690 if (concurrent_sweep) {
1691 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1692 sgen_thread_pool_job_enqueue (sweep_job);
1694 sweep_job_func (NULL, NULL);
1699 major_have_swept (void)
1701 return sweep_state == SWEEP_STATE_SWEPT;
1704 static int count_pinned_ref;
1705 static int count_pinned_nonref;
1706 static int count_nonpinned_ref;
1707 static int count_nonpinned_nonref;
1710 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1712 GCVTable vtable = LOAD_VTABLE (obj);
1714 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1715 ++count_nonpinned_ref;
1717 ++count_nonpinned_nonref;
1721 count_pinned_callback (GCObject *obj, size_t size, void *data)
1723 GCVTable vtable = LOAD_VTABLE (obj);
1725 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1728 ++count_pinned_nonref;
1731 static G_GNUC_UNUSED void
1732 count_ref_nonref_objs (void)
1736 count_pinned_ref = 0;
1737 count_pinned_nonref = 0;
1738 count_nonpinned_ref = 0;
1739 count_nonpinned_nonref = 0;
1741 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1742 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1744 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1746 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1747 count_pinned_ref, count_nonpinned_ref,
1748 count_pinned_nonref, count_nonpinned_nonref,
1749 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1753 ms_calculate_block_obj_sizes (double factor, int *arr)
1760 * Have every possible slot size starting with the minimal
1761 * object size up to and including four times that size. Then
1762 * proceed by increasing geometrically with the given factor.
1765 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1767 arr [num_sizes] = size;
1771 target_size = (double)last_size;
1774 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1775 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1777 if (size != last_size) {
1779 arr [num_sizes] = size;
1784 target_size *= factor;
1785 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1790 /* only valid during minor collections */
1791 static mword old_num_major_sections;
1794 major_start_nursery_collection (void)
1796 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1797 consistency_check ();
1800 old_num_major_sections = num_major_sections;
1804 major_finish_nursery_collection (void)
1806 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1807 consistency_check ();
1812 block_usage_comparer (const void *bl1, const void *bl2)
1814 const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
1815 const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
1817 return nused2 - nused1;
1821 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1823 MSBlockInfo **evacuated_blocks;
1824 size_t index = 0, count, num_blocks = 0, num_used = 0;
1826 MSBlockInfo * volatile *prev;
1828 for (info = *block_list; info != NULL; info = info->next_free) {
1830 num_used += info->nused;
1834 * We have a set of blocks in the freelist which will be evacuated. Instead
1835 * of evacuating all of the blocks into new ones, we traverse the freelist
1836 * sorting it by the number of occupied slots, evacuating the objects from
1837 * blocks with fewer used slots into fuller blocks.
1839 * The number of used slots is set at the end of the previous sweep. Since
1840 * we sequentially unlink slots from blocks, except for the head of the
1841 * freelist, for blocks on the freelist, the number of used slots is the same
1842 * as at the end of the previous sweep.
1844 evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
1846 for (info = *block_list; info != NULL; info = info->next_free) {
1847 evacuated_blocks [index++] = info;
1850 SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
1852 qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
1855 * Form a new freelist with the fullest blocks. These blocks will also be
1856 * marked as to_space so we don't evacuate from them.
1858 count = MS_BLOCK_FREE / block_obj_sizes [size_index];
1860 for (index = 0; index < (num_used + count - 1) / count; index++) {
1861 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
1862 info = evacuated_blocks [index];
1863 info->is_to_space = TRUE;
1865 prev = &info->next_free;
1869 sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
1873 major_start_major_collection (void)
1878 major_finish_sweep_checking ();
1881 * Clear the free lists for block sizes where we do evacuation. For those block
1882 * sizes we will have to allocate new blocks.
1884 for (i = 0; i < num_block_obj_sizes; ++i) {
1885 if (!evacuate_block_obj_sizes [i])
1888 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
1890 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
1891 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
1894 if (lazy_sweep && concurrent_sweep) {
1896 * sweep_blocks_job is created before sweep_finish, which we wait for above
1897 * (major_finish_sweep_checking). After the end of sweep, if we don't have
1898 * sweep_blocks_job set, it means that it has already been run.
1900 SgenThreadPoolJob *job = sweep_blocks_job;
1902 sgen_thread_pool_job_wait (job);
1905 if (lazy_sweep && !concurrent_sweep)
1906 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
1907 /* Sweep all unswept blocks and set them to MARKING */
1908 FOREACH_BLOCK_NO_LOCK (block) {
1909 if (lazy_sweep && !concurrent_sweep)
1910 sweep_block (block);
1911 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1912 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1914 * Swept blocks that have a null free_list are full. Evacuation is not
1915 * effective on these blocks since we expect them to have high usage anyway,
1916 * given that the survival rate for majors is relatively high.
1918 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
1919 block->is_to_space = TRUE;
1920 } END_FOREACH_BLOCK_NO_LOCK;
1921 if (lazy_sweep && !concurrent_sweep)
1922 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
1924 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1928 major_finish_major_collection (ScannedObjectCounts *counts)
1930 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1931 if (binary_protocol_is_enabled ()) {
1932 counts->num_scanned_objects = scanned_objects_list.next_slot;
1934 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1935 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1937 sgen_pointer_queue_clear (&scanned_objects_list);
1942 #if SIZEOF_VOID_P != 8
1944 compare_pointers (const void *va, const void *vb) {
1945 char *a = *(char**)va, *b = *(char**)vb;
1955 * This is called with sweep completed and the world stopped.
1958 major_free_swept_blocks (size_t allowance)
1960 /* FIXME: This is probably too much. It's assuming all objects are small. */
1961 size_t section_reserve = allowance / MS_BLOCK_SIZE;
1963 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1967 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1968 * a VirtualAlloc ()-ed block.
1973 #if SIZEOF_VOID_P != 8
1975 int i, num_empty_blocks_orig, num_blocks, arr_length;
1977 void **empty_block_arr;
1978 void **rebuild_next;
1980 if (num_empty_blocks <= section_reserve)
1982 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1984 num_empty_blocks_orig = num_empty_blocks;
1985 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1986 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1987 if (!empty_block_arr)
1991 for (block = empty_blocks; block; block = *(void**)block)
1992 empty_block_arr [i++] = block;
1993 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1995 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1998 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1999 * contiguous ones. If we do, we free them. If that's not enough to get to
2000 * section_reserve, we halve the number of contiguous blocks we're looking
2001 * for and have another go, until we're done with looking for pairs of
2002 * blocks, at which point we give up and go to the fallback.
2004 arr_length = num_empty_blocks_orig;
2005 num_blocks = MS_BLOCK_ALLOC_NUM;
2006 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2011 for (i = 0; i < arr_length; ++i) {
2013 void *block = empty_block_arr [i];
2014 SGEN_ASSERT (6, block, "we're not shifting correctly");
2016 empty_block_arr [dest] = block;
2018 * This is not strictly necessary, but we're
2021 empty_block_arr [i] = NULL;
2030 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2032 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
2037 if (d + 1 - first == num_blocks) {
2039 * We found num_blocks contiguous blocks. Free them
2040 * and null their array entries. As an optimization
2041 * we could, instead of nulling the entries, shift
2042 * the following entries over to the left, while
2046 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
2047 for (j = first; j <= d; ++j)
2048 empty_block_arr [j] = NULL;
2052 num_empty_blocks -= num_blocks;
2054 stat_major_blocks_freed += num_blocks;
2055 if (num_blocks == MS_BLOCK_ALLOC_NUM)
2056 stat_major_blocks_freed_ideal += num_blocks;
2058 stat_major_blocks_freed_less_ideal += num_blocks;
2063 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2065 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2070 /* rebuild empty_blocks free list */
2071 rebuild_next = (void**)&empty_blocks;
2072 for (i = 0; i < arr_length; ++i) {
2073 void *block = empty_block_arr [i];
2074 SGEN_ASSERT (6, block, "we're missing blocks");
2075 *rebuild_next = block;
2076 rebuild_next = (void**)block;
2078 *rebuild_next = NULL;
2081 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2084 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2088 * This is our threshold. If there's not more empty than used blocks, we won't
2089 * release uncontiguous blocks, in fear of fragmenting the address space.
2091 if (num_empty_blocks <= num_major_sections)
2095 while (num_empty_blocks > section_reserve) {
2096 void *next = *(void**)empty_blocks;
2097 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
2098 empty_blocks = next;
2100 * Needs not be atomic because this is running
2105 ++stat_major_blocks_freed;
2106 #if SIZEOF_VOID_P != 8
2107 ++stat_major_blocks_freed_individual;
2113 major_pin_objects (SgenGrayQueue *queue)
2117 FOREACH_BLOCK_NO_LOCK (block) {
2118 size_t first_entry, last_entry;
2119 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2120 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2121 &first_entry, &last_entry);
2122 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2123 } END_FOREACH_BLOCK_NO_LOCK;
2127 major_init_to_space (void)
2132 major_report_pinned_memory_usage (void)
2134 g_assert_not_reached ();
2138 major_get_used_size (void)
2144 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2145 * finished, then we can iterate over the block array.
2147 major_finish_sweep_checking ();
2149 FOREACH_BLOCK_NO_LOCK (block) {
2150 int count = MS_BLOCK_FREE / block->obj_size;
2152 size += count * block->obj_size;
2153 for (iter = block->free_list; iter; iter = (void**)*iter)
2154 size -= block->obj_size;
2155 } END_FOREACH_BLOCK_NO_LOCK;
2160 /* FIXME: return number of bytes, not of sections */
2162 get_num_major_sections (void)
2164 return num_major_sections;
2168 * Returns the number of bytes in blocks that were present when the last sweep was
2169 * initiated, and were not freed during the sweep. They are the basis for calculating the
2173 get_bytes_survived_last_sweep (void)
2175 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2176 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2180 major_handle_gc_param (const char *opt)
2182 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2183 const char *arg = strchr (opt, '=') + 1;
2184 int percentage = atoi (arg);
2185 if (percentage < 0 || percentage > 100) {
2186 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2189 evacuation_threshold = (float)percentage / 100.0f;
2191 } else if (!strcmp (opt, "lazy-sweep")) {
2194 } else if (!strcmp (opt, "no-lazy-sweep")) {
2197 } else if (!strcmp (opt, "concurrent-sweep")) {
2198 concurrent_sweep = TRUE;
2200 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2201 concurrent_sweep = FALSE;
2209 major_print_gc_param_usage (void)
2213 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2214 " (no-)lazy-sweep\n"
2215 " (no-)concurrent-sweep\n"
2220 * This callback is used to clear cards, move cards to the shadow table and do counting.
2223 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2226 gboolean has_references;
2228 major_finish_sweep_checking ();
2229 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2231 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2232 } END_FOREACH_BLOCK_NO_LOCK;
2235 #ifdef HEAVY_STATISTICS
2236 extern guint64 marked_cards;
2237 extern guint64 scanned_cards;
2238 extern guint64 scanned_objects;
2239 extern guint64 remarked_cards;
2242 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2244 * MS blocks are 16K aligned.
2245 * Cardtables are 4K aligned, at least.
2246 * This means that the cardtable of a given block is 32 bytes aligned.
2249 initial_skip_card (guint8 *card_data)
2251 mword *cards = (mword*)card_data;
2254 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2260 if (i == CARD_WORDS_PER_BLOCK)
2261 return card_data + CARDS_PER_BLOCK;
2263 #if defined(__i386__) && defined(__GNUC__)
2264 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2265 #elif defined(__x86_64__) && defined(__GNUC__)
2266 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2267 #elif defined(__s390x__) && defined(__GNUC__)
2268 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2270 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2272 return &card_data [i];
2278 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2279 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2280 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2283 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2285 SgenGrayQueue *queue = ctx.queue;
2286 ScanObjectFunc scan_func = ctx.ops->scan_object;
2287 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2288 guint8 cards_copy [CARDS_PER_BLOCK];
2290 guint8 cards_preclean [CARDS_PER_BLOCK];
2291 gboolean small_objects;
2294 guint8 *card_data, *card_base;
2295 guint8 *card_data_end;
2296 char *scan_front = NULL;
2298 /* The concurrent mark doesn't enter evacuating blocks */
2299 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2302 block_obj_size = block->obj_size;
2303 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2305 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2308 * This is safe in face of card aliasing for the following reason:
2310 * Major blocks are 16k aligned, or 32 cards aligned.
2311 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2312 * sizes, they won't overflow the cardtable overlap modulus.
2314 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2315 card_data = card_base = block->cardtable_mod_union;
2317 * This happens when the nursery collection that precedes finishing
2318 * the concurrent collection allocates new major blocks.
2323 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2324 sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2325 card_data = card_base = cards_preclean;
2328 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2329 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2331 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2333 card_data = card_base = cards_copy;
2336 card_data_end = card_data + CARDS_PER_BLOCK;
2338 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2340 card_data = initial_skip_card (card_data);
2341 while (card_data < card_data_end) {
2342 size_t card_index, first_object_index;
2345 char *first_obj, *obj;
2347 HEAVY_STAT (++scanned_cards);
2354 card_index = card_data - card_base;
2355 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2356 end = start + CARD_SIZE_IN_BYTES;
2358 if (!block_is_swept_or_marking (block))
2359 sweep_block (block);
2361 HEAVY_STAT (++marked_cards);
2364 sgen_card_table_prepare_card_for_scanning (card_data);
2367 * If the card we're looking at starts at or in the block header, we
2368 * must start at the first object in the block, without calculating
2369 * the index of the object we're hypothetically starting at, because
2370 * it would be negative.
2372 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2373 first_object_index = 0;
2375 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2377 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2379 binary_protocol_card_scan (first_obj, end - first_obj);
2382 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2385 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2386 /* FIXME: do this more efficiently */
2388 MS_CALC_MARK_BIT (w, b, obj);
2389 if (!MS_MARK_BIT (block, w, b))
2393 GCObject *object = (GCObject*)obj;
2395 if (small_objects) {
2396 HEAVY_STAT (++scanned_objects);
2397 scan_func (object, sgen_obj_get_descriptor (object), queue);
2399 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2400 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2403 obj += block_obj_size;
2404 g_assert (scan_front <= obj);
2408 HEAVY_STAT (if (*card_data) ++remarked_cards);
2413 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2418 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx)
2421 gboolean has_references;
2423 if (!concurrent_mark)
2424 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2426 major_finish_sweep_checking ();
2427 binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2428 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2429 #ifdef PREFETCH_CARDS
2430 int prefetch_index = __index + 6;
2431 if (prefetch_index < allocated_blocks.next_slot) {
2432 MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2433 PREFETCH_READ (prefetch_block);
2434 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2435 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2436 PREFETCH_WRITE (prefetch_cards);
2437 PREFETCH_WRITE (prefetch_cards + 32);
2442 if (!has_references)
2445 scan_card_table_for_block (block, scan_type, ctx);
2446 } END_FOREACH_BLOCK_NO_LOCK;
2447 binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2451 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2454 gboolean has_references;
2455 long long total_cards = 0;
2456 long long marked_cards = 0;
2458 if (sweep_in_progress ()) {
2459 *num_total_cards = -1;
2460 *num_marked_cards = -1;
2464 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2465 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2468 if (!has_references)
2471 total_cards += CARDS_PER_BLOCK;
2472 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2476 } END_FOREACH_BLOCK_NO_LOCK;
2478 *num_total_cards = total_cards;
2479 *num_marked_cards = marked_cards;
2483 update_cardtable_mod_union (void)
2487 FOREACH_BLOCK_NO_LOCK (block) {
2488 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2489 gboolean has_dirty_cards = FALSE;
2491 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2492 if (card_start [i]) {
2493 has_dirty_cards = TRUE;
2497 if (has_dirty_cards) {
2499 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2500 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2501 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2503 } END_FOREACH_BLOCK_NO_LOCK;
2506 #undef pthread_create
2509 post_param_init (SgenMajorCollector *collector)
2511 collector->sweeps_lazily = lazy_sweep;
2512 collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2516 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2520 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2522 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2523 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2524 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2526 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2527 for (i = 0; i < num_block_obj_sizes; ++i)
2528 evacuate_block_obj_sizes [i] = FALSE;
2530 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2531 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2532 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2537 g_print ("block object sizes:\n");
2538 for (i = 0; i < num_block_obj_sizes; ++i)
2539 g_print ("%d\n", block_obj_sizes [i]);
2543 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2544 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2546 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2547 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2548 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2549 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2551 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2552 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2553 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2554 #if SIZEOF_VOID_P != 8
2555 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2556 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2557 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2558 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2561 collector->section_size = MAJOR_SECTION_SIZE;
2563 concurrent_mark = is_concurrent;
2564 collector->is_concurrent = is_concurrent;
2565 collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2566 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2567 collector->supports_cardtable = TRUE;
2569 collector->alloc_heap = major_alloc_heap;
2570 collector->is_object_live = major_is_object_live;
2571 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2572 collector->alloc_degraded = major_alloc_degraded;
2574 collector->alloc_object = major_alloc_object;
2575 collector->free_pinned_object = free_pinned_object;
2576 collector->iterate_objects = major_iterate_objects;
2577 collector->free_non_pinned_object = major_free_non_pinned_object;
2578 collector->pin_objects = major_pin_objects;
2579 collector->pin_major_object = pin_major_object;
2580 collector->scan_card_table = major_scan_card_table;
2581 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2582 if (is_concurrent) {
2583 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2584 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2586 collector->init_to_space = major_init_to_space;
2587 collector->sweep = major_sweep;
2588 collector->have_swept = major_have_swept;
2589 collector->finish_sweeping = major_finish_sweep_checking;
2590 collector->free_swept_blocks = major_free_swept_blocks;
2591 collector->check_scan_starts = major_check_scan_starts;
2592 collector->dump_heap = major_dump_heap;
2593 collector->get_used_size = major_get_used_size;
2594 collector->start_nursery_collection = major_start_nursery_collection;
2595 collector->finish_nursery_collection = major_finish_nursery_collection;
2596 collector->start_major_collection = major_start_major_collection;
2597 collector->finish_major_collection = major_finish_major_collection;
2598 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2599 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2600 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2601 collector->get_num_major_sections = get_num_major_sections;
2602 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2603 collector->handle_gc_param = major_handle_gc_param;
2604 collector->print_gc_param_usage = major_print_gc_param_usage;
2605 collector->post_param_init = post_param_init;
2606 collector->is_valid_object = major_is_valid_object;
2607 collector->describe_pointer = major_describe_pointer;
2608 collector->count_cards = major_count_cards;
2610 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2611 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2612 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2613 if (is_concurrent) {
2614 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2615 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2616 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2617 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2618 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2620 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2621 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2622 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2623 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2624 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2627 #ifdef HEAVY_STATISTICS
2628 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2629 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2630 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2631 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2632 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2633 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2634 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2635 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2636 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2637 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2638 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2640 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2641 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2642 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2645 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2646 mono_os_mutex_init (&scanned_objects_list_lock);
2649 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2651 /*cardtable requires major pages to be 8 cards aligned*/
2652 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2656 sgen_marksweep_init (SgenMajorCollector *collector)
2658 sgen_marksweep_init_internal (collector, FALSE);
2662 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2664 sgen_marksweep_init_internal (collector, TRUE);