3 * The Mark & Sweep major collector.
6 * Mark Probst <mark.probst@gmail.com>
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright (C) 2012 Xamarin Inc
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
23 #include "mono/sgen/sgen-gc.h"
24 #include "mono/sgen/sgen-protocol.h"
25 #include "mono/sgen/sgen-cardtable.h"
26 #include "mono/sgen/sgen-memory-governor.h"
27 #include "mono/sgen/sgen-layout-stats.h"
28 #include "mono/sgen/sgen-pointer-queue.h"
29 #include "mono/sgen/sgen-array-list.h"
30 #include "mono/sgen/sgen-pinning.h"
31 #include "mono/sgen/sgen-workers.h"
32 #include "mono/sgen/sgen-thread-pool.h"
33 #include "mono/sgen/sgen-client.h"
34 #include "mono/utils/mono-memory-model.h"
35 #include "mono/utils/mono-proclib.h"
37 static int ms_block_size;
40 * Blocks must be at least this size, meaning that if we detect a
41 * page size lower than this, we'll use this instead.
43 #define MS_BLOCK_SIZE_MIN (1024 * 16)
45 #define CARDS_PER_BLOCK (ms_block_size / CARD_SIZE_IN_BYTES)
48 * Don't allocate single blocks, but alloc a contingent of this many
49 * blocks in one swoop. This must be a power of two.
51 #define MS_BLOCK_ALLOC_NUM 32
53 #define MS_NUM_MARK_WORDS ((ms_block_size / SGEN_ALLOC_ALIGN + sizeof (guint32) * 8 - 1) / (sizeof (guint32) * 8))
56 * Use this instead of sizeof (MSBlockInfo) since the mark_words
57 * array size depends on page size at runtime.
59 #define SIZEOF_MS_BLOCK_INFO (sizeof (MSBlockInfo) + sizeof (guint32) * (MS_NUM_MARK_WORDS - MONO_ZERO_LEN_ARRAY))
62 * Number of bytes before the first object in a block. At the start
63 * of a block is the MSBlockHeader, then opional padding, then come
64 * the objects, so this must be >= SIZEOF_MS_BLOCK_INFO.
66 #define MS_BLOCK_SKIP ((SIZEOF_MS_BLOCK_INFO + 15) & ~15)
68 #define MS_BLOCK_FREE (ms_block_size - MS_BLOCK_SKIP)
71 * Blocks progress from one state to the next:
73 * SWEPT The block is fully swept. It might or might not be in
76 * MARKING The block might or might not contain live objects. If
77 * we're in between an initial collection pause and the
78 * finishing pause, the block might or might not be in a
81 * CHECKING The sweep thread is investigating the block to determine
82 * whether or not it contains live objects. The block is
85 * NEED_SWEEPING The block contains live objects but has not yet been
86 * swept. It also contains free slots. It is in a block
89 * SWEEPING The block is being swept. It might be in a free list.
96 BLOCK_STATE_NEED_SWEEPING,
100 typedef struct _MSBlockInfo MSBlockInfo;
101 struct _MSBlockInfo {
104 * FIXME: Do we even need this? It's only used during sweep and might be worth
105 * recalculating to save the space.
107 guint16 obj_size_index;
108 /* FIXME: Reduce this - it only needs a byte. */
109 volatile gint32 state;
111 unsigned int pinned : 1;
112 unsigned int has_references : 1;
113 unsigned int has_pinned : 1; /* means cannot evacuate */
114 unsigned int is_to_space : 1;
115 void ** volatile free_list;
116 MSBlockInfo * volatile next_free;
117 guint8 * volatile cardtable_mod_union;
118 guint32 mark_words [MONO_ZERO_LEN_ARRAY];
121 #define MS_BLOCK_FOR_BLOCK_INFO(b) ((char*)(b))
123 #define MS_BLOCK_OBJ(b,i) ((GCObject *)(MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i)))
124 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
125 #define MS_BLOCK_DATA_FOR_OBJ(o) ((char*)((mword)(o) & ~(mword)(ms_block_size - 1)))
131 #define MS_BLOCK_FOR_OBJ(o) (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
133 /* object index will always be small */
134 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
136 //casting to int is fine since blocks are 32k
137 #define MS_CALC_MARK_BIT(w,b,o) do { \
138 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
143 #define MS_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] & (ONE_P << (b)))
144 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
145 #define MS_SET_MARK_BIT_PAR(bl,w,b,first) do { \
146 guint32 tmp_mark_word = (bl)->mark_words [(w)]; \
147 guint32 old_mark_word; \
149 while (!(tmp_mark_word & (ONE_P << (b)))) { \
150 old_mark_word = tmp_mark_word; \
151 tmp_mark_word = InterlockedCompareExchange ((volatile gint32*)&(bl)->mark_words [w], old_mark_word | (ONE_P << (b)), old_mark_word); \
152 if (tmp_mark_word == old_mark_word) { \
160 #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))
162 #define MS_BLOCK_OBJ_SIZE_FACTOR (pow (2.0, 1.0 / 3))
165 * This way we can lookup block object size indexes for sizes up to
166 * 256 bytes with a single load.
168 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES 32
170 static int *block_obj_sizes;
171 static int num_block_obj_sizes;
172 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
174 #define MS_BLOCK_FLAG_PINNED 1
175 #define MS_BLOCK_FLAG_REFS 2
177 #define MS_BLOCK_TYPE_MAX 4
179 static gboolean *evacuate_block_obj_sizes;
180 static float evacuation_threshold = 0.666f;
182 static gboolean lazy_sweep = TRUE;
186 SWEEP_STATE_NEED_SWEEPING,
187 SWEEP_STATE_SWEEPING,
188 SWEEP_STATE_SWEEPING_AND_ITERATING,
189 SWEEP_STATE_COMPACTING
193 SGEN_SWEEP_SERIAL = FALSE,
194 SGEN_SWEEP_CONCURRENT = TRUE,
197 static volatile int sweep_state = SWEEP_STATE_SWEPT;
199 static gboolean concurrent_mark;
200 static gboolean concurrent_sweep = DEFAULT_SWEEP_MODE;
202 int sweep_pool_context = -1;
204 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
205 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
207 #define BLOCK_IS_TAGGED_CHECKING(bl) SGEN_POINTER_IS_TAGGED_2 ((bl))
208 #define BLOCK_TAG_CHECKING(bl) SGEN_POINTER_TAG_2 ((bl))
210 #define BLOCK_UNTAG(bl) ((MSBlockInfo *)SGEN_POINTER_UNTAG_12 ((bl)))
212 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
214 /* all allocated blocks in the system */
215 static SgenArrayList allocated_blocks = SGEN_ARRAY_LIST_INIT (NULL, sgen_array_list_default_is_slot_set, sgen_array_list_default_cas_setter, INTERNAL_MEM_PIN_QUEUE);
217 /* non-allocated block free-list */
218 static void *empty_blocks = NULL;
219 static size_t num_empty_blocks = 0;
220 static gboolean compact_blocks = FALSE;
223 * We can iterate the block list also while sweep is in progress but we
224 * need to account for blocks that will be checked for sweeping and even
225 * freed in the process.
227 #define FOREACH_BLOCK_NO_LOCK(bl) { \
228 volatile gpointer *slot; \
229 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
230 (bl) = BLOCK_UNTAG (*slot); \
233 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
234 volatile gpointer *slot; \
235 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
236 (bl) = (MSBlockInfo *) (*slot); \
239 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
240 (bl) = BLOCK_UNTAG ((bl));
241 #define END_FOREACH_BLOCK_NO_LOCK } SGEN_ARRAY_LIST_END_FOREACH_SLOT; }
243 #define FOREACH_BLOCK_RANGE_HAS_REFERENCES_NO_LOCK(bl,begin,end,index,hr) { \
244 volatile gpointer *slot; \
245 SGEN_ARRAY_LIST_FOREACH_SLOT_RANGE (&allocated_blocks, begin, end, slot, index) { \
246 (bl) = (MSBlockInfo *) (*slot); \
249 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
250 (bl) = BLOCK_UNTAG ((bl));
251 #define END_FOREACH_BLOCK_RANGE_NO_LOCK } SGEN_ARRAY_LIST_END_FOREACH_SLOT_RANGE; }
253 static volatile size_t num_major_sections = 0;
255 * One free block list for each block object size. We add and remove blocks from these
256 * lists lock-free via CAS.
258 * Blocks accessed/removed from `free_block_lists`:
259 * from the mutator (with GC lock held)
260 * in nursery collections
261 * in non-concurrent major collections
262 * in the finishing pause of concurrent major collections (whole list is cleared)
264 * Blocks added to `free_block_lists`:
265 * in the sweeping thread
266 * during nursery collections
267 * from domain clearing (with the world stopped and no sweeping happening)
269 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
270 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
272 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
273 static MonoNativeTlsKey worker_block_free_list_key;
275 static guint64 stat_major_blocks_alloced = 0;
276 static guint64 stat_major_blocks_freed = 0;
277 static guint64 stat_major_blocks_lazy_swept = 0;
279 static guint64 stat_major_blocks_freed_ideal = 0;
280 static guint64 stat_major_blocks_freed_less_ideal = 0;
281 static guint64 stat_major_blocks_freed_individual = 0;
282 static guint64 stat_major_blocks_alloced_less_ideal = 0;
284 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
285 static guint64 num_major_objects_marked = 0;
286 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
288 #define INC_NUM_MAJOR_OBJECTS_MARKED()
291 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
292 static mono_mutex_t scanned_objects_list_lock;
293 static SgenPointerQueue scanned_objects_list;
296 add_scanned_object (void *ptr)
298 if (!binary_protocol_is_enabled ())
301 mono_os_mutex_lock (&scanned_objects_list_lock);
302 sgen_pointer_queue_add (&scanned_objects_list, ptr);
303 mono_os_mutex_unlock (&scanned_objects_list_lock);
307 static gboolean sweep_block (MSBlockInfo *block);
310 ms_find_block_obj_size_index (size_t size)
313 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);
314 for (i = 0; i < num_block_obj_sizes; ++i)
315 if (block_obj_sizes [i] >= size)
317 g_error ("no object of size %zd\n", size);
321 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
322 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
323 #define FREE_BLOCKS_LOCAL(p,r) (FREE_BLOCKS_FROM (((MSBlockInfo***)mono_native_tls_get_value (worker_block_free_list_key)), (p), (r)))
325 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
326 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
327 fast_block_obj_size_indexes [((s)+7)>>3] : \
328 ms_find_block_obj_size_index ((s)))
331 major_alloc_heap (mword nursery_size, mword nursery_align)
335 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
337 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
343 update_heap_boundaries_for_block (MSBlockInfo *block)
345 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size);
352 ms_get_empty_block (void)
356 void *block, *empty, *next;
361 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
362 * unsuccessful, we halve the number of blocks and try again, until we're at
363 * 1. If that doesn't work, either, we assert.
365 int alloc_num = MS_BLOCK_ALLOC_NUM;
367 p = (char *)sgen_alloc_os_memory_aligned (ms_block_size * alloc_num, ms_block_size,
368 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
369 alloc_num == 1 ? "major heap section" : NULL, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
375 for (i = 0; i < alloc_num; ++i) {
378 * We do the free list update one after the
379 * other so that other threads can use the new
380 * blocks as quickly as possible.
383 empty = empty_blocks;
384 *(void**)block = empty;
385 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
389 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
391 stat_major_blocks_alloced += alloc_num;
392 #if SIZEOF_VOID_P != 8
393 if (alloc_num != MS_BLOCK_ALLOC_NUM)
394 stat_major_blocks_alloced_less_ideal += alloc_num;
399 empty = empty_blocks;
403 next = *(void**)block;
404 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
406 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
408 *(void**)block = NULL;
410 g_assert (!((mword)block & (ms_block_size - 1)));
416 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
417 * list, where it will either be freed later on, or reused in nursery collections.
420 ms_free_block (MSBlockInfo *info)
423 char *block = MS_BLOCK_FOR_BLOCK_INFO (info);
425 sgen_memgov_release_space (ms_block_size, SPACE_MAJOR);
426 if (info->cardtable_mod_union)
427 sgen_card_table_free_mod_union (info->cardtable_mod_union, block, ms_block_size);
428 memset (block, 0, ms_block_size);
431 empty = empty_blocks;
432 *(void**)block = empty;
433 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
435 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
437 binary_protocol_block_free (block, ms_block_size);
441 sweep_in_progress (void)
443 int state = sweep_state;
444 return state == SWEEP_STATE_SWEEPING ||
445 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
446 state == SWEEP_STATE_COMPACTING;
449 static inline gboolean
450 block_is_swept_or_marking (MSBlockInfo *block)
452 gint32 state = block->state;
453 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
456 //#define MARKSWEEP_CONSISTENCY_CHECK
458 #ifdef MARKSWEEP_CONSISTENCY_CHECK
460 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
462 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
463 for (; block; block = block->next_free) {
464 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
465 g_assert (block->obj_size == size);
466 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
468 /* blocks in the free lists must have at least
470 g_assert (block->free_list);
472 /* the block must be in the allocated_blocks array */
473 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
478 check_empty_blocks (void)
482 for (p = empty_blocks; p; p = *(void**)p)
484 g_assert (i == num_empty_blocks);
488 consistency_check (void)
493 /* check all blocks */
494 FOREACH_BLOCK_NO_LOCK (block) {
495 int count = MS_BLOCK_FREE / block->obj_size;
499 /* count number of free slots */
500 for (i = 0; i < count; ++i) {
501 void **obj = (void**) MS_BLOCK_OBJ (block, i);
502 if (!MS_OBJ_ALLOCED (obj, block))
506 /* check free list */
507 for (free = block->free_list; free; free = (void**)*free) {
508 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
511 g_assert (num_free == 0);
513 /* check all mark words are zero */
514 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
515 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
516 g_assert (block->mark_words [i] == 0);
518 } END_FOREACH_BLOCK_NO_LOCK;
520 /* check free blocks */
521 for (i = 0; i < num_block_obj_sizes; ++i) {
523 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
524 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
527 check_empty_blocks ();
532 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
536 block->next_free = old = free_blocks [size_index];
537 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
540 static void major_finish_sweep_checking (void);
543 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
545 int size = block_obj_sizes [size_index];
546 int count = MS_BLOCK_FREE / size;
548 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
552 if (!sgen_memgov_try_alloc_space (ms_block_size, SPACE_MAJOR))
555 info = (MSBlockInfo*)ms_get_empty_block ();
557 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
559 info->obj_size = size;
560 info->obj_size_index = size_index;
561 info->pinned = pinned;
562 info->has_references = has_references;
563 info->has_pinned = pinned;
565 * Blocks that are to-space are not evacuated from. During an major collection
566 * blocks are allocated for two reasons: evacuating objects from the nursery and
567 * evacuating them from major blocks marked for evacuation. In both cases we don't
568 * want further evacuation. We also don't want to evacuate objects allocated during
569 * the concurrent mark since it would add pointless stress on the finishing pause.
571 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
572 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
573 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
574 info->cardtable_mod_union = NULL;
576 update_heap_boundaries_for_block (info);
578 binary_protocol_block_alloc (info, ms_block_size);
580 /* build free list */
581 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
582 info->free_list = (void**)obj_start;
583 /* we're skipping the last one - it must be nulled */
584 for (i = 0; i < count - 1; ++i) {
585 char *next_obj_start = obj_start + size;
586 *(void**)obj_start = next_obj_start;
587 obj_start = next_obj_start;
590 *(void**)obj_start = NULL;
592 add_free_block (free_blocks, size_index, info);
594 sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
596 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
601 ptr_is_in_major_block (char *ptr, char **start, gboolean *pinned)
605 FOREACH_BLOCK_NO_LOCK (block) {
606 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) {
607 int count = MS_BLOCK_FREE / block->obj_size;
612 for (i = 0; i <= count; ++i) {
613 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
615 *start = (char *)MS_BLOCK_OBJ (block, i);
620 *pinned = block->pinned;
623 } END_FOREACH_BLOCK_NO_LOCK;
628 ptr_is_from_pinned_alloc (char *ptr)
631 if (ptr_is_in_major_block (ptr, NULL, &pinned))
637 ensure_can_access_block_free_list (MSBlockInfo *block)
641 switch (block->state) {
642 case BLOCK_STATE_SWEPT:
643 case BLOCK_STATE_MARKING:
645 case BLOCK_STATE_CHECKING:
646 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
648 case BLOCK_STATE_NEED_SWEEPING:
649 if (sweep_block (block))
650 ++stat_major_blocks_lazy_swept;
652 case BLOCK_STATE_SWEEPING:
653 /* FIXME: do this more elegantly */
657 SGEN_ASSERT (0, FALSE, "Illegal block state");
664 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
666 MSBlockInfo *block, *next_free_block;
667 void *obj, *next_free_slot;
670 block = free_blocks [size_index];
671 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
673 ensure_can_access_block_free_list (block);
675 obj = block->free_list;
676 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
678 next_free_slot = *(void**)obj;
679 if (next_free_slot) {
680 block->free_list = (gpointer *)next_free_slot;
684 next_free_block = block->next_free;
685 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
688 block->free_list = NULL;
689 block->next_free = NULL;
695 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
697 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
698 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
701 if (!free_blocks [size_index]) {
702 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
706 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
708 /* FIXME: assumes object layout */
709 *(GCVTable*)obj = vtable;
711 total_allocated_major += block_obj_sizes [size_index];
713 return (GCObject *)obj;
717 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
719 return alloc_obj (vtable, size, FALSE, has_references);
723 * This can only be called by sgen workers. While this is called we assume
724 * that no other thread is accessing the block free lists. The world should
725 * be stopped and the gc thread should be waiting for workers to finish.
728 major_alloc_object_par (GCVTable vtable, size_t size, gboolean has_references)
730 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
731 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (FALSE, has_references);
732 MSBlockInfo **free_blocks_local = FREE_BLOCKS_LOCAL (FALSE, has_references);
735 if (free_blocks_local [size_index]) {
737 obj = unlink_slot_from_free_list_uncontested (free_blocks_local, size_index);
741 block = free_blocks [size_index];
743 if (G_UNLIKELY (!ms_alloc_block (size_index, FALSE, has_references)))
747 MSBlockInfo *next_free = block->next_free;
749 * Once a block is removed from the main list, it cannot return on the list until
750 * all the workers are finished and sweep is starting. This means we don't need
751 * to account for ABA problems.
753 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free, block) != block)
755 block->next_free = free_blocks_local [size_index];
756 free_blocks_local [size_index] = block;
762 /* FIXME: assumes object layout */
763 *(GCVTable*)obj = vtable;
765 /* FIXME is it worth CAS-ing here */
766 total_allocated_major += block_obj_sizes [size_index];
768 return (GCObject *)obj;
772 * We're not freeing the block if it's empty. We leave that work for
773 * the next major collection.
775 * This is just called from the domain clearing code, which runs in a
776 * single thread and has the GC lock, so we don't need an extra lock.
779 free_object (GCObject *obj, size_t size, gboolean pinned)
781 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
783 gboolean in_free_list;
785 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
787 ensure_can_access_block_free_list (block);
788 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);
789 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
790 MS_CALC_MARK_BIT (word, bit, obj);
791 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
793 memset (obj, 0, size);
795 in_free_list = !!block->free_list;
796 *(void**)obj = block->free_list;
797 block->free_list = (void**)obj;
800 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
801 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
802 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);
803 add_free_block (free_blocks, size_index, block);
808 major_free_non_pinned_object (GCObject *obj, size_t size)
810 free_object (obj, size, FALSE);
813 /* size is a multiple of SGEN_ALLOC_ALIGN */
815 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
819 res = alloc_obj (vtable, size, TRUE, has_references);
820 /*If we failed to alloc memory, we better try releasing memory
821 *as pinned alloc is requested by the runtime.
824 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE, TRUE);
825 res = alloc_obj (vtable, size, TRUE, has_references);
827 return (GCObject *)res;
831 free_pinned_object (GCObject *obj, size_t size)
833 free_object (obj, size, TRUE);
837 * size is already rounded up and we hold the GC lock.
840 major_alloc_degraded (GCVTable vtable, size_t size)
844 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
845 if (G_LIKELY (obj)) {
846 HEAVY_STAT (++stat_objects_alloced_degraded);
847 HEAVY_STAT (stat_bytes_alloced_degraded += size);
853 * obj is some object. If it's not in the major heap (i.e. if it's in
854 * the nursery or LOS), return FALSE. Otherwise return whether it's
855 * been marked or copied.
858 major_is_object_live (GCObject *obj)
864 if (sgen_ptr_in_nursery (obj))
867 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
870 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
873 /* now we know it's in a major block */
874 block = MS_BLOCK_FOR_OBJ (obj);
875 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
876 MS_CALC_MARK_BIT (word, bit, obj);
877 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
881 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
884 if (ptr_is_in_major_block (ptr, start, &pinned))
890 try_set_sweep_state (int new_, int expected)
892 int old = SGEN_CAS (&sweep_state, new_, expected);
893 return old == expected;
897 set_sweep_state (int new_, int expected)
899 gboolean success = try_set_sweep_state (new_, expected);
900 SGEN_ASSERT (0, success, "Could not set sweep state.");
903 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
905 static SgenThreadPoolJob * volatile sweep_job;
906 static SgenThreadPoolJob * volatile sweep_blocks_job;
909 major_finish_sweep_checking (void)
912 SgenThreadPoolJob *job;
915 switch (sweep_state) {
916 case SWEEP_STATE_SWEPT:
917 case SWEEP_STATE_NEED_SWEEPING:
919 case SWEEP_STATE_SWEEPING:
920 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
923 case SWEEP_STATE_SWEEPING_AND_ITERATING:
924 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
926 case SWEEP_STATE_COMPACTING:
929 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
934 * We're running with the world stopped and the only other thread doing work is the
935 * sweep thread, which doesn't add blocks to the array, so we can safely access
938 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
939 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
941 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
946 sgen_thread_pool_job_wait (sweep_pool_context, job);
947 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
948 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
952 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
954 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
955 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
956 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
959 /* No actual sweeping will take place if we are in the middle of a major collection. */
960 major_finish_sweep_checking ();
961 FOREACH_BLOCK_NO_LOCK (block) {
962 int count = MS_BLOCK_FREE / block->obj_size;
965 if (block->pinned && !pinned)
967 if (!block->pinned && !non_pinned)
969 if (sweep && lazy_sweep && !block_is_swept_or_marking (block)) {
971 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
974 for (i = 0; i < count; ++i) {
975 void **obj = (void**) MS_BLOCK_OBJ (block, i);
976 if (MS_OBJ_ALLOCED (obj, block))
977 callback ((GCObject*)obj, block->obj_size, data);
979 } END_FOREACH_BLOCK_NO_LOCK;
983 major_is_valid_object (char *object)
987 FOREACH_BLOCK_NO_LOCK (block) {
991 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) <= object))
994 idx = MS_BLOCK_OBJ_INDEX (object, block);
995 obj = (char*)MS_BLOCK_OBJ (block, idx);
998 return MS_OBJ_ALLOCED (obj, block);
999 } END_FOREACH_BLOCK_NO_LOCK;
1006 major_describe_pointer (char *ptr)
1010 FOREACH_BLOCK_NO_LOCK (block) {
1018 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) <= ptr))
1021 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
1022 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
1024 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
1025 obj = (char*)MS_BLOCK_OBJ (block, idx);
1026 live = MS_OBJ_ALLOCED (obj, block);
1027 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
1029 MS_CALC_MARK_BIT (w, b, obj);
1030 marked = MS_MARK_BIT (block, w, b);
1033 SGEN_LOG (0, "\t(");
1035 SGEN_LOG (0, "object");
1037 SGEN_LOG (0, "dead-object");
1040 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
1042 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
1045 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
1048 } END_FOREACH_BLOCK_NO_LOCK;
1054 major_check_scan_starts (void)
1059 major_dump_heap (FILE *heap_dump_file)
1062 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1063 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1066 for (i = 0; i < num_block_obj_sizes; ++i)
1067 slots_available [i] = slots_used [i] = 0;
1069 FOREACH_BLOCK_NO_LOCK (block) {
1070 int index = ms_find_block_obj_size_index (block->obj_size);
1071 int count = MS_BLOCK_FREE / block->obj_size;
1073 slots_available [index] += count;
1074 for (i = 0; i < count; ++i) {
1075 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1076 ++slots_used [index];
1078 } END_FOREACH_BLOCK_NO_LOCK;
1080 fprintf (heap_dump_file, "<occupancies>\n");
1081 for (i = 0; i < num_block_obj_sizes; ++i) {
1082 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1083 block_obj_sizes [i], slots_available [i], slots_used [i]);
1085 fprintf (heap_dump_file, "</occupancies>\n");
1087 FOREACH_BLOCK_NO_LOCK (block) {
1088 int count = MS_BLOCK_FREE / block->obj_size;
1092 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1094 for (i = 0; i <= count; ++i) {
1095 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1100 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1106 fprintf (heap_dump_file, "</section>\n");
1107 } END_FOREACH_BLOCK_NO_LOCK;
1111 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1113 guint8 *mod_union = block->cardtable_mod_union;
1119 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
1120 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1122 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1125 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
1129 static inline guint8*
1130 major_get_cardtable_mod_union_for_reference (char *ptr)
1132 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1133 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1134 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1135 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1136 return &mod_union [offset];
1140 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1143 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1145 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1146 if (sgen_safe_object_is_small (obj, type)) {
1147 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1148 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?");
1151 sgen_los_mark_mod_union_card (obj, ptr);
1153 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1156 static inline gboolean
1157 major_block_is_evacuating (MSBlockInfo *block)
1159 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1160 !block->has_pinned &&
1161 !block->is_to_space)
1166 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1167 int __word, __bit; \
1168 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1169 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1170 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1171 MS_SET_MARK_BIT ((block), __word, __bit); \
1172 if (sgen_gc_descr_has_references (desc)) \
1173 GRAY_OBJECT_ENQUEUE_SERIAL ((queue), (obj), (desc)); \
1174 binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1175 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1178 #define MS_MARK_OBJECT_AND_ENQUEUE_PAR(obj,desc,block,queue) do { \
1179 int __word, __bit; \
1181 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1182 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1183 MS_SET_MARK_BIT_PAR ((block), __word, __bit, first); \
1185 if (sgen_gc_descr_has_references (desc)) \
1186 GRAY_OBJECT_ENQUEUE_PARALLEL ((queue), (obj), (desc)); \
1187 binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1188 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1195 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1199 if (concurrent_mark)
1200 g_assert_not_reached ();
1202 block = MS_BLOCK_FOR_OBJ (obj);
1203 block->has_pinned = TRUE;
1204 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1207 #define COPY_OR_MARK_PARALLEL
1208 #include "sgen-major-copy-object.h"
1211 major_get_and_reset_num_major_objects_marked (void)
1213 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1214 long long num = num_major_objects_marked;
1215 num_major_objects_marked = 0;
1222 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1224 #undef PREFETCH_CARDS
1227 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1228 #if defined(HOST_DARWIN)
1229 #if MONO_GNUC_VERSION <= 40300
1230 #undef PREFETCH_CARDS
1234 #ifdef HEAVY_STATISTICS
1235 static guint64 stat_optimized_copy;
1236 static guint64 stat_optimized_copy_nursery;
1237 static guint64 stat_optimized_copy_nursery_forwarded;
1238 static guint64 stat_optimized_copy_nursery_pinned;
1239 static guint64 stat_optimized_copy_major;
1240 static guint64 stat_optimized_copy_major_small_fast;
1241 static guint64 stat_optimized_copy_major_small_slow;
1242 static guint64 stat_optimized_copy_major_large;
1243 static guint64 stat_optimized_copy_major_forwarded;
1244 static guint64 stat_optimized_copy_major_small_evacuate;
1245 static guint64 stat_optimized_major_scan;
1246 static guint64 stat_optimized_major_scan_no_refs;
1248 static guint64 stat_drain_prefetch_fills;
1249 static guint64 stat_drain_prefetch_fill_failures;
1250 static guint64 stat_drain_loops;
1253 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1254 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1255 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1256 #include "sgen-marksweep-drain-gray-stack.h"
1258 #define COPY_OR_MARK_PARALLEL
1259 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_par_no_evacuation
1260 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_par_no_evacuation
1261 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_par_no_evacuation
1262 #include "sgen-marksweep-drain-gray-stack.h"
1264 #define COPY_OR_MARK_WITH_EVACUATION
1265 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1266 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1267 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_with_evacuation
1268 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1269 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_with_evacuation
1270 #include "sgen-marksweep-drain-gray-stack.h"
1272 #define COPY_OR_MARK_PARALLEL
1273 #define COPY_OR_MARK_WITH_EVACUATION
1274 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_par_with_evacuation
1275 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_par_with_evacuation
1276 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_par_with_evacuation
1277 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_par_with_evacuation
1278 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_par_with_evacuation
1279 #include "sgen-marksweep-drain-gray-stack.h"
1281 #define COPY_OR_MARK_CONCURRENT
1282 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1283 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1284 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1285 #include "sgen-marksweep-drain-gray-stack.h"
1287 #define COPY_OR_MARK_PARALLEL
1288 #define COPY_OR_MARK_CONCURRENT
1289 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_par_no_evacuation
1290 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_par_no_evacuation
1291 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_par_no_evacuation
1292 #include "sgen-marksweep-drain-gray-stack.h"
1294 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1295 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1296 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1297 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_with_evacuation
1298 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_with_evacuation
1299 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1300 #include "sgen-marksweep-drain-gray-stack.h"
1302 #define COPY_OR_MARK_PARALLEL
1303 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1304 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_par_with_evacuation
1305 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_par_with_evacuation
1306 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_par_with_evacuation
1307 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_par_with_evacuation
1308 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_par_with_evacuation
1309 #include "sgen-marksweep-drain-gray-stack.h"
1311 static inline gboolean
1312 major_is_evacuating (void)
1315 for (i = 0; i < num_block_obj_sizes; ++i) {
1316 if (evacuate_block_obj_sizes [i]) {
1325 drain_gray_stack (SgenGrayQueue *queue)
1327 if (major_is_evacuating ())
1328 return drain_gray_stack_with_evacuation (queue);
1330 return drain_gray_stack_no_evacuation (queue);
1334 drain_gray_stack_par (SgenGrayQueue *queue)
1336 if (major_is_evacuating ())
1337 return drain_gray_stack_par_with_evacuation (queue);
1339 return drain_gray_stack_par_no_evacuation (queue);
1343 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1345 if (major_is_evacuating ())
1346 return drain_gray_stack_concurrent_with_evacuation (queue);
1348 return drain_gray_stack_concurrent_no_evacuation (queue);
1352 drain_gray_stack_concurrent_par (SgenGrayQueue *queue)
1354 if (major_is_evacuating ())
1355 return drain_gray_stack_concurrent_par_with_evacuation (queue);
1357 return drain_gray_stack_concurrent_par_no_evacuation (queue);
1361 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1363 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1367 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1369 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1373 major_copy_or_mark_object_concurrent_par_canonical (GCObject **ptr, SgenGrayQueue *queue)
1375 major_copy_or_mark_object_concurrent_par_with_evacuation (ptr, *ptr, queue);
1379 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1381 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1385 major_copy_or_mark_object_concurrent_par_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1387 major_copy_or_mark_object_par_with_evacuation (ptr, *ptr, queue);
1391 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1393 void **entry, **end;
1394 int last_index = -1;
1396 if (first_entry == last_entry)
1399 entry = sgen_pinning_get_entry (first_entry);
1400 end = sgen_pinning_get_entry (last_entry);
1402 for (; entry < end; ++entry) {
1403 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1405 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));
1406 if (index == last_index)
1408 obj = MS_BLOCK_OBJ (block, index);
1409 if (!MS_OBJ_ALLOCED (obj, block))
1411 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1412 sgen_pin_stats_register_object (obj, GENERATION_OLD);
1417 * There might have been potential pinning "pointers" into this block, but none of
1418 * them pointed to occupied slots, in which case we don't have to pin the block.
1420 if (last_index >= 0)
1421 block->has_pinned = TRUE;
1425 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1428 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, 0, obj_size);
1430 for (obj_index = 0; obj_index < count; ++obj_index, obj = (void*)((mword)obj + obj_size)) {
1433 MS_CALC_MARK_BIT (word, bit, obj);
1434 if (MS_MARK_BIT (block, word, bit)) {
1435 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1437 /* an unmarked object */
1438 if (MS_OBJ_ALLOCED (obj, block)) {
1440 * FIXME: Merge consecutive
1441 * slots for lower reporting
1442 * overhead. Maybe memset
1443 * will also benefit?
1445 binary_protocol_empty (obj, obj_size);
1446 memset (obj, 0, obj_size);
1448 *(void**)obj = block->free_list;
1449 block->free_list = (void **)obj;
1454 static inline gboolean
1455 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1457 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1458 gboolean success = old_state == expected_state;
1460 binary_protocol_block_set_state (block, ms_block_size, old_state, new_state);
1465 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1467 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1468 block->state = new_state;
1469 binary_protocol_block_set_state (block, ms_block_size, expected_state, new_state);
1473 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1475 * Sweeping means iterating through the block's slots and building the free-list from the
1476 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1479 sweep_block (MSBlockInfo *block)
1482 void *reversed = NULL;
1485 switch (block->state) {
1486 case BLOCK_STATE_SWEPT:
1488 case BLOCK_STATE_MARKING:
1489 case BLOCK_STATE_CHECKING:
1490 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1492 case BLOCK_STATE_SWEEPING:
1493 /* FIXME: Do this more elegantly */
1496 case BLOCK_STATE_NEED_SWEEPING:
1497 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1501 SGEN_ASSERT (0, FALSE, "Illegal block state");
1504 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1506 count = MS_BLOCK_FREE / block->obj_size;
1508 block->free_list = NULL;
1510 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1511 // FIXME: Add more sizes
1512 switch (block->obj_size) {
1514 sweep_block_for_size (block, count, 16);
1517 sweep_block_for_size (block, count, block->obj_size);
1521 /* reset mark bits */
1522 memset (block->mark_words, 0, sizeof (guint32) * MS_NUM_MARK_WORDS);
1524 /* Reverse free list so that it's in address order */
1526 while (block->free_list) {
1527 void *next = *(void**)block->free_list;
1528 *(void**)block->free_list = reversed;
1529 reversed = block->free_list;
1530 block->free_list = (void **)next;
1532 block->free_list = (void **)reversed;
1534 mono_memory_write_barrier ();
1536 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1547 if (sizeof (mword) == 8)
1548 count += __builtin_popcountll (d);
1550 count += __builtin_popcount (d);
1560 /* statistics for evacuation */
1561 static size_t *sweep_slots_available;
1562 static size_t *sweep_slots_used;
1563 static size_t *sweep_num_blocks;
1565 static volatile size_t num_major_sections_before_sweep;
1566 static volatile size_t num_major_sections_freed_in_sweep;
1569 sgen_worker_clear_free_block_lists (WorkerData *worker)
1573 if (!worker->free_block_lists)
1576 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++) {
1577 for (j = 0; j < num_block_obj_sizes; j++) {
1578 ((MSBlockInfo***) worker->free_block_lists) [i][j] = NULL;
1584 sgen_worker_clear_free_block_lists_evac (WorkerData *worker)
1588 if (!worker->free_block_lists)
1591 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++) {
1592 for (j = 0; j < num_block_obj_sizes; j++) {
1593 if (((MSBlockInfo***) worker->free_block_lists) [i][j])
1594 SGEN_ASSERT (0, !((MSBlockInfo***) worker->free_block_lists) [i][j]->next_free, "Why do we have linked free blocks on the workers");
1596 if (evacuate_block_obj_sizes [j])
1597 ((MSBlockInfo***) worker->free_block_lists) [i][j] = NULL;
1607 for (i = 0; i < num_block_obj_sizes; ++i)
1608 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1610 /* clear all the free lists */
1611 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1612 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1614 for (j = 0; j < num_block_obj_sizes; ++j)
1615 free_blocks [j] = NULL;
1618 sgen_workers_foreach (GENERATION_NURSERY, sgen_worker_clear_free_block_lists);
1619 sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists);
1621 compact_blocks = TRUE;
1624 static void sweep_finish (void);
1627 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1628 * the checking has finished.
1630 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1631 * be correct, i.e. must not be used.
1634 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1637 gboolean have_live = FALSE;
1638 gboolean have_free = FALSE;
1644 volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1646 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1649 *have_checked = FALSE;
1652 tagged_block = *(void * volatile *)block_slot;
1656 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1659 /* FIXME: do this more elegantly */
1664 if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1667 block = BLOCK_UNTAG (tagged_block);
1668 block_state = block->state;
1670 if (!sweep_in_progress ()) {
1671 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1673 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1676 switch (block_state) {
1677 case BLOCK_STATE_SWEPT:
1678 case BLOCK_STATE_NEED_SWEEPING:
1679 case BLOCK_STATE_SWEEPING:
1681 case BLOCK_STATE_MARKING:
1683 case BLOCK_STATE_CHECKING:
1684 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1687 SGEN_ASSERT (0, FALSE, "Illegal block state");
1691 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1692 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1695 *have_checked = TRUE;
1697 block->has_pinned = block->pinned;
1699 block->is_to_space = FALSE;
1701 count = MS_BLOCK_FREE / block->obj_size;
1703 if (block->cardtable_mod_union)
1704 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1706 /* Count marked objects in the block */
1707 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1708 nused += bitcount (block->mark_words [i]);
1710 block->nused = nused;
1717 int obj_size_index = block->obj_size_index;
1718 gboolean has_pinned = block->has_pinned;
1720 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1723 * FIXME: Go straight to SWEPT if there are no free slots. We need
1724 * to set the free slot list to NULL, though, and maybe update some
1728 sweep_block (block);
1731 ++sweep_num_blocks [obj_size_index];
1732 sweep_slots_used [obj_size_index] += nused;
1733 sweep_slots_available [obj_size_index] += count;
1737 * If there are free slots in the block, add
1738 * the block to the corresponding free list.
1741 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1744 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1746 add_free_block (free_blocks, obj_size_index, block);
1749 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1750 update_heap_boundaries_for_block (block);
1753 * Blocks without live objects are removed from the
1754 * block list and freed.
1756 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1757 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1759 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1760 ms_free_block (block);
1762 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1763 SGEN_ATOMIC_ADD_P (num_major_sections_freed_in_sweep, 1);
1765 tagged_block = NULL;
1770 * Once the block is written back without the checking bit other threads are
1771 * free to access it. Make sure the block state is visible before we write it
1774 mono_memory_write_barrier ();
1775 *block_slot = tagged_block;
1776 return !!tagged_block;
1780 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1782 volatile gpointer *slot;
1785 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1786 bl = BLOCK_UNTAG (*slot);
1789 } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1791 mono_memory_write_barrier ();
1793 sweep_blocks_job = NULL;
1797 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1799 guint32 block_index;
1800 guint32 num_blocks = num_major_sections_before_sweep;
1802 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1803 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1806 * We traverse the block array from high to low. Nursery collections will have to
1807 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1808 * low to high, to avoid constantly colliding on the same blocks.
1810 for (block_index = allocated_blocks.next_slot; block_index-- > 0;) {
1811 ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL);
1814 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1816 * The main GC thread is currently iterating over the block array to help us
1817 * finish the sweep. We have already finished, but we don't want to mess up
1818 * that iteration, so we just wait for it.
1823 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1824 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1825 MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1826 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1831 * Concurrently sweep all the blocks to reduce workload during minor
1832 * pauses where we need certain blocks to be swept. At the start of
1833 * the next major we need all blocks to be swept anyway.
1835 if (concurrent_sweep && lazy_sweep) {
1836 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1837 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_blocks_job);
1848 mword used_slots_size = 0;
1851 for (i = 0; i < num_block_obj_sizes; ++i) {
1852 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1853 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1854 evacuate_block_obj_sizes [i] = TRUE;
1856 g_print ("slot size %d - %d of %d used\n",
1857 block_obj_sizes [i], slots_used [i], slots_available [i]);
1860 evacuate_block_obj_sizes [i] = FALSE;
1863 used_slots_size += sweep_slots_used [i] * block_obj_sizes [i];
1866 sgen_memgov_major_post_sweep (used_slots_size);
1868 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1869 if (concurrent_sweep)
1870 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1876 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1880 num_major_sections_before_sweep = num_major_sections;
1881 num_major_sections_freed_in_sweep = 0;
1883 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1884 if (concurrent_sweep) {
1885 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1886 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_job);
1888 sweep_job_func (NULL, NULL);
1893 major_have_swept (void)
1895 return sweep_state == SWEEP_STATE_SWEPT;
1898 static int count_pinned_ref;
1899 static int count_pinned_nonref;
1900 static int count_nonpinned_ref;
1901 static int count_nonpinned_nonref;
1904 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1906 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1908 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1909 ++count_nonpinned_ref;
1911 ++count_nonpinned_nonref;
1915 count_pinned_callback (GCObject *obj, size_t size, void *data)
1917 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1919 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1922 ++count_pinned_nonref;
1925 static G_GNUC_UNUSED void
1926 count_ref_nonref_objs (void)
1930 count_pinned_ref = 0;
1931 count_pinned_nonref = 0;
1932 count_nonpinned_ref = 0;
1933 count_nonpinned_nonref = 0;
1935 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1936 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1938 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1940 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1941 count_pinned_ref, count_nonpinned_ref,
1942 count_pinned_nonref, count_nonpinned_nonref,
1943 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1947 ms_calculate_block_obj_sizes (double factor, int *arr)
1954 * Have every possible slot size starting with the minimal
1955 * object size up to and including four times that size. Then
1956 * proceed by increasing geometrically with the given factor.
1959 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1961 arr [num_sizes] = size;
1965 target_size = (double)last_size;
1968 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1969 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1971 if (size != last_size) {
1973 arr [num_sizes] = size;
1978 target_size *= factor;
1979 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1984 /* only valid during minor collections */
1985 static mword old_num_major_sections;
1988 major_start_nursery_collection (void)
1990 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1991 consistency_check ();
1994 old_num_major_sections = num_major_sections;
1996 /* Compact the block list if it hasn't been compacted in a while and nobody is using it */
1997 if (compact_blocks && !sweep_in_progress () && !sweep_blocks_job && !sgen_concurrent_collection_in_progress ()) {
1999 * We support null elements in the array but do regular compaction to avoid
2000 * excessive traversal of the array and to facilitate splitting into well
2001 * balanced sections for parallel modes. We compact as soon as possible after
2004 sgen_array_list_remove_nulls (&allocated_blocks);
2005 compact_blocks = FALSE;
2010 major_finish_nursery_collection (void)
2012 #ifdef MARKSWEEP_CONSISTENCY_CHECK
2013 consistency_check ();
2018 block_usage_comparer (const void *bl1, const void *bl2)
2020 const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
2021 const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
2023 return nused2 - nused1;
2027 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
2029 MSBlockInfo **evacuated_blocks;
2030 size_t index = 0, count, num_blocks = 0, num_used = 0;
2032 MSBlockInfo * volatile *prev;
2034 for (info = *block_list; info != NULL; info = info->next_free) {
2036 num_used += info->nused;
2040 * We have a set of blocks in the freelist which will be evacuated. Instead
2041 * of evacuating all of the blocks into new ones, we traverse the freelist
2042 * sorting it by the number of occupied slots, evacuating the objects from
2043 * blocks with fewer used slots into fuller blocks.
2045 * The number of used slots is set at the end of the previous sweep. Since
2046 * we sequentially unlink slots from blocks, except for the head of the
2047 * freelist, for blocks on the freelist, the number of used slots is the same
2048 * as at the end of the previous sweep.
2050 evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
2052 for (info = *block_list; info != NULL; info = info->next_free) {
2053 evacuated_blocks [index++] = info;
2056 SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
2058 sgen_qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
2061 * Form a new freelist with the fullest blocks. These blocks will also be
2062 * marked as to_space so we don't evacuate from them.
2064 count = MS_BLOCK_FREE / block_obj_sizes [size_index];
2066 for (index = 0; index < (num_used + count - 1) / count; index++) {
2067 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
2068 info = evacuated_blocks [index];
2069 info->is_to_space = TRUE;
2071 prev = &info->next_free;
2075 sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
2079 major_start_major_collection (void)
2084 major_finish_sweep_checking ();
2087 * Clear the free lists for block sizes where we do evacuation. For those block
2088 * sizes we will have to allocate new blocks.
2090 for (i = 0; i < num_block_obj_sizes; ++i) {
2091 if (!evacuate_block_obj_sizes [i])
2094 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
2096 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
2097 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
2100 /* We expect workers to have very few blocks on the freelist, just evacuate them */
2101 sgen_workers_foreach (GENERATION_NURSERY, sgen_worker_clear_free_block_lists_evac);
2102 sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists_evac);
2104 if (lazy_sweep && concurrent_sweep) {
2106 * sweep_blocks_job is created before sweep_finish, which we wait for above
2107 * (major_finish_sweep_checking). After the end of sweep, if we don't have
2108 * sweep_blocks_job set, it means that it has already been run.
2110 SgenThreadPoolJob *job = sweep_blocks_job;
2112 sgen_thread_pool_job_wait (sweep_pool_context, job);
2115 if (lazy_sweep && !concurrent_sweep)
2116 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
2117 /* Sweep all unswept blocks and set them to MARKING */
2118 FOREACH_BLOCK_NO_LOCK (block) {
2119 if (lazy_sweep && !concurrent_sweep)
2120 sweep_block (block);
2121 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
2122 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
2124 * Swept blocks that have a null free_list are full. Evacuation is not
2125 * effective on these blocks since we expect them to have high usage anyway,
2126 * given that the survival rate for majors is relatively high.
2128 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
2129 block->is_to_space = TRUE;
2130 } END_FOREACH_BLOCK_NO_LOCK;
2131 if (lazy_sweep && !concurrent_sweep)
2132 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
2134 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
2138 major_finish_major_collection (ScannedObjectCounts *counts)
2140 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2141 if (binary_protocol_is_enabled ()) {
2142 counts->num_scanned_objects = scanned_objects_list.next_slot;
2144 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
2145 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
2147 sgen_pointer_queue_clear (&scanned_objects_list);
2153 compare_pointers (const void *va, const void *vb) {
2154 char *a = *(char**)va, *b = *(char**)vb;
2163 * This is called with sweep completed and the world stopped.
2166 major_free_swept_blocks (size_t section_reserve)
2168 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
2170 #if defined(HOST_WIN32) || defined(HOST_ORBIS) || defined (HOST_WASM)
2172 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
2173 * a VirtualAlloc ()-ed block.
2179 int i, num_empty_blocks_orig, num_blocks, arr_length;
2181 void **empty_block_arr;
2182 void **rebuild_next;
2184 if (num_empty_blocks <= section_reserve)
2186 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
2188 num_empty_blocks_orig = num_empty_blocks;
2189 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
2190 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
2191 if (!empty_block_arr)
2195 for (block = empty_blocks; block; block = *(void**)block)
2196 empty_block_arr [i++] = block;
2197 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
2199 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
2202 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
2203 * contiguous ones. If we do, we free them. If that's not enough to get to
2204 * section_reserve, we halve the number of contiguous blocks we're looking
2205 * for and have another go, until we're done with looking for pairs of
2206 * blocks, at which point we give up and go to the fallback.
2208 arr_length = num_empty_blocks_orig;
2209 num_blocks = MS_BLOCK_ALLOC_NUM;
2210 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2215 for (i = 0; i < arr_length; ++i) {
2217 void *block = empty_block_arr [i];
2218 SGEN_ASSERT (6, block, "we're not shifting correctly");
2220 empty_block_arr [dest] = block;
2222 * This is not strictly necessary, but we're
2225 empty_block_arr [i] = NULL;
2234 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2236 if ((char*)block != ((char*)empty_block_arr [d-1]) + ms_block_size) {
2241 if (d + 1 - first == num_blocks) {
2243 * We found num_blocks contiguous blocks. Free them
2244 * and null their array entries. As an optimization
2245 * we could, instead of nulling the entries, shift
2246 * the following entries over to the left, while
2250 sgen_free_os_memory (empty_block_arr [first], ms_block_size * num_blocks, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2251 for (j = first; j <= d; ++j)
2252 empty_block_arr [j] = NULL;
2256 num_empty_blocks -= num_blocks;
2258 stat_major_blocks_freed += num_blocks;
2259 if (num_blocks == MS_BLOCK_ALLOC_NUM)
2260 stat_major_blocks_freed_ideal += num_blocks;
2262 stat_major_blocks_freed_less_ideal += num_blocks;
2267 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2269 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2274 /* rebuild empty_blocks free list */
2275 rebuild_next = (void**)&empty_blocks;
2276 for (i = 0; i < arr_length; ++i) {
2277 void *block = empty_block_arr [i];
2278 SGEN_ASSERT (6, block, "we're missing blocks");
2279 *rebuild_next = block;
2280 rebuild_next = (void**)block;
2282 *rebuild_next = NULL;
2285 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2288 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2292 * This is our threshold. If there's not more empty than used blocks, we won't
2293 * release uncontiguous blocks, in fear of fragmenting the address space.
2295 if (num_empty_blocks <= num_major_sections)
2298 while (num_empty_blocks > section_reserve) {
2299 void *next = *(void**)empty_blocks;
2300 sgen_free_os_memory (empty_blocks, ms_block_size, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2301 empty_blocks = next;
2303 * Needs not be atomic because this is running
2308 ++stat_major_blocks_freed;
2309 ++stat_major_blocks_freed_individual;
2314 major_pin_objects (SgenGrayQueue *queue)
2318 FOREACH_BLOCK_NO_LOCK (block) {
2319 size_t first_entry, last_entry;
2320 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2321 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size,
2322 &first_entry, &last_entry);
2323 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2324 } END_FOREACH_BLOCK_NO_LOCK;
2328 major_init_to_space (void)
2333 major_report_pinned_memory_usage (void)
2335 g_assert_not_reached ();
2339 major_get_used_size (void)
2345 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2346 * finished, then we can iterate over the block array.
2348 major_finish_sweep_checking ();
2350 FOREACH_BLOCK_NO_LOCK (block) {
2351 int count = MS_BLOCK_FREE / block->obj_size;
2353 size += count * block->obj_size;
2354 for (iter = block->free_list; iter; iter = (void**)*iter)
2355 size -= block->obj_size;
2356 } END_FOREACH_BLOCK_NO_LOCK;
2361 /* FIXME: return number of bytes, not of sections */
2363 get_num_major_sections (void)
2365 return num_major_sections;
2369 * Returns the number of bytes in blocks that were present when the last sweep was
2370 * initiated, and were not freed during the sweep. They are the basis for calculating the
2374 get_bytes_survived_last_sweep (void)
2376 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2377 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * ms_block_size;
2381 major_handle_gc_param (const char *opt)
2383 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2384 const char *arg = strchr (opt, '=') + 1;
2385 int percentage = atoi (arg);
2386 if (percentage < 0 || percentage > 100) {
2387 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2390 evacuation_threshold = (float)percentage / 100.0f;
2392 } else if (!strcmp (opt, "lazy-sweep")) {
2395 } else if (!strcmp (opt, "no-lazy-sweep")) {
2398 } else if (!strcmp (opt, "concurrent-sweep")) {
2399 concurrent_sweep = TRUE;
2401 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2402 concurrent_sweep = FALSE;
2410 major_print_gc_param_usage (void)
2414 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2415 " (no-)lazy-sweep\n"
2416 " (no-)concurrent-sweep\n"
2421 * This callback is used to clear cards, move cards to the shadow table and do counting.
2424 major_iterate_block_ranges (sgen_cardtable_block_callback callback)
2427 gboolean has_references;
2429 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2431 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2432 } END_FOREACH_BLOCK_NO_LOCK;
2436 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2439 gboolean has_references;
2441 major_finish_sweep_checking ();
2442 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2444 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2445 } END_FOREACH_BLOCK_NO_LOCK;
2448 #ifdef HEAVY_STATISTICS
2449 extern guint64 marked_cards;
2450 extern guint64 scanned_cards;
2451 extern guint64 scanned_objects;
2452 extern guint64 remarked_cards;
2455 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2457 * MS blocks are 16K aligned.
2458 * Cardtables are 4K aligned, at least.
2459 * This means that the cardtable of a given block is 32 bytes aligned.
2462 initial_skip_card (guint8 *card_data)
2464 mword *cards = (mword*)card_data;
2467 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2473 if (i == CARD_WORDS_PER_BLOCK)
2474 return card_data + CARDS_PER_BLOCK;
2476 #if defined(__i386__) && defined(__GNUC__)
2477 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2478 #elif defined(__x86_64__) && defined(__GNUC__)
2479 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2480 #elif defined(__s390x__) && defined(__GNUC__)
2481 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2483 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2485 return &card_data [i];
2491 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2492 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2493 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + ms_block_size))
2496 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2498 SgenGrayQueue *queue = ctx.queue;
2499 ScanObjectFunc scan_func = ctx.ops->scan_object;
2501 * FIXME: On systems with very large pages, we allocate fairly large
2502 * arrays on the stack here. This shouldn't be a problem once block
2503 * size is no longer required to be a multiple of the system page size.
2505 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2506 guint8 *cards_copy = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2508 guint8 *cards_preclean = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2509 gboolean small_objects;
2512 guint8 *card_data, *card_base;
2513 guint8 *card_data_end;
2514 char *scan_front = NULL;
2516 /* The concurrent mark doesn't enter evacuating blocks */
2517 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2520 block_obj_size = block->obj_size;
2521 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2523 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2526 * This is safe in face of card aliasing for the following reason:
2528 * Major blocks are 16k aligned, or 32 cards aligned.
2529 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2530 * sizes, they won't overflow the cardtable overlap modulus.
2532 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2533 card_data = card_base = block->cardtable_mod_union;
2535 * This happens when the nursery collection that precedes finishing
2536 * the concurrent collection allocates new major blocks.
2541 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2542 sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2543 card_data = card_base = cards_preclean;
2546 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2547 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2549 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2551 card_data = card_base = cards_copy;
2554 card_data_end = card_data + CARDS_PER_BLOCK;
2556 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2558 card_data = initial_skip_card (card_data);
2559 while (card_data < card_data_end) {
2560 size_t card_index, first_object_index;
2563 char *first_obj, *obj;
2565 HEAVY_STAT (++scanned_cards);
2572 card_index = card_data - card_base;
2573 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2574 end = start + CARD_SIZE_IN_BYTES;
2576 if (!block_is_swept_or_marking (block))
2577 sweep_block (block);
2579 HEAVY_STAT (++marked_cards);
2582 sgen_card_table_prepare_card_for_scanning (card_data);
2585 * If the card we're looking at starts at or in the block header, we
2586 * must start at the first object in the block, without calculating
2587 * the index of the object we're hypothetically starting at, because
2588 * it would be negative.
2590 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2591 first_object_index = 0;
2593 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2595 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2597 binary_protocol_card_scan (first_obj, end - first_obj);
2600 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2603 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2604 /* FIXME: do this more efficiently */
2606 MS_CALC_MARK_BIT (w, b, obj);
2607 if (!MS_MARK_BIT (block, w, b))
2611 GCObject *object = (GCObject*)obj;
2613 if (small_objects) {
2614 HEAVY_STAT (++scanned_objects);
2615 scan_func (object, sgen_obj_get_descriptor (object), queue);
2617 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2618 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2621 obj += block_obj_size;
2622 g_assert (scan_front <= obj);
2626 HEAVY_STAT (if (*card_data) ++remarked_cards);
2631 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2636 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count, int block_count)
2639 gboolean has_references, was_sweeping, skip_scan;
2640 int first_block, last_block, index;
2643 * The last_block's index is at least (num_major_sections - 1) since we
2644 * can have nulls in the allocated_blocks list. The last worker will
2645 * scan the left-overs of the list. We expect few null entries in the
2646 * allocated_blocks list, therefore using num_major_sections for computing
2647 * block_count shouldn't affect work distribution.
2649 first_block = block_count * job_index;
2650 if (job_index == job_split_count - 1)
2651 last_block = allocated_blocks.next_slot;
2653 last_block = block_count * (job_index + 1);
2655 if (!concurrent_mark)
2656 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2658 if (scan_type != CARDTABLE_SCAN_GLOBAL)
2659 SGEN_ASSERT (0, !sweep_in_progress (), "Sweep should be finished when we scan mod union card table");
2660 was_sweeping = sweep_in_progress ();
2662 binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2663 FOREACH_BLOCK_RANGE_HAS_REFERENCES_NO_LOCK (block, first_block, last_block, index, has_references) {
2664 #ifdef PREFETCH_CARDS
2665 int prefetch_index = index + 6;
2666 if (prefetch_index < allocated_blocks.next_slot) {
2667 MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2668 PREFETCH_READ (prefetch_block);
2669 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2670 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2671 PREFETCH_WRITE (prefetch_cards);
2672 PREFETCH_WRITE (prefetch_cards + 32);
2676 if (!has_references)
2680 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2681 gpointer *card_start = (gpointer*) sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2682 gboolean has_dirty_cards = FALSE;
2684 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2685 if (card_start [i]) {
2686 has_dirty_cards = TRUE;
2690 if (!has_dirty_cards) {
2694 * After the start of the concurrent collections, blocks change state
2695 * to marking. We should not sweep it in that case. We can't race with
2696 * sweep start since we are in a nursery collection. Also avoid CAS-ing
2698 if (sweep_in_progress ()) {
2699 skip_scan = !ensure_block_is_checked_for_sweeping (index, TRUE, NULL);
2700 } else if (was_sweeping) {
2701 /* Recheck in case sweep finished after dereferencing the slot */
2702 skip_scan = *sgen_array_list_get_slot (&allocated_blocks, index) == 0;
2707 scan_card_table_for_block (block, scan_type, ctx);
2708 } END_FOREACH_BLOCK_RANGE_NO_LOCK;
2709 binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2713 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2716 gboolean has_references;
2717 long long total_cards = 0;
2718 long long marked_cards = 0;
2720 if (sweep_in_progress ()) {
2721 *num_total_cards = -1;
2722 *num_marked_cards = -1;
2726 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2727 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2730 if (!has_references)
2733 total_cards += CARDS_PER_BLOCK;
2734 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2738 } END_FOREACH_BLOCK_NO_LOCK;
2740 *num_total_cards = total_cards;
2741 *num_marked_cards = marked_cards;
2745 update_cardtable_mod_union (void)
2749 FOREACH_BLOCK_NO_LOCK (block) {
2750 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2751 gboolean has_dirty_cards = FALSE;
2753 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2754 if (card_start [i]) {
2755 has_dirty_cards = TRUE;
2759 if (has_dirty_cards) {
2761 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2762 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size, &num_cards);
2763 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2765 } END_FOREACH_BLOCK_NO_LOCK;
2768 #undef pthread_create
2771 post_param_init (SgenMajorCollector *collector)
2773 collector->sweeps_lazily = lazy_sweep;
2777 * We are guaranteed to be called by the worker in question.
2778 * This provides initialization for threads that plan to do
2779 * parallel object allocation. We need to store these lists
2780 * in additional data structures so we can traverse them
2781 * at major/sweep start.
2784 sgen_init_block_free_lists (gpointer *list_p)
2787 MSBlockInfo ***worker_free_blocks = (MSBlockInfo ***) mono_native_tls_get_value (worker_block_free_list_key);
2790 * For simplification, a worker thread uses the same free block lists,
2791 * regardless of the context it is part of (major/minor).
2793 if (worker_free_blocks) {
2794 *list_p = (gpointer)worker_free_blocks;
2798 worker_free_blocks = (MSBlockInfo ***) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX, INTERNAL_MEM_MS_TABLES, TRUE);
2800 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++)
2801 worker_free_blocks [i] = (MSBlockInfo **) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2803 *list_p = (gpointer)worker_free_blocks;
2805 mono_native_tls_set_value (worker_block_free_list_key, worker_free_blocks);
2809 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent, gboolean is_parallel)
2813 ms_block_size = mono_pagesize ();
2815 if (ms_block_size < MS_BLOCK_SIZE_MIN)
2816 ms_block_size = MS_BLOCK_SIZE_MIN;
2818 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, SIZEOF_MS_BLOCK_INFO);
2820 if (mono_cpu_count () <= 1)
2821 is_parallel = FALSE;
2823 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2824 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2825 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2827 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2828 for (i = 0; i < num_block_obj_sizes; ++i)
2829 evacuate_block_obj_sizes [i] = FALSE;
2831 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2832 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2833 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2838 g_print ("block object sizes:\n");
2839 for (i = 0; i < num_block_obj_sizes; ++i)
2840 g_print ("%d\n", block_obj_sizes [i]);
2844 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2845 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2847 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2848 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2849 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2850 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2852 /* We can do this because we always init the minor before the major */
2853 if (is_parallel || sgen_get_minor_collector ()->is_parallel)
2854 mono_native_tls_alloc (&worker_block_free_list_key, NULL);
2856 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2857 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2858 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2859 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2860 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2861 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2862 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2864 collector->section_size = ms_block_size;
2866 concurrent_mark = is_concurrent;
2867 collector->is_concurrent = is_concurrent;
2868 collector->is_parallel = is_parallel;
2869 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2870 collector->supports_cardtable = TRUE;
2872 collector->alloc_heap = major_alloc_heap;
2873 collector->is_object_live = major_is_object_live;
2874 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2875 collector->alloc_degraded = major_alloc_degraded;
2877 collector->alloc_object = major_alloc_object;
2878 collector->alloc_object_par = major_alloc_object_par;
2879 collector->free_pinned_object = free_pinned_object;
2880 collector->iterate_objects = major_iterate_objects;
2881 collector->free_non_pinned_object = major_free_non_pinned_object;
2882 collector->pin_objects = major_pin_objects;
2883 collector->pin_major_object = pin_major_object;
2884 collector->scan_card_table = major_scan_card_table;
2885 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2886 collector->iterate_block_ranges = major_iterate_block_ranges;
2887 if (is_concurrent) {
2888 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2889 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2891 collector->init_to_space = major_init_to_space;
2892 collector->sweep = major_sweep;
2893 collector->have_swept = major_have_swept;
2894 collector->finish_sweeping = major_finish_sweep_checking;
2895 collector->free_swept_blocks = major_free_swept_blocks;
2896 collector->check_scan_starts = major_check_scan_starts;
2897 collector->dump_heap = major_dump_heap;
2898 collector->get_used_size = major_get_used_size;
2899 collector->start_nursery_collection = major_start_nursery_collection;
2900 collector->finish_nursery_collection = major_finish_nursery_collection;
2901 collector->start_major_collection = major_start_major_collection;
2902 collector->finish_major_collection = major_finish_major_collection;
2903 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2904 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2905 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2906 collector->get_num_major_sections = get_num_major_sections;
2907 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2908 collector->handle_gc_param = major_handle_gc_param;
2909 collector->print_gc_param_usage = major_print_gc_param_usage;
2910 collector->post_param_init = post_param_init;
2911 collector->is_valid_object = major_is_valid_object;
2912 collector->describe_pointer = major_describe_pointer;
2913 collector->count_cards = major_count_cards;
2914 collector->init_block_free_lists = sgen_init_block_free_lists;
2916 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2917 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2918 collector->major_ops_serial.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2919 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2920 if (is_concurrent) {
2921 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2922 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2923 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2924 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2925 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2927 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2928 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2929 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2930 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2931 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2934 collector->major_ops_conc_par_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_canonical;
2935 collector->major_ops_conc_par_start.scan_object = major_scan_object_concurrent_par_with_evacuation;
2936 collector->major_ops_conc_par_start.scan_vtype = major_scan_vtype_concurrent_par_with_evacuation;
2937 collector->major_ops_conc_par_start.scan_ptr_field = major_scan_ptr_field_concurrent_par_with_evacuation;
2938 collector->major_ops_conc_par_start.drain_gray_stack = drain_gray_stack_concurrent_par;
2940 collector->major_ops_conc_par_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_finish_canonical;
2941 collector->major_ops_conc_par_finish.scan_object = major_scan_object_par_with_evacuation;
2942 collector->major_ops_conc_par_finish.scan_vtype = major_scan_vtype_par_with_evacuation;
2943 collector->major_ops_conc_par_finish.scan_ptr_field = major_scan_ptr_field_par_with_evacuation;
2944 collector->major_ops_conc_par_finish.drain_gray_stack = drain_gray_stack_par;
2948 #ifdef HEAVY_STATISTICS
2949 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2950 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2951 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2952 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2953 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2954 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2955 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2956 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2957 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2958 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2959 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2961 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2962 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2963 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2966 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2967 mono_os_mutex_init (&scanned_objects_list_lock);
2970 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2972 /*cardtable requires major pages to be 8 cards aligned*/
2973 g_assert ((ms_block_size % (8 * CARD_SIZE_IN_BYTES)) == 0);
2975 if (is_concurrent && is_parallel)
2976 sgen_workers_create_context (GENERATION_OLD, mono_cpu_count ());
2977 else if (is_concurrent)
2978 sgen_workers_create_context (GENERATION_OLD, 1);
2980 if (concurrent_sweep)
2981 sweep_pool_context = sgen_thread_pool_create_context (1, NULL, NULL, NULL, NULL, NULL);
2985 sgen_marksweep_init (SgenMajorCollector *collector)
2987 sgen_marksweep_init_internal (collector, FALSE, FALSE);
2991 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2993 sgen_marksweep_init_internal (collector, TRUE, FALSE);
2997 sgen_marksweep_conc_par_init (SgenMajorCollector *collector)
2999 sgen_marksweep_init_internal (collector, TRUE, TRUE);