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
192 static volatile int sweep_state = SWEEP_STATE_SWEPT;
194 static gboolean concurrent_mark;
195 static gboolean concurrent_sweep = TRUE;
197 int sweep_pool_context = -1;
199 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
200 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
202 #define BLOCK_IS_TAGGED_CHECKING(bl) SGEN_POINTER_IS_TAGGED_2 ((bl))
203 #define BLOCK_TAG_CHECKING(bl) SGEN_POINTER_TAG_2 ((bl))
205 #define BLOCK_UNTAG(bl) ((MSBlockInfo *)SGEN_POINTER_UNTAG_12 ((bl)))
207 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
209 /* all allocated blocks in the system */
210 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);
212 /* non-allocated block free-list */
213 static void *empty_blocks = NULL;
214 static size_t num_empty_blocks = 0;
217 * We can iterate the block list also while sweep is in progress but we
218 * need to account for blocks that will be checked for sweeping and even
219 * freed in the process.
221 #define FOREACH_BLOCK_NO_LOCK(bl) { \
222 volatile gpointer *slot; \
223 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
224 (bl) = BLOCK_UNTAG (*slot); \
227 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
228 volatile gpointer *slot; \
229 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) { \
230 (bl) = (MSBlockInfo *) (*slot); \
233 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
234 (bl) = BLOCK_UNTAG ((bl));
235 #define END_FOREACH_BLOCK_NO_LOCK } SGEN_ARRAY_LIST_END_FOREACH_SLOT; }
237 static volatile size_t num_major_sections = 0;
239 * One free block list for each block object size. We add and remove blocks from these
240 * lists lock-free via CAS.
242 * Blocks accessed/removed from `free_block_lists`:
243 * from the mutator (with GC lock held)
244 * in nursery collections
245 * in non-concurrent major collections
246 * in the finishing pause of concurrent major collections (whole list is cleared)
248 * Blocks added to `free_block_lists`:
249 * in the sweeping thread
250 * during nursery collections
251 * from domain clearing (with the world stopped and no sweeping happening)
253 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
254 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
256 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
257 static MonoNativeTlsKey worker_block_free_list_key;
259 static guint64 stat_major_blocks_alloced = 0;
260 static guint64 stat_major_blocks_freed = 0;
261 static guint64 stat_major_blocks_lazy_swept = 0;
263 static guint64 stat_major_blocks_freed_ideal = 0;
264 static guint64 stat_major_blocks_freed_less_ideal = 0;
265 static guint64 stat_major_blocks_freed_individual = 0;
266 static guint64 stat_major_blocks_alloced_less_ideal = 0;
268 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
269 static guint64 num_major_objects_marked = 0;
270 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
272 #define INC_NUM_MAJOR_OBJECTS_MARKED()
275 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
276 static mono_mutex_t scanned_objects_list_lock;
277 static SgenPointerQueue scanned_objects_list;
280 add_scanned_object (void *ptr)
282 if (!binary_protocol_is_enabled ())
285 mono_os_mutex_lock (&scanned_objects_list_lock);
286 sgen_pointer_queue_add (&scanned_objects_list, ptr);
287 mono_os_mutex_unlock (&scanned_objects_list_lock);
291 static gboolean sweep_block (MSBlockInfo *block);
294 ms_find_block_obj_size_index (size_t size)
297 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);
298 for (i = 0; i < num_block_obj_sizes; ++i)
299 if (block_obj_sizes [i] >= size)
301 g_error ("no object of size %zd\n", size);
305 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
306 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
307 #define FREE_BLOCKS_LOCAL(p,r) (FREE_BLOCKS_FROM (((MSBlockInfo***)mono_native_tls_get_value (worker_block_free_list_key)), (p), (r)))
309 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
310 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
311 fast_block_obj_size_indexes [((s)+7)>>3] : \
312 ms_find_block_obj_size_index ((s)))
315 major_alloc_heap (mword nursery_size, mword nursery_align)
319 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
321 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery", MONO_MEM_ACCOUNT_SGEN_NURSERY);
327 update_heap_boundaries_for_block (MSBlockInfo *block)
329 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size);
336 ms_get_empty_block (void)
340 void *block, *empty, *next;
345 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
346 * unsuccessful, we halve the number of blocks and try again, until we're at
347 * 1. If that doesn't work, either, we assert.
349 int alloc_num = MS_BLOCK_ALLOC_NUM;
351 p = (char *)sgen_alloc_os_memory_aligned (ms_block_size * alloc_num, ms_block_size,
352 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
353 alloc_num == 1 ? "major heap section" : NULL, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
359 for (i = 0; i < alloc_num; ++i) {
362 * We do the free list update one after the
363 * other so that other threads can use the new
364 * blocks as quickly as possible.
367 empty = empty_blocks;
368 *(void**)block = empty;
369 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
373 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
375 stat_major_blocks_alloced += alloc_num;
376 #if SIZEOF_VOID_P != 8
377 if (alloc_num != MS_BLOCK_ALLOC_NUM)
378 stat_major_blocks_alloced_less_ideal += alloc_num;
383 empty = empty_blocks;
387 next = *(void**)block;
388 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
390 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
392 *(void**)block = NULL;
394 g_assert (!((mword)block & (ms_block_size - 1)));
400 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
401 * list, where it will either be freed later on, or reused in nursery collections.
404 ms_free_block (MSBlockInfo *info)
407 char *block = MS_BLOCK_FOR_BLOCK_INFO (info);
409 sgen_memgov_release_space (ms_block_size, SPACE_MAJOR);
410 if (info->cardtable_mod_union)
411 sgen_card_table_free_mod_union (info->cardtable_mod_union, block, ms_block_size);
412 memset (block, 0, ms_block_size);
415 empty = empty_blocks;
416 *(void**)block = empty;
417 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
419 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
421 binary_protocol_block_free (block, ms_block_size);
425 sweep_in_progress (void)
427 int state = sweep_state;
428 return state == SWEEP_STATE_SWEEPING ||
429 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
430 state == SWEEP_STATE_COMPACTING;
433 static inline gboolean
434 block_is_swept_or_marking (MSBlockInfo *block)
436 gint32 state = block->state;
437 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
440 //#define MARKSWEEP_CONSISTENCY_CHECK
442 #ifdef MARKSWEEP_CONSISTENCY_CHECK
444 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
446 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
447 for (; block; block = block->next_free) {
448 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
449 g_assert (block->obj_size == size);
450 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
452 /* blocks in the free lists must have at least
454 g_assert (block->free_list);
456 /* the block must be in the allocated_blocks array */
457 g_assert (sgen_array_list_find (&allocated_blocks, BLOCK_TAG (block)) != (guint32)-1);
462 check_empty_blocks (void)
466 for (p = empty_blocks; p; p = *(void**)p)
468 g_assert (i == num_empty_blocks);
472 consistency_check (void)
477 /* check all blocks */
478 FOREACH_BLOCK_NO_LOCK (block) {
479 int count = MS_BLOCK_FREE / block->obj_size;
483 /* count number of free slots */
484 for (i = 0; i < count; ++i) {
485 void **obj = (void**) MS_BLOCK_OBJ (block, i);
486 if (!MS_OBJ_ALLOCED (obj, block))
490 /* check free list */
491 for (free = block->free_list; free; free = (void**)*free) {
492 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
495 g_assert (num_free == 0);
497 /* check all mark words are zero */
498 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
499 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
500 g_assert (block->mark_words [i] == 0);
502 } END_FOREACH_BLOCK_NO_LOCK;
504 /* check free blocks */
505 for (i = 0; i < num_block_obj_sizes; ++i) {
507 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
508 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
511 check_empty_blocks ();
516 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
520 block->next_free = old = free_blocks [size_index];
521 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
524 static void major_finish_sweep_checking (void);
527 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
529 int size = block_obj_sizes [size_index];
530 int count = MS_BLOCK_FREE / size;
532 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
536 if (!sgen_memgov_try_alloc_space (ms_block_size, SPACE_MAJOR))
539 info = (MSBlockInfo*)ms_get_empty_block ();
541 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
543 info->obj_size = size;
544 info->obj_size_index = size_index;
545 info->pinned = pinned;
546 info->has_references = has_references;
547 info->has_pinned = pinned;
549 * Blocks that are to-space are not evacuated from. During an major collection
550 * blocks are allocated for two reasons: evacuating objects from the nursery and
551 * evacuating them from major blocks marked for evacuation. In both cases we don't
552 * want further evacuation. We also don't want to evacuate objects allocated during
553 * the concurrent mark since it would add pointless stress on the finishing pause.
555 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
556 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
557 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
558 info->cardtable_mod_union = NULL;
560 update_heap_boundaries_for_block (info);
562 binary_protocol_block_alloc (info, ms_block_size);
564 /* build free list */
565 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
566 info->free_list = (void**)obj_start;
567 /* we're skipping the last one - it must be nulled */
568 for (i = 0; i < count - 1; ++i) {
569 char *next_obj_start = obj_start + size;
570 *(void**)obj_start = next_obj_start;
571 obj_start = next_obj_start;
574 *(void**)obj_start = NULL;
576 add_free_block (free_blocks, size_index, info);
578 sgen_array_list_add (&allocated_blocks, BLOCK_TAG (info), 0, FALSE);
580 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
585 ptr_is_in_major_block (char *ptr, char **start, gboolean *pinned)
589 FOREACH_BLOCK_NO_LOCK (block) {
590 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) {
591 int count = MS_BLOCK_FREE / block->obj_size;
596 for (i = 0; i <= count; ++i) {
597 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
599 *start = (char *)MS_BLOCK_OBJ (block, i);
604 *pinned = block->pinned;
607 } END_FOREACH_BLOCK_NO_LOCK;
612 ptr_is_from_pinned_alloc (char *ptr)
615 if (ptr_is_in_major_block (ptr, NULL, &pinned))
621 ensure_can_access_block_free_list (MSBlockInfo *block)
625 switch (block->state) {
626 case BLOCK_STATE_SWEPT:
627 case BLOCK_STATE_MARKING:
629 case BLOCK_STATE_CHECKING:
630 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
632 case BLOCK_STATE_NEED_SWEEPING:
633 if (sweep_block (block))
634 ++stat_major_blocks_lazy_swept;
636 case BLOCK_STATE_SWEEPING:
637 /* FIXME: do this more elegantly */
641 SGEN_ASSERT (0, FALSE, "Illegal block state");
648 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
650 MSBlockInfo *block, *next_free_block;
651 void *obj, *next_free_slot;
654 block = free_blocks [size_index];
655 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
657 ensure_can_access_block_free_list (block);
659 obj = block->free_list;
660 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
662 next_free_slot = *(void**)obj;
663 if (next_free_slot) {
664 block->free_list = (gpointer *)next_free_slot;
668 next_free_block = block->next_free;
669 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
672 block->free_list = NULL;
673 block->next_free = NULL;
679 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
681 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
682 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
685 if (!free_blocks [size_index]) {
686 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
690 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
692 /* FIXME: assumes object layout */
693 *(GCVTable*)obj = vtable;
695 total_allocated_major += block_obj_sizes [size_index];
697 return (GCObject *)obj;
701 major_alloc_object (GCVTable vtable, size_t size, gboolean has_references)
703 return alloc_obj (vtable, size, FALSE, has_references);
707 * This can only be called by sgen workers. While this is called we assume
708 * that no other thread is accessing the block free lists. The world should
709 * be stopped and the gc thread should be waiting for workers to finish.
712 major_alloc_object_par (GCVTable vtable, size_t size, gboolean has_references)
714 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
715 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (FALSE, has_references);
716 MSBlockInfo **free_blocks_local = FREE_BLOCKS_LOCAL (FALSE, has_references);
719 if (free_blocks_local [size_index]) {
721 obj = unlink_slot_from_free_list_uncontested (free_blocks_local, size_index);
725 block = free_blocks [size_index];
727 if (G_UNLIKELY (!ms_alloc_block (size_index, FALSE, has_references)))
731 MSBlockInfo *next_free = block->next_free;
733 * Once a block is removed from the main list, it cannot return on the list until
734 * all the workers are finished and sweep is starting. This means we don't need
735 * to account for ABA problems.
737 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free, block) != block)
739 block->next_free = free_blocks_local [size_index];
740 free_blocks_local [size_index] = block;
746 /* FIXME: assumes object layout */
747 *(GCVTable*)obj = vtable;
749 /* FIXME is it worth CAS-ing here */
750 total_allocated_major += block_obj_sizes [size_index];
752 return (GCObject *)obj;
756 * We're not freeing the block if it's empty. We leave that work for
757 * the next major collection.
759 * This is just called from the domain clearing code, which runs in a
760 * single thread and has the GC lock, so we don't need an extra lock.
763 free_object (GCObject *obj, size_t size, gboolean pinned)
765 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
767 gboolean in_free_list;
769 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
771 ensure_can_access_block_free_list (block);
772 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);
773 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
774 MS_CALC_MARK_BIT (word, bit, obj);
775 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set", obj);
777 memset (obj, 0, size);
779 in_free_list = !!block->free_list;
780 *(void**)obj = block->free_list;
781 block->free_list = (void**)obj;
784 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
785 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
786 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);
787 add_free_block (free_blocks, size_index, block);
792 major_free_non_pinned_object (GCObject *obj, size_t size)
794 free_object (obj, size, FALSE);
797 /* size is a multiple of SGEN_ALLOC_ALIGN */
799 major_alloc_small_pinned_obj (GCVTable vtable, size_t size, gboolean has_references)
803 res = alloc_obj (vtable, size, TRUE, has_references);
804 /*If we failed to alloc memory, we better try releasing memory
805 *as pinned alloc is requested by the runtime.
808 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE, TRUE);
809 res = alloc_obj (vtable, size, TRUE, has_references);
811 return (GCObject *)res;
815 free_pinned_object (GCObject *obj, size_t size)
817 free_object (obj, size, TRUE);
821 * size is already rounded up and we hold the GC lock.
824 major_alloc_degraded (GCVTable vtable, size_t size)
828 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
829 if (G_LIKELY (obj)) {
830 HEAVY_STAT (++stat_objects_alloced_degraded);
831 HEAVY_STAT (stat_bytes_alloced_degraded += size);
837 * obj is some object. If it's not in the major heap (i.e. if it's in
838 * the nursery or LOS), return FALSE. Otherwise return whether it's
839 * been marked or copied.
842 major_is_object_live (GCObject *obj)
848 if (sgen_ptr_in_nursery (obj))
851 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
854 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
857 /* now we know it's in a major block */
858 block = MS_BLOCK_FOR_OBJ (obj);
859 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
860 MS_CALC_MARK_BIT (word, bit, obj);
861 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
865 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
868 if (ptr_is_in_major_block (ptr, start, &pinned))
874 try_set_sweep_state (int new_, int expected)
876 int old = SGEN_CAS (&sweep_state, new_, expected);
877 return old == expected;
881 set_sweep_state (int new_, int expected)
883 gboolean success = try_set_sweep_state (new_, expected);
884 SGEN_ASSERT (0, success, "Could not set sweep state.");
887 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
889 static SgenThreadPoolJob * volatile sweep_job;
890 static SgenThreadPoolJob * volatile sweep_blocks_job;
893 major_finish_sweep_checking (void)
896 SgenThreadPoolJob *job;
899 switch (sweep_state) {
900 case SWEEP_STATE_SWEPT:
901 case SWEEP_STATE_NEED_SWEEPING:
903 case SWEEP_STATE_SWEEPING:
904 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
907 case SWEEP_STATE_SWEEPING_AND_ITERATING:
908 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
910 case SWEEP_STATE_COMPACTING:
913 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
918 * We're running with the world stopped and the only other thread doing work is the
919 * sweep thread, which doesn't add blocks to the array, so we can safely access
922 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
923 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
925 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
930 sgen_thread_pool_job_wait (sweep_pool_context, job);
931 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
932 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
936 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
938 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
939 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
940 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
943 /* No actual sweeping will take place if we are in the middle of a major collection. */
944 major_finish_sweep_checking ();
945 FOREACH_BLOCK_NO_LOCK (block) {
946 int count = MS_BLOCK_FREE / block->obj_size;
949 if (block->pinned && !pinned)
951 if (!block->pinned && !non_pinned)
953 if (sweep && lazy_sweep && !block_is_swept_or_marking (block)) {
955 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
958 for (i = 0; i < count; ++i) {
959 void **obj = (void**) MS_BLOCK_OBJ (block, i);
960 if (MS_OBJ_ALLOCED (obj, block))
961 callback ((GCObject*)obj, block->obj_size, data);
963 } END_FOREACH_BLOCK_NO_LOCK;
967 major_is_valid_object (char *object)
971 FOREACH_BLOCK_NO_LOCK (block) {
975 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) <= object))
978 idx = MS_BLOCK_OBJ_INDEX (object, block);
979 obj = (char*)MS_BLOCK_OBJ (block, idx);
982 return MS_OBJ_ALLOCED (obj, block);
983 } END_FOREACH_BLOCK_NO_LOCK;
990 major_describe_pointer (char *ptr)
994 FOREACH_BLOCK_NO_LOCK (block) {
1002 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size) <= ptr))
1005 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
1006 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
1008 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
1009 obj = (char*)MS_BLOCK_OBJ (block, idx);
1010 live = MS_OBJ_ALLOCED (obj, block);
1011 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
1013 MS_CALC_MARK_BIT (w, b, obj);
1014 marked = MS_MARK_BIT (block, w, b);
1017 SGEN_LOG (0, "\t(");
1019 SGEN_LOG (0, "object");
1021 SGEN_LOG (0, "dead-object");
1024 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
1026 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
1029 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
1032 } END_FOREACH_BLOCK_NO_LOCK;
1038 major_check_scan_starts (void)
1043 major_dump_heap (FILE *heap_dump_file)
1046 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1047 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
1050 for (i = 0; i < num_block_obj_sizes; ++i)
1051 slots_available [i] = slots_used [i] = 0;
1053 FOREACH_BLOCK_NO_LOCK (block) {
1054 int index = ms_find_block_obj_size_index (block->obj_size);
1055 int count = MS_BLOCK_FREE / block->obj_size;
1057 slots_available [index] += count;
1058 for (i = 0; i < count; ++i) {
1059 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1060 ++slots_used [index];
1062 } END_FOREACH_BLOCK_NO_LOCK;
1064 fprintf (heap_dump_file, "<occupancies>\n");
1065 for (i = 0; i < num_block_obj_sizes; ++i) {
1066 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1067 block_obj_sizes [i], slots_available [i], slots_used [i]);
1069 fprintf (heap_dump_file, "</occupancies>\n");
1071 FOREACH_BLOCK_NO_LOCK (block) {
1072 int count = MS_BLOCK_FREE / block->obj_size;
1076 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1078 for (i = 0; i <= count; ++i) {
1079 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1084 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1090 fprintf (heap_dump_file, "</section>\n");
1091 } END_FOREACH_BLOCK_NO_LOCK;
1095 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1097 guint8 *mod_union = block->cardtable_mod_union;
1103 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
1104 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1106 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1109 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
1113 static inline guint8*
1114 major_get_cardtable_mod_union_for_reference (char *ptr)
1116 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1117 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1118 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1119 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1120 return &mod_union [offset];
1124 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1127 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1129 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1130 if (sgen_safe_object_is_small (obj, type)) {
1131 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1132 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?");
1135 sgen_los_mark_mod_union_card (obj, ptr);
1137 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1140 static inline gboolean
1141 major_block_is_evacuating (MSBlockInfo *block)
1143 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1144 !block->has_pinned &&
1145 !block->is_to_space)
1150 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1151 int __word, __bit; \
1152 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1153 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1154 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1155 MS_SET_MARK_BIT ((block), __word, __bit); \
1156 if (sgen_gc_descr_has_references (desc)) \
1157 GRAY_OBJECT_ENQUEUE_SERIAL ((queue), (obj), (desc)); \
1158 binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1159 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1162 #define MS_MARK_OBJECT_AND_ENQUEUE_PAR(obj,desc,block,queue) do { \
1163 int __word, __bit; \
1165 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1166 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1167 MS_SET_MARK_BIT_PAR ((block), __word, __bit, first); \
1169 if (sgen_gc_descr_has_references (desc)) \
1170 GRAY_OBJECT_ENQUEUE_PARALLEL ((queue), (obj), (desc)); \
1171 binary_protocol_mark ((obj), (gpointer)SGEN_LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1172 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1179 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1183 if (concurrent_mark)
1184 g_assert_not_reached ();
1186 block = MS_BLOCK_FOR_OBJ (obj);
1187 block->has_pinned = TRUE;
1188 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1191 #define COPY_OR_MARK_PARALLEL
1192 #include "sgen-major-copy-object.h"
1195 major_get_and_reset_num_major_objects_marked (void)
1197 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1198 long long num = num_major_objects_marked;
1199 num_major_objects_marked = 0;
1206 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1208 #undef PREFETCH_CARDS
1211 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1212 #if defined(PLATFORM_MACOSX)
1213 #if MONO_GNUC_VERSION <= 40300
1214 #undef PREFETCH_CARDS
1218 #ifdef HEAVY_STATISTICS
1219 static guint64 stat_optimized_copy;
1220 static guint64 stat_optimized_copy_nursery;
1221 static guint64 stat_optimized_copy_nursery_forwarded;
1222 static guint64 stat_optimized_copy_nursery_pinned;
1223 static guint64 stat_optimized_copy_major;
1224 static guint64 stat_optimized_copy_major_small_fast;
1225 static guint64 stat_optimized_copy_major_small_slow;
1226 static guint64 stat_optimized_copy_major_large;
1227 static guint64 stat_optimized_copy_major_forwarded;
1228 static guint64 stat_optimized_copy_major_small_evacuate;
1229 static guint64 stat_optimized_major_scan;
1230 static guint64 stat_optimized_major_scan_no_refs;
1232 static guint64 stat_drain_prefetch_fills;
1233 static guint64 stat_drain_prefetch_fill_failures;
1234 static guint64 stat_drain_loops;
1237 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1238 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1239 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1240 #include "sgen-marksweep-drain-gray-stack.h"
1242 #define COPY_OR_MARK_PARALLEL
1243 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_par_no_evacuation
1244 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_par_no_evacuation
1245 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_par_no_evacuation
1246 #include "sgen-marksweep-drain-gray-stack.h"
1248 #define COPY_OR_MARK_WITH_EVACUATION
1249 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1250 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1251 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_with_evacuation
1252 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1253 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_with_evacuation
1254 #include "sgen-marksweep-drain-gray-stack.h"
1256 #define COPY_OR_MARK_PARALLEL
1257 #define COPY_OR_MARK_WITH_EVACUATION
1258 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_par_with_evacuation
1259 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_par_with_evacuation
1260 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_par_with_evacuation
1261 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_par_with_evacuation
1262 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_par_with_evacuation
1263 #include "sgen-marksweep-drain-gray-stack.h"
1265 #define COPY_OR_MARK_CONCURRENT
1266 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1267 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1268 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1269 #include "sgen-marksweep-drain-gray-stack.h"
1271 #define COPY_OR_MARK_PARALLEL
1272 #define COPY_OR_MARK_CONCURRENT
1273 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_par_no_evacuation
1274 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_par_no_evacuation
1275 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_par_no_evacuation
1276 #include "sgen-marksweep-drain-gray-stack.h"
1278 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1279 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1280 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1281 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_with_evacuation
1282 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_with_evacuation
1283 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1284 #include "sgen-marksweep-drain-gray-stack.h"
1286 #define COPY_OR_MARK_PARALLEL
1287 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1288 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_par_with_evacuation
1289 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_par_with_evacuation
1290 #define SCAN_VTYPE_FUNCTION_NAME major_scan_vtype_concurrent_par_with_evacuation
1291 #define SCAN_PTR_FIELD_FUNCTION_NAME major_scan_ptr_field_concurrent_par_with_evacuation
1292 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_par_with_evacuation
1293 #include "sgen-marksweep-drain-gray-stack.h"
1295 static inline gboolean
1296 major_is_evacuating (void)
1299 for (i = 0; i < num_block_obj_sizes; ++i) {
1300 if (evacuate_block_obj_sizes [i]) {
1309 drain_gray_stack (SgenGrayQueue *queue)
1311 if (major_is_evacuating ())
1312 return drain_gray_stack_with_evacuation (queue);
1314 return drain_gray_stack_no_evacuation (queue);
1318 drain_gray_stack_par (SgenGrayQueue *queue)
1320 if (major_is_evacuating ())
1321 return drain_gray_stack_par_with_evacuation (queue);
1323 return drain_gray_stack_par_no_evacuation (queue);
1327 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1329 if (major_is_evacuating ())
1330 return drain_gray_stack_concurrent_with_evacuation (queue);
1332 return drain_gray_stack_concurrent_no_evacuation (queue);
1336 drain_gray_stack_concurrent_par (SgenGrayQueue *queue)
1338 if (major_is_evacuating ())
1339 return drain_gray_stack_concurrent_par_with_evacuation (queue);
1341 return drain_gray_stack_concurrent_par_no_evacuation (queue);
1345 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1347 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1351 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1353 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1357 major_copy_or_mark_object_concurrent_par_canonical (GCObject **ptr, SgenGrayQueue *queue)
1359 major_copy_or_mark_object_concurrent_par_with_evacuation (ptr, *ptr, queue);
1363 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1365 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1369 major_copy_or_mark_object_concurrent_par_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1371 major_copy_or_mark_object_par_with_evacuation (ptr, *ptr, queue);
1375 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1377 void **entry, **end;
1378 int last_index = -1;
1380 if (first_entry == last_entry)
1383 entry = sgen_pinning_get_entry (first_entry);
1384 end = sgen_pinning_get_entry (last_entry);
1386 for (; entry < end; ++entry) {
1387 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1389 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));
1390 if (index == last_index)
1392 obj = MS_BLOCK_OBJ (block, index);
1393 if (!MS_OBJ_ALLOCED (obj, block))
1395 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1396 sgen_pin_stats_register_object (obj, GENERATION_OLD);
1401 * There might have been potential pinning "pointers" into this block, but none of
1402 * them pointed to occupied slots, in which case we don't have to pin the block.
1404 if (last_index >= 0)
1405 block->has_pinned = TRUE;
1409 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1412 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, 0, obj_size);
1414 for (obj_index = 0; obj_index < count; ++obj_index, obj = (void*)((mword)obj + obj_size)) {
1417 MS_CALC_MARK_BIT (word, bit, obj);
1418 if (MS_MARK_BIT (block, word, bit)) {
1419 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1421 /* an unmarked object */
1422 if (MS_OBJ_ALLOCED (obj, block)) {
1424 * FIXME: Merge consecutive
1425 * slots for lower reporting
1426 * overhead. Maybe memset
1427 * will also benefit?
1429 binary_protocol_empty (obj, obj_size);
1430 memset (obj, 0, obj_size);
1432 *(void**)obj = block->free_list;
1433 block->free_list = (void **)obj;
1438 static inline gboolean
1439 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1441 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1442 gboolean success = old_state == expected_state;
1444 binary_protocol_block_set_state (block, ms_block_size, old_state, new_state);
1449 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1451 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1452 block->state = new_state;
1453 binary_protocol_block_set_state (block, ms_block_size, expected_state, new_state);
1457 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1459 * Sweeping means iterating through the block's slots and building the free-list from the
1460 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1463 sweep_block (MSBlockInfo *block)
1466 void *reversed = NULL;
1469 switch (block->state) {
1470 case BLOCK_STATE_SWEPT:
1472 case BLOCK_STATE_MARKING:
1473 case BLOCK_STATE_CHECKING:
1474 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1476 case BLOCK_STATE_SWEEPING:
1477 /* FIXME: Do this more elegantly */
1480 case BLOCK_STATE_NEED_SWEEPING:
1481 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1485 SGEN_ASSERT (0, FALSE, "Illegal block state");
1488 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1490 count = MS_BLOCK_FREE / block->obj_size;
1492 block->free_list = NULL;
1494 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1495 // FIXME: Add more sizes
1496 switch (block->obj_size) {
1498 sweep_block_for_size (block, count, 16);
1501 sweep_block_for_size (block, count, block->obj_size);
1505 /* reset mark bits */
1506 memset (block->mark_words, 0, sizeof (guint32) * MS_NUM_MARK_WORDS);
1508 /* Reverse free list so that it's in address order */
1510 while (block->free_list) {
1511 void *next = *(void**)block->free_list;
1512 *(void**)block->free_list = reversed;
1513 reversed = block->free_list;
1514 block->free_list = (void **)next;
1516 block->free_list = (void **)reversed;
1518 mono_memory_write_barrier ();
1520 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1531 if (sizeof (mword) == 8)
1532 count += __builtin_popcountll (d);
1534 count += __builtin_popcount (d);
1544 /* statistics for evacuation */
1545 static size_t *sweep_slots_available;
1546 static size_t *sweep_slots_used;
1547 static size_t *sweep_num_blocks;
1549 static volatile size_t num_major_sections_before_sweep;
1550 static volatile size_t num_major_sections_freed_in_sweep;
1553 sgen_worker_clear_free_block_lists (WorkerData *worker)
1557 if (!worker->free_block_lists)
1560 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++) {
1561 for (j = 0; j < num_block_obj_sizes; j++) {
1562 ((MSBlockInfo***) worker->free_block_lists) [i][j] = NULL;
1568 sgen_worker_clear_free_block_lists_evac (WorkerData *worker)
1572 if (!worker->free_block_lists)
1575 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++) {
1576 for (j = 0; j < num_block_obj_sizes; j++) {
1577 if (((MSBlockInfo***) worker->free_block_lists) [i][j])
1578 SGEN_ASSERT (0, !((MSBlockInfo***) worker->free_block_lists) [i][j]->next_free, "Why do we have linked free blocks on the workers");
1580 if (evacuate_block_obj_sizes [j])
1581 ((MSBlockInfo***) worker->free_block_lists) [i][j] = NULL;
1591 for (i = 0; i < num_block_obj_sizes; ++i)
1592 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1594 /* clear all the free lists */
1595 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1596 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1598 for (j = 0; j < num_block_obj_sizes; ++j)
1599 free_blocks [j] = NULL;
1602 sgen_workers_foreach (GENERATION_NURSERY, sgen_worker_clear_free_block_lists);
1603 sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists);
1606 static void sweep_finish (void);
1609 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1610 * the checking has finished.
1612 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1613 * be correct, i.e. must not be used.
1616 ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked)
1619 gboolean have_live = FALSE;
1620 gboolean have_free = FALSE;
1626 volatile gpointer *block_slot = sgen_array_list_get_slot (&allocated_blocks, block_index);
1628 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1631 *have_checked = FALSE;
1634 tagged_block = *(void * volatile *)block_slot;
1638 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1641 /* FIXME: do this more elegantly */
1646 if (SGEN_CAS_PTR (block_slot, BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1649 block = BLOCK_UNTAG (tagged_block);
1650 block_state = block->state;
1652 if (!sweep_in_progress ()) {
1653 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1655 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1658 switch (block_state) {
1659 case BLOCK_STATE_SWEPT:
1660 case BLOCK_STATE_NEED_SWEEPING:
1661 case BLOCK_STATE_SWEEPING:
1663 case BLOCK_STATE_MARKING:
1665 case BLOCK_STATE_CHECKING:
1666 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1669 SGEN_ASSERT (0, FALSE, "Illegal block state");
1673 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1674 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1677 *have_checked = TRUE;
1679 block->has_pinned = block->pinned;
1681 block->is_to_space = FALSE;
1683 count = MS_BLOCK_FREE / block->obj_size;
1685 if (block->cardtable_mod_union)
1686 memset (block->cardtable_mod_union, 0, CARDS_PER_BLOCK);
1688 /* Count marked objects in the block */
1689 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1690 nused += bitcount (block->mark_words [i]);
1692 block->nused = nused;
1699 int obj_size_index = block->obj_size_index;
1700 gboolean has_pinned = block->has_pinned;
1702 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1705 * FIXME: Go straight to SWEPT if there are no free slots. We need
1706 * to set the free slot list to NULL, though, and maybe update some
1710 sweep_block (block);
1713 ++sweep_num_blocks [obj_size_index];
1714 sweep_slots_used [obj_size_index] += nused;
1715 sweep_slots_available [obj_size_index] += count;
1719 * If there are free slots in the block, add
1720 * the block to the corresponding free list.
1723 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1726 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1728 add_free_block (free_blocks, obj_size_index, block);
1731 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1732 update_heap_boundaries_for_block (block);
1735 * Blocks without live objects are removed from the
1736 * block list and freed.
1738 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1739 SGEN_ASSERT (6, *block_slot == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1741 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1742 ms_free_block (block);
1744 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1745 SGEN_ATOMIC_ADD_P (num_major_sections_freed_in_sweep, 1);
1747 tagged_block = NULL;
1752 * Once the block is written back without the checking bit other threads are
1753 * free to access it. Make sure the block state is visible before we write it
1756 mono_memory_write_barrier ();
1757 *block_slot = tagged_block;
1758 return !!tagged_block;
1762 sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1764 volatile gpointer *slot;
1767 SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
1768 bl = BLOCK_UNTAG (*slot);
1771 } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
1773 mono_memory_write_barrier ();
1775 sweep_blocks_job = NULL;
1779 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1781 guint32 block_index;
1782 guint32 num_blocks = num_major_sections_before_sweep;
1784 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1785 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1788 * We traverse the block array from high to low. Nursery collections will have to
1789 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1790 * low to high, to avoid constantly colliding on the same blocks.
1792 for (block_index = allocated_blocks.next_slot; block_index-- > 0;) {
1793 ensure_block_is_checked_for_sweeping (block_index, TRUE, NULL);
1796 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1798 * The main GC thread is currently iterating over the block array to help us
1799 * finish the sweep. We have already finished, but we don't want to mess up
1800 * that iteration, so we just wait for it.
1805 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1806 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1807 MSBlockInfo *block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, block_index));
1808 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1813 * Concurrently sweep all the blocks to reduce workload during minor
1814 * pauses where we need certain blocks to be swept. At the start of
1815 * the next major we need all blocks to be swept anyway.
1817 if (concurrent_sweep && lazy_sweep) {
1818 sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
1819 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_blocks_job);
1830 mword used_slots_size = 0;
1833 for (i = 0; i < num_block_obj_sizes; ++i) {
1834 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1835 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1836 evacuate_block_obj_sizes [i] = TRUE;
1838 g_print ("slot size %d - %d of %d used\n",
1839 block_obj_sizes [i], slots_used [i], slots_available [i]);
1842 evacuate_block_obj_sizes [i] = FALSE;
1845 used_slots_size += sweep_slots_used [i] * block_obj_sizes [i];
1848 sgen_memgov_major_post_sweep (used_slots_size);
1850 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1851 if (concurrent_sweep)
1852 binary_protocol_concurrent_sweep_end (sgen_timestamp ());
1858 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1862 num_major_sections_before_sweep = num_major_sections;
1863 num_major_sections_freed_in_sweep = 0;
1865 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1866 if (concurrent_sweep) {
1867 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1868 sgen_thread_pool_job_enqueue (sweep_pool_context, sweep_job);
1870 sweep_job_func (NULL, NULL);
1875 major_have_swept (void)
1877 return sweep_state == SWEEP_STATE_SWEPT;
1880 static int count_pinned_ref;
1881 static int count_pinned_nonref;
1882 static int count_nonpinned_ref;
1883 static int count_nonpinned_nonref;
1886 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1888 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1890 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1891 ++count_nonpinned_ref;
1893 ++count_nonpinned_nonref;
1897 count_pinned_callback (GCObject *obj, size_t size, void *data)
1899 GCVTable vtable = SGEN_LOAD_VTABLE (obj);
1901 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1904 ++count_pinned_nonref;
1907 static G_GNUC_UNUSED void
1908 count_ref_nonref_objs (void)
1912 count_pinned_ref = 0;
1913 count_pinned_nonref = 0;
1914 count_nonpinned_ref = 0;
1915 count_nonpinned_nonref = 0;
1917 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1918 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1920 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1922 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1923 count_pinned_ref, count_nonpinned_ref,
1924 count_pinned_nonref, count_nonpinned_nonref,
1925 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1929 ms_calculate_block_obj_sizes (double factor, int *arr)
1936 * Have every possible slot size starting with the minimal
1937 * object size up to and including four times that size. Then
1938 * proceed by increasing geometrically with the given factor.
1941 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1943 arr [num_sizes] = size;
1947 target_size = (double)last_size;
1950 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1951 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1953 if (size != last_size) {
1955 arr [num_sizes] = size;
1960 target_size *= factor;
1961 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1966 /* only valid during minor collections */
1967 static mword old_num_major_sections;
1970 major_start_nursery_collection (void)
1972 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1973 consistency_check ();
1976 old_num_major_sections = num_major_sections;
1980 major_finish_nursery_collection (void)
1982 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1983 consistency_check ();
1988 block_usage_comparer (const void *bl1, const void *bl2)
1990 const gint16 nused1 = (*(MSBlockInfo**)bl1)->nused;
1991 const gint16 nused2 = (*(MSBlockInfo**)bl2)->nused;
1993 return nused2 - nused1;
1997 sgen_evacuation_freelist_blocks (MSBlockInfo * volatile *block_list, int size_index)
1999 MSBlockInfo **evacuated_blocks;
2000 size_t index = 0, count, num_blocks = 0, num_used = 0;
2002 MSBlockInfo * volatile *prev;
2004 for (info = *block_list; info != NULL; info = info->next_free) {
2006 num_used += info->nused;
2010 * We have a set of blocks in the freelist which will be evacuated. Instead
2011 * of evacuating all of the blocks into new ones, we traverse the freelist
2012 * sorting it by the number of occupied slots, evacuating the objects from
2013 * blocks with fewer used slots into fuller blocks.
2015 * The number of used slots is set at the end of the previous sweep. Since
2016 * we sequentially unlink slots from blocks, except for the head of the
2017 * freelist, for blocks on the freelist, the number of used slots is the same
2018 * as at the end of the previous sweep.
2020 evacuated_blocks = (MSBlockInfo**)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY, TRUE);
2022 for (info = *block_list; info != NULL; info = info->next_free) {
2023 evacuated_blocks [index++] = info;
2026 SGEN_ASSERT (0, num_blocks == index, "Why did the freelist change ?");
2028 sgen_qsort (evacuated_blocks, num_blocks, sizeof (gpointer), block_usage_comparer);
2031 * Form a new freelist with the fullest blocks. These blocks will also be
2032 * marked as to_space so we don't evacuate from them.
2034 count = MS_BLOCK_FREE / block_obj_sizes [size_index];
2036 for (index = 0; index < (num_used + count - 1) / count; index++) {
2037 SGEN_ASSERT (0, index < num_blocks, "Why do we need more blocks for compaction than we already had ?");
2038 info = evacuated_blocks [index];
2039 info->is_to_space = TRUE;
2041 prev = &info->next_free;
2045 sgen_free_internal_dynamic (evacuated_blocks, sizeof (MSBlockInfo*) * num_blocks, INTERNAL_MEM_TEMPORARY);
2049 major_start_major_collection (void)
2054 major_finish_sweep_checking ();
2057 * Clear the free lists for block sizes where we do evacuation. For those block
2058 * sizes we will have to allocate new blocks.
2060 for (i = 0; i < num_block_obj_sizes; ++i) {
2061 if (!evacuate_block_obj_sizes [i])
2064 binary_protocol_evacuating_blocks (block_obj_sizes [i]);
2066 sgen_evacuation_freelist_blocks (&free_block_lists [0][i], i);
2067 sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
2070 /* We expect workers to have very few blocks on the freelist, just evacuate them */
2071 sgen_workers_foreach (GENERATION_NURSERY, sgen_worker_clear_free_block_lists_evac);
2072 sgen_workers_foreach (GENERATION_OLD, sgen_worker_clear_free_block_lists_evac);
2074 if (lazy_sweep && concurrent_sweep) {
2076 * sweep_blocks_job is created before sweep_finish, which we wait for above
2077 * (major_finish_sweep_checking). After the end of sweep, if we don't have
2078 * sweep_blocks_job set, it means that it has already been run.
2080 SgenThreadPoolJob *job = sweep_blocks_job;
2082 sgen_thread_pool_job_wait (sweep_pool_context, job);
2085 if (lazy_sweep && !concurrent_sweep)
2086 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
2087 /* Sweep all unswept blocks and set them to MARKING */
2088 FOREACH_BLOCK_NO_LOCK (block) {
2089 if (lazy_sweep && !concurrent_sweep)
2090 sweep_block (block);
2091 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
2092 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
2094 * Swept blocks that have a null free_list are full. Evacuation is not
2095 * effective on these blocks since we expect them to have high usage anyway,
2096 * given that the survival rate for majors is relatively high.
2098 if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
2099 block->is_to_space = TRUE;
2100 } END_FOREACH_BLOCK_NO_LOCK;
2101 if (lazy_sweep && !concurrent_sweep)
2102 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
2104 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
2108 major_finish_major_collection (ScannedObjectCounts *counts)
2110 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2111 if (binary_protocol_is_enabled ()) {
2112 counts->num_scanned_objects = scanned_objects_list.next_slot;
2114 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
2115 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
2117 sgen_pointer_queue_clear (&scanned_objects_list);
2123 compare_pointers (const void *va, const void *vb) {
2124 char *a = *(char**)va, *b = *(char**)vb;
2133 * This is called with sweep completed and the world stopped.
2136 major_free_swept_blocks (size_t section_reserve)
2138 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
2140 #if defined(HOST_WIN32) || defined(HOST_ORBIS)
2142 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
2143 * a VirtualAlloc ()-ed block.
2149 int i, num_empty_blocks_orig, num_blocks, arr_length;
2151 void **empty_block_arr;
2152 void **rebuild_next;
2154 if (num_empty_blocks <= section_reserve)
2156 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
2158 num_empty_blocks_orig = num_empty_blocks;
2159 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
2160 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
2161 if (!empty_block_arr)
2165 for (block = empty_blocks; block; block = *(void**)block)
2166 empty_block_arr [i++] = block;
2167 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
2169 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
2172 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
2173 * contiguous ones. If we do, we free them. If that's not enough to get to
2174 * section_reserve, we halve the number of contiguous blocks we're looking
2175 * for and have another go, until we're done with looking for pairs of
2176 * blocks, at which point we give up and go to the fallback.
2178 arr_length = num_empty_blocks_orig;
2179 num_blocks = MS_BLOCK_ALLOC_NUM;
2180 while (num_empty_blocks > section_reserve && num_blocks > 1) {
2185 for (i = 0; i < arr_length; ++i) {
2187 void *block = empty_block_arr [i];
2188 SGEN_ASSERT (6, block, "we're not shifting correctly");
2190 empty_block_arr [dest] = block;
2192 * This is not strictly necessary, but we're
2195 empty_block_arr [i] = NULL;
2204 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
2206 if ((char*)block != ((char*)empty_block_arr [d-1]) + ms_block_size) {
2211 if (d + 1 - first == num_blocks) {
2213 * We found num_blocks contiguous blocks. Free them
2214 * and null their array entries. As an optimization
2215 * we could, instead of nulling the entries, shift
2216 * the following entries over to the left, while
2220 sgen_free_os_memory (empty_block_arr [first], ms_block_size * num_blocks, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2221 for (j = first; j <= d; ++j)
2222 empty_block_arr [j] = NULL;
2226 num_empty_blocks -= num_blocks;
2228 stat_major_blocks_freed += num_blocks;
2229 if (num_blocks == MS_BLOCK_ALLOC_NUM)
2230 stat_major_blocks_freed_ideal += num_blocks;
2232 stat_major_blocks_freed_less_ideal += num_blocks;
2237 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
2239 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
2244 /* rebuild empty_blocks free list */
2245 rebuild_next = (void**)&empty_blocks;
2246 for (i = 0; i < arr_length; ++i) {
2247 void *block = empty_block_arr [i];
2248 SGEN_ASSERT (6, block, "we're missing blocks");
2249 *rebuild_next = block;
2250 rebuild_next = (void**)block;
2252 *rebuild_next = NULL;
2255 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
2258 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
2262 * This is our threshold. If there's not more empty than used blocks, we won't
2263 * release uncontiguous blocks, in fear of fragmenting the address space.
2265 if (num_empty_blocks <= num_major_sections)
2268 while (num_empty_blocks > section_reserve) {
2269 void *next = *(void**)empty_blocks;
2270 sgen_free_os_memory (empty_blocks, ms_block_size, SGEN_ALLOC_HEAP, MONO_MEM_ACCOUNT_SGEN_MARKSWEEP);
2271 empty_blocks = next;
2273 * Needs not be atomic because this is running
2278 ++stat_major_blocks_freed;
2279 ++stat_major_blocks_freed_individual;
2284 major_pin_objects (SgenGrayQueue *queue)
2288 FOREACH_BLOCK_NO_LOCK (block) {
2289 size_t first_entry, last_entry;
2290 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2291 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + ms_block_size,
2292 &first_entry, &last_entry);
2293 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2294 } END_FOREACH_BLOCK_NO_LOCK;
2298 major_init_to_space (void)
2303 major_report_pinned_memory_usage (void)
2305 g_assert_not_reached ();
2309 major_get_used_size (void)
2315 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2316 * finished, then we can iterate over the block array.
2318 major_finish_sweep_checking ();
2320 FOREACH_BLOCK_NO_LOCK (block) {
2321 int count = MS_BLOCK_FREE / block->obj_size;
2323 size += count * block->obj_size;
2324 for (iter = block->free_list; iter; iter = (void**)*iter)
2325 size -= block->obj_size;
2326 } END_FOREACH_BLOCK_NO_LOCK;
2331 /* FIXME: return number of bytes, not of sections */
2333 get_num_major_sections (void)
2335 return num_major_sections;
2339 * Returns the number of bytes in blocks that were present when the last sweep was
2340 * initiated, and were not freed during the sweep. They are the basis for calculating the
2344 get_bytes_survived_last_sweep (void)
2346 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2347 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * ms_block_size;
2351 major_handle_gc_param (const char *opt)
2353 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2354 const char *arg = strchr (opt, '=') + 1;
2355 int percentage = atoi (arg);
2356 if (percentage < 0 || percentage > 100) {
2357 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2360 evacuation_threshold = (float)percentage / 100.0f;
2362 } else if (!strcmp (opt, "lazy-sweep")) {
2365 } else if (!strcmp (opt, "no-lazy-sweep")) {
2368 } else if (!strcmp (opt, "concurrent-sweep")) {
2369 concurrent_sweep = TRUE;
2371 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2372 concurrent_sweep = FALSE;
2380 major_print_gc_param_usage (void)
2384 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2385 " (no-)lazy-sweep\n"
2386 " (no-)concurrent-sweep\n"
2391 * This callback is used to clear cards, move cards to the shadow table and do counting.
2394 major_iterate_block_ranges (sgen_cardtable_block_callback callback)
2397 gboolean has_references;
2399 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2401 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2402 } END_FOREACH_BLOCK_NO_LOCK;
2406 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2409 gboolean has_references;
2411 major_finish_sweep_checking ();
2412 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2414 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size);
2415 } END_FOREACH_BLOCK_NO_LOCK;
2418 #ifdef HEAVY_STATISTICS
2419 extern guint64 marked_cards;
2420 extern guint64 scanned_cards;
2421 extern guint64 scanned_objects;
2422 extern guint64 remarked_cards;
2425 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2427 * MS blocks are 16K aligned.
2428 * Cardtables are 4K aligned, at least.
2429 * This means that the cardtable of a given block is 32 bytes aligned.
2432 initial_skip_card (guint8 *card_data)
2434 mword *cards = (mword*)card_data;
2437 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2443 if (i == CARD_WORDS_PER_BLOCK)
2444 return card_data + CARDS_PER_BLOCK;
2446 #if defined(__i386__) && defined(__GNUC__)
2447 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2448 #elif defined(__x86_64__) && defined(__GNUC__)
2449 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2450 #elif defined(__s390x__) && defined(__GNUC__)
2451 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2453 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2455 return &card_data [i];
2461 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2462 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2463 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + ms_block_size))
2466 scan_card_table_for_block (MSBlockInfo *block, CardTableScanType scan_type, ScanCopyContext ctx)
2468 SgenGrayQueue *queue = ctx.queue;
2469 ScanObjectFunc scan_func = ctx.ops->scan_object;
2471 * FIXME: On systems with very large pages, we allocate fairly large
2472 * arrays on the stack here. This shouldn't be a problem once block
2473 * size is no longer required to be a multiple of the system page size.
2475 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2476 guint8 *cards_copy = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2478 guint8 *cards_preclean = alloca (sizeof (guint8) * CARDS_PER_BLOCK);
2479 gboolean small_objects;
2482 guint8 *card_data, *card_base;
2483 guint8 *card_data_end;
2484 char *scan_front = NULL;
2486 /* The concurrent mark doesn't enter evacuating blocks */
2487 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN && major_block_is_evacuating (block))
2490 block_obj_size = block->obj_size;
2491 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2493 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2496 * This is safe in face of card aliasing for the following reason:
2498 * Major blocks are 16k aligned, or 32 cards aligned.
2499 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2500 * sizes, they won't overflow the cardtable overlap modulus.
2502 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2503 card_data = card_base = block->cardtable_mod_union;
2505 * This happens when the nursery collection that precedes finishing
2506 * the concurrent collection allocates new major blocks.
2511 if (scan_type == CARDTABLE_SCAN_MOD_UNION_PRECLEAN) {
2512 sgen_card_table_preclean_mod_union (card_data, cards_preclean, CARDS_PER_BLOCK);
2513 card_data = card_base = cards_preclean;
2516 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2517 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2519 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2521 card_data = card_base = cards_copy;
2524 card_data_end = card_data + CARDS_PER_BLOCK;
2526 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2528 card_data = initial_skip_card (card_data);
2529 while (card_data < card_data_end) {
2530 size_t card_index, first_object_index;
2533 char *first_obj, *obj;
2535 HEAVY_STAT (++scanned_cards);
2542 card_index = card_data - card_base;
2543 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2544 end = start + CARD_SIZE_IN_BYTES;
2546 if (!block_is_swept_or_marking (block))
2547 sweep_block (block);
2549 HEAVY_STAT (++marked_cards);
2552 sgen_card_table_prepare_card_for_scanning (card_data);
2555 * If the card we're looking at starts at or in the block header, we
2556 * must start at the first object in the block, without calculating
2557 * the index of the object we're hypothetically starting at, because
2558 * it would be negative.
2560 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2561 first_object_index = 0;
2563 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2565 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2567 binary_protocol_card_scan (first_obj, end - first_obj);
2570 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2573 if (scan_type & CARDTABLE_SCAN_MOD_UNION) {
2574 /* FIXME: do this more efficiently */
2576 MS_CALC_MARK_BIT (w, b, obj);
2577 if (!MS_MARK_BIT (block, w, b))
2581 GCObject *object = (GCObject*)obj;
2583 if (small_objects) {
2584 HEAVY_STAT (++scanned_objects);
2585 scan_func (object, sgen_obj_get_descriptor (object), queue);
2587 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2588 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, ctx);
2591 obj += block_obj_size;
2592 g_assert (scan_front <= obj);
2596 HEAVY_STAT (if (*card_data) ++remarked_cards);
2601 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2606 major_scan_card_table (CardTableScanType scan_type, ScanCopyContext ctx, int job_index, int job_split_count)
2609 gboolean has_references, was_sweeping, skip_scan;
2611 if (!concurrent_mark)
2612 g_assert (scan_type == CARDTABLE_SCAN_GLOBAL);
2614 if (scan_type != CARDTABLE_SCAN_GLOBAL)
2615 SGEN_ASSERT (0, !sweep_in_progress (), "Sweep should be finished when we scan mod union card table");
2616 was_sweeping = sweep_in_progress ();
2618 binary_protocol_major_card_table_scan_start (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2619 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2620 if (__index % job_split_count != job_index)
2622 #ifdef PREFETCH_CARDS
2623 int prefetch_index = __index + 6 * job_split_count;
2624 if (prefetch_index < allocated_blocks.next_slot) {
2625 MSBlockInfo *prefetch_block = BLOCK_UNTAG (*sgen_array_list_get_slot (&allocated_blocks, prefetch_index));
2626 PREFETCH_READ (prefetch_block);
2627 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2628 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2629 PREFETCH_WRITE (prefetch_cards);
2630 PREFETCH_WRITE (prefetch_cards + 32);
2635 if (!has_references)
2639 if (scan_type == CARDTABLE_SCAN_GLOBAL) {
2640 gpointer *card_start = (gpointer*) sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2641 gboolean has_dirty_cards = FALSE;
2643 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2644 if (card_start [i]) {
2645 has_dirty_cards = TRUE;
2649 if (!has_dirty_cards) {
2653 * After the start of the concurrent collections, blocks change state
2654 * to marking. We should not sweep it in that case. We can't race with
2655 * sweep start since we are in a nursery collection. Also avoid CAS-ing
2657 if (sweep_in_progress ()) {
2658 skip_scan = !ensure_block_is_checked_for_sweeping (__index, TRUE, NULL);
2659 } else if (was_sweeping) {
2660 /* Recheck in case sweep finished after dereferencing the slot */
2661 skip_scan = *sgen_array_list_get_slot (&allocated_blocks, __index) == 0;
2666 scan_card_table_for_block (block, scan_type, ctx);
2667 } END_FOREACH_BLOCK_NO_LOCK;
2668 binary_protocol_major_card_table_scan_end (sgen_timestamp (), scan_type & CARDTABLE_SCAN_MOD_UNION);
2672 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2675 gboolean has_references;
2676 long long total_cards = 0;
2677 long long marked_cards = 0;
2679 if (sweep_in_progress ()) {
2680 *num_total_cards = -1;
2681 *num_marked_cards = -1;
2685 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2686 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2689 if (!has_references)
2692 total_cards += CARDS_PER_BLOCK;
2693 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2697 } END_FOREACH_BLOCK_NO_LOCK;
2699 *num_total_cards = total_cards;
2700 *num_marked_cards = marked_cards;
2704 update_cardtable_mod_union (void)
2708 FOREACH_BLOCK_NO_LOCK (block) {
2709 gpointer *card_start = (gpointer*) sgen_card_table_get_card_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (block));
2710 gboolean has_dirty_cards = FALSE;
2712 for (i = 0; i < CARDS_PER_BLOCK / sizeof(gpointer); i++) {
2713 if (card_start [i]) {
2714 has_dirty_cards = TRUE;
2718 if (has_dirty_cards) {
2720 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2721 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), ms_block_size, &num_cards);
2722 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2724 } END_FOREACH_BLOCK_NO_LOCK;
2727 #undef pthread_create
2730 post_param_init (SgenMajorCollector *collector)
2732 collector->sweeps_lazily = lazy_sweep;
2736 * We are guaranteed to be called by the worker in question.
2737 * This provides initialization for threads that plan to do
2738 * parallel object allocation. We need to store these lists
2739 * in additional data structures so we can traverse them
2740 * at major/sweep start.
2743 sgen_init_block_free_lists (gpointer *list_p)
2746 MSBlockInfo ***worker_free_blocks = (MSBlockInfo ***) mono_native_tls_get_value (worker_block_free_list_key);
2749 * For simplification, a worker thread uses the same free block lists,
2750 * regardless of the context it is part of (major/minor).
2752 if (worker_free_blocks) {
2753 *list_p = (gpointer)worker_free_blocks;
2757 worker_free_blocks = (MSBlockInfo ***) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX, INTERNAL_MEM_MS_TABLES, TRUE);
2759 for (i = 0; i < MS_BLOCK_TYPE_MAX; i++)
2760 worker_free_blocks [i] = (MSBlockInfo **) sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2762 *list_p = (gpointer)worker_free_blocks;
2764 mono_native_tls_set_value (worker_block_free_list_key, worker_free_blocks);
2768 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent, gboolean is_parallel)
2772 ms_block_size = mono_pagesize ();
2774 if (ms_block_size < MS_BLOCK_SIZE_MIN)
2775 ms_block_size = MS_BLOCK_SIZE_MIN;
2777 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, SIZEOF_MS_BLOCK_INFO);
2779 if (mono_cpu_count () <= 1)
2780 is_parallel = FALSE;
2782 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2783 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2784 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2786 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2787 for (i = 0; i < num_block_obj_sizes; ++i)
2788 evacuate_block_obj_sizes [i] = FALSE;
2790 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2791 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2792 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2797 g_print ("block object sizes:\n");
2798 for (i = 0; i < num_block_obj_sizes; ++i)
2799 g_print ("%d\n", block_obj_sizes [i]);
2803 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2804 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2806 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2807 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2808 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2809 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2811 /* We can do this because we always init the minor before the major */
2812 if (is_parallel || sgen_get_minor_collector ()->is_parallel)
2813 mono_native_tls_alloc (&worker_block_free_list_key, NULL);
2815 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2816 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2817 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2818 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2819 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2820 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2821 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2823 collector->section_size = ms_block_size;
2825 concurrent_mark = is_concurrent;
2826 collector->is_concurrent = is_concurrent;
2827 collector->is_parallel = is_parallel;
2828 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2829 collector->supports_cardtable = TRUE;
2831 collector->alloc_heap = major_alloc_heap;
2832 collector->is_object_live = major_is_object_live;
2833 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2834 collector->alloc_degraded = major_alloc_degraded;
2836 collector->alloc_object = major_alloc_object;
2837 collector->alloc_object_par = major_alloc_object_par;
2838 collector->free_pinned_object = free_pinned_object;
2839 collector->iterate_objects = major_iterate_objects;
2840 collector->free_non_pinned_object = major_free_non_pinned_object;
2841 collector->pin_objects = major_pin_objects;
2842 collector->pin_major_object = pin_major_object;
2843 collector->scan_card_table = major_scan_card_table;
2844 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2845 collector->iterate_block_ranges = major_iterate_block_ranges;
2846 if (is_concurrent) {
2847 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2848 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2850 collector->init_to_space = major_init_to_space;
2851 collector->sweep = major_sweep;
2852 collector->have_swept = major_have_swept;
2853 collector->finish_sweeping = major_finish_sweep_checking;
2854 collector->free_swept_blocks = major_free_swept_blocks;
2855 collector->check_scan_starts = major_check_scan_starts;
2856 collector->dump_heap = major_dump_heap;
2857 collector->get_used_size = major_get_used_size;
2858 collector->start_nursery_collection = major_start_nursery_collection;
2859 collector->finish_nursery_collection = major_finish_nursery_collection;
2860 collector->start_major_collection = major_start_major_collection;
2861 collector->finish_major_collection = major_finish_major_collection;
2862 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2863 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2864 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2865 collector->get_num_major_sections = get_num_major_sections;
2866 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2867 collector->handle_gc_param = major_handle_gc_param;
2868 collector->print_gc_param_usage = major_print_gc_param_usage;
2869 collector->post_param_init = post_param_init;
2870 collector->is_valid_object = major_is_valid_object;
2871 collector->describe_pointer = major_describe_pointer;
2872 collector->count_cards = major_count_cards;
2873 collector->init_block_free_lists = sgen_init_block_free_lists;
2875 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2876 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2877 collector->major_ops_serial.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2878 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2879 if (is_concurrent) {
2880 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2881 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2882 collector->major_ops_concurrent_start.scan_vtype = major_scan_vtype_concurrent_with_evacuation;
2883 collector->major_ops_concurrent_start.scan_ptr_field = major_scan_ptr_field_concurrent_with_evacuation;
2884 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2886 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2887 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2888 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_with_evacuation;
2889 collector->major_ops_concurrent_finish.scan_ptr_field = major_scan_ptr_field_with_evacuation;
2890 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2893 collector->major_ops_conc_par_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_canonical;
2894 collector->major_ops_conc_par_start.scan_object = major_scan_object_concurrent_par_with_evacuation;
2895 collector->major_ops_conc_par_start.scan_vtype = major_scan_vtype_concurrent_par_with_evacuation;
2896 collector->major_ops_conc_par_start.scan_ptr_field = major_scan_ptr_field_concurrent_par_with_evacuation;
2897 collector->major_ops_conc_par_start.drain_gray_stack = drain_gray_stack_concurrent_par;
2899 collector->major_ops_conc_par_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_par_finish_canonical;
2900 collector->major_ops_conc_par_finish.scan_object = major_scan_object_par_with_evacuation;
2901 collector->major_ops_conc_par_finish.scan_vtype = major_scan_vtype_par_with_evacuation;
2902 collector->major_ops_conc_par_finish.scan_ptr_field = major_scan_ptr_field_par_with_evacuation;
2903 collector->major_ops_conc_par_finish.drain_gray_stack = drain_gray_stack_par;
2907 #ifdef HEAVY_STATISTICS
2908 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2909 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2910 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2911 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2912 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2913 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2914 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2915 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2916 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2917 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2918 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2920 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2921 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2922 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2925 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2926 mono_os_mutex_init (&scanned_objects_list_lock);
2929 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2931 /*cardtable requires major pages to be 8 cards aligned*/
2932 g_assert ((ms_block_size % (8 * CARD_SIZE_IN_BYTES)) == 0);
2934 if (is_concurrent && is_parallel)
2935 sgen_workers_create_context (GENERATION_OLD, mono_cpu_count ());
2936 else if (is_concurrent)
2937 sgen_workers_create_context (GENERATION_OLD, 1);
2939 if (concurrent_sweep)
2940 sweep_pool_context = sgen_thread_pool_create_context (1, NULL, NULL, NULL, NULL, NULL);
2944 sgen_marksweep_init (SgenMajorCollector *collector)
2946 sgen_marksweep_init_internal (collector, FALSE, FALSE);
2950 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2952 sgen_marksweep_init_internal (collector, TRUE, FALSE);
2956 sgen_marksweep_conc_par_init (SgenMajorCollector *collector)
2958 sgen_marksweep_init_internal (collector, TRUE, TRUE);