2 * sgen-marksweep.c: The Mark & Sweep major collector.
5 * Mark Probst <mark.probst@gmail.com>
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright (C) 2012 Xamarin Inc
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License 2.0 as published by the Free Software Foundation;
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public
20 * License 2.0 along with this library; if not, write to the Free
21 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #include "utils/mono-counters.h"
32 #include "utils/mono-semaphore.h"
33 #include "utils/mono-time.h"
34 #include "metadata/object-internals.h"
35 #include "metadata/profiler-private.h"
37 #include "metadata/sgen-gc.h"
38 #include "metadata/sgen-protocol.h"
39 #include "metadata/sgen-cardtable.h"
40 #include "metadata/sgen-memory-governor.h"
41 #include "metadata/sgen-layout-stats.h"
42 #include "metadata/gc-internal.h"
43 #include "metadata/sgen-pointer-queue.h"
44 #include "metadata/sgen-pinning.h"
45 #include "metadata/sgen-workers.h"
46 #include "metadata/sgen-thread-pool.h"
48 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
49 #define MS_BLOCK_SIZE ARCH_MIN_MS_BLOCK_SIZE
50 #define MS_BLOCK_SIZE_SHIFT ARCH_MIN_MS_BLOCK_SIZE_SHIFT
52 #define MS_BLOCK_SIZE_SHIFT 14 /* INT FASTENABLE */
53 #define MS_BLOCK_SIZE (1 << MS_BLOCK_SIZE_SHIFT)
55 #define MAJOR_SECTION_SIZE MS_BLOCK_SIZE
56 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
59 * Don't allocate single blocks, but alloc a contingent of this many
60 * blocks in one swoop. This must be a power of two.
62 #define MS_BLOCK_ALLOC_NUM 32
65 * Number of bytes before the first object in a block. At the start
66 * of a block is the MSBlockHeader, then opional padding, then come
67 * the objects, so this must be >= sizeof (MSBlockHeader).
69 #define MS_BLOCK_SKIP ((sizeof (MSBlockHeader) + 15) & ~15)
71 #define MS_BLOCK_FREE (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
73 #define MS_NUM_MARK_WORDS ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
76 * Blocks progress from one state to the next:
78 * SWEPT The block is fully swept. It might or might not be in
81 * MARKING The block might or might not contain live objects. If
82 * we're in between an initial collection pause and the
83 * finishing pause, the block might or might not be in a
86 * CHECKING The sweep thread is investigating the block to determine
87 * whether or not it contains live objects. The block is
90 * NEED_SWEEPING The block contains live objects but has not yet been
91 * swept. It also contains free slots. It is in a block
94 * SWEEPING The block is being swept. It might be in a free list.
100 BLOCK_STATE_CHECKING,
101 BLOCK_STATE_NEED_SWEEPING,
105 typedef struct _MSBlockInfo MSBlockInfo;
106 struct _MSBlockInfo {
109 * FIXME: Do we even need this? It's only used during sweep and might be worth
110 * recalculating to save the space.
112 guint16 obj_size_index;
113 /* FIXME: Reduce this - it only needs a byte. */
114 volatile gint32 state;
115 unsigned int pinned : 1;
116 unsigned int has_references : 1;
117 unsigned int has_pinned : 1; /* means cannot evacuate */
118 unsigned int is_to_space : 1;
119 void ** volatile free_list;
120 MSBlockInfo * volatile next_free;
121 guint8 *cardtable_mod_union;
122 mword mark_words [MS_NUM_MARK_WORDS];
125 #define MS_BLOCK_FOR_BLOCK_INFO(b) ((char*)(b))
127 #define MS_BLOCK_OBJ(b,i) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i))
128 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
129 #define MS_BLOCK_DATA_FOR_OBJ(o) ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
135 #define MS_BLOCK_FOR_OBJ(o) (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
137 /* object index will always be small */
138 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
140 //casting to int is fine since blocks are 32k
141 #define MS_CALC_MARK_BIT(w,b,o) do { \
142 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
143 if (sizeof (mword) == 4) { \
152 #define MS_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] & (ONE_P << (b)))
153 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
155 #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))
157 #define MS_BLOCK_OBJ_SIZE_FACTOR (pow (2.0, 1.0 / 3))
160 * This way we can lookup block object size indexes for sizes up to
161 * 256 bytes with a single load.
163 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES 32
165 static int *block_obj_sizes;
166 static int num_block_obj_sizes;
167 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
169 #define MS_BLOCK_FLAG_PINNED 1
170 #define MS_BLOCK_FLAG_REFS 2
172 #define MS_BLOCK_TYPE_MAX 4
174 static gboolean *evacuate_block_obj_sizes;
175 static float evacuation_threshold = 0.666f;
176 static float concurrent_evacuation_threshold = 0.666f;
177 static gboolean want_evacuation = FALSE;
179 static gboolean lazy_sweep = FALSE;
183 SWEEP_STATE_NEED_SWEEPING,
184 SWEEP_STATE_SWEEPING,
185 SWEEP_STATE_SWEEPING_AND_ITERATING,
186 SWEEP_STATE_COMPACTING
189 static volatile int sweep_state = SWEEP_STATE_SWEPT;
191 static gboolean concurrent_mark;
192 static gboolean concurrent_sweep = TRUE;
194 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
195 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
197 #define BLOCK_IS_TAGGED_CHECKING(bl) SGEN_POINTER_IS_TAGGED_2 ((bl))
198 #define BLOCK_TAG_CHECKING(bl) SGEN_POINTER_TAG_2 ((bl))
200 #define BLOCK_UNTAG(bl) SGEN_POINTER_UNTAG_12 ((bl))
202 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
204 /* all allocated blocks in the system */
205 static SgenPointerQueue allocated_blocks;
207 /* non-allocated block free-list */
208 static void *empty_blocks = NULL;
209 static size_t num_empty_blocks = 0;
211 #define FOREACH_BLOCK_NO_LOCK_CONDITION(cond,bl) { \
213 SGEN_ASSERT (0, (cond) && !sweep_in_progress (), "Can't iterate blocks while the world is running or sweep is in progress."); \
214 for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { \
215 (bl) = BLOCK_UNTAG (allocated_blocks.data [__index]);
216 #define FOREACH_BLOCK_NO_LOCK(bl) \
217 FOREACH_BLOCK_NO_LOCK_CONDITION(sgen_is_world_stopped (), bl)
218 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
220 SGEN_ASSERT (0, sgen_is_world_stopped () && !sweep_in_progress (), "Can't iterate blocks while the world is running or sweep is in progress."); \
221 for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { \
222 (bl) = allocated_blocks.data [__index]; \
223 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
224 (bl) = BLOCK_UNTAG ((bl));
225 #define END_FOREACH_BLOCK_NO_LOCK } }
227 static volatile size_t num_major_sections = 0;
229 * One free block list for each block object size. We add and remove blocks from these
230 * lists lock-free via CAS.
232 * Blocks accessed/removed from `free_block_lists`:
233 * from the mutator (with GC lock held)
234 * in nursery collections
235 * in non-concurrent major collections
236 * in the finishing pause of concurrent major collections (whole list is cleared)
238 * Blocks added to `free_block_lists`:
239 * in the sweeping thread
240 * during nursery collections
241 * from domain clearing (with the world stopped and no sweeping happening)
243 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
244 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
246 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
248 static guint64 stat_major_blocks_alloced = 0;
249 static guint64 stat_major_blocks_freed = 0;
250 static guint64 stat_major_blocks_lazy_swept = 0;
251 static guint64 stat_major_objects_evacuated = 0;
253 #if SIZEOF_VOID_P != 8
254 static guint64 stat_major_blocks_freed_ideal = 0;
255 static guint64 stat_major_blocks_freed_less_ideal = 0;
256 static guint64 stat_major_blocks_freed_individual = 0;
257 static guint64 stat_major_blocks_alloced_less_ideal = 0;
260 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
261 static guint64 num_major_objects_marked = 0;
262 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
264 #define INC_NUM_MAJOR_OBJECTS_MARKED()
267 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
268 static mono_mutex_t scanned_objects_list_lock;
269 static SgenPointerQueue scanned_objects_list;
272 add_scanned_object (void *ptr)
274 if (!binary_protocol_is_enabled ())
277 mono_mutex_lock (&scanned_objects_list_lock);
278 sgen_pointer_queue_add (&scanned_objects_list, ptr);
279 mono_mutex_unlock (&scanned_objects_list_lock);
283 static gboolean sweep_block (MSBlockInfo *block);
286 ms_find_block_obj_size_index (size_t size)
289 SGEN_ASSERT (9, size <= SGEN_MAX_SMALL_OBJ_SIZE, "size %d is bigger than max small object size %d", size, SGEN_MAX_SMALL_OBJ_SIZE);
290 for (i = 0; i < num_block_obj_sizes; ++i)
291 if (block_obj_sizes [i] >= size)
293 g_error ("no object of size %d\n", size);
296 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
297 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
299 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
300 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
301 fast_block_obj_size_indexes [((s)+7)>>3] : \
302 ms_find_block_obj_size_index ((s)))
305 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
309 start = sgen_alloc_os_memory_aligned (nursery_size, nursery_align, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
311 start = sgen_alloc_os_memory (nursery_size, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
317 update_heap_boundaries_for_block (MSBlockInfo *block)
319 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
326 ms_get_empty_block (void)
330 void *block, *empty, *next;
335 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
336 * unsuccessful, we halve the number of blocks and try again, until we're at
337 * 1. If that doesn't work, either, we assert.
339 int alloc_num = MS_BLOCK_ALLOC_NUM;
341 p = sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE,
342 alloc_num == 1 ? "major heap section" : NULL);
348 for (i = 0; i < alloc_num; ++i) {
351 * We do the free list update one after the
352 * other so that other threads can use the new
353 * blocks as quickly as possible.
356 empty = empty_blocks;
357 *(void**)block = empty;
358 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
362 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
364 stat_major_blocks_alloced += alloc_num;
365 #if SIZEOF_VOID_P != 8
366 if (alloc_num != MS_BLOCK_ALLOC_NUM)
367 stat_major_blocks_alloced_less_ideal += alloc_num;
372 empty = empty_blocks;
376 next = *(void**)block;
377 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
379 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
381 *(void**)block = NULL;
383 g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
389 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
390 * list, where it will either be freed later on, or reused in nursery collections.
393 ms_free_block (void *block)
397 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
398 memset (block, 0, MS_BLOCK_SIZE);
401 empty = empty_blocks;
402 *(void**)block = empty;
403 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
405 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
407 binary_protocol_block_free (block, MS_BLOCK_SIZE);
411 sweep_in_progress (void)
413 int state = sweep_state;
414 return state == SWEEP_STATE_SWEEPING ||
415 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
416 state == SWEEP_STATE_COMPACTING;
419 static inline gboolean
420 block_is_swept_or_marking (MSBlockInfo *block)
422 gint32 state = block->state;
423 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
426 //#define MARKSWEEP_CONSISTENCY_CHECK
428 #ifdef MARKSWEEP_CONSISTENCY_CHECK
430 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
432 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
433 for (; block; block = block->next_free) {
434 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
435 g_assert (block->obj_size == size);
436 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
438 /* blocks in the free lists must have at least
440 g_assert (block->free_list);
442 /* the block must be in the allocated_blocks array */
443 g_assert (sgen_pointer_queue_find (&allocated_blocks, BLOCK_TAG (block)) != (size_t)-1);
448 check_empty_blocks (void)
452 for (p = empty_blocks; p; p = *(void**)p)
454 g_assert (i == num_empty_blocks);
458 consistency_check (void)
463 /* check all blocks */
464 FOREACH_BLOCK_NO_LOCK (block) {
465 int count = MS_BLOCK_FREE / block->obj_size;
469 /* count number of free slots */
470 for (i = 0; i < count; ++i) {
471 void **obj = (void**) MS_BLOCK_OBJ (block, i);
472 if (!MS_OBJ_ALLOCED (obj, block))
476 /* check free list */
477 for (free = block->free_list; free; free = (void**)*free) {
478 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
481 g_assert (num_free == 0);
483 /* check all mark words are zero */
484 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
485 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
486 g_assert (block->mark_words [i] == 0);
488 } END_FOREACH_BLOCK_NO_LOCK;
490 /* check free blocks */
491 for (i = 0; i < num_block_obj_sizes; ++i) {
493 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
494 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
497 check_empty_blocks ();
502 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
506 block->next_free = old = free_blocks [size_index];
507 } while (SGEN_CAS_PTR ((gpointer)&free_blocks [size_index], block, old) != old);
510 static void major_finish_sweep_checking (void);
513 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
515 int size = block_obj_sizes [size_index];
516 int count = MS_BLOCK_FREE / size;
518 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
522 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
525 info = (MSBlockInfo*)ms_get_empty_block ();
527 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
529 info->obj_size = size;
530 info->obj_size_index = size_index;
531 info->pinned = pinned;
532 info->has_references = has_references;
533 info->has_pinned = pinned;
535 * Blocks that are to-space are not evacuated from. During an major collection
536 * blocks are allocated for two reasons: evacuating objects from the nursery and
537 * evacuating them from major blocks marked for evacuation. In both cases we don't
538 * want further evacuation.
540 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD);
541 info->state = (info->is_to_space || sgen_concurrent_collection_in_progress ()) ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
542 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
543 info->cardtable_mod_union = NULL;
545 update_heap_boundaries_for_block (info);
547 binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
549 /* build free list */
550 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
551 info->free_list = (void**)obj_start;
552 /* we're skipping the last one - it must be nulled */
553 for (i = 0; i < count - 1; ++i) {
554 char *next_obj_start = obj_start + size;
555 *(void**)obj_start = next_obj_start;
556 obj_start = next_obj_start;
559 *(void**)obj_start = NULL;
561 add_free_block (free_blocks, size_index, info);
564 * This is the only place where the `allocated_blocks` array can potentially grow.
565 * We need to make sure concurrent sweep isn't running when that happens, so in that
566 * specific case we just wait for sweep to finish.
568 if (sgen_pointer_queue_will_grow (&allocated_blocks))
569 major_finish_sweep_checking ();
571 sgen_pointer_queue_add (&allocated_blocks, BLOCK_TAG (info));
573 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
578 obj_is_from_pinned_alloc (char *ptr)
582 FOREACH_BLOCK_NO_LOCK (block) {
583 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
584 return block->pinned;
585 } END_FOREACH_BLOCK_NO_LOCK;
590 ensure_can_access_block_free_list (MSBlockInfo *block)
594 switch (block->state) {
595 case BLOCK_STATE_SWEPT:
596 case BLOCK_STATE_MARKING:
598 case BLOCK_STATE_CHECKING:
599 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
601 case BLOCK_STATE_NEED_SWEEPING:
602 if (sweep_block (block))
603 ++stat_major_blocks_lazy_swept;
605 case BLOCK_STATE_SWEEPING:
606 /* FIXME: do this more elegantly */
610 SGEN_ASSERT (0, FALSE, "Illegal block state");
617 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
619 MSBlockInfo *block, *next_free_block;
620 void *obj, *next_free_slot;
623 block = free_blocks [size_index];
624 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
626 ensure_can_access_block_free_list (block);
628 obj = block->free_list;
629 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
631 next_free_slot = *(void**)obj;
632 if (next_free_slot) {
633 block->free_list = next_free_slot;
637 next_free_block = block->next_free;
638 if (SGEN_CAS_PTR ((gpointer)&free_blocks [size_index], next_free_block, block) != block)
641 block->free_list = NULL;
642 block->next_free = NULL;
648 alloc_obj (MonoVTable *vtable, size_t size, gboolean pinned, gboolean has_references)
650 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
651 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
654 if (!free_blocks [size_index]) {
655 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
659 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
661 *(MonoVTable**)obj = vtable;
667 major_alloc_object (MonoVTable *vtable, size_t size, gboolean has_references)
669 return alloc_obj (vtable, size, FALSE, has_references);
673 * We're not freeing the block if it's empty. We leave that work for
674 * the next major collection.
676 * This is just called from the domain clearing code, which runs in a
677 * single thread and has the GC lock, so we don't need an extra lock.
680 free_object (char *obj, size_t size, gboolean pinned)
682 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
684 gboolean in_free_list;
686 SGEN_ASSERT (9, sweep_state == SWEEP_STATE_SWEPT, "Should have waited for sweep to free objects.");
688 ensure_can_access_block_free_list (block);
689 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);
690 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
691 MS_CALC_MARK_BIT (word, bit, obj);
692 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set");
694 memset (obj, 0, size);
696 in_free_list = !!block->free_list;
697 *(void**)obj = block->free_list;
698 block->free_list = (void**)obj;
701 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (pinned, block->has_references);
702 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
703 SGEN_ASSERT (9, !block->next_free, "block %p doesn't have a free-list of object but belongs to a free-list of blocks");
704 add_free_block (free_blocks, size_index, block);
709 major_free_non_pinned_object (char *obj, size_t size)
711 free_object (obj, size, FALSE);
714 /* size is a multiple of SGEN_ALLOC_ALIGN */
716 major_alloc_small_pinned_obj (MonoVTable *vtable, size_t size, gboolean has_references)
720 res = alloc_obj (vtable, size, TRUE, has_references);
721 /*If we failed to alloc memory, we better try releasing memory
722 *as pinned alloc is requested by the runtime.
725 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
726 res = alloc_obj (vtable, size, TRUE, has_references);
732 free_pinned_object (char *obj, size_t size)
734 free_object (obj, size, TRUE);
738 * size is already rounded up and we hold the GC lock.
741 major_alloc_degraded (MonoVTable *vtable, size_t size)
743 void *obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
744 if (G_LIKELY (obj)) {
745 HEAVY_STAT (++stat_objects_alloced_degraded);
746 HEAVY_STAT (stat_bytes_alloced_degraded += size);
752 * obj is some object. If it's not in the major heap (i.e. if it's in
753 * the nursery or LOS), return FALSE. Otherwise return whether it's
754 * been marked or copied.
757 major_is_object_live (char *obj)
763 if (sgen_ptr_in_nursery (obj))
766 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
769 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
772 /* now we know it's in a major block */
773 block = MS_BLOCK_FOR_OBJ (obj);
774 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?");
775 MS_CALC_MARK_BIT (word, bit, obj);
776 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
780 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
784 FOREACH_BLOCK_NO_LOCK (block) {
785 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
786 int count = MS_BLOCK_FREE / block->obj_size;
790 for (i = 0; i <= count; ++i) {
791 if (ptr >= MS_BLOCK_OBJ (block, i) && ptr < MS_BLOCK_OBJ (block, i + 1)) {
792 *start = MS_BLOCK_OBJ (block, i);
796 return !block->pinned;
798 } END_FOREACH_BLOCK_NO_LOCK;
803 try_set_sweep_state (int new, int expected)
805 int old = SGEN_CAS (&sweep_state, new, expected);
806 return old == expected;
810 set_sweep_state (int new, int expected)
812 gboolean success = try_set_sweep_state (new, expected);
813 SGEN_ASSERT (0, success, "Could not set sweep state.");
816 static gboolean ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked);
818 static SgenThreadPoolJob * volatile sweep_job;
821 major_finish_sweep_checking (void)
824 SgenThreadPoolJob *job;
827 switch (sweep_state) {
828 case SWEEP_STATE_SWEPT:
829 case SWEEP_STATE_NEED_SWEEPING:
831 case SWEEP_STATE_SWEEPING:
832 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
835 case SWEEP_STATE_SWEEPING_AND_ITERATING:
836 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
838 case SWEEP_STATE_COMPACTING:
841 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
846 * We're running with the world stopped and the only other thread doing work is the
847 * sweep thread, which doesn't add blocks to the array, so we can safely access
850 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
851 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
853 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
858 sgen_thread_pool_job_wait (job);
859 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
860 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
864 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
866 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
867 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
868 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
871 major_finish_sweep_checking ();
872 FOREACH_BLOCK_NO_LOCK (block) {
873 int count = MS_BLOCK_FREE / block->obj_size;
876 if (block->pinned && !pinned)
878 if (!block->pinned && !non_pinned)
880 if (sweep && lazy_sweep) {
882 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
885 for (i = 0; i < count; ++i) {
886 void **obj = (void**) MS_BLOCK_OBJ (block, i);
888 * We've finished sweep checking, but if we're sweeping lazily and
889 * the flags don't require us to sweep, the block might still need
890 * sweeping. In that case, we need to consult the mark bits to tell
891 * us whether an object slot is live.
893 if (!block_is_swept_or_marking (block)) {
895 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
896 MS_CALC_MARK_BIT (word, bit, obj);
897 if (!MS_MARK_BIT (block, word, bit))
900 if (MS_OBJ_ALLOCED (obj, block))
901 callback ((char*)obj, block->obj_size, data);
903 } END_FOREACH_BLOCK_NO_LOCK;
907 major_is_valid_object (char *object)
911 FOREACH_BLOCK_NO_LOCK (block) {
915 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
918 idx = MS_BLOCK_OBJ_INDEX (object, block);
919 obj = (char*)MS_BLOCK_OBJ (block, idx);
922 return MS_OBJ_ALLOCED (obj, block);
923 } END_FOREACH_BLOCK_NO_LOCK;
930 major_describe_pointer (char *ptr)
934 FOREACH_BLOCK_NO_LOCK (block) {
942 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
945 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
946 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
948 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
949 obj = (char*)MS_BLOCK_OBJ (block, idx);
950 live = MS_OBJ_ALLOCED (obj, block);
951 vtable = live ? (MonoVTable*)SGEN_LOAD_VTABLE (obj) : NULL;
953 MS_CALC_MARK_BIT (w, b, obj);
954 marked = MS_MARK_BIT (block, w, b);
959 SGEN_LOG (0, "object");
961 SGEN_LOG (0, "dead-object");
964 SGEN_LOG (0, "interior-ptr offset %td", ptr - obj);
966 SGEN_LOG (0, "dead-interior-ptr offset %td", ptr - obj);
969 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
972 } END_FOREACH_BLOCK_NO_LOCK;
978 major_check_scan_starts (void)
983 major_dump_heap (FILE *heap_dump_file)
986 int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
987 int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
990 for (i = 0; i < num_block_obj_sizes; ++i)
991 slots_available [i] = slots_used [i] = 0;
993 FOREACH_BLOCK_NO_LOCK (block) {
994 int index = ms_find_block_obj_size_index (block->obj_size);
995 int count = MS_BLOCK_FREE / block->obj_size;
997 slots_available [index] += count;
998 for (i = 0; i < count; ++i) {
999 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1000 ++slots_used [index];
1002 } END_FOREACH_BLOCK_NO_LOCK;
1004 fprintf (heap_dump_file, "<occupancies>\n");
1005 for (i = 0; i < num_block_obj_sizes; ++i) {
1006 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1007 block_obj_sizes [i], slots_available [i], slots_used [i]);
1009 fprintf (heap_dump_file, "</occupancies>\n");
1011 FOREACH_BLOCK_NO_LOCK (block) {
1012 int count = MS_BLOCK_FREE / block->obj_size;
1016 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1018 for (i = 0; i <= count; ++i) {
1019 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1024 sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1030 fprintf (heap_dump_file, "</section>\n");
1031 } END_FOREACH_BLOCK_NO_LOCK;
1034 #define LOAD_VTABLE SGEN_LOAD_VTABLE
1036 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do { \
1037 int __word, __bit; \
1038 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1039 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
1040 MS_SET_MARK_BIT ((block), __word, __bit); \
1041 if (sgen_gc_descr_has_references (desc)) \
1042 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1043 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
1044 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1047 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1048 int __word, __bit; \
1049 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1050 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1051 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1052 MS_SET_MARK_BIT ((block), __word, __bit); \
1053 if (sgen_gc_descr_has_references (desc)) \
1054 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1055 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
1056 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1061 pin_major_object (char *obj, SgenGrayQueue *queue)
1065 if (concurrent_mark)
1066 g_assert_not_reached ();
1068 block = MS_BLOCK_FOR_OBJ (obj);
1069 block->has_pinned = TRUE;
1070 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1073 #include "sgen-major-copy-object.h"
1076 major_copy_or_mark_object_with_evacuation_concurrent (void **ptr, void *obj, SgenGrayQueue *queue)
1078 SGEN_ASSERT (9, sgen_concurrent_collection_in_progress (), "Why are we scanning concurrently when there's no concurrent collection on?");
1079 SGEN_ASSERT (9, !sgen_workers_are_working () || sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "We must not scan from two threads at the same time!");
1081 g_assert (!SGEN_OBJECT_IS_FORWARDED (obj));
1083 if (!sgen_ptr_in_nursery (obj)) {
1086 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
1088 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE) {
1089 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
1090 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1092 if (sgen_los_object_is_pinned (obj))
1095 #ifdef ENABLE_DTRACE
1096 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1097 MonoVTable *vt = (MonoVTable*)SGEN_LOAD_VTABLE (obj);
1098 MONO_GC_OBJ_PINNED ((mword)obj, sgen_safe_object_get_size (obj), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
1102 sgen_los_pin_object (obj);
1103 if (SGEN_OBJECT_HAS_REFERENCES (obj))
1104 GRAY_OBJECT_ENQUEUE (queue, obj, sgen_obj_get_descriptor (obj));
1105 INC_NUM_MAJOR_OBJECTS_MARKED ();
1111 major_get_and_reset_num_major_objects_marked (void)
1113 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1114 long long num = num_major_objects_marked;
1115 num_major_objects_marked = 0;
1122 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1124 #undef PREFETCH_CARDS
1127 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1128 #if defined(PLATFORM_MACOSX)
1129 #define GCC_VERSION (__GNUC__ * 10000 \
1130 + __GNUC_MINOR__ * 100 \
1131 + __GNUC_PATCHLEVEL__)
1132 #if GCC_VERSION <= 40300
1133 #undef PREFETCH_CARDS
1137 #ifdef HEAVY_STATISTICS
1138 static guint64 stat_optimized_copy;
1139 static guint64 stat_optimized_copy_nursery;
1140 static guint64 stat_optimized_copy_nursery_forwarded;
1141 static guint64 stat_optimized_copy_nursery_pinned;
1142 static guint64 stat_optimized_copy_major;
1143 static guint64 stat_optimized_copy_major_small_fast;
1144 static guint64 stat_optimized_copy_major_small_slow;
1145 static guint64 stat_optimized_copy_major_large;
1146 static guint64 stat_optimized_copy_major_forwarded;
1147 static guint64 stat_optimized_copy_major_small_evacuate;
1148 static guint64 stat_optimized_major_scan;
1149 static guint64 stat_optimized_major_scan_no_refs;
1151 static guint64 stat_drain_prefetch_fills;
1152 static guint64 stat_drain_prefetch_fill_failures;
1153 static guint64 stat_drain_loops;
1156 static void major_scan_object_with_evacuation (char *start, mword desc, SgenGrayQueue *queue);
1158 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1159 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1160 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1161 #include "sgen-marksweep-drain-gray-stack.h"
1163 #define COPY_OR_MARK_WITH_EVACUATION
1164 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1165 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1166 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1167 #include "sgen-marksweep-drain-gray-stack.h"
1170 drain_gray_stack (ScanCopyContext ctx)
1172 gboolean evacuation = FALSE;
1174 for (i = 0; i < num_block_obj_sizes; ++i) {
1175 if (evacuate_block_obj_sizes [i]) {
1182 return drain_gray_stack_with_evacuation (ctx);
1184 return drain_gray_stack_no_evacuation (ctx);
1187 #include "sgen-marksweep-scan-object-concurrent.h"
1190 major_copy_or_mark_object_canonical (void **ptr, SgenGrayQueue *queue)
1192 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1196 major_copy_or_mark_object_concurrent_canonical (void **ptr, SgenGrayQueue *queue)
1198 major_copy_or_mark_object_with_evacuation_concurrent (ptr, *ptr, queue);
1202 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1204 void **entry, **end;
1205 int last_index = -1;
1207 if (first_entry == last_entry)
1210 block->has_pinned = TRUE;
1212 entry = sgen_pinning_get_entry (first_entry);
1213 end = sgen_pinning_get_entry (last_entry);
1215 for (; entry < end; ++entry) {
1216 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1218 SGEN_ASSERT (9, index >= 0 && index < MS_BLOCK_FREE / block->obj_size, "invalid object %p index %d max-index %d", *entry, index, MS_BLOCK_FREE / block->obj_size);
1219 if (index == last_index)
1221 obj = MS_BLOCK_OBJ (block, index);
1222 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1228 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1232 for (obj_index = 0; obj_index < count; ++obj_index) {
1234 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1236 MS_CALC_MARK_BIT (word, bit, obj);
1237 if (MS_MARK_BIT (block, word, bit)) {
1238 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1240 /* an unmarked object */
1241 if (MS_OBJ_ALLOCED (obj, block)) {
1243 * FIXME: Merge consecutive
1244 * slots for lower reporting
1245 * overhead. Maybe memset
1246 * will also benefit?
1248 binary_protocol_empty (obj, obj_size);
1249 MONO_GC_MAJOR_SWEPT ((mword)obj, obj_size);
1250 memset (obj, 0, obj_size);
1252 *(void**)obj = block->free_list;
1253 block->free_list = obj;
1258 static inline gboolean
1259 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1261 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1262 gboolean success = old_state == expected_state;
1264 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1269 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1271 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1272 block->state = new_state;
1276 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1278 * Sweeping means iterating through the block's slots and building the free-list from the
1279 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1282 sweep_block (MSBlockInfo *block)
1285 void *reversed = NULL;
1288 switch (block->state) {
1289 case BLOCK_STATE_SWEPT:
1291 case BLOCK_STATE_MARKING:
1292 case BLOCK_STATE_CHECKING:
1293 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1295 case BLOCK_STATE_SWEEPING:
1296 /* FIXME: Do this more elegantly */
1299 case BLOCK_STATE_NEED_SWEEPING:
1300 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1304 SGEN_ASSERT (0, FALSE, "Illegal block state");
1307 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1309 count = MS_BLOCK_FREE / block->obj_size;
1311 block->free_list = NULL;
1313 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1314 // FIXME: Add more sizes
1315 switch (block->obj_size) {
1317 sweep_block_for_size (block, count, 16);
1320 sweep_block_for_size (block, count, block->obj_size);
1324 /* reset mark bits */
1325 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1327 /* Reverse free list so that it's in address order */
1329 while (block->free_list) {
1330 void *next = *(void**)block->free_list;
1331 *(void**)block->free_list = reversed;
1332 reversed = block->free_list;
1333 block->free_list = next;
1335 block->free_list = reversed;
1337 mono_memory_write_barrier ();
1339 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1350 if (sizeof (mword) == sizeof (unsigned long))
1351 count += __builtin_popcountl (d);
1353 count += __builtin_popcount (d);
1363 /* statistics for evacuation */
1364 static size_t *sweep_slots_available;
1365 static size_t *sweep_slots_used;
1366 static size_t *sweep_num_blocks;
1368 static volatile size_t num_major_sections_before_sweep;
1369 static volatile size_t num_major_sections_freed_in_sweep;
1376 for (i = 0; i < num_block_obj_sizes; ++i)
1377 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1379 /* clear all the free lists */
1380 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1381 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1383 for (j = 0; j < num_block_obj_sizes; ++j)
1384 free_blocks [j] = NULL;
1388 static void sweep_finish (void);
1391 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1392 * the checking has finished.
1394 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1395 * be correct, i.e. must not be used.
1398 ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked)
1401 gboolean have_live = FALSE;
1402 gboolean have_free = FALSE;
1409 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1412 *have_checked = FALSE;
1415 tagged_block = *(void * volatile *)&allocated_blocks.data [block_index];
1419 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1422 /* FIXME: do this more elegantly */
1427 if (SGEN_CAS_PTR (&allocated_blocks.data [block_index], BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1430 block = BLOCK_UNTAG (tagged_block);
1431 block_state = block->state;
1433 if (!sweep_in_progress ()) {
1434 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1436 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1439 switch (block_state) {
1440 case BLOCK_STATE_SWEPT:
1441 case BLOCK_STATE_NEED_SWEEPING:
1442 case BLOCK_STATE_SWEEPING:
1444 case BLOCK_STATE_MARKING:
1446 case BLOCK_STATE_CHECKING:
1447 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1450 SGEN_ASSERT (0, FALSE, "Illegal block state");
1454 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1455 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1458 *have_checked = TRUE;
1460 block->has_pinned = block->pinned;
1462 block->is_to_space = FALSE;
1464 count = MS_BLOCK_FREE / block->obj_size;
1466 if (block->cardtable_mod_union) {
1467 sgen_free_internal_dynamic (block->cardtable_mod_union, CARDS_PER_BLOCK, INTERNAL_MEM_CARDTABLE_MOD_UNION);
1468 block->cardtable_mod_union = NULL;
1471 /* Count marked objects in the block */
1472 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1473 nused += bitcount (block->mark_words [i]);
1481 int obj_size_index = block->obj_size_index;
1482 gboolean has_pinned = block->has_pinned;
1484 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1487 * FIXME: Go straight to SWEPT if there are no free slots. We need
1488 * to set the free slot list to NULL, though, and maybe update some
1492 sweep_block (block);
1495 ++sweep_num_blocks [obj_size_index];
1496 sweep_slots_used [obj_size_index] += nused;
1497 sweep_slots_available [obj_size_index] += count;
1501 * If there are free slots in the block, add
1502 * the block to the corresponding free list.
1505 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1508 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1510 add_free_block (free_blocks, obj_size_index, block);
1513 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1514 update_heap_boundaries_for_block (block);
1517 * Blocks without live objects are removed from the
1518 * block list and freed.
1520 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1521 SGEN_ASSERT (6, allocated_blocks.data [block_index] == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1523 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1524 ms_free_block (block);
1526 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1528 tagged_block = NULL;
1532 allocated_blocks.data [block_index] = tagged_block;
1533 return !!tagged_block;
1537 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1540 int num_blocks = num_major_sections_before_sweep;
1542 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1543 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1546 * We traverse the block array from high to low. Nursery collections will have to
1547 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1548 * low to high, to avoid constantly colliding on the same blocks.
1550 for (block_index = num_blocks - 1; block_index >= 0; --block_index) {
1551 gboolean have_checked;
1554 * The block might have been freed by another thread doing some checking
1557 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, &have_checked))
1558 ++num_major_sections_freed_in_sweep;
1561 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1563 * The main GC thread is currently iterating over the block array to help us
1564 * finish the sweep. We have already finished, but we don't want to mess up
1565 * that iteration, so we just wait for it.
1570 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1571 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1572 MSBlockInfo *block = BLOCK_UNTAG (allocated_blocks.data [block_index]);
1573 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1577 sgen_pointer_queue_remove_nulls (&allocated_blocks);
1587 mword total_evacuate_heap = 0;
1588 mword total_evacuate_saved = 0;
1591 for (i = 0; i < num_block_obj_sizes; ++i) {
1592 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1593 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1594 evacuate_block_obj_sizes [i] = TRUE;
1596 g_print ("slot size %d - %d of %d used\n",
1597 block_obj_sizes [i], slots_used [i], slots_available [i]);
1600 evacuate_block_obj_sizes [i] = FALSE;
1603 mword total_bytes = block_obj_sizes [i] * sweep_slots_available [i];
1604 total_evacuate_heap += total_bytes;
1605 if (evacuate_block_obj_sizes [i])
1606 total_evacuate_saved += total_bytes - block_obj_sizes [i] * sweep_slots_used [i];
1610 want_evacuation = (float)total_evacuate_saved / (float)total_evacuate_heap > (1 - concurrent_evacuation_threshold);
1612 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1618 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1622 SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1624 num_major_sections_before_sweep = num_major_sections;
1625 num_major_sections_freed_in_sweep = 0;
1627 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1628 if (concurrent_sweep) {
1629 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1630 sgen_thread_pool_job_enqueue (sweep_job);
1632 sweep_job_func (NULL, NULL);
1637 major_have_swept (void)
1639 return sweep_state == SWEEP_STATE_SWEPT;
1642 static int count_pinned_ref;
1643 static int count_pinned_nonref;
1644 static int count_nonpinned_ref;
1645 static int count_nonpinned_nonref;
1648 count_nonpinned_callback (char *obj, size_t size, void *data)
1650 MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1652 if (vtable->klass->has_references)
1653 ++count_nonpinned_ref;
1655 ++count_nonpinned_nonref;
1659 count_pinned_callback (char *obj, size_t size, void *data)
1661 MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1663 if (vtable->klass->has_references)
1666 ++count_pinned_nonref;
1669 static G_GNUC_UNUSED void
1670 count_ref_nonref_objs (void)
1674 count_pinned_ref = 0;
1675 count_pinned_nonref = 0;
1676 count_nonpinned_ref = 0;
1677 count_nonpinned_nonref = 0;
1679 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1680 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1682 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1684 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1685 count_pinned_ref, count_nonpinned_ref,
1686 count_pinned_nonref, count_nonpinned_nonref,
1687 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1691 ms_calculate_block_obj_sizes (double factor, int *arr)
1698 * Have every possible slot size starting with the minimal
1699 * object size up to and including four times that size. Then
1700 * proceed by increasing geometrically with the given factor.
1703 for (int size = sizeof (MonoObject); size <= 4 * sizeof (MonoObject); size += SGEN_ALLOC_ALIGN) {
1705 arr [num_sizes] = size;
1709 target_size = (double)last_size;
1712 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1713 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1715 if (size != last_size) {
1717 arr [num_sizes] = size;
1722 target_size *= factor;
1723 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1728 /* only valid during minor collections */
1729 static mword old_num_major_sections;
1732 major_start_nursery_collection (void)
1734 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1735 consistency_check ();
1738 old_num_major_sections = num_major_sections;
1742 major_finish_nursery_collection (void)
1744 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1745 consistency_check ();
1750 major_start_major_collection (void)
1755 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Major collection on unswept heap");
1758 * Clear the free lists for block sizes where we do evacuation. For those block
1759 * sizes we will have to allocate new blocks.
1761 for (i = 0; i < num_block_obj_sizes; ++i) {
1762 if (!evacuate_block_obj_sizes [i])
1765 free_block_lists [0][i] = NULL;
1766 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1770 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, TRUE);
1772 /* Sweep all unswept blocks and set them to MARKING */
1773 FOREACH_BLOCK_NO_LOCK (block) {
1775 sweep_block (block);
1776 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1777 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1778 } END_FOREACH_BLOCK_NO_LOCK;
1781 MONO_GC_SWEEP_END (GENERATION_OLD, TRUE);
1783 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1787 major_finish_major_collection (ScannedObjectCounts *counts)
1789 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1790 if (binary_protocol_is_enabled ()) {
1791 counts->num_scanned_objects = scanned_objects_list.next_slot;
1793 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1794 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1796 sgen_pointer_queue_clear (&scanned_objects_list);
1801 #if SIZEOF_VOID_P != 8
1803 compare_pointers (const void *va, const void *vb) {
1804 char *a = *(char**)va, *b = *(char**)vb;
1814 * This is called with sweep completed and the world stopped.
1817 major_free_swept_blocks (size_t allowance)
1819 /* FIXME: This is probably too much. It's assuming all objects are small. */
1820 size_t section_reserve = allowance / MS_BLOCK_SIZE;
1822 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1824 #if SIZEOF_VOID_P != 8
1826 int i, num_empty_blocks_orig, num_blocks, arr_length;
1828 void **empty_block_arr;
1829 void **rebuild_next;
1833 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1834 * a VirtualAlloc ()-ed block.
1839 if (num_empty_blocks <= section_reserve)
1841 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1843 num_empty_blocks_orig = num_empty_blocks;
1844 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1845 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1846 if (!empty_block_arr)
1850 for (block = empty_blocks; block; block = *(void**)block)
1851 empty_block_arr [i++] = block;
1852 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1854 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1857 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1858 * contiguous ones. If we do, we free them. If that's not enough to get to
1859 * section_reserve, we halve the number of contiguous blocks we're looking
1860 * for and have another go, until we're done with looking for pairs of
1861 * blocks, at which point we give up and go to the fallback.
1863 arr_length = num_empty_blocks_orig;
1864 num_blocks = MS_BLOCK_ALLOC_NUM;
1865 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1870 for (i = 0; i < arr_length; ++i) {
1872 void *block = empty_block_arr [i];
1873 SGEN_ASSERT (6, block, "we're not shifting correctly");
1875 empty_block_arr [dest] = block;
1877 * This is not strictly necessary, but we're
1880 empty_block_arr [i] = NULL;
1889 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
1891 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1896 if (d + 1 - first == num_blocks) {
1898 * We found num_blocks contiguous blocks. Free them
1899 * and null their array entries. As an optimization
1900 * we could, instead of nulling the entries, shift
1901 * the following entries over to the left, while
1905 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1906 for (j = first; j <= d; ++j)
1907 empty_block_arr [j] = NULL;
1911 num_empty_blocks -= num_blocks;
1913 stat_major_blocks_freed += num_blocks;
1914 if (num_blocks == MS_BLOCK_ALLOC_NUM)
1915 stat_major_blocks_freed_ideal += num_blocks;
1917 stat_major_blocks_freed_less_ideal += num_blocks;
1922 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
1924 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
1929 /* rebuild empty_blocks free list */
1930 rebuild_next = (void**)&empty_blocks;
1931 for (i = 0; i < arr_length; ++i) {
1932 void *block = empty_block_arr [i];
1933 SGEN_ASSERT (6, block, "we're missing blocks");
1934 *rebuild_next = block;
1935 rebuild_next = (void**)block;
1937 *rebuild_next = NULL;
1940 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1943 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1947 * This is our threshold. If there's not more empty than used blocks, we won't
1948 * release uncontiguous blocks, in fear of fragmenting the address space.
1950 if (num_empty_blocks <= num_major_sections)
1954 while (num_empty_blocks > section_reserve) {
1955 void *next = *(void**)empty_blocks;
1956 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
1957 empty_blocks = next;
1959 * Needs not be atomic because this is running
1964 ++stat_major_blocks_freed;
1965 #if SIZEOF_VOID_P != 8
1966 ++stat_major_blocks_freed_individual;
1972 major_pin_objects (SgenGrayQueue *queue)
1976 FOREACH_BLOCK_NO_LOCK (block) {
1977 size_t first_entry, last_entry;
1978 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
1979 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
1980 &first_entry, &last_entry);
1981 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
1982 } END_FOREACH_BLOCK_NO_LOCK;
1986 major_init_to_space (void)
1991 major_report_pinned_memory_usage (void)
1993 g_assert_not_reached ();
1997 major_get_used_size (void)
2003 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2004 * finished, then we can iterate over the block array.
2006 major_finish_sweep_checking ();
2008 FOREACH_BLOCK_NO_LOCK_CONDITION (TRUE, block) {
2009 int count = MS_BLOCK_FREE / block->obj_size;
2011 size += count * block->obj_size;
2012 for (iter = block->free_list; iter; iter = (void**)*iter)
2013 size -= block->obj_size;
2014 } END_FOREACH_BLOCK_NO_LOCK;
2019 /* FIXME: return number of bytes, not of sections */
2021 get_num_major_sections (void)
2023 return num_major_sections;
2027 * Returns the number of bytes in blocks that were present when the last sweep was
2028 * initiated, and were not freed during the sweep. They are the basis for calculating the
2032 get_bytes_survived_last_sweep (void)
2034 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2035 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2039 major_handle_gc_param (const char *opt)
2041 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2042 const char *arg = strchr (opt, '=') + 1;
2043 int percentage = atoi (arg);
2044 if (percentage < 0 || percentage > 100) {
2045 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2048 evacuation_threshold = (float)percentage / 100.0f;
2050 } else if (!strcmp (opt, "lazy-sweep")) {
2053 } else if (!strcmp (opt, "no-lazy-sweep")) {
2056 } else if (!strcmp (opt, "concurrent-sweep")) {
2057 concurrent_sweep = TRUE;
2059 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2060 concurrent_sweep = FALSE;
2068 major_print_gc_param_usage (void)
2072 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2073 " (no-)lazy-sweep\n"
2074 " (no-)concurrent-sweep\n"
2079 * This callback is used to clear cards, move cards to the shadow table and do counting.
2082 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2085 gboolean has_references;
2087 major_finish_sweep_checking ();
2088 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2090 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2091 } END_FOREACH_BLOCK_NO_LOCK;
2094 #ifdef HEAVY_STATISTICS
2095 extern guint64 marked_cards;
2096 extern guint64 scanned_cards;
2097 extern guint64 scanned_objects;
2098 extern guint64 remarked_cards;
2101 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2103 * MS blocks are 16K aligned.
2104 * Cardtables are 4K aligned, at least.
2105 * This means that the cardtable of a given block is 32 bytes aligned.
2108 initial_skip_card (guint8 *card_data)
2110 mword *cards = (mword*)card_data;
2113 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2119 if (i == CARD_WORDS_PER_BLOCK)
2120 return card_data + CARDS_PER_BLOCK;
2122 #if defined(__i386__) && defined(__GNUC__)
2123 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2124 #elif defined(__x86_64__) && defined(__GNUC__)
2125 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2126 #elif defined(__s390x__) && defined(__GNUC__)
2127 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2129 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2131 return &card_data [i];
2137 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2138 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2139 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2142 card_offset (char *obj, char *base)
2144 return (obj - base) >> CARD_BITS;
2148 scan_card_table_for_block (MSBlockInfo *block, gboolean mod_union, ScanObjectFunc scan_func, SgenGrayQueue *queue)
2150 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2151 guint8 cards_copy [CARDS_PER_BLOCK];
2153 gboolean small_objects;
2156 guint8 *card_data, *card_base;
2157 guint8 *card_data_end;
2158 char *scan_front = NULL;
2160 block_obj_size = block->obj_size;
2161 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2163 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2166 * This is safe in face of card aliasing for the following reason:
2168 * Major blocks are 16k aligned, or 32 cards aligned.
2169 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2170 * sizes, they won't overflow the cardtable overlap modulus.
2173 card_data = card_base = block->cardtable_mod_union;
2175 * This happens when the nursery collection that precedes finishing
2176 * the concurrent collection allocates new major blocks.
2181 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2182 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2184 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2186 card_data = card_base = cards_copy;
2189 card_data_end = card_data + CARDS_PER_BLOCK;
2191 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2193 card_data = initial_skip_card (card_data);
2194 while (card_data < card_data_end) {
2195 size_t card_index, first_object_index;
2198 char *first_obj, *obj;
2200 HEAVY_STAT (++scanned_cards);
2207 card_index = card_data - card_base;
2208 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2209 end = start + CARD_SIZE_IN_BYTES;
2211 if (!block_is_swept_or_marking (block))
2212 sweep_block (block);
2214 HEAVY_STAT (++marked_cards);
2217 sgen_card_table_prepare_card_for_scanning (card_data);
2220 * If the card we're looking at starts at or in the block header, we
2221 * must start at the first object in the block, without calculating
2222 * the index of the object we're hypothetically starting at, because
2223 * it would be negative.
2225 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2226 first_object_index = 0;
2228 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2230 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2232 binary_protocol_card_scan (first_obj, end - first_obj);
2235 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2239 /* FIXME: do this more efficiently */
2241 MS_CALC_MARK_BIT (w, b, obj);
2242 if (!MS_MARK_BIT (block, w, b))
2246 if (small_objects) {
2247 HEAVY_STAT (++scanned_objects);
2248 scan_func (obj, sgen_obj_get_descriptor (obj), queue);
2250 size_t offset = card_offset (obj, block_start);
2251 sgen_cardtable_scan_object (obj, block_obj_size, card_base + offset, mod_union, queue);
2254 obj += block_obj_size;
2255 g_assert (scan_front <= obj);
2259 HEAVY_STAT (if (*card_data) ++remarked_cards);
2264 card_data = card_base + card_offset (obj, block_start);
2269 major_scan_card_table (gboolean mod_union, SgenGrayQueue *queue)
2271 ScanObjectFunc scan_func = sgen_get_current_object_ops ()->scan_object;
2273 gboolean has_references;
2275 if (!concurrent_mark)
2276 g_assert (!mod_union);
2278 major_finish_sweep_checking ();
2279 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2280 #ifdef PREFETCH_CARDS
2281 int prefetch_index = __index + 6;
2282 if (prefetch_index < allocated_blocks.next_slot) {
2283 MSBlockInfo *prefetch_block = BLOCK_UNTAG (allocated_blocks.data [prefetch_index]);
2284 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2285 PREFETCH_READ (prefetch_block);
2286 PREFETCH_WRITE (prefetch_cards);
2287 PREFETCH_WRITE (prefetch_cards + 32);
2291 if (!has_references)
2294 scan_card_table_for_block (block, mod_union, scan_func, queue);
2295 } END_FOREACH_BLOCK_NO_LOCK;
2299 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2302 gboolean has_references;
2303 long long total_cards = 0;
2304 long long marked_cards = 0;
2306 if (sweep_in_progress ()) {
2307 *num_total_cards = -1;
2308 *num_marked_cards = -1;
2312 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2313 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2316 if (!has_references)
2319 total_cards += CARDS_PER_BLOCK;
2320 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2324 } END_FOREACH_BLOCK_NO_LOCK;
2326 *num_total_cards = total_cards;
2327 *num_marked_cards = marked_cards;
2331 update_cardtable_mod_union (void)
2335 FOREACH_BLOCK_NO_LOCK (block) {
2338 block->cardtable_mod_union = sgen_card_table_update_mod_union (block->cardtable_mod_union,
2339 MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2341 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2342 } END_FOREACH_BLOCK_NO_LOCK;
2346 major_get_cardtable_mod_union_for_object (char *obj)
2348 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
2349 size_t offset = card_offset (obj, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
2350 return &block->cardtable_mod_union [offset];
2353 #undef pthread_create
2356 post_param_init (SgenMajorCollector *collector)
2358 collector->sweeps_lazily = lazy_sweep;
2359 collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2363 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2367 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2369 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2370 block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2371 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2373 evacuate_block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2374 for (i = 0; i < num_block_obj_sizes; ++i)
2375 evacuate_block_obj_sizes [i] = FALSE;
2377 sweep_slots_available = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2378 sweep_slots_used = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2379 sweep_num_blocks = sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2384 g_print ("block object sizes:\n");
2385 for (i = 0; i < num_block_obj_sizes; ++i)
2386 g_print ("%d\n", block_obj_sizes [i]);
2390 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2391 free_block_lists [i] = sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2393 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2394 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2395 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2396 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2398 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2399 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2400 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2401 mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_objects_evacuated);
2402 #if SIZEOF_VOID_P != 8
2403 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2404 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2405 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2406 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2409 collector->section_size = MAJOR_SECTION_SIZE;
2411 concurrent_mark = is_concurrent;
2412 collector->is_concurrent = is_concurrent;
2413 collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2415 collector->want_synchronous_collection = &want_evacuation;
2417 collector->want_synchronous_collection = NULL;
2418 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2419 collector->supports_cardtable = TRUE;
2421 collector->alloc_heap = major_alloc_heap;
2422 collector->is_object_live = major_is_object_live;
2423 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2424 collector->alloc_degraded = major_alloc_degraded;
2426 collector->alloc_object = major_alloc_object;
2427 collector->free_pinned_object = free_pinned_object;
2428 collector->iterate_objects = major_iterate_objects;
2429 collector->free_non_pinned_object = major_free_non_pinned_object;
2430 collector->pin_objects = major_pin_objects;
2431 collector->pin_major_object = pin_major_object;
2432 collector->scan_card_table = major_scan_card_table;
2433 collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2434 if (is_concurrent) {
2435 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2436 collector->get_cardtable_mod_union_for_object = major_get_cardtable_mod_union_for_object;
2438 collector->init_to_space = major_init_to_space;
2439 collector->sweep = major_sweep;
2440 collector->have_swept = major_have_swept;
2441 collector->finish_sweeping = major_finish_sweep_checking;
2442 collector->free_swept_blocks = major_free_swept_blocks;
2443 collector->check_scan_starts = major_check_scan_starts;
2444 collector->dump_heap = major_dump_heap;
2445 collector->get_used_size = major_get_used_size;
2446 collector->start_nursery_collection = major_start_nursery_collection;
2447 collector->finish_nursery_collection = major_finish_nursery_collection;
2448 collector->start_major_collection = major_start_major_collection;
2449 collector->finish_major_collection = major_finish_major_collection;
2450 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2451 collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2452 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2453 collector->get_num_major_sections = get_num_major_sections;
2454 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2455 collector->handle_gc_param = major_handle_gc_param;
2456 collector->print_gc_param_usage = major_print_gc_param_usage;
2457 collector->post_param_init = post_param_init;
2458 collector->is_valid_object = major_is_valid_object;
2459 collector->describe_pointer = major_describe_pointer;
2460 collector->count_cards = major_count_cards;
2462 collector->major_ops.copy_or_mark_object = major_copy_or_mark_object_canonical;
2463 collector->major_ops.scan_object = major_scan_object_with_evacuation;
2464 if (is_concurrent) {
2465 collector->major_concurrent_ops.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2466 collector->major_concurrent_ops.scan_object = major_scan_object_no_mark_concurrent;
2467 collector->major_concurrent_ops.scan_vtype = major_scan_vtype_concurrent;
2470 #if !defined (FIXED_HEAP) && !defined (SGEN_PARALLEL_MARK)
2472 collector->drain_gray_stack = drain_gray_stack;
2474 #ifdef HEAVY_STATISTICS
2475 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2476 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2477 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2478 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2479 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2480 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2481 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2482 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2483 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2484 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2486 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2487 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2488 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2492 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2493 mono_mutex_init (&scanned_objects_list_lock);
2496 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2498 /*cardtable requires major pages to be 8 cards aligned*/
2499 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2503 sgen_marksweep_init (SgenMajorCollector *collector)
2505 sgen_marksweep_init_internal (collector, FALSE);
2509 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2511 sgen_marksweep_init_internal (collector, TRUE);