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"
47 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
48 #define MS_BLOCK_SIZE ARCH_MIN_MS_BLOCK_SIZE
49 #define MS_BLOCK_SIZE_SHIFT ARCH_MIN_MS_BLOCK_SIZE_SHIFT
51 #define MS_BLOCK_SIZE_SHIFT 14 /* INT FASTENABLE */
52 #define MS_BLOCK_SIZE (1 << MS_BLOCK_SIZE_SHIFT)
54 #define MAJOR_SECTION_SIZE MS_BLOCK_SIZE
55 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
58 * Don't allocate single blocks, but alloc a contingent of this many
59 * blocks in one swoop. This must be a power of two.
61 #define MS_BLOCK_ALLOC_NUM 32
64 * Number of bytes before the first object in a block. At the start
65 * of a block is the MSBlockHeader, then opional padding, then come
66 * the objects, so this must be >= sizeof (MSBlockHeader).
68 #define MS_BLOCK_SKIP ((sizeof (MSBlockHeader) + 15) & ~15)
70 #define MS_BLOCK_FREE (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
72 #define MS_NUM_MARK_WORDS ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
74 typedef struct _MSBlockInfo MSBlockInfo;
78 * FIXME: Do we even need this? It's only used during sweep and might be worth
79 * recalculating to save the space.
81 guint16 obj_size_index;
82 unsigned int pinned : 1;
83 unsigned int has_references : 1;
84 unsigned int has_pinned : 1; /* means cannot evacuate */
85 unsigned int is_to_space : 1;
86 unsigned int swept : 1;
87 void ** volatile free_list;
88 MSBlockInfo * volatile next_free;
89 guint8 *cardtable_mod_union;
90 mword mark_words [MS_NUM_MARK_WORDS];
93 #define MS_BLOCK_FOR_BLOCK_INFO(b) ((char*)(b))
95 #define MS_BLOCK_OBJ(b,i) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i))
96 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
97 #define MS_BLOCK_DATA_FOR_OBJ(o) ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
103 #define MS_BLOCK_FOR_OBJ(o) (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
105 /* object index will always be small */
106 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
108 //casting to int is fine since blocks are 32k
109 #define MS_CALC_MARK_BIT(w,b,o) do { \
110 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
111 if (sizeof (mword) == 4) { \
120 #define MS_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] & (ONE_P << (b)))
121 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
123 #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))
125 #define MS_BLOCK_OBJ_SIZE_FACTOR (pow (2.0, 1.0 / 3))
128 * This way we can lookup block object size indexes for sizes up to
129 * 256 bytes with a single load.
131 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES 32
133 static int *block_obj_sizes;
134 static int num_block_obj_sizes;
135 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
137 #define MS_BLOCK_FLAG_PINNED 1
138 #define MS_BLOCK_FLAG_REFS 2
140 #define MS_BLOCK_TYPE_MAX 4
142 static gboolean *evacuate_block_obj_sizes;
143 static float evacuation_threshold = 0.666f;
144 static float concurrent_evacuation_threshold = 0.666f;
145 static gboolean want_evacuation = FALSE;
147 static gboolean lazy_sweep = TRUE;
148 static gboolean have_swept = TRUE;
150 static gboolean concurrent_mark;
152 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
153 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
154 #define BLOCK_UNTAG_HAS_REFERENCES(bl) SGEN_POINTER_UNTAG_1 ((bl))
156 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
158 /* all allocated blocks in the system */
159 static SgenPointerQueue allocated_blocks;
161 /* non-allocated block free-list */
162 static void *empty_blocks = NULL;
163 static size_t num_empty_blocks = 0;
165 #define FOREACH_BLOCK(bl) { size_t __index; for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { (bl) = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [__index]);
166 #define FOREACH_BLOCK_HAS_REFERENCES(bl,hr) { size_t __index; for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { (bl) = allocated_blocks.data [__index]; (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); (bl) = BLOCK_UNTAG_HAS_REFERENCES ((bl));
167 #define END_FOREACH_BLOCK } }
168 #define DELETE_BLOCK_IN_FOREACH() (allocated_blocks.data [__index] = NULL)
170 static size_t num_major_sections = 0;
171 /* one free block list for each block object size */
172 static MSBlockInfo **free_block_lists [MS_BLOCK_TYPE_MAX];
174 static guint64 stat_major_blocks_alloced = 0;
175 static guint64 stat_major_blocks_freed = 0;
176 static guint64 stat_major_blocks_lazy_swept = 0;
177 static guint64 stat_major_objects_evacuated = 0;
179 #if SIZEOF_VOID_P != 8
180 static guint64 stat_major_blocks_freed_ideal = 0;
181 static guint64 stat_major_blocks_freed_less_ideal = 0;
182 static guint64 stat_major_blocks_freed_individual = 0;
183 static guint64 stat_major_blocks_alloced_less_ideal = 0;
186 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
187 static guint64 num_major_objects_marked = 0;
188 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
190 #define INC_NUM_MAJOR_OBJECTS_MARKED()
193 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
194 static mono_mutex_t scanned_objects_list_lock;
195 static SgenPointerQueue scanned_objects_list;
198 add_scanned_object (void *ptr)
200 if (!binary_protocol_is_enabled ())
203 mono_mutex_lock (&scanned_objects_list_lock);
204 sgen_pointer_queue_add (&scanned_objects_list, ptr);
205 mono_mutex_unlock (&scanned_objects_list_lock);
210 sweep_block (MSBlockInfo *block, gboolean during_major_collection);
213 ms_find_block_obj_size_index (size_t size)
216 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);
217 for (i = 0; i < num_block_obj_sizes; ++i)
218 if (block_obj_sizes [i] >= size)
220 g_error ("no object of size %d\n", size);
223 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
224 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
226 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
227 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
228 fast_block_obj_size_indexes [((s)+7)>>3] : \
229 ms_find_block_obj_size_index ((s)))
232 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
236 start = sgen_alloc_os_memory_aligned (nursery_size, nursery_align, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
238 start = sgen_alloc_os_memory (nursery_size, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE, "nursery");
244 update_heap_boundaries_for_block (MSBlockInfo *block)
246 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
250 ms_get_empty_block (void)
254 void *block, *empty, *next;
259 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
260 * unsuccessful, we halve the number of blocks and try again, until we're at
261 * 1. If that doesn't work, either, we assert.
263 int alloc_num = MS_BLOCK_ALLOC_NUM;
265 p = sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE,
266 alloc_num == 1 ? "major heap section" : NULL);
272 for (i = 0; i < alloc_num; ++i) {
275 * We do the free list update one after the
276 * other so that other threads can use the new
277 * blocks as quickly as possible.
280 empty = empty_blocks;
281 *(void**)block = empty;
282 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
286 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
288 stat_major_blocks_alloced += alloc_num;
289 #if SIZEOF_VOID_P != 8
290 if (alloc_num != MS_BLOCK_ALLOC_NUM)
291 stat_major_blocks_alloced_less_ideal += alloc_num;
296 empty = empty_blocks;
300 next = *(void**)block;
301 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
303 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
305 *(void**)block = NULL;
307 g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
313 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
314 * list, where it will either be freed later on, or reused in nursery collections.
317 ms_free_block (void *block)
321 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
322 memset (block, 0, MS_BLOCK_SIZE);
325 empty = empty_blocks;
326 *(void**)block = empty;
327 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
329 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
332 //#define MARKSWEEP_CONSISTENCY_CHECK
334 #ifdef MARKSWEEP_CONSISTENCY_CHECK
336 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
340 for (; block; block = block->next_free) {
341 g_assert (block->obj_size == size);
342 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
344 /* blocks in the free lists must have at least
347 g_assert (block->free_list);
349 /* the block must be in the allocated_blocks array */
350 g_assert (sgen_pointer_queue_find (&allocated_blocks, BLOCK_TAG (block)) != (size_t)-1);
355 check_empty_blocks (void)
359 for (p = empty_blocks; p; p = *(void**)p)
361 g_assert (i == num_empty_blocks);
365 consistency_check (void)
370 /* check all blocks */
371 FOREACH_BLOCK (block) {
372 int count = MS_BLOCK_FREE / block->obj_size;
376 /* check block header */
377 g_assert (((MSBlockHeader*)block->block)->info == block);
379 /* count number of free slots */
380 for (i = 0; i < count; ++i) {
381 void **obj = (void**) MS_BLOCK_OBJ (block, i);
382 if (!MS_OBJ_ALLOCED (obj, block))
386 /* check free list */
387 for (free = block->free_list; free; free = (void**)*free) {
388 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
391 g_assert (num_free == 0);
393 /* check all mark words are zero */
395 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
396 g_assert (block->mark_words [i] == 0);
400 /* check free blocks */
401 for (i = 0; i < num_block_obj_sizes; ++i) {
403 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
404 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
407 check_empty_blocks ();
412 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
414 int size = block_obj_sizes [size_index];
415 int count = MS_BLOCK_FREE / size;
417 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
421 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
424 info = (MSBlockInfo*)ms_get_empty_block ();
426 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
428 info->obj_size = size;
429 info->obj_size_index = size_index;
430 info->pinned = pinned;
431 info->has_references = has_references;
432 info->has_pinned = pinned;
434 * Blocks that are to-space are not evacuated from. During an major collection
435 * blocks are allocated for two reasons: evacuating objects from the nursery and
436 * evacuating them from major blocks marked for evacuation. In both cases we don't
437 * want further evacuation.
439 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD);
441 info->cardtable_mod_union = NULL;
443 update_heap_boundaries_for_block (info);
445 /* build free list */
446 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
447 info->free_list = (void**)obj_start;
448 /* we're skipping the last one - it must be nulled */
449 for (i = 0; i < count - 1; ++i) {
450 char *next_obj_start = obj_start + size;
451 *(void**)obj_start = next_obj_start;
452 obj_start = next_obj_start;
455 *(void**)obj_start = NULL;
457 info->next_free = free_blocks [size_index];
458 free_blocks [size_index] = info;
460 sgen_pointer_queue_add (&allocated_blocks, BLOCK_TAG (info));
462 ++num_major_sections;
467 obj_is_from_pinned_alloc (char *ptr)
471 FOREACH_BLOCK (block) {
472 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
473 return block->pinned;
479 unlink_slot_from_free_list_uncontested (MSBlockInfo **free_blocks, int size_index)
484 block = free_blocks [size_index];
485 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
487 if (G_UNLIKELY (!block->swept)) {
488 stat_major_blocks_lazy_swept ++;
489 sweep_block (block, FALSE);
492 obj = block->free_list;
493 SGEN_ASSERT (9, obj, "block %p in free list had no available object to alloc from", block);
495 block->free_list = *(void**)obj;
496 if (!block->free_list) {
497 free_blocks [size_index] = block->next_free;
498 block->next_free = NULL;
505 alloc_obj (MonoVTable *vtable, size_t size, gboolean pinned, gboolean has_references)
507 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
508 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
511 if (!free_blocks [size_index]) {
512 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
516 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
518 *(MonoVTable**)obj = vtable;
524 major_alloc_object (MonoVTable *vtable, size_t size, gboolean has_references)
526 return alloc_obj (vtable, size, FALSE, has_references);
530 * We're not freeing the block if it's empty. We leave that work for
531 * the next major collection.
533 * This is just called from the domain clearing code, which runs in a
534 * single thread and has the GC lock, so we don't need an extra lock.
537 free_object (char *obj, size_t size, gboolean pinned)
539 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
543 sweep_block (block, FALSE);
544 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);
545 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p is already free", obj);
546 MS_CALC_MARK_BIT (word, bit, obj);
547 SGEN_ASSERT (9, !MS_MARK_BIT (block, word, bit), "object %p has mark bit set");
548 if (!block->free_list) {
549 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, block->has_references);
550 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
551 SGEN_ASSERT (9, !block->next_free, "block %p doesn't have a free-list of object but belongs to a free-list of blocks");
552 block->next_free = free_blocks [size_index];
553 free_blocks [size_index] = block;
555 memset (obj, 0, size);
556 *(void**)obj = block->free_list;
557 block->free_list = (void**)obj;
561 major_free_non_pinned_object (char *obj, size_t size)
563 free_object (obj, size, FALSE);
566 /* size is a multiple of SGEN_ALLOC_ALIGN */
568 major_alloc_small_pinned_obj (MonoVTable *vtable, size_t size, gboolean has_references)
572 res = alloc_obj (vtable, size, TRUE, has_references);
573 /*If we failed to alloc memory, we better try releasing memory
574 *as pinned alloc is requested by the runtime.
577 sgen_perform_collection (0, GENERATION_OLD, "pinned alloc failure", TRUE);
578 res = alloc_obj (vtable, size, TRUE, has_references);
584 free_pinned_object (char *obj, size_t size)
586 free_object (obj, size, TRUE);
590 * size is already rounded up and we hold the GC lock.
593 major_alloc_degraded (MonoVTable *vtable, size_t size)
596 size_t old_num_sections;
598 old_num_sections = num_major_sections;
600 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
601 if (G_LIKELY (obj)) {
602 HEAVY_STAT (++stat_objects_alloced_degraded);
603 HEAVY_STAT (stat_bytes_alloced_degraded += size);
604 g_assert (num_major_sections >= old_num_sections);
605 sgen_register_major_sections_alloced (num_major_sections - old_num_sections);
611 * obj is some object. If it's not in the major heap (i.e. if it's in
612 * the nursery or LOS), return FALSE. Otherwise return whether it's
613 * been marked or copied.
616 major_is_object_live (char *obj)
622 if (sgen_ptr_in_nursery (obj))
625 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
628 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
631 /* now we know it's in a major block */
632 block = MS_BLOCK_FOR_OBJ (obj);
633 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?");
634 MS_CALC_MARK_BIT (word, bit, obj);
635 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
639 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
643 FOREACH_BLOCK (block) {
644 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
645 int count = MS_BLOCK_FREE / block->obj_size;
649 for (i = 0; i <= count; ++i) {
650 if (ptr >= MS_BLOCK_OBJ (block, i) && ptr < MS_BLOCK_OBJ (block, i + 1)) {
651 *start = MS_BLOCK_OBJ (block, i);
655 return !block->pinned;
662 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
664 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
665 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
666 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
669 FOREACH_BLOCK (block) {
670 int count = MS_BLOCK_FREE / block->obj_size;
673 if (block->pinned && !pinned)
675 if (!block->pinned && !non_pinned)
677 if (sweep && lazy_sweep) {
678 sweep_block (block, FALSE);
679 SGEN_ASSERT (0, block->swept, "Block must be swept after sweeping");
682 for (i = 0; i < count; ++i) {
683 void **obj = (void**) MS_BLOCK_OBJ (block, i);
686 MS_CALC_MARK_BIT (word, bit, obj);
687 if (!MS_MARK_BIT (block, word, bit))
690 if (MS_OBJ_ALLOCED (obj, block))
691 callback ((char*)obj, block->obj_size, data);
697 major_is_valid_object (char *object)
701 FOREACH_BLOCK (block) {
705 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
708 idx = MS_BLOCK_OBJ_INDEX (object, block);
709 obj = (char*)MS_BLOCK_OBJ (block, idx);
712 return MS_OBJ_ALLOCED (obj, block);
720 major_describe_pointer (char *ptr)
724 FOREACH_BLOCK (block) {
732 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
735 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
736 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
738 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
739 obj = (char*)MS_BLOCK_OBJ (block, idx);
740 live = MS_OBJ_ALLOCED (obj, block);
741 vtable = live ? (MonoVTable*)SGEN_LOAD_VTABLE (obj) : NULL;
743 MS_CALC_MARK_BIT (w, b, obj);
744 marked = MS_MARK_BIT (block, w, b);
749 SGEN_LOG (0, "object");
751 SGEN_LOG (0, "dead-object");
754 SGEN_LOG (0, "interior-ptr offset %td", ptr - obj);
756 SGEN_LOG (0, "dead-interior-ptr offset %td", ptr - obj);
759 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
768 major_check_scan_starts (void)
773 major_dump_heap (FILE *heap_dump_file)
776 int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
777 int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
780 for (i = 0; i < num_block_obj_sizes; ++i)
781 slots_available [i] = slots_used [i] = 0;
783 FOREACH_BLOCK (block) {
784 int index = ms_find_block_obj_size_index (block->obj_size);
785 int count = MS_BLOCK_FREE / block->obj_size;
787 slots_available [index] += count;
788 for (i = 0; i < count; ++i) {
789 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
790 ++slots_used [index];
794 fprintf (heap_dump_file, "<occupancies>\n");
795 for (i = 0; i < num_block_obj_sizes; ++i) {
796 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
797 block_obj_sizes [i], slots_available [i], slots_used [i]);
799 fprintf (heap_dump_file, "</occupancies>\n");
801 FOREACH_BLOCK (block) {
802 int count = MS_BLOCK_FREE / block->obj_size;
806 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
808 for (i = 0; i <= count; ++i) {
809 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
814 sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
820 fprintf (heap_dump_file, "</section>\n");
824 #define LOAD_VTABLE SGEN_LOAD_VTABLE
826 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do { \
828 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
829 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
830 MS_SET_MARK_BIT ((block), __word, __bit); \
831 if (sgen_gc_descr_has_references (desc)) \
832 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
833 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
834 INC_NUM_MAJOR_OBJECTS_MARKED (); \
837 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
839 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
840 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
841 if (!MS_MARK_BIT ((block), __word, __bit)) { \
842 MS_SET_MARK_BIT ((block), __word, __bit); \
843 if (sgen_gc_descr_has_references (desc)) \
844 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
845 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((MonoObject*)(obj))); \
846 INC_NUM_MAJOR_OBJECTS_MARKED (); \
851 pin_major_object (char *obj, SgenGrayQueue *queue)
856 g_assert_not_reached ();
858 block = MS_BLOCK_FOR_OBJ (obj);
859 block->has_pinned = TRUE;
860 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
863 #include "sgen-major-copy-object.h"
866 major_copy_or_mark_object_with_evacuation_concurrent (void **ptr, void *obj, SgenGrayQueue *queue)
868 SGEN_ASSERT (9, sgen_concurrent_collection_in_progress (), "Why are we scanning concurrently when there's no concurrent collection on?");
869 SGEN_ASSERT (9, !sgen_workers_are_working () || sgen_is_worker_thread (mono_native_thread_id_get ()), "We must not scan from two threads at the same time!");
871 g_assert (!SGEN_OBJECT_IS_FORWARDED (obj));
873 if (!sgen_ptr_in_nursery (obj)) {
876 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)obj));
878 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE) {
879 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
880 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
882 if (sgen_los_object_is_pinned (obj))
886 if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
887 MonoVTable *vt = (MonoVTable*)SGEN_LOAD_VTABLE (obj);
888 MONO_GC_OBJ_PINNED ((mword)obj, sgen_safe_object_get_size (obj), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
892 sgen_los_pin_object (obj);
893 if (SGEN_OBJECT_HAS_REFERENCES (obj))
894 GRAY_OBJECT_ENQUEUE (queue, obj, sgen_obj_get_descriptor (obj));
895 INC_NUM_MAJOR_OBJECTS_MARKED ();
901 major_get_and_reset_num_major_objects_marked (void)
903 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
904 long long num = num_major_objects_marked;
905 num_major_objects_marked = 0;
912 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
914 #undef PREFETCH_CARDS
917 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
918 #if defined(PLATFORM_MACOSX)
919 #define GCC_VERSION (__GNUC__ * 10000 \
920 + __GNUC_MINOR__ * 100 \
921 + __GNUC_PATCHLEVEL__)
922 #if GCC_VERSION <= 40300
923 #undef PREFETCH_CARDS
927 #ifdef HEAVY_STATISTICS
928 static guint64 stat_optimized_copy;
929 static guint64 stat_optimized_copy_nursery;
930 static guint64 stat_optimized_copy_nursery_forwarded;
931 static guint64 stat_optimized_copy_nursery_pinned;
932 static guint64 stat_optimized_copy_major;
933 static guint64 stat_optimized_copy_major_small_fast;
934 static guint64 stat_optimized_copy_major_small_slow;
935 static guint64 stat_optimized_copy_major_large;
936 static guint64 stat_optimized_copy_major_forwarded;
937 static guint64 stat_optimized_copy_major_small_evacuate;
938 static guint64 stat_optimized_major_scan;
939 static guint64 stat_optimized_major_scan_no_refs;
941 static guint64 stat_drain_prefetch_fills;
942 static guint64 stat_drain_prefetch_fill_failures;
943 static guint64 stat_drain_loops;
946 static void major_scan_object_with_evacuation (char *start, mword desc, SgenGrayQueue *queue);
948 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
949 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
950 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
951 #include "sgen-marksweep-drain-gray-stack.h"
953 #define COPY_OR_MARK_WITH_EVACUATION
954 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
955 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
956 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
957 #include "sgen-marksweep-drain-gray-stack.h"
960 drain_gray_stack (ScanCopyContext ctx)
962 gboolean evacuation = FALSE;
964 for (i = 0; i < num_block_obj_sizes; ++i) {
965 if (evacuate_block_obj_sizes [i]) {
972 return drain_gray_stack_with_evacuation (ctx);
974 return drain_gray_stack_no_evacuation (ctx);
977 #include "sgen-marksweep-scan-object-concurrent.h"
980 major_copy_or_mark_object_canonical (void **ptr, SgenGrayQueue *queue)
982 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
986 major_copy_or_mark_object_concurrent_canonical (void **ptr, SgenGrayQueue *queue)
988 major_copy_or_mark_object_with_evacuation_concurrent (ptr, *ptr, queue);
992 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
997 if (first_entry == last_entry)
1000 block->has_pinned = TRUE;
1002 entry = sgen_pinning_get_entry (first_entry);
1003 end = sgen_pinning_get_entry (last_entry);
1005 for (; entry < end; ++entry) {
1006 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1008 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);
1009 if (index == last_index)
1011 obj = MS_BLOCK_OBJ (block, index);
1012 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1018 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1022 for (obj_index = 0; obj_index < count; ++obj_index) {
1024 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1026 MS_CALC_MARK_BIT (word, bit, obj);
1027 if (MS_MARK_BIT (block, word, bit)) {
1028 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1030 /* an unmarked object */
1031 if (MS_OBJ_ALLOCED (obj, block)) {
1033 * FIXME: Merge consecutive
1034 * slots for lower reporting
1035 * overhead. Maybe memset
1036 * will also benefit?
1038 binary_protocol_empty (obj, obj_size);
1039 MONO_GC_MAJOR_SWEPT ((mword)obj, obj_size);
1040 memset (obj, 0, obj_size);
1042 *(void**)obj = block->free_list;
1043 block->free_list = obj;
1051 * Traverse BLOCK, freeing and zeroing unused objects.
1054 sweep_block (MSBlockInfo *block, gboolean during_major_collection)
1057 void *reversed = NULL;
1059 if (!during_major_collection)
1060 g_assert (!sgen_concurrent_collection_in_progress ());
1065 count = MS_BLOCK_FREE / block->obj_size;
1067 block->free_list = NULL;
1069 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1070 // FIXME: Add more sizes
1071 switch (block->obj_size) {
1073 sweep_block_for_size (block, count, 16);
1076 sweep_block_for_size (block, count, block->obj_size);
1080 /* reset mark bits */
1081 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1083 /* Reverse free list so that it's in address order */
1085 while (block->free_list) {
1086 void *next = *(void**)block->free_list;
1087 *(void**)block->free_list = reversed;
1088 reversed = block->free_list;
1089 block->free_list = next;
1091 block->free_list = reversed;
1102 if (sizeof (mword) == sizeof (unsigned long))
1103 count += __builtin_popcountl (d);
1105 count += __builtin_popcount (d);
1121 /* statistics for evacuation */
1122 int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1123 int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1124 int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1126 mword total_evacuate_heap = 0;
1127 mword total_evacuate_saved = 0;
1129 for (i = 0; i < num_block_obj_sizes; ++i)
1130 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1132 /* clear all the free lists */
1133 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1134 MSBlockInfo **free_blocks = free_block_lists [i];
1136 for (j = 0; j < num_block_obj_sizes; ++j)
1137 free_blocks [j] = NULL;
1140 /* traverse all blocks, free and zero unmarked objects */
1141 FOREACH_BLOCK (block) {
1143 gboolean have_live = FALSE;
1144 gboolean has_pinned;
1145 gboolean have_free = FALSE;
1149 obj_size_index = block->obj_size_index;
1151 has_pinned = block->has_pinned;
1152 block->has_pinned = block->pinned;
1154 block->is_to_space = FALSE;
1157 count = MS_BLOCK_FREE / block->obj_size;
1159 if (block->cardtable_mod_union) {
1160 sgen_free_internal_dynamic (block->cardtable_mod_union, CARDS_PER_BLOCK, INTERNAL_MEM_CARDTABLE_MOD_UNION);
1161 block->cardtable_mod_union = NULL;
1164 /* Count marked objects in the block */
1165 for (i = 0; i < MS_NUM_MARK_WORDS; ++i) {
1166 nused += bitcount (block->mark_words [i]);
1175 sweep_block (block, TRUE);
1179 ++num_blocks [obj_size_index];
1180 slots_used [obj_size_index] += nused;
1181 slots_available [obj_size_index] += count;
1185 * If there are free slots in the block, add
1186 * the block to the corresponding free list.
1189 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1190 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1191 block->next_free = free_blocks [index];
1192 free_blocks [index] = block;
1195 update_heap_boundaries_for_block (block);
1198 * Blocks without live objects are removed from the
1199 * block list and freed.
1201 DELETE_BLOCK_IN_FOREACH ();
1203 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1204 ms_free_block (block);
1206 --num_major_sections;
1208 } END_FOREACH_BLOCK;
1209 sgen_pointer_queue_remove_nulls (&allocated_blocks);
1211 for (i = 0; i < num_block_obj_sizes; ++i) {
1212 float usage = (float)slots_used [i] / (float)slots_available [i];
1213 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1214 evacuate_block_obj_sizes [i] = TRUE;
1216 g_print ("slot size %d - %d of %d used\n",
1217 block_obj_sizes [i], slots_used [i], slots_available [i]);
1220 evacuate_block_obj_sizes [i] = FALSE;
1223 mword total_bytes = block_obj_sizes [i] * slots_available [i];
1224 total_evacuate_heap += total_bytes;
1225 if (evacuate_block_obj_sizes [i])
1226 total_evacuate_saved += total_bytes - block_obj_sizes [i] * slots_used [i];
1230 want_evacuation = (float)total_evacuate_saved / (float)total_evacuate_heap > (1 - concurrent_evacuation_threshold);
1236 major_have_finished_sweeping (void)
1241 static int count_pinned_ref;
1242 static int count_pinned_nonref;
1243 static int count_nonpinned_ref;
1244 static int count_nonpinned_nonref;
1247 count_nonpinned_callback (char *obj, size_t size, void *data)
1249 MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1251 if (vtable->klass->has_references)
1252 ++count_nonpinned_ref;
1254 ++count_nonpinned_nonref;
1258 count_pinned_callback (char *obj, size_t size, void *data)
1260 MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1262 if (vtable->klass->has_references)
1265 ++count_pinned_nonref;
1268 static G_GNUC_UNUSED void
1269 count_ref_nonref_objs (void)
1273 count_pinned_ref = 0;
1274 count_pinned_nonref = 0;
1275 count_nonpinned_ref = 0;
1276 count_nonpinned_nonref = 0;
1278 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1279 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1281 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1283 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1284 count_pinned_ref, count_nonpinned_ref,
1285 count_pinned_nonref, count_nonpinned_nonref,
1286 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1290 ms_calculate_block_obj_sizes (double factor, int *arr)
1297 * Have every possible slot size starting with the minimal
1298 * object size up to and including four times that size. Then
1299 * proceed by increasing geometrically with the given factor.
1302 for (int size = sizeof (MonoObject); size <= 4 * sizeof (MonoObject); size += SGEN_ALLOC_ALIGN) {
1304 arr [num_sizes] = size;
1308 target_size = (double)last_size;
1311 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1312 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1314 if (size != last_size) {
1316 arr [num_sizes] = size;
1321 target_size *= factor;
1322 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1327 /* only valid during minor collections */
1328 static mword old_num_major_sections;
1331 major_start_nursery_collection (void)
1333 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1334 consistency_check ();
1337 old_num_major_sections = num_major_sections;
1341 major_finish_nursery_collection (void)
1343 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1344 consistency_check ();
1346 sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1350 major_start_major_collection (void)
1354 /* clear the free lists */
1355 for (i = 0; i < num_block_obj_sizes; ++i) {
1356 if (!evacuate_block_obj_sizes [i])
1359 free_block_lists [0][i] = NULL;
1360 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1363 // Sweep all unswept blocks
1367 MONO_GC_SWEEP_BEGIN (GENERATION_OLD, TRUE);
1369 FOREACH_BLOCK (block) {
1370 sweep_block (block, TRUE);
1371 } END_FOREACH_BLOCK;
1373 MONO_GC_SWEEP_END (GENERATION_OLD, TRUE);
1376 SGEN_ASSERT (0, have_swept, "Cannot start major collection without having finished sweeping");
1381 major_finish_major_collection (ScannedObjectCounts *counts)
1383 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1384 if (binary_protocol_is_enabled ()) {
1385 counts->num_scanned_objects = scanned_objects_list.next_slot;
1387 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1388 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1390 sgen_pointer_queue_clear (&scanned_objects_list);
1395 #if SIZEOF_VOID_P != 8
1397 compare_pointers (const void *va, const void *vb) {
1398 char *a = *(char**)va, *b = *(char**)vb;
1408 major_free_swept_blocks (void)
1410 size_t section_reserve = sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1412 g_assert (have_swept);
1414 #if SIZEOF_VOID_P != 8
1416 int i, num_empty_blocks_orig, num_blocks, arr_length;
1418 void **empty_block_arr;
1419 void **rebuild_next;
1423 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1424 * a VirtualAlloc ()-ed block.
1429 if (num_empty_blocks <= section_reserve)
1431 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1433 num_empty_blocks_orig = num_empty_blocks;
1434 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1435 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1436 if (!empty_block_arr)
1440 for (block = empty_blocks; block; block = *(void**)block)
1441 empty_block_arr [i++] = block;
1442 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1444 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1447 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1448 * contiguous ones. If we do, we free them. If that's not enough to get to
1449 * section_reserve, we halve the number of contiguous blocks we're looking
1450 * for and have another go, until we're done with looking for pairs of
1451 * blocks, at which point we give up and go to the fallback.
1453 arr_length = num_empty_blocks_orig;
1454 num_blocks = MS_BLOCK_ALLOC_NUM;
1455 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1460 for (i = 0; i < arr_length; ++i) {
1462 void *block = empty_block_arr [i];
1463 SGEN_ASSERT (0, block, "we're not shifting correctly");
1465 empty_block_arr [dest] = block;
1467 * This is not strictly necessary, but we're
1470 empty_block_arr [i] = NULL;
1479 SGEN_ASSERT (0, first >= 0 && d > first, "algorithm is wrong");
1481 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1486 if (d + 1 - first == num_blocks) {
1488 * We found num_blocks contiguous blocks. Free them
1489 * and null their array entries. As an optimization
1490 * we could, instead of nulling the entries, shift
1491 * the following entries over to the left, while
1495 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1496 for (j = first; j <= d; ++j)
1497 empty_block_arr [j] = NULL;
1501 num_empty_blocks -= num_blocks;
1503 stat_major_blocks_freed += num_blocks;
1504 if (num_blocks == MS_BLOCK_ALLOC_NUM)
1505 stat_major_blocks_freed_ideal += num_blocks;
1507 stat_major_blocks_freed_less_ideal += num_blocks;
1512 SGEN_ASSERT (0, dest <= i && dest <= arr_length, "array length is off");
1514 SGEN_ASSERT (0, arr_length == num_empty_blocks, "array length is off");
1519 /* rebuild empty_blocks free list */
1520 rebuild_next = (void**)&empty_blocks;
1521 for (i = 0; i < arr_length; ++i) {
1522 void *block = empty_block_arr [i];
1523 SGEN_ASSERT (0, block, "we're missing blocks");
1524 *rebuild_next = block;
1525 rebuild_next = (void**)block;
1527 *rebuild_next = NULL;
1530 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1533 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1537 * This is our threshold. If there's not more empty than used blocks, we won't
1538 * release uncontiguous blocks, in fear of fragmenting the address space.
1540 if (num_empty_blocks <= num_major_sections)
1544 while (num_empty_blocks > section_reserve) {
1545 void *next = *(void**)empty_blocks;
1546 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
1547 empty_blocks = next;
1549 * Needs not be atomic because this is running
1554 ++stat_major_blocks_freed;
1555 #if SIZEOF_VOID_P != 8
1556 ++stat_major_blocks_freed_individual;
1562 major_pin_objects (SgenGrayQueue *queue)
1566 FOREACH_BLOCK (block) {
1567 size_t first_entry, last_entry;
1568 SGEN_ASSERT (0, block->swept, "All blocks must be swept when we're pinning.");
1569 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
1570 &first_entry, &last_entry);
1571 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
1572 } END_FOREACH_BLOCK;
1576 major_init_to_space (void)
1581 major_report_pinned_memory_usage (void)
1583 g_assert_not_reached ();
1587 major_get_used_size (void)
1592 FOREACH_BLOCK (block) {
1593 int count = MS_BLOCK_FREE / block->obj_size;
1595 size += count * block->obj_size;
1596 for (iter = block->free_list; iter; iter = (void**)*iter)
1597 size -= block->obj_size;
1598 } END_FOREACH_BLOCK;
1604 get_num_major_sections (void)
1606 return num_major_sections;
1610 major_handle_gc_param (const char *opt)
1612 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1613 const char *arg = strchr (opt, '=') + 1;
1614 int percentage = atoi (arg);
1615 if (percentage < 0 || percentage > 100) {
1616 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1619 evacuation_threshold = (float)percentage / 100.0f;
1621 } else if (!strcmp (opt, "lazy-sweep")) {
1624 } else if (!strcmp (opt, "no-lazy-sweep")) {
1633 major_print_gc_param_usage (void)
1637 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1638 " (no-)lazy-sweep\n"
1643 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1646 gboolean has_references;
1648 FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1650 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1651 } END_FOREACH_BLOCK;
1654 #ifdef HEAVY_STATISTICS
1655 extern guint64 marked_cards;
1656 extern guint64 scanned_cards;
1657 extern guint64 scanned_objects;
1658 extern guint64 remarked_cards;
1661 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1663 * MS blocks are 16K aligned.
1664 * Cardtables are 4K aligned, at least.
1665 * This means that the cardtable of a given block is 32 bytes aligned.
1668 initial_skip_card (guint8 *card_data)
1670 mword *cards = (mword*)card_data;
1673 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1679 if (i == CARD_WORDS_PER_BLOCK)
1680 return card_data + CARDS_PER_BLOCK;
1682 #if defined(__i386__) && defined(__GNUC__)
1683 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
1684 #elif defined(__x86_64__) && defined(__GNUC__)
1685 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
1686 #elif defined(__s390x__) && defined(__GNUC__)
1687 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
1689 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1691 return &card_data [i];
1697 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1698 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
1699 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1702 card_offset (char *obj, char *base)
1704 return (obj - base) >> CARD_BITS;
1708 major_scan_card_table (gboolean mod_union, SgenGrayQueue *queue)
1711 gboolean has_references;
1712 ScanObjectFunc scan_func = sgen_get_current_object_ops ()->scan_object;
1714 if (!concurrent_mark)
1715 g_assert (!mod_union);
1717 FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1718 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1719 guint8 cards_copy [CARDS_PER_BLOCK];
1721 gboolean small_objects;
1724 guint8 *card_data, *card_base;
1725 guint8 *card_data_end;
1726 char *scan_front = NULL;
1728 #ifdef PREFETCH_CARDS
1729 int prefetch_index = __index + 6;
1730 if (prefetch_index < allocated_blocks.next_slot) {
1731 MSBlockInfo *prefetch_block = BLOCK_UNTAG_HAS_REFERENCES (allocated_blocks.data [prefetch_index]);
1732 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
1733 PREFETCH_READ (prefetch_block);
1734 PREFETCH_WRITE (prefetch_cards);
1735 PREFETCH_WRITE (prefetch_cards + 32);
1739 if (!has_references)
1742 block_obj_size = block->obj_size;
1743 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
1745 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
1748 * This is safe in face of card aliasing for the following reason:
1750 * Major blocks are 16k aligned, or 32 cards aligned.
1751 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1752 * sizes, they won't overflow the cardtable overlap modulus.
1755 card_data = card_base = block->cardtable_mod_union;
1757 * This happens when the nursery collection that precedes finishing
1758 * the concurrent collection allocates new major blocks.
1763 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1764 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1766 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
1768 card_data = card_base = cards_copy;
1771 card_data_end = card_data + CARDS_PER_BLOCK;
1773 card_data += MS_BLOCK_SKIP >> CARD_BITS;
1775 card_data = initial_skip_card (card_data);
1776 while (card_data < card_data_end) {
1777 size_t card_index, first_object_index;
1780 char *first_obj, *obj;
1782 HEAVY_STAT (++scanned_cards);
1789 card_index = card_data - card_base;
1790 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
1791 end = start + CARD_SIZE_IN_BYTES;
1794 sweep_block (block, FALSE);
1796 HEAVY_STAT (++marked_cards);
1799 sgen_card_table_prepare_card_for_scanning (card_data);
1802 * If the card we're looking at starts at or in the block header, we
1803 * must start at the first object in the block, without calculating
1804 * the index of the object we're hypothetically starting at, because
1805 * it would be negative.
1807 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
1808 first_object_index = 0;
1810 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1812 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
1815 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
1819 /* FIXME: do this more efficiently */
1821 MS_CALC_MARK_BIT (w, b, obj);
1822 if (!MS_MARK_BIT (block, w, b))
1826 if (small_objects) {
1827 HEAVY_STAT (++scanned_objects);
1828 scan_func (obj, sgen_obj_get_descriptor (obj), queue);
1830 size_t offset = card_offset (obj, block_start);
1831 sgen_cardtable_scan_object (obj, block_obj_size, card_base + offset, mod_union, queue);
1834 obj += block_obj_size;
1835 g_assert (scan_front <= obj);
1839 HEAVY_STAT (if (*card_data) ++remarked_cards);
1840 binary_protocol_card_scan (first_obj, obj - first_obj);
1845 card_data = card_base + card_offset (obj, block_start);
1847 } END_FOREACH_BLOCK;
1851 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
1854 gboolean has_references;
1855 long long total_cards = 0;
1856 long long marked_cards = 0;
1858 FOREACH_BLOCK_HAS_REFERENCES (block, has_references) {
1859 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
1862 if (!has_references)
1865 total_cards += CARDS_PER_BLOCK;
1866 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
1870 } END_FOREACH_BLOCK;
1872 *num_total_cards = total_cards;
1873 *num_marked_cards = marked_cards;
1877 update_cardtable_mod_union (void)
1881 FOREACH_BLOCK (block) {
1884 block->cardtable_mod_union = sgen_card_table_update_mod_union (block->cardtable_mod_union,
1885 MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
1887 SGEN_ASSERT (0, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
1888 } END_FOREACH_BLOCK;
1892 major_get_cardtable_mod_union_for_object (char *obj)
1894 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
1895 size_t offset = card_offset (obj, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1896 return &block->cardtable_mod_union [offset];
1900 alloc_free_block_lists (MSBlockInfo ***lists)
1903 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1904 lists [i] = sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1907 #undef pthread_create
1910 post_param_init (SgenMajorCollector *collector)
1912 collector->sweeps_lazily = lazy_sweep;
1916 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
1920 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
1922 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
1923 block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1924 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
1926 evacuate_block_obj_sizes = sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
1927 for (i = 0; i < num_block_obj_sizes; ++i)
1928 evacuate_block_obj_sizes [i] = FALSE;
1933 g_print ("block object sizes:\n");
1934 for (i = 0; i < num_block_obj_sizes; ++i)
1935 g_print ("%d\n", block_obj_sizes [i]);
1939 alloc_free_block_lists (free_block_lists);
1941 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
1942 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
1943 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
1944 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
1946 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
1947 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
1948 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
1949 mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_objects_evacuated);
1950 #if SIZEOF_VOID_P != 8
1951 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
1952 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
1953 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
1954 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
1957 collector->section_size = MAJOR_SECTION_SIZE;
1959 concurrent_mark = is_concurrent;
1960 if (is_concurrent) {
1961 collector->is_concurrent = TRUE;
1962 collector->want_synchronous_collection = &want_evacuation;
1964 collector->is_concurrent = FALSE;
1965 collector->want_synchronous_collection = NULL;
1967 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
1968 collector->supports_cardtable = TRUE;
1970 collector->alloc_heap = major_alloc_heap;
1971 collector->is_object_live = major_is_object_live;
1972 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
1973 collector->alloc_degraded = major_alloc_degraded;
1975 collector->alloc_object = major_alloc_object;
1976 collector->free_pinned_object = free_pinned_object;
1977 collector->iterate_objects = major_iterate_objects;
1978 collector->free_non_pinned_object = major_free_non_pinned_object;
1979 collector->pin_objects = major_pin_objects;
1980 collector->pin_major_object = pin_major_object;
1981 collector->scan_card_table = major_scan_card_table;
1982 collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
1983 if (is_concurrent) {
1984 collector->update_cardtable_mod_union = update_cardtable_mod_union;
1985 collector->get_cardtable_mod_union_for_object = major_get_cardtable_mod_union_for_object;
1987 collector->init_to_space = major_init_to_space;
1988 collector->sweep = major_sweep;
1989 collector->have_finished_sweeping = major_have_finished_sweeping;
1990 collector->free_swept_blocks = major_free_swept_blocks;
1991 collector->check_scan_starts = major_check_scan_starts;
1992 collector->dump_heap = major_dump_heap;
1993 collector->get_used_size = major_get_used_size;
1994 collector->start_nursery_collection = major_start_nursery_collection;
1995 collector->finish_nursery_collection = major_finish_nursery_collection;
1996 collector->start_major_collection = major_start_major_collection;
1997 collector->finish_major_collection = major_finish_major_collection;
1998 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
1999 collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2000 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2001 collector->get_num_major_sections = get_num_major_sections;
2002 collector->handle_gc_param = major_handle_gc_param;
2003 collector->print_gc_param_usage = major_print_gc_param_usage;
2004 collector->post_param_init = post_param_init;
2005 collector->is_valid_object = major_is_valid_object;
2006 collector->describe_pointer = major_describe_pointer;
2007 collector->count_cards = major_count_cards;
2009 collector->major_ops.copy_or_mark_object = major_copy_or_mark_object_canonical;
2010 collector->major_ops.scan_object = major_scan_object_with_evacuation;
2011 if (is_concurrent) {
2012 collector->major_concurrent_ops.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2013 collector->major_concurrent_ops.scan_object = major_scan_object_no_mark_concurrent;
2014 collector->major_concurrent_ops.scan_vtype = major_scan_vtype_concurrent;
2017 #if !defined (FIXED_HEAP) && !defined (SGEN_PARALLEL_MARK)
2018 /* FIXME: this will not work with evacuation or the split nursery. */
2020 collector->drain_gray_stack = drain_gray_stack;
2022 #ifdef HEAVY_STATISTICS
2023 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2024 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2025 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2026 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2027 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2028 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2029 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2030 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2031 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2032 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2034 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2035 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2036 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2040 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2041 mono_mutex_init (&scanned_objects_list_lock);
2044 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2046 /*cardtable requires major pages to be 8 cards aligned*/
2047 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2051 sgen_marksweep_init (SgenMajorCollector *collector)
2053 sgen_marksweep_init_internal (collector, FALSE);
2057 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2059 sgen_marksweep_init_internal (collector, TRUE);