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.
33 #include "mono/sgen/sgen-gc.h"
34 #include "mono/sgen/sgen-protocol.h"
35 #include "mono/sgen/sgen-cardtable.h"
36 #include "mono/sgen/sgen-memory-governor.h"
37 #include "mono/sgen/sgen-layout-stats.h"
38 #include "mono/sgen/sgen-pointer-queue.h"
39 #include "mono/sgen/sgen-pinning.h"
40 #include "mono/sgen/sgen-workers.h"
41 #include "mono/sgen/sgen-thread-pool.h"
42 #include "mono/sgen/sgen-client.h"
43 #include "mono/utils/mono-membar.h"
45 #if defined(ARCH_MIN_MS_BLOCK_SIZE) && defined(ARCH_MIN_MS_BLOCK_SIZE_SHIFT)
46 #define MS_BLOCK_SIZE ARCH_MIN_MS_BLOCK_SIZE
47 #define MS_BLOCK_SIZE_SHIFT ARCH_MIN_MS_BLOCK_SIZE_SHIFT
49 #define MS_BLOCK_SIZE_SHIFT 14 /* INT FASTENABLE */
50 #define MS_BLOCK_SIZE (1 << MS_BLOCK_SIZE_SHIFT)
52 #define MAJOR_SECTION_SIZE MS_BLOCK_SIZE
53 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
56 * Don't allocate single blocks, but alloc a contingent of this many
57 * blocks in one swoop. This must be a power of two.
59 #define MS_BLOCK_ALLOC_NUM 32
62 * Number of bytes before the first object in a block. At the start
63 * of a block is the MSBlockHeader, then opional padding, then come
64 * the objects, so this must be >= sizeof (MSBlockHeader).
66 #define MS_BLOCK_SKIP ((sizeof (MSBlockHeader) + 15) & ~15)
68 #define MS_BLOCK_FREE (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
70 #define MS_NUM_MARK_WORDS ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
73 * Blocks progress from one state to the next:
75 * SWEPT The block is fully swept. It might or might not be in
78 * MARKING The block might or might not contain live objects. If
79 * we're in between an initial collection pause and the
80 * finishing pause, the block might or might not be in a
83 * CHECKING The sweep thread is investigating the block to determine
84 * whether or not it contains live objects. The block is
87 * NEED_SWEEPING The block contains live objects but has not yet been
88 * swept. It also contains free slots. It is in a block
91 * SWEEPING The block is being swept. It might be in a free list.
98 BLOCK_STATE_NEED_SWEEPING,
102 typedef struct _MSBlockInfo MSBlockInfo;
103 struct _MSBlockInfo {
106 * FIXME: Do we even need this? It's only used during sweep and might be worth
107 * recalculating to save the space.
109 guint16 obj_size_index;
110 /* FIXME: Reduce this - it only needs a byte. */
111 volatile gint32 state;
112 unsigned int pinned : 1;
113 unsigned int has_references : 1;
114 unsigned int has_pinned : 1; /* means cannot evacuate */
115 unsigned int is_to_space : 1;
116 void ** volatile free_list;
117 MSBlockInfo * volatile next_free;
118 guint8 * volatile cardtable_mod_union;
119 mword mark_words [MS_NUM_MARK_WORDS];
122 #define MS_BLOCK_FOR_BLOCK_INFO(b) ((char*)(b))
124 #define MS_BLOCK_OBJ(b,i) ((GCObject *)(MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (b)->obj_size * (i)))
125 #define MS_BLOCK_OBJ_FOR_SIZE(b,i,obj_size) (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP + (obj_size) * (i))
126 #define MS_BLOCK_DATA_FOR_OBJ(o) ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
132 #define MS_BLOCK_FOR_OBJ(o) (&((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
134 /* object index will always be small */
135 #define MS_BLOCK_OBJ_INDEX(o,b) ((int)(((char*)(o) - (MS_BLOCK_FOR_BLOCK_INFO(b) + MS_BLOCK_SKIP)) / (b)->obj_size))
137 //casting to int is fine since blocks are 32k
138 #define MS_CALC_MARK_BIT(w,b,o) do { \
139 int i = ((int)((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o)))) >> SGEN_ALLOC_ALIGN_BITS; \
140 if (sizeof (mword) == 4) { \
149 #define MS_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] & (ONE_P << (b)))
150 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (ONE_P << (b)))
152 #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))
154 #define MS_BLOCK_OBJ_SIZE_FACTOR (pow (2.0, 1.0 / 3))
157 * This way we can lookup block object size indexes for sizes up to
158 * 256 bytes with a single load.
160 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES 32
162 static int *block_obj_sizes;
163 static int num_block_obj_sizes;
164 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
166 #define MS_BLOCK_FLAG_PINNED 1
167 #define MS_BLOCK_FLAG_REFS 2
169 #define MS_BLOCK_TYPE_MAX 4
171 static gboolean *evacuate_block_obj_sizes;
172 static float evacuation_threshold = 0.666f;
174 static gboolean lazy_sweep = FALSE;
178 SWEEP_STATE_NEED_SWEEPING,
179 SWEEP_STATE_SWEEPING,
180 SWEEP_STATE_SWEEPING_AND_ITERATING,
181 SWEEP_STATE_COMPACTING
184 static volatile int sweep_state = SWEEP_STATE_SWEPT;
186 static gboolean concurrent_mark;
187 static gboolean concurrent_sweep = TRUE;
189 #define BLOCK_IS_TAGGED_HAS_REFERENCES(bl) SGEN_POINTER_IS_TAGGED_1 ((bl))
190 #define BLOCK_TAG_HAS_REFERENCES(bl) SGEN_POINTER_TAG_1 ((bl))
192 #define BLOCK_IS_TAGGED_CHECKING(bl) SGEN_POINTER_IS_TAGGED_2 ((bl))
193 #define BLOCK_TAG_CHECKING(bl) SGEN_POINTER_TAG_2 ((bl))
195 #define BLOCK_UNTAG(bl) ((MSBlockInfo *)SGEN_POINTER_UNTAG_12 ((bl)))
197 #define BLOCK_TAG(bl) ((bl)->has_references ? BLOCK_TAG_HAS_REFERENCES ((bl)) : (bl))
199 /* all allocated blocks in the system */
200 static SgenPointerQueue allocated_blocks;
202 /* non-allocated block free-list */
203 static void *empty_blocks = NULL;
204 static size_t num_empty_blocks = 0;
206 #define FOREACH_BLOCK_NO_LOCK_CONDITION(cond,bl) { \
208 SGEN_ASSERT (0, (cond) && !sweep_in_progress (), "Can't iterate blocks while the world is running or sweep is in progress."); \
209 for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { \
210 (bl) = BLOCK_UNTAG (allocated_blocks.data [__index]);
211 #define FOREACH_BLOCK_NO_LOCK(bl) \
212 FOREACH_BLOCK_NO_LOCK_CONDITION(sgen_is_world_stopped (), bl)
213 #define FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK(bl,hr) { \
215 SGEN_ASSERT (0, sgen_is_world_stopped () && !sweep_in_progress (), "Can't iterate blocks while the world is running or sweep is in progress."); \
216 for (__index = 0; __index < allocated_blocks.next_slot; ++__index) { \
217 (bl) = (MSBlockInfo *)allocated_blocks.data [__index]; \
218 (hr) = BLOCK_IS_TAGGED_HAS_REFERENCES ((bl)); \
219 (bl) = BLOCK_UNTAG ((bl));
220 #define END_FOREACH_BLOCK_NO_LOCK } }
222 static volatile size_t num_major_sections = 0;
224 * One free block list for each block object size. We add and remove blocks from these
225 * lists lock-free via CAS.
227 * Blocks accessed/removed from `free_block_lists`:
228 * from the mutator (with GC lock held)
229 * in nursery collections
230 * in non-concurrent major collections
231 * in the finishing pause of concurrent major collections (whole list is cleared)
233 * Blocks added to `free_block_lists`:
234 * in the sweeping thread
235 * during nursery collections
236 * from domain clearing (with the world stopped and no sweeping happening)
238 * The only item of those that doesn't require the GC lock is the sweep thread. The sweep
239 * thread only ever adds blocks to the free list, so the ABA problem can't occur.
241 static MSBlockInfo * volatile *free_block_lists [MS_BLOCK_TYPE_MAX];
243 static guint64 stat_major_blocks_alloced = 0;
244 static guint64 stat_major_blocks_freed = 0;
245 static guint64 stat_major_blocks_lazy_swept = 0;
247 #if SIZEOF_VOID_P != 8
248 static guint64 stat_major_blocks_freed_ideal = 0;
249 static guint64 stat_major_blocks_freed_less_ideal = 0;
250 static guint64 stat_major_blocks_freed_individual = 0;
251 static guint64 stat_major_blocks_alloced_less_ideal = 0;
254 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
255 static guint64 num_major_objects_marked = 0;
256 #define INC_NUM_MAJOR_OBJECTS_MARKED() (++num_major_objects_marked)
258 #define INC_NUM_MAJOR_OBJECTS_MARKED()
261 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
262 static mono_mutex_t scanned_objects_list_lock;
263 static SgenPointerQueue scanned_objects_list;
266 add_scanned_object (void *ptr)
268 if (!binary_protocol_is_enabled ())
271 mono_os_mutex_lock (&scanned_objects_list_lock);
272 sgen_pointer_queue_add (&scanned_objects_list, ptr);
273 mono_os_mutex_unlock (&scanned_objects_list_lock);
277 static gboolean sweep_block (MSBlockInfo *block);
280 ms_find_block_obj_size_index (size_t size)
283 SGEN_ASSERT (9, size <= SGEN_MAX_SMALL_OBJ_SIZE, "size %zd is bigger than max small object size %d", size, SGEN_MAX_SMALL_OBJ_SIZE);
284 for (i = 0; i < num_block_obj_sizes; ++i)
285 if (block_obj_sizes [i] >= size)
287 g_error ("no object of size %zd\n", size);
291 #define FREE_BLOCKS_FROM(lists,p,r) (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
292 #define FREE_BLOCKS(p,r) (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
294 #define MS_BLOCK_OBJ_SIZE_INDEX(s) \
295 (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ? \
296 fast_block_obj_size_indexes [((s)+7)>>3] : \
297 ms_find_block_obj_size_index ((s)))
300 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
304 start = (char *)sgen_alloc_os_memory_aligned (nursery_size, nursery_align, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
306 start = (char *)sgen_alloc_os_memory (nursery_size, (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE), "nursery");
312 update_heap_boundaries_for_block (MSBlockInfo *block)
314 sgen_update_heap_boundaries ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), (mword)MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE);
321 ms_get_empty_block (void)
325 void *block, *empty, *next;
330 * We try allocating MS_BLOCK_ALLOC_NUM blocks first. If that's
331 * unsuccessful, we halve the number of blocks and try again, until we're at
332 * 1. If that doesn't work, either, we assert.
334 int alloc_num = MS_BLOCK_ALLOC_NUM;
336 p = (char *)sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * alloc_num, MS_BLOCK_SIZE,
337 (SgenAllocFlags)(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE),
338 alloc_num == 1 ? "major heap section" : NULL);
344 for (i = 0; i < alloc_num; ++i) {
347 * We do the free list update one after the
348 * other so that other threads can use the new
349 * blocks as quickly as possible.
352 empty = empty_blocks;
353 *(void**)block = empty;
354 } while (SGEN_CAS_PTR ((gpointer*)&empty_blocks, block, empty) != empty);
358 SGEN_ATOMIC_ADD_P (num_empty_blocks, alloc_num);
360 stat_major_blocks_alloced += alloc_num;
361 #if SIZEOF_VOID_P != 8
362 if (alloc_num != MS_BLOCK_ALLOC_NUM)
363 stat_major_blocks_alloced_less_ideal += alloc_num;
368 empty = empty_blocks;
372 next = *(void**)block;
373 } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
375 SGEN_ATOMIC_ADD_P (num_empty_blocks, -1);
377 *(void**)block = NULL;
379 g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
385 * This doesn't actually free a block immediately, but enqueues it into the `empty_blocks`
386 * list, where it will either be freed later on, or reused in nursery collections.
389 ms_free_block (void *block)
393 sgen_memgov_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
394 memset (block, 0, MS_BLOCK_SIZE);
397 empty = empty_blocks;
398 *(void**)block = empty;
399 } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
401 SGEN_ATOMIC_ADD_P (num_empty_blocks, 1);
403 binary_protocol_block_free (block, MS_BLOCK_SIZE);
407 sweep_in_progress (void)
409 int state = sweep_state;
410 return state == SWEEP_STATE_SWEEPING ||
411 state == SWEEP_STATE_SWEEPING_AND_ITERATING ||
412 state == SWEEP_STATE_COMPACTING;
415 static inline gboolean
416 block_is_swept_or_marking (MSBlockInfo *block)
418 gint32 state = block->state;
419 return state == BLOCK_STATE_SWEPT || state == BLOCK_STATE_MARKING;
422 //#define MARKSWEEP_CONSISTENCY_CHECK
424 #ifdef MARKSWEEP_CONSISTENCY_CHECK
426 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
428 SGEN_ASSERT (0, !sweep_in_progress (), "Can't examine allocated blocks during sweep");
429 for (; block; block = block->next_free) {
430 SGEN_ASSERT (0, block->state != BLOCK_STATE_CHECKING, "Can't have a block we're checking in a free list.");
431 g_assert (block->obj_size == size);
432 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
434 /* blocks in the free lists must have at least
436 g_assert (block->free_list);
438 /* the block must be in the allocated_blocks array */
439 g_assert (sgen_pointer_queue_find (&allocated_blocks, BLOCK_TAG (block)) != (size_t)-1);
444 check_empty_blocks (void)
448 for (p = empty_blocks; p; p = *(void**)p)
450 g_assert (i == num_empty_blocks);
454 consistency_check (void)
459 /* check all blocks */
460 FOREACH_BLOCK_NO_LOCK (block) {
461 int count = MS_BLOCK_FREE / block->obj_size;
465 /* count number of free slots */
466 for (i = 0; i < count; ++i) {
467 void **obj = (void**) MS_BLOCK_OBJ (block, i);
468 if (!MS_OBJ_ALLOCED (obj, block))
472 /* check free list */
473 for (free = block->free_list; free; free = (void**)*free) {
474 g_assert (MS_BLOCK_FOR_OBJ (free) == block);
477 g_assert (num_free == 0);
479 /* check all mark words are zero */
480 if (!sgen_concurrent_collection_in_progress () && block_is_swept_or_marking (block)) {
481 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
482 g_assert (block->mark_words [i] == 0);
484 } END_FOREACH_BLOCK_NO_LOCK;
486 /* check free blocks */
487 for (i = 0; i < num_block_obj_sizes; ++i) {
489 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
490 check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
493 check_empty_blocks ();
498 add_free_block (MSBlockInfo * volatile *free_blocks, int size_index, MSBlockInfo *block)
502 block->next_free = old = free_blocks [size_index];
503 } while (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], block, old) != old);
506 static void major_finish_sweep_checking (void);
509 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
511 int size = block_obj_sizes [size_index];
512 int count = MS_BLOCK_FREE / size;
514 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
518 if (!sgen_memgov_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
521 info = (MSBlockInfo*)ms_get_empty_block ();
523 SGEN_ASSERT (9, count >= 2, "block with %d objects, it must hold at least 2", count);
525 info->obj_size = size;
526 info->obj_size_index = size_index;
527 info->pinned = pinned;
528 info->has_references = has_references;
529 info->has_pinned = pinned;
531 * Blocks that are to-space are not evacuated from. During an major collection
532 * blocks are allocated for two reasons: evacuating objects from the nursery and
533 * evacuating them from major blocks marked for evacuation. In both cases we don't
534 * want further evacuation. We also don't want to evacuate objects allocated during
535 * the concurrent mark since it would add pointless stress on the finishing pause.
537 info->is_to_space = (sgen_get_current_collection_generation () == GENERATION_OLD) || sgen_concurrent_collection_in_progress ();
538 info->state = info->is_to_space ? BLOCK_STATE_MARKING : BLOCK_STATE_SWEPT;
539 SGEN_ASSERT (6, !sweep_in_progress () || info->state == BLOCK_STATE_SWEPT, "How do we add a new block to be swept while sweeping?");
540 info->cardtable_mod_union = NULL;
542 update_heap_boundaries_for_block (info);
544 binary_protocol_block_alloc (info, MS_BLOCK_SIZE);
546 /* build free list */
547 obj_start = MS_BLOCK_FOR_BLOCK_INFO (info) + MS_BLOCK_SKIP;
548 info->free_list = (void**)obj_start;
549 /* we're skipping the last one - it must be nulled */
550 for (i = 0; i < count - 1; ++i) {
551 char *next_obj_start = obj_start + size;
552 *(void**)obj_start = next_obj_start;
553 obj_start = next_obj_start;
556 *(void**)obj_start = NULL;
558 add_free_block (free_blocks, size_index, info);
561 * Adding to the allocated_blocks array is racy with the removal of nulls when
562 * sweeping. We wait for sweep to finish to avoid that.
564 * The memory barrier here and in `sweep_job_func()` are required because we need
565 * `allocated_blocks` synchronized between this and the sweep thread.
567 major_finish_sweep_checking ();
568 mono_memory_barrier ();
570 sgen_pointer_queue_add (&allocated_blocks, BLOCK_TAG (info));
572 SGEN_ATOMIC_ADD_P (num_major_sections, 1);
577 ptr_is_from_pinned_alloc (char *ptr)
581 FOREACH_BLOCK_NO_LOCK (block) {
582 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE)
583 return block->pinned;
584 } END_FOREACH_BLOCK_NO_LOCK;
589 ensure_can_access_block_free_list (MSBlockInfo *block)
593 switch (block->state) {
594 case BLOCK_STATE_SWEPT:
595 case BLOCK_STATE_MARKING:
597 case BLOCK_STATE_CHECKING:
598 SGEN_ASSERT (0, FALSE, "How did we get a block that's being checked from a free list?");
600 case BLOCK_STATE_NEED_SWEEPING:
601 if (sweep_block (block))
602 ++stat_major_blocks_lazy_swept;
604 case BLOCK_STATE_SWEEPING:
605 /* FIXME: do this more elegantly */
609 SGEN_ASSERT (0, FALSE, "Illegal block state");
616 unlink_slot_from_free_list_uncontested (MSBlockInfo * volatile *free_blocks, int size_index)
618 MSBlockInfo *block, *next_free_block;
619 void *obj, *next_free_slot;
622 block = free_blocks [size_index];
623 SGEN_ASSERT (9, block, "no free block to unlink from free_blocks %p size_index %d", free_blocks, size_index);
625 ensure_can_access_block_free_list (block);
627 obj = block->free_list;
628 SGEN_ASSERT (6, obj, "block %p in free list had no available object to alloc from", block);
630 next_free_slot = *(void**)obj;
631 if (next_free_slot) {
632 block->free_list = (gpointer *)next_free_slot;
636 next_free_block = block->next_free;
637 if (SGEN_CAS_PTR ((volatile gpointer *)&free_blocks [size_index], next_free_block, block) != block)
640 block->free_list = NULL;
641 block->next_free = NULL;
647 alloc_obj (GCVTable vtable, size_t size, gboolean pinned, gboolean has_references)
649 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
650 MSBlockInfo * volatile * free_blocks = FREE_BLOCKS (pinned, has_references);
653 if (!free_blocks [size_index]) {
654 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
658 obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
660 /* FIXME: assumes object layout */
661 *(GCVTable*)obj = vtable;
663 return (GCObject *)obj;
667 major_alloc_object (GCVTable 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 (GCObject *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", obj);
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", block);
704 add_free_block (free_blocks, size_index, block);
709 major_free_non_pinned_object (GCObject *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 (GCVTable 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);
728 return (GCObject *)res;
732 free_pinned_object (GCObject *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 (GCVTable vtable, size_t size)
745 obj = alloc_obj (vtable, size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
746 if (G_LIKELY (obj)) {
747 HEAVY_STAT (++stat_objects_alloced_degraded);
748 HEAVY_STAT (stat_bytes_alloced_degraded += size);
754 * obj is some object. If it's not in the major heap (i.e. if it's in
755 * the nursery or LOS), return FALSE. Otherwise return whether it's
756 * been marked or copied.
759 major_is_object_live (GCObject *obj)
765 if (sgen_ptr_in_nursery (obj))
768 objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size (obj));
771 if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
774 /* now we know it's in a major block */
775 block = MS_BLOCK_FOR_OBJ (obj);
776 SGEN_ASSERT (9, !block->pinned, "block %p is pinned, BTW why is this bad?", block);
777 MS_CALC_MARK_BIT (word, bit, obj);
778 return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
782 major_ptr_is_in_non_pinned_space (char *ptr, char **start)
786 FOREACH_BLOCK_NO_LOCK (block) {
787 if (ptr >= MS_BLOCK_FOR_BLOCK_INFO (block) && ptr <= MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) {
788 int count = MS_BLOCK_FREE / block->obj_size;
792 for (i = 0; i <= count; ++i) {
793 if (ptr >= (char*)MS_BLOCK_OBJ (block, i) && ptr < (char*)MS_BLOCK_OBJ (block, i + 1)) {
794 *start = (char *)MS_BLOCK_OBJ (block, i);
798 return !block->pinned;
800 } END_FOREACH_BLOCK_NO_LOCK;
805 try_set_sweep_state (int new_, int expected)
807 int old = SGEN_CAS (&sweep_state, new_, expected);
808 return old == expected;
812 set_sweep_state (int new_, int expected)
814 gboolean success = try_set_sweep_state (new_, expected);
815 SGEN_ASSERT (0, success, "Could not set sweep state.");
818 static gboolean ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked);
820 static SgenThreadPoolJob * volatile sweep_job;
823 major_finish_sweep_checking (void)
826 SgenThreadPoolJob *job;
829 switch (sweep_state) {
830 case SWEEP_STATE_SWEPT:
831 case SWEEP_STATE_NEED_SWEEPING:
833 case SWEEP_STATE_SWEEPING:
834 if (try_set_sweep_state (SWEEP_STATE_SWEEPING_AND_ITERATING, SWEEP_STATE_SWEEPING))
837 case SWEEP_STATE_SWEEPING_AND_ITERATING:
838 SGEN_ASSERT (0, FALSE, "Is there another minor collection running?");
840 case SWEEP_STATE_COMPACTING:
843 SGEN_ASSERT (0, FALSE, "Invalid sweep state.");
848 * We're running with the world stopped and the only other thread doing work is the
849 * sweep thread, which doesn't add blocks to the array, so we can safely access
852 for (block_index = 0; block_index < allocated_blocks.next_slot; ++block_index)
853 ensure_block_is_checked_for_sweeping (block_index, FALSE, NULL);
855 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_SWEEPING_AND_ITERATING);
860 sgen_thread_pool_job_wait (job);
861 SGEN_ASSERT (0, !sweep_job, "Why did the sweep job not null itself?");
862 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "How is the sweep job done but we're not swept?");
866 major_iterate_objects (IterateObjectsFlags flags, IterateObjectCallbackFunc callback, void *data)
868 gboolean sweep = flags & ITERATE_OBJECTS_SWEEP;
869 gboolean non_pinned = flags & ITERATE_OBJECTS_NON_PINNED;
870 gboolean pinned = flags & ITERATE_OBJECTS_PINNED;
873 major_finish_sweep_checking ();
874 FOREACH_BLOCK_NO_LOCK (block) {
875 int count = MS_BLOCK_FREE / block->obj_size;
878 if (block->pinned && !pinned)
880 if (!block->pinned && !non_pinned)
882 if (sweep && lazy_sweep) {
884 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEPT, "Block must be swept after sweeping");
887 for (i = 0; i < count; ++i) {
888 void **obj = (void**) MS_BLOCK_OBJ (block, i);
890 * We've finished sweep checking, but if we're sweeping lazily and
891 * the flags don't require us to sweep, the block might still need
892 * sweeping. In that case, we need to consult the mark bits to tell
893 * us whether an object slot is live.
895 if (!block_is_swept_or_marking (block)) {
897 SGEN_ASSERT (6, !sweep && block->state == BLOCK_STATE_NEED_SWEEPING, "Has sweeping not finished?");
898 MS_CALC_MARK_BIT (word, bit, obj);
899 if (!MS_MARK_BIT (block, word, bit))
902 if (MS_OBJ_ALLOCED (obj, block))
903 callback ((GCObject*)obj, block->obj_size, data);
905 } END_FOREACH_BLOCK_NO_LOCK;
909 major_is_valid_object (char *object)
913 FOREACH_BLOCK_NO_LOCK (block) {
917 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > object) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= object))
920 idx = MS_BLOCK_OBJ_INDEX (object, block);
921 obj = (char*)MS_BLOCK_OBJ (block, idx);
924 return MS_OBJ_ALLOCED (obj, block);
925 } END_FOREACH_BLOCK_NO_LOCK;
932 major_describe_pointer (char *ptr)
936 FOREACH_BLOCK_NO_LOCK (block) {
944 if ((MS_BLOCK_FOR_BLOCK_INFO (block) > ptr) || ((MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE) <= ptr))
947 SGEN_LOG (0, "major-ptr (block %p sz %d pin %d ref %d)\n",
948 MS_BLOCK_FOR_BLOCK_INFO (block), block->obj_size, block->pinned, block->has_references);
950 idx = MS_BLOCK_OBJ_INDEX (ptr, block);
951 obj = (char*)MS_BLOCK_OBJ (block, idx);
952 live = MS_OBJ_ALLOCED (obj, block);
953 vtable = live ? SGEN_LOAD_VTABLE ((GCObject*)obj) : NULL;
955 MS_CALC_MARK_BIT (w, b, obj);
956 marked = MS_MARK_BIT (block, w, b);
961 SGEN_LOG (0, "object");
963 SGEN_LOG (0, "dead-object");
966 SGEN_LOG (0, "interior-ptr offset %zd", ptr - obj);
968 SGEN_LOG (0, "dead-interior-ptr offset %zd", ptr - obj);
971 SGEN_LOG (0, " marked %d)\n", marked ? 1 : 0);
974 } END_FOREACH_BLOCK_NO_LOCK;
980 major_check_scan_starts (void)
985 major_dump_heap (FILE *heap_dump_file)
988 int *slots_available = (int *)alloca (sizeof (int) * num_block_obj_sizes);
989 int *slots_used = (int *)alloca (sizeof (int) * num_block_obj_sizes);
992 for (i = 0; i < num_block_obj_sizes; ++i)
993 slots_available [i] = slots_used [i] = 0;
995 FOREACH_BLOCK_NO_LOCK (block) {
996 int index = ms_find_block_obj_size_index (block->obj_size);
997 int count = MS_BLOCK_FREE / block->obj_size;
999 slots_available [index] += count;
1000 for (i = 0; i < count; ++i) {
1001 if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
1002 ++slots_used [index];
1004 } END_FOREACH_BLOCK_NO_LOCK;
1006 fprintf (heap_dump_file, "<occupancies>\n");
1007 for (i = 0; i < num_block_obj_sizes; ++i) {
1008 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
1009 block_obj_sizes [i], slots_available [i], slots_used [i]);
1011 fprintf (heap_dump_file, "</occupancies>\n");
1013 FOREACH_BLOCK_NO_LOCK (block) {
1014 int count = MS_BLOCK_FREE / block->obj_size;
1018 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
1020 for (i = 0; i <= count; ++i) {
1021 if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
1026 sgen_dump_occupied ((char *)MS_BLOCK_OBJ (block, start), (char *)MS_BLOCK_OBJ (block, i), MS_BLOCK_FOR_BLOCK_INFO (block));
1032 fprintf (heap_dump_file, "</section>\n");
1033 } END_FOREACH_BLOCK_NO_LOCK;
1037 get_cardtable_mod_union_for_block (MSBlockInfo *block, gboolean allocate)
1039 guint8 *mod_union = block->cardtable_mod_union;
1045 mod_union = sgen_card_table_alloc_mod_union (MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1046 other = (guint8 *)SGEN_CAS_PTR ((gpointer*)&block->cardtable_mod_union, mod_union, NULL);
1048 SGEN_ASSERT (0, block->cardtable_mod_union == mod_union, "Why did CAS not replace?");
1051 sgen_card_table_free_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1055 static inline guint8*
1056 major_get_cardtable_mod_union_for_reference (char *ptr)
1058 MSBlockInfo *block = MS_BLOCK_FOR_OBJ (ptr);
1059 size_t offset = sgen_card_table_get_card_offset (ptr, (char*)sgen_card_table_align_pointer (MS_BLOCK_FOR_BLOCK_INFO (block)));
1060 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
1061 SGEN_ASSERT (0, mod_union, "FIXME: optionally allocate the mod union if it's not here and CAS it in.");
1062 return &mod_union [offset];
1066 * Mark the mod-union card for `ptr`, which must be a reference within the object `obj`.
1069 mark_mod_union_card (GCObject *obj, void **ptr, GCObject *value_obj)
1071 int type = sgen_obj_get_descriptor (obj) & DESC_TYPE_MASK;
1072 if (sgen_safe_object_is_small (obj, type)) {
1073 guint8 *card_byte = major_get_cardtable_mod_union_for_reference ((char*)ptr);
1074 SGEN_ASSERT (0, MS_BLOCK_FOR_OBJ (obj) == MS_BLOCK_FOR_OBJ (ptr), "How can an object and a reference inside it not be in the same block?");
1077 sgen_los_mark_mod_union_card (obj, ptr);
1080 binary_protocol_mod_union_remset (obj, ptr, value_obj, SGEN_LOAD_VTABLE (value_obj));
1083 static inline gboolean
1084 major_block_is_evacuating (MSBlockInfo *block)
1086 if (evacuate_block_obj_sizes [block->obj_size_index] &&
1087 !block->has_pinned &&
1088 !block->is_to_space)
1093 #define LOAD_VTABLE SGEN_LOAD_VTABLE
1095 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,desc,block,queue) do { \
1096 int __word, __bit; \
1097 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1098 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
1099 MS_SET_MARK_BIT ((block), __word, __bit); \
1100 if (sgen_gc_descr_has_references (desc)) \
1101 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1102 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1103 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1106 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,desc,block,queue) do { \
1107 int __word, __bit; \
1108 MS_CALC_MARK_BIT (__word, __bit, (obj)); \
1109 SGEN_ASSERT (9, MS_OBJ_ALLOCED ((obj), (block)), "object %p not allocated", obj); \
1110 if (!MS_MARK_BIT ((block), __word, __bit)) { \
1111 MS_SET_MARK_BIT ((block), __word, __bit); \
1112 if (sgen_gc_descr_has_references (desc)) \
1113 GRAY_OBJECT_ENQUEUE ((queue), (obj), (desc)); \
1114 binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), sgen_safe_object_get_size ((obj))); \
1115 INC_NUM_MAJOR_OBJECTS_MARKED (); \
1120 pin_major_object (GCObject *obj, SgenGrayQueue *queue)
1124 if (concurrent_mark)
1125 g_assert_not_reached ();
1127 block = MS_BLOCK_FOR_OBJ (obj);
1128 block->has_pinned = TRUE;
1129 MS_MARK_OBJECT_AND_ENQUEUE (obj, sgen_obj_get_descriptor (obj), block, queue);
1132 #include "sgen-major-copy-object.h"
1135 major_get_and_reset_num_major_objects_marked (void)
1137 #ifdef SGEN_COUNT_NUMBER_OF_MAJOR_OBJECTS_MARKED
1138 long long num = num_major_objects_marked;
1139 num_major_objects_marked = 0;
1146 #define PREFETCH_CARDS 1 /* BOOL FASTENABLE */
1148 #undef PREFETCH_CARDS
1151 /* gcc 4.2.1 from xcode4 crashes on sgen_card_table_get_card_address () when this is enabled */
1152 #if defined(PLATFORM_MACOSX)
1153 #define GCC_VERSION (__GNUC__ * 10000 \
1154 + __GNUC_MINOR__ * 100 \
1155 + __GNUC_PATCHLEVEL__)
1156 #if GCC_VERSION <= 40300
1157 #undef PREFETCH_CARDS
1161 #ifdef HEAVY_STATISTICS
1162 static guint64 stat_optimized_copy;
1163 static guint64 stat_optimized_copy_nursery;
1164 static guint64 stat_optimized_copy_nursery_forwarded;
1165 static guint64 stat_optimized_copy_nursery_pinned;
1166 static guint64 stat_optimized_copy_major;
1167 static guint64 stat_optimized_copy_major_small_fast;
1168 static guint64 stat_optimized_copy_major_small_slow;
1169 static guint64 stat_optimized_copy_major_large;
1170 static guint64 stat_optimized_copy_major_forwarded;
1171 static guint64 stat_optimized_copy_major_small_evacuate;
1172 static guint64 stat_optimized_major_scan;
1173 static guint64 stat_optimized_major_scan_no_refs;
1175 static guint64 stat_drain_prefetch_fills;
1176 static guint64 stat_drain_prefetch_fill_failures;
1177 static guint64 stat_drain_loops;
1180 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_no_evacuation
1181 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_no_evacuation
1182 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_no_evacuation
1183 #include "sgen-marksweep-drain-gray-stack.h"
1185 #define COPY_OR_MARK_WITH_EVACUATION
1186 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_with_evacuation
1187 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_with_evacuation
1188 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_with_evacuation
1189 #include "sgen-marksweep-drain-gray-stack.h"
1191 #undef COPY_OR_MARK_WITH_EVACUATION
1192 #define COPY_OR_MARK_CONCURRENT
1193 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_no_evacuation
1194 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_no_evacuation
1195 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_no_evacuation
1196 #include "sgen-marksweep-drain-gray-stack.h"
1198 #undef COPY_OR_MARK_CONCURRENT
1199 #define COPY_OR_MARK_CONCURRENT_WITH_EVACUATION
1200 #define COPY_OR_MARK_FUNCTION_NAME major_copy_or_mark_object_concurrent_with_evacuation
1201 #define SCAN_OBJECT_FUNCTION_NAME major_scan_object_concurrent_with_evacuation
1202 #define DRAIN_GRAY_STACK_FUNCTION_NAME drain_gray_stack_concurrent_with_evacuation
1203 #include "sgen-marksweep-drain-gray-stack.h"
1205 static inline gboolean
1206 major_is_evacuating (void)
1209 for (i = 0; i < num_block_obj_sizes; ++i) {
1210 if (evacuate_block_obj_sizes [i]) {
1219 drain_gray_stack (SgenGrayQueue *queue)
1221 if (major_is_evacuating ())
1222 return drain_gray_stack_with_evacuation (queue);
1224 return drain_gray_stack_no_evacuation (queue);
1228 drain_gray_stack_concurrent (SgenGrayQueue *queue)
1230 if (major_is_evacuating ())
1231 return drain_gray_stack_concurrent_with_evacuation (queue);
1233 return drain_gray_stack_concurrent_no_evacuation (queue);
1236 #include "sgen-marksweep-scan-object-concurrent.h"
1239 major_copy_or_mark_object_canonical (GCObject **ptr, SgenGrayQueue *queue)
1241 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1245 major_copy_or_mark_object_concurrent_canonical (GCObject **ptr, SgenGrayQueue *queue)
1247 major_copy_or_mark_object_concurrent_with_evacuation (ptr, *ptr, queue);
1251 major_copy_or_mark_object_concurrent_finish_canonical (GCObject **ptr, SgenGrayQueue *queue)
1253 major_copy_or_mark_object_with_evacuation (ptr, *ptr, queue);
1257 mark_pinned_objects_in_block (MSBlockInfo *block, size_t first_entry, size_t last_entry, SgenGrayQueue *queue)
1259 void **entry, **end;
1260 int last_index = -1;
1262 if (first_entry == last_entry)
1265 block->has_pinned = TRUE;
1267 entry = sgen_pinning_get_entry (first_entry);
1268 end = sgen_pinning_get_entry (last_entry);
1270 for (; entry < end; ++entry) {
1271 int index = MS_BLOCK_OBJ_INDEX (*entry, block);
1273 SGEN_ASSERT (9, index >= 0 && index < MS_BLOCK_FREE / block->obj_size, "invalid object %p index %d max-index %d", *entry, index, (int)(MS_BLOCK_FREE / block->obj_size));
1274 if (index == last_index)
1276 obj = MS_BLOCK_OBJ (block, index);
1277 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (obj, sgen_obj_get_descriptor (obj), block, queue);
1283 sweep_block_for_size (MSBlockInfo *block, int count, int obj_size)
1287 for (obj_index = 0; obj_index < count; ++obj_index) {
1289 void *obj = MS_BLOCK_OBJ_FOR_SIZE (block, obj_index, obj_size);
1291 MS_CALC_MARK_BIT (word, bit, obj);
1292 if (MS_MARK_BIT (block, word, bit)) {
1293 SGEN_ASSERT (9, MS_OBJ_ALLOCED (obj, block), "object %p not allocated", obj);
1295 /* an unmarked object */
1296 if (MS_OBJ_ALLOCED (obj, block)) {
1298 * FIXME: Merge consecutive
1299 * slots for lower reporting
1300 * overhead. Maybe memset
1301 * will also benefit?
1303 binary_protocol_empty (obj, obj_size);
1304 memset (obj, 0, obj_size);
1306 *(void**)obj = block->free_list;
1307 block->free_list = (void **)obj;
1312 static inline gboolean
1313 try_set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1315 gint32 old_state = SGEN_CAS (&block->state, new_state, expected_state);
1316 gboolean success = old_state == expected_state;
1318 binary_protocol_block_set_state (block, MS_BLOCK_SIZE, old_state, new_state);
1323 set_block_state (MSBlockInfo *block, gint32 new_state, gint32 expected_state)
1325 SGEN_ASSERT (6, block->state == expected_state, "Block state incorrect before set");
1326 block->state = new_state;
1330 * If `block` needs sweeping, sweep it and return TRUE. Otherwise return FALSE.
1332 * Sweeping means iterating through the block's slots and building the free-list from the
1333 * unmarked ones. They will also be zeroed. The mark bits will be reset.
1336 sweep_block (MSBlockInfo *block)
1339 void *reversed = NULL;
1342 switch (block->state) {
1343 case BLOCK_STATE_SWEPT:
1345 case BLOCK_STATE_MARKING:
1346 case BLOCK_STATE_CHECKING:
1347 SGEN_ASSERT (0, FALSE, "How did we get to sweep a block that's being marked or being checked?");
1349 case BLOCK_STATE_SWEEPING:
1350 /* FIXME: Do this more elegantly */
1353 case BLOCK_STATE_NEED_SWEEPING:
1354 if (!try_set_block_state (block, BLOCK_STATE_SWEEPING, BLOCK_STATE_NEED_SWEEPING))
1358 SGEN_ASSERT (0, FALSE, "Illegal block state");
1361 SGEN_ASSERT (6, block->state == BLOCK_STATE_SWEEPING, "How did we get here without setting state to sweeping?");
1363 count = MS_BLOCK_FREE / block->obj_size;
1365 block->free_list = NULL;
1367 /* Use inline instances specialized to constant sizes, this allows the compiler to replace the memset calls with inline code */
1368 // FIXME: Add more sizes
1369 switch (block->obj_size) {
1371 sweep_block_for_size (block, count, 16);
1374 sweep_block_for_size (block, count, block->obj_size);
1378 /* reset mark bits */
1379 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1381 /* Reverse free list so that it's in address order */
1383 while (block->free_list) {
1384 void *next = *(void**)block->free_list;
1385 *(void**)block->free_list = reversed;
1386 reversed = block->free_list;
1387 block->free_list = (void **)next;
1389 block->free_list = (void **)reversed;
1391 mono_memory_write_barrier ();
1393 set_block_state (block, BLOCK_STATE_SWEPT, BLOCK_STATE_SWEEPING);
1404 if (sizeof (mword) == sizeof (unsigned long))
1405 count += __builtin_popcountl (d);
1407 count += __builtin_popcount (d);
1417 /* statistics for evacuation */
1418 static size_t *sweep_slots_available;
1419 static size_t *sweep_slots_used;
1420 static size_t *sweep_num_blocks;
1422 static volatile size_t num_major_sections_before_sweep;
1423 static volatile size_t num_major_sections_freed_in_sweep;
1430 for (i = 0; i < num_block_obj_sizes; ++i)
1431 sweep_slots_available [i] = sweep_slots_used [i] = sweep_num_blocks [i] = 0;
1433 /* clear all the free lists */
1434 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1435 MSBlockInfo * volatile *free_blocks = free_block_lists [i];
1437 for (j = 0; j < num_block_obj_sizes; ++j)
1438 free_blocks [j] = NULL;
1442 static void sweep_finish (void);
1445 * If `wait` is TRUE and the block is currently being checked, this function will wait until
1446 * the checking has finished.
1448 * Returns whether the block is still there. If `wait` is FALSE, the return value will not
1449 * be correct, i.e. must not be used.
1452 ensure_block_is_checked_for_sweeping (int block_index, gboolean wait, gboolean *have_checked)
1455 gboolean have_live = FALSE;
1456 gboolean have_free = FALSE;
1463 SGEN_ASSERT (6, sweep_in_progress (), "Why do we call this function if there's no sweep in progress?");
1466 *have_checked = FALSE;
1469 tagged_block = *(void * volatile *)&allocated_blocks.data [block_index];
1473 if (BLOCK_IS_TAGGED_CHECKING (tagged_block)) {
1476 /* FIXME: do this more elegantly */
1481 if (SGEN_CAS_PTR (&allocated_blocks.data [block_index], BLOCK_TAG_CHECKING (tagged_block), tagged_block) != tagged_block)
1484 block = BLOCK_UNTAG (tagged_block);
1485 block_state = block->state;
1487 if (!sweep_in_progress ()) {
1488 SGEN_ASSERT (6, block_state != BLOCK_STATE_SWEEPING && block_state != BLOCK_STATE_CHECKING, "Invalid block state.");
1490 SGEN_ASSERT (6, block_state != BLOCK_STATE_NEED_SWEEPING, "Invalid block state.");
1493 switch (block_state) {
1494 case BLOCK_STATE_SWEPT:
1495 case BLOCK_STATE_NEED_SWEEPING:
1496 case BLOCK_STATE_SWEEPING:
1498 case BLOCK_STATE_MARKING:
1500 case BLOCK_STATE_CHECKING:
1501 SGEN_ASSERT (0, FALSE, "We set the CHECKING bit - how can the stage be CHECKING?");
1504 SGEN_ASSERT (0, FALSE, "Illegal block state");
1508 SGEN_ASSERT (6, block->state == BLOCK_STATE_MARKING, "When we sweep all blocks must start out marking.");
1509 set_block_state (block, BLOCK_STATE_CHECKING, BLOCK_STATE_MARKING);
1512 *have_checked = TRUE;
1514 block->has_pinned = block->pinned;
1516 block->is_to_space = FALSE;
1518 count = MS_BLOCK_FREE / block->obj_size;
1520 if (block->cardtable_mod_union) {
1521 sgen_card_table_free_mod_union (block->cardtable_mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
1522 block->cardtable_mod_union = NULL;
1525 /* Count marked objects in the block */
1526 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
1527 nused += bitcount (block->mark_words [i]);
1535 int obj_size_index = block->obj_size_index;
1536 gboolean has_pinned = block->has_pinned;
1538 set_block_state (block, BLOCK_STATE_NEED_SWEEPING, BLOCK_STATE_CHECKING);
1541 * FIXME: Go straight to SWEPT if there are no free slots. We need
1542 * to set the free slot list to NULL, though, and maybe update some
1546 sweep_block (block);
1549 ++sweep_num_blocks [obj_size_index];
1550 sweep_slots_used [obj_size_index] += nused;
1551 sweep_slots_available [obj_size_index] += count;
1555 * If there are free slots in the block, add
1556 * the block to the corresponding free list.
1559 MSBlockInfo * volatile *free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1562 SGEN_ASSERT (6, block->free_list, "How do we not have a free list when there are free slots?");
1564 add_free_block (free_blocks, obj_size_index, block);
1567 /* FIXME: Do we need the heap boundaries while we do nursery collections? */
1568 update_heap_boundaries_for_block (block);
1571 * Blocks without live objects are removed from the
1572 * block list and freed.
1574 SGEN_ASSERT (6, block_index < allocated_blocks.next_slot, "How did the number of blocks shrink?");
1575 SGEN_ASSERT (6, allocated_blocks.data [block_index] == BLOCK_TAG_CHECKING (tagged_block), "How did the block move?");
1577 binary_protocol_empty (MS_BLOCK_OBJ (block, 0), (char*)MS_BLOCK_OBJ (block, count) - (char*)MS_BLOCK_OBJ (block, 0));
1578 ms_free_block (block);
1580 SGEN_ATOMIC_ADD_P (num_major_sections, -1);
1582 tagged_block = NULL;
1586 allocated_blocks.data [block_index] = tagged_block;
1587 return !!tagged_block;
1591 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
1594 int num_blocks = num_major_sections_before_sweep;
1596 SGEN_ASSERT (0, sweep_in_progress (), "Sweep thread called with wrong state");
1597 SGEN_ASSERT (0, num_blocks <= allocated_blocks.next_slot, "How did we lose blocks?");
1600 * We traverse the block array from high to low. Nursery collections will have to
1601 * cooperate with the sweep thread to finish sweeping, and they will traverse from
1602 * low to high, to avoid constantly colliding on the same blocks.
1604 for (block_index = num_blocks - 1; block_index >= 0; --block_index) {
1605 gboolean have_checked;
1608 * The block might have been freed by another thread doing some checking
1611 if (!ensure_block_is_checked_for_sweeping (block_index, TRUE, &have_checked))
1612 ++num_major_sections_freed_in_sweep;
1615 while (!try_set_sweep_state (SWEEP_STATE_COMPACTING, SWEEP_STATE_SWEEPING)) {
1617 * The main GC thread is currently iterating over the block array to help us
1618 * finish the sweep. We have already finished, but we don't want to mess up
1619 * that iteration, so we just wait for it.
1624 if (SGEN_MAX_ASSERT_LEVEL >= 6) {
1625 for (block_index = num_blocks; block_index < allocated_blocks.next_slot; ++block_index) {
1626 MSBlockInfo *block = BLOCK_UNTAG (allocated_blocks.data [block_index]);
1627 SGEN_ASSERT (6, block && block->state == BLOCK_STATE_SWEPT, "How did a new block to be swept get added while swept?");
1631 sgen_pointer_queue_remove_nulls (&allocated_blocks);
1632 mono_memory_barrier ();
1644 for (i = 0; i < num_block_obj_sizes; ++i) {
1645 float usage = (float)sweep_slots_used [i] / (float)sweep_slots_available [i];
1646 if (sweep_num_blocks [i] > 5 && usage < evacuation_threshold) {
1647 evacuate_block_obj_sizes [i] = TRUE;
1649 g_print ("slot size %d - %d of %d used\n",
1650 block_obj_sizes [i], slots_used [i], slots_available [i]);
1653 evacuate_block_obj_sizes [i] = FALSE;
1657 set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
1663 set_sweep_state (SWEEP_STATE_SWEEPING, SWEEP_STATE_NEED_SWEEPING);
1667 SGEN_ASSERT (0, num_major_sections == allocated_blocks.next_slot, "We don't know how many blocks we have?");
1669 num_major_sections_before_sweep = num_major_sections;
1670 num_major_sections_freed_in_sweep = 0;
1672 SGEN_ASSERT (0, !sweep_job, "We haven't finished the last sweep?");
1673 if (concurrent_sweep) {
1674 sweep_job = sgen_thread_pool_job_alloc ("sweep", sweep_job_func, sizeof (SgenThreadPoolJob));
1675 sgen_thread_pool_job_enqueue (sweep_job);
1677 sweep_job_func (NULL, NULL);
1682 major_have_swept (void)
1684 return sweep_state == SWEEP_STATE_SWEPT;
1687 static int count_pinned_ref;
1688 static int count_pinned_nonref;
1689 static int count_nonpinned_ref;
1690 static int count_nonpinned_nonref;
1693 count_nonpinned_callback (GCObject *obj, size_t size, void *data)
1695 GCVTable vtable = LOAD_VTABLE (obj);
1697 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1698 ++count_nonpinned_ref;
1700 ++count_nonpinned_nonref;
1704 count_pinned_callback (GCObject *obj, size_t size, void *data)
1706 GCVTable vtable = LOAD_VTABLE (obj);
1708 if (SGEN_VTABLE_HAS_REFERENCES (vtable))
1711 ++count_pinned_nonref;
1714 static G_GNUC_UNUSED void
1715 count_ref_nonref_objs (void)
1719 count_pinned_ref = 0;
1720 count_pinned_nonref = 0;
1721 count_nonpinned_ref = 0;
1722 count_nonpinned_nonref = 0;
1724 major_iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, count_nonpinned_callback, NULL);
1725 major_iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, count_pinned_callback, NULL);
1727 total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1729 g_print ("ref: %d pinned %d non-pinned non-ref: %d pinned %d non-pinned -- %.1f\n",
1730 count_pinned_ref, count_nonpinned_ref,
1731 count_pinned_nonref, count_nonpinned_nonref,
1732 (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1736 ms_calculate_block_obj_sizes (double factor, int *arr)
1743 * Have every possible slot size starting with the minimal
1744 * object size up to and including four times that size. Then
1745 * proceed by increasing geometrically with the given factor.
1748 for (int size = SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size <= 4 * SGEN_CLIENT_MINIMUM_OBJECT_SIZE; size += SGEN_ALLOC_ALIGN) {
1750 arr [num_sizes] = size;
1754 target_size = (double)last_size;
1757 int target_count = (int)floor (MS_BLOCK_FREE / target_size);
1758 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1760 if (size != last_size) {
1762 arr [num_sizes] = size;
1767 target_size *= factor;
1768 } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1773 /* only valid during minor collections */
1774 static mword old_num_major_sections;
1777 major_start_nursery_collection (void)
1779 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1780 consistency_check ();
1783 old_num_major_sections = num_major_sections;
1787 major_finish_nursery_collection (void)
1789 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1790 consistency_check ();
1795 major_start_major_collection (void)
1800 major_finish_sweep_checking ();
1803 * Clear the free lists for block sizes where we do evacuation. For those block
1804 * sizes we will have to allocate new blocks.
1806 for (i = 0; i < num_block_obj_sizes; ++i) {
1807 if (!evacuate_block_obj_sizes [i])
1810 free_block_lists [0][i] = NULL;
1811 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1815 binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
1817 /* Sweep all unswept blocks and set them to MARKING */
1818 FOREACH_BLOCK_NO_LOCK (block) {
1820 sweep_block (block);
1821 SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
1822 set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
1823 } END_FOREACH_BLOCK_NO_LOCK;
1826 binary_protocol_sweep_end (GENERATION_OLD, TRUE);
1828 set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
1832 major_finish_major_collection (ScannedObjectCounts *counts)
1834 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
1835 if (binary_protocol_is_enabled ()) {
1836 counts->num_scanned_objects = scanned_objects_list.next_slot;
1838 sgen_pointer_queue_sort_uniq (&scanned_objects_list);
1839 counts->num_unique_scanned_objects = scanned_objects_list.next_slot;
1841 sgen_pointer_queue_clear (&scanned_objects_list);
1846 #if SIZEOF_VOID_P != 8
1848 compare_pointers (const void *va, const void *vb) {
1849 char *a = *(char**)va, *b = *(char**)vb;
1859 * This is called with sweep completed and the world stopped.
1862 major_free_swept_blocks (size_t allowance)
1864 /* FIXME: This is probably too much. It's assuming all objects are small. */
1865 size_t section_reserve = allowance / MS_BLOCK_SIZE;
1867 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Sweeping must have finished before freeing blocks");
1871 * sgen_free_os_memory () asserts in mono_vfree () because windows doesn't like freeing the middle of
1872 * a VirtualAlloc ()-ed block.
1877 #if SIZEOF_VOID_P != 8
1879 int i, num_empty_blocks_orig, num_blocks, arr_length;
1881 void **empty_block_arr;
1882 void **rebuild_next;
1884 if (num_empty_blocks <= section_reserve)
1886 SGEN_ASSERT (0, num_empty_blocks > 0, "section reserve can't be negative");
1888 num_empty_blocks_orig = num_empty_blocks;
1889 empty_block_arr = (void**)sgen_alloc_internal_dynamic (sizeof (void*) * num_empty_blocks_orig,
1890 INTERNAL_MEM_MS_BLOCK_INFO_SORT, FALSE);
1891 if (!empty_block_arr)
1895 for (block = empty_blocks; block; block = *(void**)block)
1896 empty_block_arr [i++] = block;
1897 SGEN_ASSERT (0, i == num_empty_blocks, "empty block count wrong");
1899 sgen_qsort (empty_block_arr, num_empty_blocks, sizeof (void*), compare_pointers);
1902 * We iterate over the free blocks, trying to find MS_BLOCK_ALLOC_NUM
1903 * contiguous ones. If we do, we free them. If that's not enough to get to
1904 * section_reserve, we halve the number of contiguous blocks we're looking
1905 * for and have another go, until we're done with looking for pairs of
1906 * blocks, at which point we give up and go to the fallback.
1908 arr_length = num_empty_blocks_orig;
1909 num_blocks = MS_BLOCK_ALLOC_NUM;
1910 while (num_empty_blocks > section_reserve && num_blocks > 1) {
1915 for (i = 0; i < arr_length; ++i) {
1917 void *block = empty_block_arr [i];
1918 SGEN_ASSERT (6, block, "we're not shifting correctly");
1920 empty_block_arr [dest] = block;
1922 * This is not strictly necessary, but we're
1925 empty_block_arr [i] = NULL;
1934 SGEN_ASSERT (6, first >= 0 && d > first, "algorithm is wrong");
1936 if ((char*)block != ((char*)empty_block_arr [d-1]) + MS_BLOCK_SIZE) {
1941 if (d + 1 - first == num_blocks) {
1943 * We found num_blocks contiguous blocks. Free them
1944 * and null their array entries. As an optimization
1945 * we could, instead of nulling the entries, shift
1946 * the following entries over to the left, while
1950 sgen_free_os_memory (empty_block_arr [first], MS_BLOCK_SIZE * num_blocks, SGEN_ALLOC_HEAP);
1951 for (j = first; j <= d; ++j)
1952 empty_block_arr [j] = NULL;
1956 num_empty_blocks -= num_blocks;
1958 stat_major_blocks_freed += num_blocks;
1959 if (num_blocks == MS_BLOCK_ALLOC_NUM)
1960 stat_major_blocks_freed_ideal += num_blocks;
1962 stat_major_blocks_freed_less_ideal += num_blocks;
1967 SGEN_ASSERT (6, dest <= i && dest <= arr_length, "array length is off");
1969 SGEN_ASSERT (6, arr_length == num_empty_blocks, "array length is off");
1974 /* rebuild empty_blocks free list */
1975 rebuild_next = (void**)&empty_blocks;
1976 for (i = 0; i < arr_length; ++i) {
1977 void *block = empty_block_arr [i];
1978 SGEN_ASSERT (6, block, "we're missing blocks");
1979 *rebuild_next = block;
1980 rebuild_next = (void**)block;
1982 *rebuild_next = NULL;
1985 sgen_free_internal_dynamic (empty_block_arr, sizeof (void*) * num_empty_blocks_orig, INTERNAL_MEM_MS_BLOCK_INFO_SORT);
1988 SGEN_ASSERT (0, num_empty_blocks >= 0, "we freed more blocks than we had in the first place?");
1992 * This is our threshold. If there's not more empty than used blocks, we won't
1993 * release uncontiguous blocks, in fear of fragmenting the address space.
1995 if (num_empty_blocks <= num_major_sections)
1999 while (num_empty_blocks > section_reserve) {
2000 void *next = *(void**)empty_blocks;
2001 sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE, SGEN_ALLOC_HEAP);
2002 empty_blocks = next;
2004 * Needs not be atomic because this is running
2009 ++stat_major_blocks_freed;
2010 #if SIZEOF_VOID_P != 8
2011 ++stat_major_blocks_freed_individual;
2017 major_pin_objects (SgenGrayQueue *queue)
2021 FOREACH_BLOCK_NO_LOCK (block) {
2022 size_t first_entry, last_entry;
2023 SGEN_ASSERT (6, block_is_swept_or_marking (block), "All blocks must be swept when we're pinning.");
2024 sgen_find_optimized_pin_queue_area (MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SKIP, MS_BLOCK_FOR_BLOCK_INFO (block) + MS_BLOCK_SIZE,
2025 &first_entry, &last_entry);
2026 mark_pinned_objects_in_block (block, first_entry, last_entry, queue);
2027 } END_FOREACH_BLOCK_NO_LOCK;
2031 major_init_to_space (void)
2036 major_report_pinned_memory_usage (void)
2038 g_assert_not_reached ();
2042 major_get_used_size (void)
2048 * We're holding the GC lock, but the sweep thread might be running. Make sure it's
2049 * finished, then we can iterate over the block array.
2051 major_finish_sweep_checking ();
2053 FOREACH_BLOCK_NO_LOCK_CONDITION (TRUE, block) {
2054 int count = MS_BLOCK_FREE / block->obj_size;
2056 size += count * block->obj_size;
2057 for (iter = block->free_list; iter; iter = (void**)*iter)
2058 size -= block->obj_size;
2059 } END_FOREACH_BLOCK_NO_LOCK;
2064 /* FIXME: return number of bytes, not of sections */
2066 get_num_major_sections (void)
2068 return num_major_sections;
2072 * Returns the number of bytes in blocks that were present when the last sweep was
2073 * initiated, and were not freed during the sweep. They are the basis for calculating the
2077 get_bytes_survived_last_sweep (void)
2079 SGEN_ASSERT (0, sweep_state == SWEEP_STATE_SWEPT, "Can only query unswept sections after sweep");
2080 return (num_major_sections_before_sweep - num_major_sections_freed_in_sweep) * MS_BLOCK_SIZE;
2084 major_handle_gc_param (const char *opt)
2086 if (g_str_has_prefix (opt, "evacuation-threshold=")) {
2087 const char *arg = strchr (opt, '=') + 1;
2088 int percentage = atoi (arg);
2089 if (percentage < 0 || percentage > 100) {
2090 fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
2093 evacuation_threshold = (float)percentage / 100.0f;
2095 } else if (!strcmp (opt, "lazy-sweep")) {
2098 } else if (!strcmp (opt, "no-lazy-sweep")) {
2101 } else if (!strcmp (opt, "concurrent-sweep")) {
2102 concurrent_sweep = TRUE;
2104 } else if (!strcmp (opt, "no-concurrent-sweep")) {
2105 concurrent_sweep = FALSE;
2113 major_print_gc_param_usage (void)
2117 " evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
2118 " (no-)lazy-sweep\n"
2119 " (no-)concurrent-sweep\n"
2124 * This callback is used to clear cards, move cards to the shadow table and do counting.
2127 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
2130 gboolean has_references;
2132 major_finish_sweep_checking ();
2133 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2135 callback ((mword)MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE);
2136 } END_FOREACH_BLOCK_NO_LOCK;
2139 #ifdef HEAVY_STATISTICS
2140 extern guint64 marked_cards;
2141 extern guint64 scanned_cards;
2142 extern guint64 scanned_objects;
2143 extern guint64 remarked_cards;
2146 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
2148 * MS blocks are 16K aligned.
2149 * Cardtables are 4K aligned, at least.
2150 * This means that the cardtable of a given block is 32 bytes aligned.
2153 initial_skip_card (guint8 *card_data)
2155 mword *cards = (mword*)card_data;
2158 for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
2164 if (i == CARD_WORDS_PER_BLOCK)
2165 return card_data + CARDS_PER_BLOCK;
2167 #if defined(__i386__) && defined(__GNUC__)
2168 return card_data + i * 4 + (__builtin_ffs (card) - 1) / 8;
2169 #elif defined(__x86_64__) && defined(__GNUC__)
2170 return card_data + i * 8 + (__builtin_ffsll (card) - 1) / 8;
2171 #elif defined(__s390x__) && defined(__GNUC__)
2172 return card_data + i * 8 + (__builtin_ffsll (GUINT64_TO_LE(card)) - 1) / 8;
2174 for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
2176 return &card_data [i];
2182 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
2183 #define MS_BLOCK_OBJ_FAST(b,os,i) ((b) + MS_BLOCK_SKIP + (os) * (i))
2184 #define MS_OBJ_ALLOCED_FAST(o,b) (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
2187 scan_card_table_for_block (MSBlockInfo *block, gboolean mod_union, ScanCopyContext ctx)
2189 SgenGrayQueue *queue = ctx.queue;
2190 ScanObjectFunc scan_func = ctx.ops->scan_object;
2191 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
2192 guint8 cards_copy [CARDS_PER_BLOCK];
2194 gboolean small_objects;
2197 guint8 *card_data, *card_base;
2198 guint8 *card_data_end;
2199 char *scan_front = NULL;
2201 block_obj_size = block->obj_size;
2202 small_objects = block_obj_size < CARD_SIZE_IN_BYTES;
2204 block_start = MS_BLOCK_FOR_BLOCK_INFO (block);
2207 * This is safe in face of card aliasing for the following reason:
2209 * Major blocks are 16k aligned, or 32 cards aligned.
2210 * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
2211 * sizes, they won't overflow the cardtable overlap modulus.
2214 card_data = card_base = block->cardtable_mod_union;
2216 * This happens when the nursery collection that precedes finishing
2217 * the concurrent collection allocates new major blocks.
2222 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
2223 card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
2225 if (!sgen_card_table_get_card_data (cards_copy, (mword)block_start, CARDS_PER_BLOCK))
2227 card_data = card_base = cards_copy;
2230 card_data_end = card_data + CARDS_PER_BLOCK;
2232 card_data += MS_BLOCK_SKIP >> CARD_BITS;
2234 card_data = initial_skip_card (card_data);
2235 while (card_data < card_data_end) {
2236 size_t card_index, first_object_index;
2239 char *first_obj, *obj;
2241 HEAVY_STAT (++scanned_cards);
2248 card_index = card_data - card_base;
2249 start = (char*)(block_start + card_index * CARD_SIZE_IN_BYTES);
2250 end = start + CARD_SIZE_IN_BYTES;
2252 if (!block_is_swept_or_marking (block))
2253 sweep_block (block);
2255 HEAVY_STAT (++marked_cards);
2258 sgen_card_table_prepare_card_for_scanning (card_data);
2261 * If the card we're looking at starts at or in the block header, we
2262 * must start at the first object in the block, without calculating
2263 * the index of the object we're hypothetically starting at, because
2264 * it would be negative.
2266 if (card_index <= (MS_BLOCK_SKIP >> CARD_BITS))
2267 first_object_index = 0;
2269 first_object_index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
2271 obj = first_obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, first_object_index);
2273 binary_protocol_card_scan (first_obj, end - first_obj);
2276 if (obj < scan_front || !MS_OBJ_ALLOCED_FAST (obj, block_start))
2280 /* FIXME: do this more efficiently */
2282 MS_CALC_MARK_BIT (w, b, obj);
2283 if (!MS_MARK_BIT (block, w, b))
2287 GCObject *object = (GCObject*)obj;
2289 if (small_objects) {
2290 HEAVY_STAT (++scanned_objects);
2291 scan_func (object, sgen_obj_get_descriptor (object), queue);
2293 size_t offset = sgen_card_table_get_card_offset (obj, block_start);
2294 sgen_cardtable_scan_object (object, block_obj_size, card_base + offset, mod_union, ctx);
2297 obj += block_obj_size;
2298 g_assert (scan_front <= obj);
2302 HEAVY_STAT (if (*card_data) ++remarked_cards);
2307 card_data = card_base + sgen_card_table_get_card_offset (obj, block_start);
2312 major_scan_card_table (gboolean mod_union, ScanCopyContext ctx)
2315 gboolean has_references;
2317 if (!concurrent_mark)
2318 g_assert (!mod_union);
2320 major_finish_sweep_checking ();
2321 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2322 #ifdef PREFETCH_CARDS
2323 int prefetch_index = __index + 6;
2324 if (prefetch_index < allocated_blocks.next_slot) {
2325 MSBlockInfo *prefetch_block = BLOCK_UNTAG (allocated_blocks.data [prefetch_index]);
2326 guint8 *prefetch_cards = sgen_card_table_get_card_scan_address ((mword)MS_BLOCK_FOR_BLOCK_INFO (prefetch_block));
2327 PREFETCH_READ (prefetch_block);
2328 PREFETCH_WRITE (prefetch_cards);
2329 PREFETCH_WRITE (prefetch_cards + 32);
2333 if (!has_references)
2336 scan_card_table_for_block (block, mod_union, ctx);
2337 } END_FOREACH_BLOCK_NO_LOCK;
2341 major_count_cards (long long *num_total_cards, long long *num_marked_cards)
2344 gboolean has_references;
2345 long long total_cards = 0;
2346 long long marked_cards = 0;
2348 if (sweep_in_progress ()) {
2349 *num_total_cards = -1;
2350 *num_marked_cards = -1;
2354 FOREACH_BLOCK_HAS_REFERENCES_NO_LOCK (block, has_references) {
2355 guint8 *cards = sgen_card_table_get_card_scan_address ((mword) MS_BLOCK_FOR_BLOCK_INFO (block));
2358 if (!has_references)
2361 total_cards += CARDS_PER_BLOCK;
2362 for (i = 0; i < CARDS_PER_BLOCK; ++i) {
2366 } END_FOREACH_BLOCK_NO_LOCK;
2368 *num_total_cards = total_cards;
2369 *num_marked_cards = marked_cards;
2373 update_cardtable_mod_union (void)
2377 FOREACH_BLOCK_NO_LOCK (block) {
2379 guint8 *mod_union = get_cardtable_mod_union_for_block (block, TRUE);
2380 sgen_card_table_update_mod_union (mod_union, MS_BLOCK_FOR_BLOCK_INFO (block), MS_BLOCK_SIZE, &num_cards);
2381 SGEN_ASSERT (6, num_cards == CARDS_PER_BLOCK, "Number of cards calculation is wrong");
2382 } END_FOREACH_BLOCK_NO_LOCK;
2385 #undef pthread_create
2388 post_param_init (SgenMajorCollector *collector)
2390 collector->sweeps_lazily = lazy_sweep;
2391 collector->needs_thread_pool = concurrent_mark || concurrent_sweep;
2395 sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurrent)
2399 sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
2401 num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
2402 block_obj_sizes = (int *)sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2403 ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
2405 evacuate_block_obj_sizes = (gboolean *)sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2406 for (i = 0; i < num_block_obj_sizes; ++i)
2407 evacuate_block_obj_sizes [i] = FALSE;
2409 sweep_slots_available = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2410 sweep_slots_used = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2411 sweep_num_blocks = (size_t *)sgen_alloc_internal_dynamic (sizeof (size_t) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2416 g_print ("block object sizes:\n");
2417 for (i = 0; i < num_block_obj_sizes; ++i)
2418 g_print ("%d\n", block_obj_sizes [i]);
2422 for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
2423 free_block_lists [i] = (MSBlockInfo *volatile *)sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES, TRUE);
2425 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2426 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2427 for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2428 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2430 mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced);
2431 mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed);
2432 mono_counters_register ("# major blocks lazy swept", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_lazy_swept);
2433 #if SIZEOF_VOID_P != 8
2434 mono_counters_register ("# major blocks freed ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_ideal);
2435 mono_counters_register ("# major blocks freed less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_less_ideal);
2436 mono_counters_register ("# major blocks freed individually", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_freed_individual);
2437 mono_counters_register ("# major blocks allocated less ideally", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_major_blocks_alloced_less_ideal);
2440 collector->section_size = MAJOR_SECTION_SIZE;
2442 concurrent_mark = is_concurrent;
2443 collector->is_concurrent = is_concurrent;
2444 collector->needs_thread_pool = is_concurrent || concurrent_sweep;
2445 collector->get_and_reset_num_major_objects_marked = major_get_and_reset_num_major_objects_marked;
2446 collector->supports_cardtable = TRUE;
2448 collector->alloc_heap = major_alloc_heap;
2449 collector->is_object_live = major_is_object_live;
2450 collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2451 collector->alloc_degraded = major_alloc_degraded;
2453 collector->alloc_object = major_alloc_object;
2454 collector->free_pinned_object = free_pinned_object;
2455 collector->iterate_objects = major_iterate_objects;
2456 collector->free_non_pinned_object = major_free_non_pinned_object;
2457 collector->pin_objects = major_pin_objects;
2458 collector->pin_major_object = pin_major_object;
2459 collector->scan_card_table = major_scan_card_table;
2460 collector->iterate_live_block_ranges = major_iterate_live_block_ranges;
2461 if (is_concurrent) {
2462 collector->update_cardtable_mod_union = update_cardtable_mod_union;
2463 collector->get_cardtable_mod_union_for_reference = major_get_cardtable_mod_union_for_reference;
2465 collector->init_to_space = major_init_to_space;
2466 collector->sweep = major_sweep;
2467 collector->have_swept = major_have_swept;
2468 collector->finish_sweeping = major_finish_sweep_checking;
2469 collector->free_swept_blocks = major_free_swept_blocks;
2470 collector->check_scan_starts = major_check_scan_starts;
2471 collector->dump_heap = major_dump_heap;
2472 collector->get_used_size = major_get_used_size;
2473 collector->start_nursery_collection = major_start_nursery_collection;
2474 collector->finish_nursery_collection = major_finish_nursery_collection;
2475 collector->start_major_collection = major_start_major_collection;
2476 collector->finish_major_collection = major_finish_major_collection;
2477 collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2478 collector->ptr_is_from_pinned_alloc = ptr_is_from_pinned_alloc;
2479 collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2480 collector->get_num_major_sections = get_num_major_sections;
2481 collector->get_bytes_survived_last_sweep = get_bytes_survived_last_sweep;
2482 collector->handle_gc_param = major_handle_gc_param;
2483 collector->print_gc_param_usage = major_print_gc_param_usage;
2484 collector->post_param_init = post_param_init;
2485 collector->is_valid_object = major_is_valid_object;
2486 collector->describe_pointer = major_describe_pointer;
2487 collector->count_cards = major_count_cards;
2489 collector->major_ops_serial.copy_or_mark_object = major_copy_or_mark_object_canonical;
2490 collector->major_ops_serial.scan_object = major_scan_object_with_evacuation;
2491 collector->major_ops_serial.drain_gray_stack = drain_gray_stack;
2492 if (is_concurrent) {
2493 collector->major_ops_concurrent_start.copy_or_mark_object = major_copy_or_mark_object_concurrent_canonical;
2494 collector->major_ops_concurrent_start.scan_object = major_scan_object_concurrent_with_evacuation;
2495 collector->major_ops_concurrent_start.drain_gray_stack = drain_gray_stack_concurrent;
2497 collector->major_ops_concurrent_finish.copy_or_mark_object = major_copy_or_mark_object_concurrent_finish_canonical;
2498 collector->major_ops_concurrent_finish.scan_object = major_scan_object_with_evacuation;
2499 collector->major_ops_concurrent_finish.scan_vtype = major_scan_vtype_concurrent_finish;
2500 collector->major_ops_concurrent_finish.drain_gray_stack = drain_gray_stack;
2503 #ifdef HEAVY_STATISTICS
2504 mono_counters_register ("Optimized copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy);
2505 mono_counters_register ("Optimized copy nursery", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery);
2506 mono_counters_register ("Optimized copy nursery forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_forwarded);
2507 mono_counters_register ("Optimized copy nursery pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_nursery_pinned);
2508 mono_counters_register ("Optimized copy major", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major);
2509 mono_counters_register ("Optimized copy major small fast", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_fast);
2510 mono_counters_register ("Optimized copy major small slow", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_slow);
2511 mono_counters_register ("Optimized copy major small evacuate", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_small_evacuate);
2512 mono_counters_register ("Optimized copy major large", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_copy_major_large);
2513 mono_counters_register ("Optimized major scan", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan);
2514 mono_counters_register ("Optimized major scan no refs", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_optimized_major_scan_no_refs);
2516 mono_counters_register ("Gray stack drain loops", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_loops);
2517 mono_counters_register ("Gray stack prefetch fills", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fills);
2518 mono_counters_register ("Gray stack prefetch failures", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_drain_prefetch_fill_failures);
2521 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2522 mono_os_mutex_init (&scanned_objects_list_lock);
2525 SGEN_ASSERT (0, SGEN_MAX_SMALL_OBJ_SIZE <= MS_BLOCK_FREE / 2, "MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2");
2527 /*cardtable requires major pages to be 8 cards aligned*/
2528 g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2532 sgen_marksweep_init (SgenMajorCollector *collector)
2534 sgen_marksweep_init_internal (collector, FALSE);
2538 sgen_marksweep_conc_init (SgenMajorCollector *collector)
2540 sgen_marksweep_init_internal (collector, TRUE);