Merge branch 'master' of github.com:mono/mono
[mono.git] / mono / metadata / sgen-marksweep.c
1 /*
2  * sgen-marksweep.c: Simple generational GC.
3  *
4  * Author:
5  *      Mark Probst <mark.probst@gmail.com>
6  *
7  * Copyright 2009-2010 Novell, Inc.
8  * 
9  * Permission is hereby granted, free of charge, to any person obtaining
10  * a copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 #ifdef HAVE_SGEN_GC
30
31 #include <math.h>
32 #include <errno.h>
33
34 #include "utils/mono-counters.h"
35 #include "utils/mono-semaphore.h"
36 #include "utils/mono-time.h"
37 #include "metadata/object-internals.h"
38 #include "metadata/profiler-private.h"
39
40 #include "metadata/sgen-gc.h"
41 #include "metadata/sgen-protocol.h"
42 #include "metadata/sgen-cardtable.h"
43 #include "metadata/gc-internal.h"
44
45 #define MS_BLOCK_SIZE   (16*1024)
46 #define MS_BLOCK_SIZE_SHIFT     14
47 #define MAJOR_SECTION_SIZE      MS_BLOCK_SIZE
48 #define CARDS_PER_BLOCK (MS_BLOCK_SIZE / CARD_SIZE_IN_BYTES)
49
50 #ifdef FIXED_HEAP
51 #define MS_DEFAULT_HEAP_NUM_BLOCKS      (32 * 1024) /* 512 MB */
52 #endif
53
54 /*
55  * Don't allocate single blocks, but alloc a contingent of this many
56  * blocks in one swoop.
57  */
58 #define MS_BLOCK_ALLOC_NUM      32
59
60 /*
61  * Number of bytes before the first object in a block.  At the start
62  * of a block is the MSBlockHeader, then opional padding, then come
63  * the objects, so this must be >= sizeof (MSBlockHeader).
64  */
65 #ifdef FIXED_HEAP
66 #define MS_BLOCK_SKIP   0
67 #else
68 #define MS_BLOCK_SKIP   16
69 #endif
70
71 #define MS_BLOCK_FREE   (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
72
73 #define MS_NUM_MARK_WORDS       ((MS_BLOCK_SIZE / SGEN_ALLOC_ALIGN + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
74
75 #if SGEN_MAX_SMALL_OBJ_SIZE > MS_BLOCK_FREE / 2
76 #error MAX_SMALL_OBJ_SIZE must be at most MS_BLOCK_FREE / 2
77 #endif
78
79 typedef struct _MSBlockInfo MSBlockInfo;
80 struct _MSBlockInfo {
81         int obj_size;
82         int obj_size_index;
83         int pin_queue_num_entries;
84         unsigned int pinned : 1;
85         unsigned int has_references : 1;
86         unsigned int has_pinned : 1;    /* means cannot evacuate */
87         unsigned int is_to_space : 1;
88 #ifdef FIXED_HEAP
89         unsigned int used : 1;
90         unsigned int zeroed : 1;
91 #endif
92         MSBlockInfo *next;
93         char *block;
94         void **free_list;
95         MSBlockInfo *next_free;
96         void **pin_queue_start;
97         mword mark_words [MS_NUM_MARK_WORDS];
98 };
99
100 #ifdef FIXED_HEAP
101 static int ms_heap_num_blocks = MS_DEFAULT_HEAP_NUM_BLOCKS;
102
103 #define ms_heap_start   nursery_end
104 static char *ms_heap_end;
105
106 #define MS_PTR_IN_SMALL_MAJOR_HEAP(p)   ((char*)(p) >= ms_heap_start && (char*)(p) < ms_heap_end)
107
108 /* array of all all block infos in the system */
109 static MSBlockInfo *block_infos;
110 #endif
111
112 #define MS_BLOCK_OBJ(b,i)               ((b)->block + MS_BLOCK_SKIP + (b)->obj_size * (i))
113 #define MS_BLOCK_DATA_FOR_OBJ(o)        ((char*)((mword)(o) & ~(mword)(MS_BLOCK_SIZE - 1)))
114
115 #ifdef FIXED_HEAP
116 #define MS_BLOCK_FOR_OBJ(o)             (&block_infos [(mword)((char*)(o) - ms_heap_start) >> MS_BLOCK_SIZE_SHIFT])
117 #else
118 typedef struct {
119         MSBlockInfo *info;
120 } MSBlockHeader;
121
122 #define MS_BLOCK_FOR_OBJ(o)             (((MSBlockHeader*)MS_BLOCK_DATA_FOR_OBJ ((o)))->info)
123 #endif
124
125 #define MS_BLOCK_OBJ_INDEX(o,b) (((char*)(o) - ((b)->block + MS_BLOCK_SKIP)) / (b)->obj_size)
126
127 #define MS_CALC_MARK_BIT(w,b,o)         do {                            \
128                 int i = ((char*)(o) - MS_BLOCK_DATA_FOR_OBJ ((o))) >> SGEN_ALLOC_ALIGN_BITS; \
129                 if (sizeof (mword) == 4) {                              \
130                         (w) = i >> 5;                                   \
131                         (b) = i & 31;                                   \
132                 } else {                                                \
133                         (w) = i >> 6;                                   \
134                         (b) = i & 63;                                   \
135                 }                                                       \
136         } while (0)
137
138 #define MS_MARK_BIT(bl,w,b)     ((bl)->mark_words [(w)] & (1L << (b)))
139 #define MS_SET_MARK_BIT(bl,w,b) ((bl)->mark_words [(w)] |= (1L << (b)))
140 #define MS_PAR_SET_MARK_BIT(was_marked,bl,w,b)  do {                    \
141                 mword __old = (bl)->mark_words [(w)];                   \
142                 mword __bitmask = 1L << (b);                            \
143                 if (__old & __bitmask) {                                \
144                         was_marked = TRUE;                              \
145                         break;                                          \
146                 }                                                       \
147                 if (SGEN_CAS_PTR ((gpointer*)&(bl)->mark_words [(w)],   \
148                                                 (gpointer)(__old | __bitmask), \
149                                                 (gpointer)__old) ==     \
150                                 (gpointer)__old) {                      \
151                         was_marked = FALSE;                             \
152                         break;                                          \
153                 }                                                       \
154         } while (1)
155
156 #define MS_OBJ_ALLOCED(o,b)     (*(void**)(o) && (*(char**)(o) < (b)->block || *(char**)(o) >= (b)->block + MS_BLOCK_SIZE))
157
158 #define MS_BLOCK_OBJ_SIZE_FACTOR        (sqrt (2.0))
159
160 /*
161  * This way we can lookup block object size indexes for sizes up to
162  * 256 bytes with a single load.
163  */
164 #define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES      32
165
166 static int *block_obj_sizes;
167 static int num_block_obj_sizes;
168 static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
169
170 #define MS_BLOCK_FLAG_PINNED    1
171 #define MS_BLOCK_FLAG_REFS      2
172
173 #define MS_BLOCK_TYPE_MAX       4
174
175 #ifdef SGEN_PARALLEL_MARK
176 static LOCK_DECLARE (ms_block_list_mutex);
177 #define LOCK_MS_BLOCK_LIST pthread_mutex_lock (&ms_block_list_mutex)
178 #define UNLOCK_MS_BLOCK_LIST pthread_mutex_unlock (&ms_block_list_mutex)
179 #endif
180
181 /* we get this at init */
182 static int nursery_bits;
183 static char *nursery_start;
184 static char *nursery_end;
185
186 static gboolean *evacuate_block_obj_sizes;
187 static float evacuation_threshold = 0.666;
188
189 static gboolean concurrent_sweep = FALSE;
190 static gboolean have_swept;
191
192 #define ptr_in_nursery(p)       (SGEN_PTR_IN_NURSERY ((p), nursery_bits, nursery_start, nursery_end))
193
194 /* all allocated blocks in the system */
195 static MSBlockInfo *all_blocks;
196
197 #ifdef FIXED_HEAP
198 /* non-allocated block free-list */
199 static MSBlockInfo *empty_blocks = NULL;
200 #else
201 /* non-allocated block free-list */
202 static void *empty_blocks = NULL;
203 static int num_empty_blocks = 0;
204 #endif
205
206 #define FOREACH_BLOCK(bl)       for ((bl) = all_blocks; (bl); (bl) = (bl)->next) {
207 #define END_FOREACH_BLOCK       }
208
209 static int num_major_sections = 0;
210 /* one free block list for each block object size */
211 static MSBlockInfo **free_block_lists [MS_BLOCK_TYPE_MAX];
212
213 #ifdef SGEN_PARALLEL_MARK
214 #ifdef HAVE_KW_THREAD
215 static __thread MSBlockInfo ***workers_free_block_lists;
216 #else
217 static pthread_key_t workers_free_block_lists_key;
218 #endif
219 #endif
220
221 static long long stat_major_blocks_alloced = 0;
222 static long long stat_major_blocks_freed = 0;
223 static long long stat_major_objects_evacuated = 0;
224 static long long stat_time_wait_for_sweep = 0;
225 #ifdef SGEN_PARALLEL_MARK
226 static long long stat_slots_allocated_in_vain = 0;
227 #endif
228
229 static gboolean ms_sweep_in_progress = FALSE;
230 static pthread_t ms_sweep_thread;
231 static MonoSemType ms_sweep_cmd_semaphore;
232 static MonoSemType ms_sweep_done_semaphore;
233
234 static void
235 ms_signal_sweep_command (void)
236 {
237         if (!concurrent_sweep)
238                 return;
239
240         g_assert (!ms_sweep_in_progress);
241         ms_sweep_in_progress = TRUE;
242         MONO_SEM_POST (&ms_sweep_cmd_semaphore);
243 }
244
245 static void
246 ms_signal_sweep_done (void)
247 {
248         if (!concurrent_sweep)
249                 return;
250
251         MONO_SEM_POST (&ms_sweep_done_semaphore);
252 }
253
254 static void
255 ms_wait_for_sweep_done (void)
256 {
257         SGEN_TV_DECLARE (atv);
258         SGEN_TV_DECLARE (btv);
259         int result;
260
261         if (!concurrent_sweep)
262                 return;
263
264         if (!ms_sweep_in_progress)
265                 return;
266
267         SGEN_TV_GETTIME (atv);
268         while ((result = MONO_SEM_WAIT (&ms_sweep_done_semaphore)) != 0) {
269                 if (errno != EINTR)
270                         g_error ("MONO_SEM_WAIT");
271         }
272         SGEN_TV_GETTIME (btv);
273         stat_time_wait_for_sweep += SGEN_TV_ELAPSED_MS (atv, btv);
274
275         g_assert (ms_sweep_in_progress);
276         ms_sweep_in_progress = FALSE;
277 }
278
279 static int
280 ms_find_block_obj_size_index (int size)
281 {
282         int i;
283         DEBUG (9, g_assert (size <= SGEN_MAX_SMALL_OBJ_SIZE));
284         for (i = 0; i < num_block_obj_sizes; ++i)
285                 if (block_obj_sizes [i] >= size)
286                         return i;
287         g_assert_not_reached ();
288 }
289
290 #define FREE_BLOCKS_FROM(lists,p,r)     (lists [((p) ? MS_BLOCK_FLAG_PINNED : 0) | ((r) ? MS_BLOCK_FLAG_REFS : 0)])
291 #define FREE_BLOCKS(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
292 #ifdef SGEN_PARALLEL_MARK
293 #ifdef HAVE_KW_THREAD
294 #define FREE_BLOCKS_LOCAL(p,r)          (FREE_BLOCKS_FROM (workers_free_block_lists, (p), (r)))
295 #else
296 #define FREE_BLOCKS_LOCAL(p,r)          (FREE_BLOCKS_FROM (((MSBlockInfo***)(pthread_getspecific (workers_free_block_lists_key))), (p), (r)))
297 #endif
298 #else
299 //#define FREE_BLOCKS_LOCAL(p,r)                (FREE_BLOCKS_FROM (free_block_lists, (p), (r)))
300 #endif
301
302 #define MS_BLOCK_OBJ_SIZE_INDEX(s)                              \
303         (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ?      \
304          fast_block_obj_size_indexes [((s)+7)>>3] :             \
305          ms_find_block_obj_size_index ((s)))
306
307 #ifdef FIXED_HEAP
308 static void*
309 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
310 {
311         char *heap_start;
312         mword major_heap_size = ms_heap_num_blocks * MS_BLOCK_SIZE;
313         mword alloc_size = nursery_size + major_heap_size;
314         int i;
315
316         g_assert (ms_heap_num_blocks > 0);
317         g_assert (nursery_size % MS_BLOCK_SIZE == 0);
318         if (nursery_align)
319                 g_assert (nursery_align % MS_BLOCK_SIZE == 0);
320
321         nursery_start = mono_sgen_alloc_os_memory_aligned (alloc_size, nursery_align ? nursery_align : MS_BLOCK_SIZE, TRUE);
322         nursery_end = heap_start = nursery_start + nursery_size;
323         nursery_bits = the_nursery_bits;
324
325         ms_heap_end = heap_start + major_heap_size;
326
327         block_infos = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo) * ms_heap_num_blocks, INTERNAL_MEM_MS_BLOCK_INFO);
328
329         for (i = 0; i < ms_heap_num_blocks; ++i) {
330                 block_infos [i].block = heap_start + i * MS_BLOCK_SIZE;
331                 if (i < ms_heap_num_blocks - 1)
332                         block_infos [i].next_free = &block_infos [i + 1];
333                 else
334                         block_infos [i].next_free = NULL;
335                 block_infos [i].zeroed = TRUE;
336         }
337
338         empty_blocks = &block_infos [0];
339
340         return nursery_start;
341 }
342 #else
343 static void*
344 major_alloc_heap (mword nursery_size, mword nursery_align, int the_nursery_bits)
345 {
346         if (nursery_align)
347                 nursery_start = mono_sgen_alloc_os_memory_aligned (nursery_size, nursery_align, TRUE);
348         else
349                 nursery_start = mono_sgen_alloc_os_memory (nursery_size, TRUE);
350
351         nursery_end = nursery_start + nursery_size;
352         nursery_bits = the_nursery_bits;
353
354         return nursery_start;
355 }
356 #endif
357
358 static void
359 update_heap_boundaries_for_block (MSBlockInfo *block)
360 {
361         mono_sgen_update_heap_boundaries ((mword)block->block, (mword)block->block + MS_BLOCK_SIZE);
362 }
363
364 #ifdef FIXED_HEAP
365 static MSBlockInfo*
366 ms_get_empty_block (void)
367 {
368         MSBlockInfo *block;
369
370         g_assert (empty_blocks);
371
372         block = empty_blocks;
373         empty_blocks = empty_blocks->next_free;
374
375         block->used = TRUE;
376
377         if (!block->zeroed)
378                 memset (block->block, 0, MS_BLOCK_SIZE);
379
380         return block;
381 }
382
383 static void
384 ms_free_block (MSBlockInfo *block)
385 {
386         block->next_free = empty_blocks;
387         empty_blocks = block;
388         block->used = FALSE;
389         block->zeroed = FALSE;
390         mono_sgen_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
391 }
392 #else
393 static void*
394 ms_get_empty_block (void)
395 {
396         char *p;
397         int i;
398         void *block, *empty, *next;
399
400  retry:
401         if (!empty_blocks) {
402                 p = mono_sgen_alloc_os_memory_aligned (MS_BLOCK_SIZE * MS_BLOCK_ALLOC_NUM, MS_BLOCK_SIZE, TRUE);
403
404                 for (i = 0; i < MS_BLOCK_ALLOC_NUM; ++i) {
405                         block = p;
406                         /*
407                          * We do the free list update one after the
408                          * other so that other threads can use the new
409                          * blocks as quickly as possible.
410                          */
411                         do {
412                                 empty = empty_blocks;
413                                 *(void**)block = empty;
414                         } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
415                         p += MS_BLOCK_SIZE;
416                 }
417
418                 SGEN_ATOMIC_ADD (num_empty_blocks, MS_BLOCK_ALLOC_NUM);
419
420                 stat_major_blocks_alloced += MS_BLOCK_ALLOC_NUM;
421         }
422
423         do {
424                 empty = empty_blocks;
425                 if (!empty)
426                         goto retry;
427                 block = empty;
428                 next = *(void**)block;
429         } while (SGEN_CAS_PTR (&empty_blocks, next, empty) != empty);
430
431         SGEN_ATOMIC_ADD (num_empty_blocks, -1);
432
433         *(void**)block = NULL;
434
435         g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
436
437         return block;
438 }
439
440 static void
441 ms_free_block (void *block)
442 {
443         void *empty;
444
445         mono_sgen_release_space (MS_BLOCK_SIZE, SPACE_MAJOR);
446         memset (block, 0, MS_BLOCK_SIZE);
447
448         do {
449                 empty = empty_blocks;
450                 *(void**)block = empty;
451         } while (SGEN_CAS_PTR (&empty_blocks, block, empty) != empty);
452
453         SGEN_ATOMIC_ADD (num_empty_blocks, 1);
454 }
455 #endif
456
457 //#define MARKSWEEP_CONSISTENCY_CHECK
458
459 #ifdef MARKSWEEP_CONSISTENCY_CHECK
460 static void
461 check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
462 {
463         MSBlockInfo *b;
464
465         for (; block; block = block->next_free) {
466                 g_assert (block->obj_size == size);
467                 g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
468
469                 /* blocks in the free lists must have at least
470                    one free slot */
471                 g_assert (block->free_list);
472
473 #ifdef FIXED_HEAP
474                 /* the block must not be in the empty_blocks list */
475                 for (b = empty_blocks; b; b = b->next_free)
476                         g_assert (b != block);
477 #endif
478                 /* the block must be in the all_blocks list */
479                 for (b = all_blocks; b; b = b->next) {
480                         if (b == block)
481                                 break;
482                 }
483                 g_assert (b == block);
484         }
485 }
486
487 static void
488 check_empty_blocks (void)
489 {
490 #ifndef FIXED_HEAP
491         void *p;
492         int i = 0;
493         for (p = empty_blocks; p; p = *(void**)p)
494                 ++i;
495         g_assert (i == num_empty_blocks);
496 #endif
497 }
498
499 static void
500 consistency_check (void)
501 {
502         MSBlockInfo *block;
503         int i;
504
505         /* check all blocks */
506         FOREACH_BLOCK (block) {
507                 int count = MS_BLOCK_FREE / block->obj_size;
508                 int num_free = 0;
509                 void **free;
510
511 #ifndef FIXED_HEAP
512                 /* check block header */
513                 g_assert (((MSBlockHeader*)block->block)->info == block);
514 #endif
515
516                 /* count number of free slots */
517                 for (i = 0; i < count; ++i) {
518                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
519                         if (!MS_OBJ_ALLOCED (obj, block))
520                                 ++num_free;
521                 }
522
523                 /* check free list */
524                 for (free = block->free_list; free; free = (void**)*free) {
525                         g_assert (MS_BLOCK_FOR_OBJ (free) == block);
526                         --num_free;
527                 }
528                 g_assert (num_free == 0);
529
530                 /* check all mark words are zero */
531                 for (i = 0; i < MS_NUM_MARK_WORDS; ++i)
532                         g_assert (block->mark_words [i] == 0);
533         } END_FOREACH_BLOCK;
534
535         /* check free blocks */
536         for (i = 0; i < num_block_obj_sizes; ++i) {
537                 int j;
538                 for (j = 0; j < MS_BLOCK_TYPE_MAX; ++j)
539                         check_block_free_list (free_block_lists [j][i], block_obj_sizes [i], j & MS_BLOCK_FLAG_PINNED);
540         }
541
542         check_empty_blocks ();
543 }
544 #endif
545
546 static gboolean
547 ms_alloc_block (int size_index, gboolean pinned, gboolean has_references)
548 {
549         int size = block_obj_sizes [size_index];
550         int count = MS_BLOCK_FREE / size;
551         MSBlockInfo *info;
552 #ifdef SGEN_PARALLEL_MARK
553         MSBlockInfo *next;
554 #endif
555 #ifndef FIXED_HEAP
556         MSBlockHeader *header;
557 #endif
558         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
559         char *obj_start;
560         int i;
561
562         if (!mono_sgen_try_alloc_space (MS_BLOCK_SIZE, SPACE_MAJOR))
563                 return FALSE;
564
565 #ifdef FIXED_HEAP
566         info = ms_get_empty_block ();
567 #else
568         info = mono_sgen_alloc_internal (INTERNAL_MEM_MS_BLOCK_INFO);
569 #endif
570
571         DEBUG (9, g_assert (count >= 2));
572
573         info->obj_size = size;
574         info->obj_size_index = size_index;
575         info->pinned = pinned;
576         info->has_references = has_references;
577         info->has_pinned = pinned;
578         info->is_to_space = (mono_sgen_get_current_collection_generation () == GENERATION_OLD);
579 #ifndef FIXED_HEAP
580         info->block = ms_get_empty_block ();
581
582         header = (MSBlockHeader*) info->block;
583         header->info = info;
584 #endif
585
586         update_heap_boundaries_for_block (info);
587
588         /* build free list */
589         obj_start = info->block + MS_BLOCK_SKIP;
590         info->free_list = (void**)obj_start;
591         /* we're skipping the last one - it must be nulled */
592         for (i = 0; i < count - 1; ++i) {
593                 char *next_obj_start = obj_start + size;
594                 *(void**)obj_start = next_obj_start;
595                 obj_start = next_obj_start;
596         }
597         /* the last one */
598         *(void**)obj_start = NULL;
599
600 #ifdef SGEN_PARALLEL_MARK
601         do {
602                 next = info->next_free = free_blocks [size_index];
603         } while (SGEN_CAS_PTR ((void**)&free_blocks [size_index], info, next) != next);
604
605         do {
606                 next = info->next = all_blocks;
607         } while (SGEN_CAS_PTR ((void**)&all_blocks, info, next) != next);
608 #else
609         info->next_free = free_blocks [size_index];
610         free_blocks [size_index] = info;
611
612         info->next = all_blocks;
613         all_blocks = info;
614 #endif
615
616         ++num_major_sections;
617         return TRUE;
618 }
619
620 static gboolean
621 obj_is_from_pinned_alloc (char *ptr)
622 {
623         MSBlockInfo *block;
624
625         FOREACH_BLOCK (block) {
626                 if (ptr >= block->block && ptr <= block->block + MS_BLOCK_SIZE)
627                         return block->pinned;
628         } END_FOREACH_BLOCK;
629         return FALSE;
630 }
631
632 static void*
633 unlink_slot_from_free_list_uncontested (MSBlockInfo **free_blocks, int size_index)
634 {
635         MSBlockInfo *block;
636         void *obj;
637
638         block = free_blocks [size_index];
639         DEBUG (9, g_assert (block));
640
641         obj = block->free_list;
642         DEBUG (9, g_assert (obj));
643
644         block->free_list = *(void**)obj;
645         if (!block->free_list) {
646                 free_blocks [size_index] = block->next_free;
647                 block->next_free = NULL;
648         }
649
650         return obj;
651 }
652
653 #ifdef SGEN_PARALLEL_MARK
654 static gboolean
655 try_remove_block_from_free_list (MSBlockInfo *block, MSBlockInfo **free_blocks, int size_index)
656 {
657         /*
658          * No more free slots in the block, so try to free the block.
659          * Don't try again if we don't succeed - another thread will
660          * already have done it.
661          */
662         MSBlockInfo *next_block = block->next_free;
663         if (SGEN_CAS_PTR ((void**)&free_blocks [size_index], next_block, block) == block) {
664                 /*
665                 void *old = SGEN_CAS_PTR ((void**)&block->next_free, NULL, next_block);
666                 g_assert (old == next_block);
667                 */
668                 block->next_free = NULL;
669                 return TRUE;
670         }
671         return FALSE;
672 }
673
674 static void*
675 alloc_obj_par (int size, gboolean pinned, gboolean has_references)
676 {
677         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
678         MSBlockInfo **free_blocks_local = FREE_BLOCKS_LOCAL (pinned, has_references);
679         MSBlockInfo *block;
680         void *obj;
681
682         DEBUG (9, g_assert (!ms_sweep_in_progress));
683         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
684
685         if (free_blocks_local [size_index]) {
686         get_slot:
687                 obj = unlink_slot_from_free_list_uncontested (free_blocks_local, size_index);
688         } else {
689                 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
690
691         get_block:
692                 block = free_blocks [size_index];
693                 if (block) {
694                         if (!try_remove_block_from_free_list (block, free_blocks, size_index))
695                                 goto get_block;
696
697                         g_assert (block->next_free == NULL);
698                         g_assert (block->free_list);
699                         block->next_free = free_blocks_local [size_index];
700                         free_blocks_local [size_index] = block;
701
702                         goto get_slot;
703                 } else {
704                         gboolean success;
705
706                         LOCK_MS_BLOCK_LIST;
707                         success = ms_alloc_block (size_index, pinned, has_references);
708                         UNLOCK_MS_BLOCK_LIST;
709
710                         if (G_UNLIKELY (!success))
711                                 return NULL;
712
713                         goto get_block;
714                 }
715         }
716
717         /*
718          * FIXME: This should not be necessary because it'll be
719          * overwritten by the vtable immediately.
720          */
721         *(void**)obj = NULL;
722
723         return obj;
724 }
725 #endif
726
727 static void*
728 alloc_obj (int size, gboolean pinned, gboolean has_references)
729 {
730         int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
731         MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, has_references);
732         void *obj;
733
734 #ifdef SGEN_PARALLEL_MARK
735         DEBUG (9, g_assert (current_collection_generation != GENERATION_OLD));
736 #endif
737
738         DEBUG (9, g_assert (!ms_sweep_in_progress));
739
740         if (!free_blocks [size_index]) {
741                 if (G_UNLIKELY (!ms_alloc_block (size_index, pinned, has_references)))
742                         return NULL;
743         }
744
745         obj = unlink_slot_from_free_list_uncontested (free_blocks, size_index);
746
747         /*
748          * FIXME: This should not be necessary because it'll be
749          * overwritten by the vtable immediately.
750          */
751         *(void**)obj = NULL;
752
753         return obj;
754 }
755
756 static void*
757 major_alloc_object (int size, gboolean has_references)
758 {
759         return alloc_obj (size, FALSE, has_references);
760 }
761
762 /*
763  * We're not freeing the block if it's empty.  We leave that work for
764  * the next major collection.
765  *
766  * This is just called from the domain clearing code, which runs in a
767  * single thread and has the GC lock, so we don't need an extra lock.
768  */
769 static void
770 free_object (char *obj, size_t size, gboolean pinned)
771 {
772         MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
773         int word, bit;
774         DEBUG (9, g_assert ((pinned && block->pinned) || (!pinned && !block->pinned)));
775         DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
776         MS_CALC_MARK_BIT (word, bit, obj);
777         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
778         if (!block->free_list) {
779                 MSBlockInfo **free_blocks = FREE_BLOCKS (pinned, block->has_references);
780                 int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
781                 DEBUG (9, g_assert (!block->next_free));
782                 block->next_free = free_blocks [size_index];
783                 free_blocks [size_index] = block;
784         }
785         memset (obj, 0, size);
786         *(void**)obj = block->free_list;
787         block->free_list = (void**)obj;
788 }
789
790 static void
791 major_free_non_pinned_object (char *obj, size_t size)
792 {
793         free_object (obj, size, FALSE);
794 }
795
796 /* size is a multiple of SGEN_ALLOC_ALIGN */
797 static void*
798 major_alloc_small_pinned_obj (size_t size, gboolean has_references)
799 {
800         void *res;
801
802         ms_wait_for_sweep_done ();
803
804         res = alloc_obj (size, TRUE, has_references);
805          /*If we failed to alloc memory, we better try releasing memory
806           *as pinned alloc is requested by the runtime.
807           */
808          if (!res) {
809                  sgen_collect_major_no_lock ("pinned alloc failure");
810                  res = alloc_obj (size, TRUE, has_references);
811          }
812          return res;
813 }
814
815 static void
816 free_pinned_object (char *obj, size_t size)
817 {
818         free_object (obj, size, TRUE);
819 }
820
821 /*
822  * size is already rounded up and we hold the GC lock.
823  */
824 static void*
825 major_alloc_degraded (MonoVTable *vtable, size_t size)
826 {
827         void *obj;
828         int old_num_sections;
829
830         ms_wait_for_sweep_done ();
831
832         old_num_sections = num_major_sections;
833
834         obj = alloc_obj (size, FALSE, SGEN_VTABLE_HAS_REFERENCES (vtable));
835         if (G_LIKELY (obj)) {
836                 *(MonoVTable**)obj = vtable;
837                 HEAVY_STAT (++stat_objects_alloced_degraded);
838                 HEAVY_STAT (stat_bytes_alloced_degraded += size);
839                 g_assert (num_major_sections >= old_num_sections);
840                 mono_sgen_register_major_sections_alloced (num_major_sections - old_num_sections);
841         }
842         return obj;
843 }
844
845 #define MAJOR_OBJ_IS_IN_TO_SPACE(obj)   FALSE
846
847 /*
848  * obj is some object.  If it's not in the major heap (i.e. if it's in
849  * the nursery or LOS), return FALSE.  Otherwise return whether it's
850  * been marked or copied.
851  */
852 static gboolean
853 major_is_object_live (char *obj)
854 {
855         MSBlockInfo *block;
856         int word, bit;
857 #ifndef FIXED_HEAP
858         mword objsize;
859 #endif
860
861         if (ptr_in_nursery (obj))
862                 return FALSE;
863
864 #ifdef FIXED_HEAP
865         /* LOS */
866         if (!MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
867                 return FALSE;
868 #else
869         objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
870
871         /* LOS */
872         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
873                 return FALSE;
874 #endif
875
876         /* now we know it's in a major block */
877         block = MS_BLOCK_FOR_OBJ (obj);
878         DEBUG (9, g_assert (!block->pinned));
879         MS_CALC_MARK_BIT (word, bit, obj);
880         return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
881 }
882
883 static gboolean
884 major_ptr_is_in_non_pinned_space (char *ptr)
885 {
886         MSBlockInfo *block;
887
888         FOREACH_BLOCK (block) {
889                 if (ptr >= block->block && ptr <= block->block + MS_BLOCK_SIZE)
890                         return !block->pinned;
891         } END_FOREACH_BLOCK;
892         return FALSE;
893 }
894
895 static void
896 major_iterate_objects (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data)
897 {
898         MSBlockInfo *block;
899
900         ms_wait_for_sweep_done ();
901
902         FOREACH_BLOCK (block) {
903                 int count = MS_BLOCK_FREE / block->obj_size;
904                 int i;
905
906                 if (block->pinned && !pinned)
907                         continue;
908                 if (!block->pinned && !non_pinned)
909                         continue;
910
911                 for (i = 0; i < count; ++i) {
912                         void **obj = (void**) MS_BLOCK_OBJ (block, i);
913                         if (MS_OBJ_ALLOCED (obj, block))
914                                 callback ((char*)obj, block->obj_size, data);
915                 }
916         } END_FOREACH_BLOCK;
917 }
918
919 static void
920 major_check_scan_starts (void)
921 {
922 }
923
924 static void
925 major_dump_heap (FILE *heap_dump_file)
926 {
927         MSBlockInfo *block;
928         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
929         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
930         int i;
931
932         for (i = 0; i < num_block_obj_sizes; ++i)
933                 slots_available [i] = slots_used [i] = 0;
934
935         FOREACH_BLOCK (block) {
936                 int index = ms_find_block_obj_size_index (block->obj_size);
937                 int count = MS_BLOCK_FREE / block->obj_size;
938
939                 slots_available [index] += count;
940                 for (i = 0; i < count; ++i) {
941                         if (MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block))
942                                 ++slots_used [index];
943                 }
944         } END_FOREACH_BLOCK;
945
946         fprintf (heap_dump_file, "<occupancies>\n");
947         for (i = 0; i < num_block_obj_sizes; ++i) {
948                 fprintf (heap_dump_file, "<occupancy size=\"%d\" available=\"%d\" used=\"%d\" />\n",
949                                 block_obj_sizes [i], slots_available [i], slots_used [i]);
950         }
951         fprintf (heap_dump_file, "</occupancies>\n");
952
953         FOREACH_BLOCK (block) {
954                 int count = MS_BLOCK_FREE / block->obj_size;
955                 int i;
956                 int start = -1;
957
958                 fprintf (heap_dump_file, "<section type=\"%s\" size=\"%zu\">\n", "old", (size_t)MS_BLOCK_FREE);
959
960                 for (i = 0; i <= count; ++i) {
961                         if ((i < count) && MS_OBJ_ALLOCED (MS_BLOCK_OBJ (block, i), block)) {
962                                 if (start < 0)
963                                         start = i;
964                         } else {
965                                 if (start >= 0) {
966                                         mono_sgen_dump_occupied (MS_BLOCK_OBJ (block, start), MS_BLOCK_OBJ (block, i), block->block);
967                                         start = -1;
968                                 }
969                         }
970                 }
971
972                 fprintf (heap_dump_file, "</section>\n");
973         } END_FOREACH_BLOCK;
974 }
975
976 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
977
978 #define MS_MARK_OBJECT_AND_ENQUEUE_CHECKED(obj,block,queue) do {        \
979                 int __word, __bit;                                      \
980                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
981                 if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
982                         MS_SET_MARK_BIT ((block), __word, __bit);       \
983                         if ((block)->has_references)                    \
984                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
985                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
986                 }                                                       \
987         } while (0)
988 #define MS_MARK_OBJECT_AND_ENQUEUE(obj,block,queue) do {                \
989                 int __word, __bit;                                      \
990                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
991                 DEBUG (9, g_assert (MS_OBJ_ALLOCED ((obj), (block))));  \
992                 if (!MS_MARK_BIT ((block), __word, __bit)) {            \
993                         MS_SET_MARK_BIT ((block), __word, __bit);       \
994                         if ((block)->has_references)                    \
995                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
996                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
997                 }                                                       \
998         } while (0)
999 #define MS_PAR_MARK_OBJECT_AND_ENQUEUE(obj,block,queue) do {            \
1000                 int __word, __bit;                                      \
1001                 gboolean __was_marked;                                  \
1002                 DEBUG (9, g_assert (MS_OBJ_ALLOCED ((obj), (block))));  \
1003                 MS_CALC_MARK_BIT (__word, __bit, (obj));                \
1004                 MS_PAR_SET_MARK_BIT (__was_marked, (block), __word, __bit); \
1005                 if (!__was_marked) {                                    \
1006                         if ((block)->has_references)                    \
1007                                 GRAY_OBJECT_ENQUEUE ((queue), (obj));   \
1008                         binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), mono_sgen_safe_object_get_size ((MonoObject*)(obj))); \
1009                 }                                                       \
1010         } while (0)
1011
1012 #ifdef SGEN_PARALLEL_MARK
1013 static void
1014 pin_or_update_par (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue)
1015 {
1016         for (;;) {
1017                 mword vtable_word;
1018
1019                 if (SGEN_CAS_PTR (obj, (void*)((mword)vt | SGEN_PINNED_BIT), vt) == vt) {
1020                         mono_sgen_pin_object (obj, queue);
1021                         break;
1022                 }
1023
1024                 vtable_word = *(mword*)obj;
1025                 /*someone else forwarded it, update the pointer and bail out*/
1026                 if (vtable_word & SGEN_FORWARDED_BIT) {
1027                         *ptr = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1028                         break;
1029                 }
1030
1031                 /*someone pinned it, nothing to do.*/
1032                 if (vtable_word & SGEN_PINNED_BIT)
1033                         break;
1034         }
1035 }
1036 #endif
1037
1038 #include "sgen-major-copy-object.h"
1039
1040 #ifdef SGEN_PARALLEL_MARK
1041 static void
1042 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1043 {
1044         void *obj = *ptr;
1045         mword objsize;
1046         MSBlockInfo *block;
1047         MonoVTable *vt;
1048
1049         HEAVY_STAT (++stat_copy_object_called_major);
1050
1051         DEBUG (9, g_assert (obj));
1052         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1053
1054         if (ptr_in_nursery (obj)) {
1055                 int word, bit;
1056                 gboolean has_references;
1057                 void *destination;
1058                 mword vtable_word = *(mword*)obj;
1059                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1060
1061                 if (vtable_word & SGEN_FORWARDED_BIT) {
1062                         *ptr = (void*)vt;
1063                         return;
1064                 }
1065
1066                 if (vtable_word & SGEN_PINNED_BIT)
1067                         return;
1068
1069                 HEAVY_STAT (++stat_objects_copied_major);
1070
1071         do_copy_object:
1072                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1073                 has_references = SGEN_VTABLE_HAS_REFERENCES (vt);
1074
1075                 destination = alloc_obj_par (objsize, FALSE, has_references);
1076                 if (G_UNLIKELY (!destination)) {
1077                         if (!ptr_in_nursery (obj)) {
1078                                 int size_index;
1079                                 block = MS_BLOCK_FOR_OBJ (obj);
1080                                 size_index = block->obj_size_index;
1081                                 evacuate_block_obj_sizes [size_index] = FALSE;
1082                         }
1083
1084                         pin_or_update_par (ptr, obj, vt, queue);
1085                         return;
1086                 }
1087
1088                 /*
1089                  * We do this before the CAS because we want to make
1090                  * sure that if another thread sees the destination
1091                  * pointer the VTable is already in place.  Not doing
1092                  * this can crash binary protocols.
1093                  */
1094                 *(MonoVTable**)destination = vt;
1095
1096                 if (SGEN_CAS_PTR (obj, (void*)((mword)destination | SGEN_FORWARDED_BIT), vt) == vt) {
1097                         gboolean was_marked;
1098
1099                         par_copy_object_no_checks (destination, vt, obj, objsize, has_references ? queue : NULL);
1100                         obj = destination;
1101                         *ptr = obj;
1102
1103                         /*
1104                          * FIXME: If we make major_alloc_object() give
1105                          * us the block info, too, we won't have to
1106                          * re-fetch it here.
1107                          */
1108                         block = MS_BLOCK_FOR_OBJ (obj);
1109                         MS_CALC_MARK_BIT (word, bit, obj);
1110                         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1111                         MS_PAR_SET_MARK_BIT (was_marked, block, word, bit);
1112                 } else {
1113                         /*
1114                          * FIXME: We have allocated destination, but
1115                          * we cannot use it.  Give it back to the
1116                          * allocator.
1117                          */
1118                         *(void**)destination = NULL;
1119
1120                         vtable_word = *(mword*)obj;
1121                         g_assert (vtable_word & SGEN_FORWARDED_BIT);
1122
1123                         obj = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1124
1125                         *ptr = obj;
1126
1127                         ++stat_slots_allocated_in_vain;
1128                 }
1129         } else {
1130 #ifdef FIXED_HEAP
1131                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1132 #else
1133                 mword vtable_word = *(mword*)obj;
1134                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1135
1136                 /* see comment in the non-parallel version below */
1137                 if (vtable_word & SGEN_FORWARDED_BIT) {
1138                         *ptr = (void*)vt;
1139                         return;
1140                 }
1141                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1142
1143                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1144 #endif
1145                 {
1146                         int size_index;
1147
1148                         block = MS_BLOCK_FOR_OBJ (obj);
1149                         size_index = block->obj_size_index;
1150
1151                         if (!block->has_pinned && evacuate_block_obj_sizes [size_index]) {
1152                                 if (block->is_to_space)
1153                                         return;
1154
1155 #ifdef FIXED_HEAP
1156                                 {
1157                                         mword vtable_word = *(mword*)obj;
1158                                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1159
1160                                         if (vtable_word & SGEN_FORWARDED_BIT) {
1161                                                 *ptr = (void*)vt;
1162                                                 return;
1163                                         }
1164                                 }
1165 #endif
1166
1167                                 HEAVY_STAT (++stat_major_objects_evacuated);
1168                                 goto do_copy_object;
1169                         }
1170
1171                         MS_PAR_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1172                 } else {
1173 #ifdef FIXED_HEAP
1174                         mword vtable_word = *(mword*)obj;
1175                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1176 #endif
1177
1178                         if (vtable_word & SGEN_PINNED_BIT)
1179                                 return;
1180                         binary_protocol_pin (obj, vt, mono_sgen_safe_object_get_size ((MonoObject*)obj));
1181                         if (SGEN_CAS_PTR (obj, (void*)(vtable_word | SGEN_PINNED_BIT), (void*)vtable_word) == (void*)vtable_word) {
1182                                 if (SGEN_VTABLE_HAS_REFERENCES (vt))
1183                                         GRAY_OBJECT_ENQUEUE (queue, obj);
1184                         } else {
1185                                 g_assert (SGEN_OBJECT_IS_PINNED (obj));
1186                         }
1187                 }
1188         }
1189 }
1190 #else
1191 static void
1192 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1193 {
1194         void *obj = *ptr;
1195         MSBlockInfo *block;
1196
1197         HEAVY_STAT (++stat_copy_object_called_major);
1198
1199         DEBUG (9, g_assert (obj));
1200         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1201
1202         if (ptr_in_nursery (obj)) {
1203                 int word, bit;
1204                 char *forwarded, *old_obj;
1205
1206                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1207                         *ptr = forwarded;
1208                         return;
1209                 }
1210                 if (SGEN_OBJECT_IS_PINNED (obj))
1211                         return;
1212
1213                 HEAVY_STAT (++stat_objects_copied_major);
1214
1215         do_copy_object:
1216                 old_obj = obj;
1217                 obj = copy_object_no_checks (obj, queue);
1218                 if (G_UNLIKELY (old_obj == obj)) {
1219                         /*If we fail to evacuate an object we just stop doing it for a given block size as all other will surely fail too.*/
1220                         if (!ptr_in_nursery (obj)) {
1221                                 int size_index;
1222                                 block = MS_BLOCK_FOR_OBJ (obj);
1223                                 size_index = block->obj_size_index;
1224                                 evacuate_block_obj_sizes [size_index] = FALSE;
1225                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1226                         }
1227                         return;
1228                 }
1229                 *ptr = obj;
1230
1231                 /*
1232                  * FIXME: See comment for copy_object_no_checks().  If
1233                  * we have that, we can let the allocation function
1234                  * give us the block info, too, and we won't have to
1235                  * re-fetch it.
1236                  */
1237                 block = MS_BLOCK_FOR_OBJ (obj);
1238                 MS_CALC_MARK_BIT (word, bit, obj);
1239                 DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1240                 MS_SET_MARK_BIT (block, word, bit);
1241         } else {
1242                 char *forwarded;
1243 #ifdef FIXED_HEAP
1244                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1245 #else
1246                 mword objsize;
1247
1248                 /*
1249                  * If we have don't have a fixed heap we cannot know
1250                  * whether an object is in the LOS or in the small
1251                  * object major heap without checking its size.  To do
1252                  * that, however, we need to know that we actually
1253                  * have a valid object, not a forwarding pointer, so
1254                  * we have to do this check first.
1255                  */
1256                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1257                         *ptr = forwarded;
1258                         return;
1259                 }
1260
1261                 objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
1262
1263                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1264 #endif
1265                 {
1266                         int size_index;
1267                         gboolean evacuate;
1268
1269                         block = MS_BLOCK_FOR_OBJ (obj);
1270                         size_index = block->obj_size_index;
1271                         evacuate = evacuate_block_obj_sizes [size_index];
1272
1273 #ifdef FIXED_HEAP
1274                         /*
1275                          * We could also check for !block->has_pinned
1276                          * here, but it would only make an uncommon case
1277                          * faster, namely objects that are in blocks
1278                          * whose slot sizes are evacuated but which have
1279                          * pinned objects.
1280                          */
1281                         if (evacuate && (forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1282                                 *ptr = forwarded;
1283                                 return;
1284                         }
1285 #endif
1286
1287                         if (evacuate && !block->has_pinned) {
1288                                 if (block->is_to_space)
1289                                         return;
1290                                 HEAVY_STAT (++stat_major_objects_evacuated);
1291                                 goto do_copy_object;
1292                         } else {
1293                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1294                         }
1295                 } else {
1296                         if (SGEN_OBJECT_IS_PINNED (obj))
1297                                 return;
1298                         binary_protocol_pin (obj, (gpointer)SGEN_LOAD_VTABLE (obj), mono_sgen_safe_object_get_size ((MonoObject*)obj));
1299                         SGEN_PIN_OBJECT (obj);
1300                         /* FIXME: only enqueue if object has references */
1301                         GRAY_OBJECT_ENQUEUE (queue, obj);
1302                 }
1303         }
1304 }
1305 #endif
1306
1307 #include "sgen-major-scan-object.h"
1308
1309 static void
1310 mark_pinned_objects_in_block (MSBlockInfo *block, SgenGrayQueue *queue)
1311 {
1312         int i;
1313         int last_index = -1;
1314
1315         if (!block->pin_queue_num_entries)
1316                 return;
1317
1318         block->has_pinned = TRUE;
1319
1320         for (i = 0; i < block->pin_queue_num_entries; ++i) {
1321                 int index = MS_BLOCK_OBJ_INDEX (block->pin_queue_start [i], block);
1322                 DEBUG (9, g_assert (index >= 0 && index < MS_BLOCK_FREE / block->obj_size));
1323                 if (index == last_index)
1324                         continue;
1325                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (MS_BLOCK_OBJ (block, index), block, queue);
1326                 last_index = index;
1327         }
1328 }
1329
1330 static void
1331 ms_sweep (void)
1332 {
1333         int i;
1334         MSBlockInfo **iter;
1335
1336         /* statistics for evacuation */
1337         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1338         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1339         int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1340
1341         for (i = 0; i < num_block_obj_sizes; ++i)
1342                 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1343
1344         /* clear all the free lists */
1345         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1346                 MSBlockInfo **free_blocks = free_block_lists [i];
1347                 int j;
1348                 for (j = 0; j < num_block_obj_sizes; ++j)
1349                         free_blocks [j] = NULL;
1350         }
1351
1352         /* traverse all blocks, free and zero unmarked objects */
1353         iter = &all_blocks;
1354         while (*iter) {
1355                 MSBlockInfo *block = *iter;
1356                 int count;
1357                 gboolean have_live = FALSE;
1358                 gboolean has_pinned;
1359                 int obj_index;
1360                 int obj_size_index;
1361
1362                 obj_size_index = block->obj_size_index;
1363
1364                 has_pinned = block->has_pinned;
1365                 block->has_pinned = block->pinned;
1366
1367                 block->is_to_space = FALSE;
1368
1369                 count = MS_BLOCK_FREE / block->obj_size;
1370                 block->free_list = NULL;
1371
1372                 for (obj_index = 0; obj_index < count; ++obj_index) {
1373                         int word, bit;
1374                         void *obj = MS_BLOCK_OBJ (block, obj_index);
1375
1376                         MS_CALC_MARK_BIT (word, bit, obj);
1377                         if (MS_MARK_BIT (block, word, bit)) {
1378                                 DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
1379                                 have_live = TRUE;
1380                                 if (!has_pinned)
1381                                         ++slots_used [obj_size_index];
1382                         } else {
1383                                 /* an unmarked object */
1384                                 if (MS_OBJ_ALLOCED (obj, block)) {
1385                                         binary_protocol_empty (obj, block->obj_size);
1386                                         memset (obj, 0, block->obj_size);
1387                                 }
1388                                 *(void**)obj = block->free_list;
1389                                 block->free_list = obj;
1390                         }
1391                 }
1392
1393                 /* reset mark bits */
1394                 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1395
1396                 /*
1397                  * FIXME: reverse free list so that it's in address
1398                  * order
1399                  */
1400
1401                 if (have_live) {
1402                         if (!has_pinned) {
1403                                 ++num_blocks [obj_size_index];
1404                                 slots_available [obj_size_index] += count;
1405                         }
1406
1407                         iter = &block->next;
1408
1409                         /*
1410                          * If there are free slots in the block, add
1411                          * the block to the corresponding free list.
1412                          */
1413                         if (block->free_list) {
1414                                 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1415                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1416                                 block->next_free = free_blocks [index];
1417                                 free_blocks [index] = block;
1418                         }
1419
1420                         update_heap_boundaries_for_block (block);
1421                 } else {
1422                         /*
1423                          * Blocks without live objects are removed from the
1424                          * block list and freed.
1425                          */
1426                         *iter = block->next;
1427
1428 #ifdef FIXED_HEAP
1429                         ms_free_block (block);
1430 #else
1431                         ms_free_block (block->block);
1432
1433                         mono_sgen_free_internal (block, INTERNAL_MEM_MS_BLOCK_INFO);
1434 #endif
1435
1436                         --num_major_sections;
1437                 }
1438         }
1439
1440         for (i = 0; i < num_block_obj_sizes; ++i) {
1441                 float usage = (float)slots_used [i] / (float)slots_available [i];
1442                 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1443                         evacuate_block_obj_sizes [i] = TRUE;
1444                         /*
1445                         g_print ("slot size %d - %d of %d used\n",
1446                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1447                         */
1448                 } else {
1449                         evacuate_block_obj_sizes [i] = FALSE;
1450                 }
1451         }
1452
1453         have_swept = TRUE;
1454 }
1455
1456 static void*
1457 ms_sweep_thread_func (void *dummy)
1458 {
1459         g_assert (concurrent_sweep);
1460
1461         for (;;) {
1462                 int result;
1463
1464                 while ((result = MONO_SEM_WAIT (&ms_sweep_cmd_semaphore)) != 0) {
1465                         if (errno != EINTR)
1466                                 g_error ("MONO_SEM_WAIT");
1467                 }
1468
1469                 ms_sweep ();
1470
1471                 ms_signal_sweep_done ();
1472         }
1473
1474         return NULL;
1475 }
1476
1477 static void
1478 major_sweep (void)
1479 {
1480         if (concurrent_sweep) {
1481                 g_assert (ms_sweep_thread);
1482                 ms_signal_sweep_command ();
1483         } else {
1484                 ms_sweep ();
1485         }
1486 }
1487
1488 static int count_pinned_ref;
1489 static int count_pinned_nonref;
1490 static int count_nonpinned_ref;
1491 static int count_nonpinned_nonref;
1492
1493 static void
1494 count_nonpinned_callback (char *obj, size_t size, void *data)
1495 {
1496         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1497
1498         if (vtable->klass->has_references)
1499                 ++count_nonpinned_ref;
1500         else
1501                 ++count_nonpinned_nonref;
1502 }
1503
1504 static void
1505 count_pinned_callback (char *obj, size_t size, void *data)
1506 {
1507         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1508
1509         if (vtable->klass->has_references)
1510                 ++count_pinned_ref;
1511         else
1512                 ++count_pinned_nonref;
1513 }
1514
1515 static void __attribute__ ((unused))
1516 count_ref_nonref_objs (void)
1517 {
1518         int total;
1519
1520         count_pinned_ref = 0;
1521         count_pinned_nonref = 0;
1522         count_nonpinned_ref = 0;
1523         count_nonpinned_nonref = 0;
1524
1525         major_iterate_objects (TRUE, FALSE, count_nonpinned_callback, NULL);
1526         major_iterate_objects (FALSE, TRUE, count_pinned_callback, NULL);
1527
1528         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1529
1530         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1531                         count_pinned_ref, count_nonpinned_ref,
1532                         count_pinned_nonref, count_nonpinned_nonref,
1533                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1534 }
1535
1536 static int
1537 ms_calculate_block_obj_sizes (double factor, int *arr)
1538 {
1539         double target_size = sizeof (MonoObject);
1540         int num_sizes = 0;
1541         int last_size = 0;
1542
1543         do {
1544                 int target_count = ceil (MS_BLOCK_FREE / target_size);
1545                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1546
1547                 if (size != last_size) {
1548                         if (arr)
1549                                 arr [num_sizes] = size;
1550                         ++num_sizes;
1551                         last_size = size;
1552                 }
1553
1554                 target_size *= factor;
1555         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1556
1557         return num_sizes;
1558 }
1559
1560 /* only valid during minor collections */
1561 static int old_num_major_sections;
1562
1563 static void
1564 major_start_nursery_collection (void)
1565 {
1566         ms_wait_for_sweep_done ();
1567
1568 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1569         consistency_check ();
1570 #endif
1571
1572         old_num_major_sections = num_major_sections;
1573 }
1574
1575 static void
1576 major_finish_nursery_collection (void)
1577 {
1578 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1579         consistency_check ();
1580 #endif
1581         mono_sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1582 }
1583
1584 static void
1585 major_start_major_collection (void)
1586 {
1587         int i;
1588
1589         ms_wait_for_sweep_done ();
1590
1591         /* clear the free lists */
1592         for (i = 0; i < num_block_obj_sizes; ++i) {
1593                 if (!evacuate_block_obj_sizes [i])
1594                         continue;
1595
1596                 free_block_lists [0][i] = NULL;
1597                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1598         }
1599 }
1600
1601 static void
1602 major_finish_major_collection (void)
1603 {
1604 }
1605
1606 static void
1607 major_have_computer_minor_collection_allowance (void)
1608 {
1609 #ifndef FIXED_HEAP
1610         int section_reserve = mono_sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1611
1612         g_assert (have_swept);
1613         ms_wait_for_sweep_done ();
1614         g_assert (!ms_sweep_in_progress);
1615
1616         /*
1617          * FIXME: We don't free blocks on 32 bit platforms because it
1618          * can lead to address space fragmentation, since we're
1619          * allocating blocks in larger contingents.
1620          */
1621         if (sizeof (mword) < 8)
1622                 return;
1623
1624         while (num_empty_blocks > section_reserve) {
1625                 void *next = *(void**)empty_blocks;
1626                 mono_sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE);
1627                 empty_blocks = next;
1628                 /*
1629                  * Needs not be atomic because this is running
1630                  * single-threaded.
1631                  */
1632                 --num_empty_blocks;
1633
1634                 ++stat_major_blocks_freed;
1635         }
1636 #endif
1637 }
1638
1639 static void
1640 major_find_pin_queue_start_ends (SgenGrayQueue *queue)
1641 {
1642         MSBlockInfo *block;
1643
1644         FOREACH_BLOCK (block) {
1645                 block->pin_queue_start = mono_sgen_find_optimized_pin_queue_area (block->block + MS_BLOCK_SKIP, block->block + MS_BLOCK_SIZE,
1646                                 &block->pin_queue_num_entries);
1647         } END_FOREACH_BLOCK;
1648 }
1649
1650 static void
1651 major_pin_objects (SgenGrayQueue *queue)
1652 {
1653         MSBlockInfo *block;
1654
1655         FOREACH_BLOCK (block) {
1656                 mark_pinned_objects_in_block (block, queue);
1657         } END_FOREACH_BLOCK;
1658 }
1659
1660 static void
1661 major_init_to_space (void)
1662 {
1663 }
1664
1665 static void
1666 major_report_pinned_memory_usage (void)
1667 {
1668         g_assert_not_reached ();
1669 }
1670
1671 static gint64
1672 major_get_used_size (void)
1673 {
1674         gint64 size = 0;
1675         MSBlockInfo *block;
1676
1677         FOREACH_BLOCK (block) {
1678                 int count = MS_BLOCK_FREE / block->obj_size;
1679                 void **iter;
1680                 size += count * block->obj_size;
1681                 for (iter = block->free_list; iter; iter = (void**)*iter)
1682                         size -= block->obj_size;
1683         } END_FOREACH_BLOCK;
1684
1685         return size;
1686 }
1687
1688 static int
1689 get_num_major_sections (void)
1690 {
1691         return num_major_sections;
1692 }
1693
1694 static gboolean
1695 major_handle_gc_param (const char *opt)
1696 {
1697 #ifdef FIXED_HEAP
1698         if (g_str_has_prefix (opt, "major-heap-size=")) {
1699                 const char *arg = strchr (opt, '=') + 1;
1700                 glong size;
1701                 if (!mono_gc_parse_environment_string_extract_number (arg, &size))
1702                         return FALSE;
1703                 ms_heap_num_blocks = (size + MS_BLOCK_SIZE - 1) / MS_BLOCK_SIZE;
1704                 g_assert (ms_heap_num_blocks > 0);
1705                 return TRUE;
1706         } else
1707 #endif
1708         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1709                 const char *arg = strchr (opt, '=') + 1;
1710                 int percentage = atoi (arg);
1711                 if (percentage < 0 || percentage > 100) {
1712                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1713                         exit (1);
1714                 }
1715                 evacuation_threshold = (float)percentage / 100.0;
1716                 return TRUE;
1717         } else if (!strcmp (opt, "concurrent-sweep")) {
1718                 concurrent_sweep = TRUE;
1719                 return TRUE;
1720         } else if (!strcmp (opt, "no-concurrent-sweep")) {
1721                 concurrent_sweep = FALSE;
1722                 return TRUE;
1723         }
1724
1725         return FALSE;
1726 }
1727
1728 static void
1729 major_print_gc_param_usage (void)
1730 {
1731         fprintf (stderr,
1732                         ""
1733 #ifdef FIXED_HEAP
1734                         "  major-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n"
1735 #endif
1736                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1737                         "  (no-)concurrent-sweep\n"
1738                         );
1739 }
1740
1741 #ifdef SGEN_HAVE_CARDTABLE
1742 static void
1743 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1744 {
1745         MSBlockInfo *block;
1746
1747         FOREACH_BLOCK (block) {
1748                 if (block->has_references)
1749                         callback ((mword)block->block, MS_BLOCK_SIZE);
1750         } END_FOREACH_BLOCK;
1751 }
1752
1753 #ifdef HEAVY_STATISTICS
1754 extern long long marked_cards;
1755 extern long long scanned_cards;
1756 extern long long scanned_objects;
1757
1758 #endif
1759
1760 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1761 /*
1762  * MS blocks are 16K aligned.
1763  * Cardtables are 4K aligned, at least.
1764  * This means that the cardtable of a given block is 32 bytes aligned.
1765  */
1766 static guint8*
1767 initial_skip_card (guint8 *card_data)
1768 {
1769         mword *cards = (mword*)card_data;
1770         mword card;
1771         int i;
1772         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1773                 card = cards [i];
1774                 if (card)
1775                         break;
1776         }
1777
1778         if (i == CARD_WORDS_PER_BLOCK)
1779                 return card_data + CARDS_PER_BLOCK;
1780
1781 #if defined(__i386__) && defined(__GNUC__)
1782         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1783 #elif defined(__x86_64__) && defined(__GNUC__)
1784         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1785 #elif defined(__s390x__) && defined(__GNUC__)
1786         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1787 #else
1788         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1789                 if (card_data [i])
1790                         return &card_data [i];
1791         }
1792         return card_data;
1793 #endif
1794 }
1795
1796
1797 static G_GNUC_UNUSED guint8*
1798 skip_card (guint8 *card_data, guint8 *card_data_end)
1799 {
1800         while (card_data < card_data_end && !*card_data)
1801                 ++card_data;
1802         return card_data;
1803 }
1804
1805 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1806 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1807 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1808
1809 static void
1810 major_scan_card_table (SgenGrayQueue *queue)
1811 {
1812         MSBlockInfo *block;
1813
1814         FOREACH_BLOCK (block) {
1815                 int block_obj_size;
1816                 char *block_start;
1817
1818                 if (!block->has_references)
1819                         continue;
1820
1821                 block_obj_size = block->obj_size;
1822                 block_start = block->block;
1823
1824                 if (block_obj_size >= CARD_SIZE_IN_BYTES) {
1825                         guint8 *cards;
1826 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1827                         guint8 cards_data [CARDS_PER_BLOCK];
1828 #endif
1829                         char *obj, *end, *base;
1830
1831                         /*We can avoid the extra copy since the remark cardtable was cleaned before */
1832 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1833                         cards = sgen_card_table_get_card_scan_address ((mword)block_start);
1834 #else
1835                         cards = cards_data;
1836                         if (!sgen_card_table_get_card_data (cards_data, (mword)block_start, CARDS_PER_BLOCK))
1837                                 continue;
1838 #endif
1839
1840                         obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, 0);
1841                         end = block_start + MS_BLOCK_SIZE;
1842                         base = sgen_card_table_align_pointer (obj);
1843
1844                         while (obj < end) {
1845                                 if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1846                                         int card_offset = (obj - base) >> CARD_BITS;
1847                                         sgen_cardtable_scan_object (obj, block_obj_size, cards + card_offset, queue);
1848                                 }
1849                                 obj += block_obj_size;
1850                         }
1851                 } else {
1852                         guint8 *card_data, *card_base;
1853                         guint8 *card_data_end;
1854
1855                         /*
1856                          * This is safe in face of card aliasing for the following reason:
1857                          *
1858                          * Major blocks are 16k aligned, or 32 cards aligned.
1859                          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1860                          * sizes, they won't overflow the cardtable overlap modulus.
1861                          */
1862                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1863                         card_data_end = card_data + CARDS_PER_BLOCK;
1864
1865                         for (card_data = initial_skip_card (card_data); card_data < card_data_end; ++card_data) { //card_data = skip_card (card_data + 1, card_data_end)) {
1866                                 int index;
1867                                 int idx = card_data - card_base;
1868                                 char *start = (char*)(block_start + idx * CARD_SIZE_IN_BYTES);
1869                                 char *end = start + CARD_SIZE_IN_BYTES;
1870                                 char *obj;
1871
1872                                 HEAVY_STAT (++scanned_cards);
1873
1874                                 if (!*card_data)
1875                                         continue;
1876
1877                                 HEAVY_STAT (++marked_cards);
1878
1879                                 sgen_card_table_prepare_card_for_scanning (card_data);
1880
1881                                 if (idx == 0)
1882                                         index = 0;
1883                                 else
1884                                         index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1885
1886                                 obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, index);
1887                                 while (obj < end) {
1888                                         if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1889                                                 HEAVY_STAT (++scanned_objects);
1890                                                 minor_scan_object (obj, queue);
1891                                         }
1892                                         obj += block_obj_size;
1893                                 }
1894                         }
1895                 }
1896         } END_FOREACH_BLOCK;
1897 }
1898 #endif
1899
1900 static gboolean
1901 major_is_worker_thread (pthread_t thread)
1902 {
1903         if (concurrent_sweep)
1904                 return thread == ms_sweep_thread;
1905         else
1906                 return FALSE;
1907 }
1908
1909 static void
1910 alloc_free_block_lists (MSBlockInfo ***lists)
1911 {
1912         int i;
1913         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1914                 lists [i] = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1915 }
1916
1917 #ifdef SGEN_PARALLEL_MARK
1918 static void*
1919 major_alloc_worker_data (void)
1920 {
1921         /* FIXME: free this when the workers come down */
1922         MSBlockInfo ***lists = malloc (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX);
1923         alloc_free_block_lists (lists);
1924         return lists;
1925 }
1926
1927 static void
1928 major_init_worker_thread (void *data)
1929 {
1930         MSBlockInfo ***lists = data;
1931         int i;
1932
1933         g_assert (lists && lists != free_block_lists);
1934         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1935                 int j;
1936                 for (j = 0; j < num_block_obj_sizes; ++j)
1937                         g_assert (!lists [i][j]);
1938         }
1939
1940 #ifdef HAVE_KW_THREAD
1941         workers_free_block_lists = data;
1942 #else
1943         pthread_setspecific (workers_free_block_lists_key, data);
1944 #endif
1945 }
1946
1947 static void
1948 major_reset_worker_data (void *data)
1949 {
1950         MSBlockInfo ***lists = data;
1951         int i;
1952         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1953                 int j;
1954                 for (j = 0; j < num_block_obj_sizes; ++j)
1955                         lists [i][j] = NULL;
1956         }
1957 }
1958 #endif
1959
1960 #undef pthread_create
1961
1962 static void
1963 post_param_init (void)
1964 {
1965         if (concurrent_sweep) {
1966                 if (pthread_create (&ms_sweep_thread, NULL, ms_sweep_thread_func, NULL)) {
1967                         fprintf (stderr, "Error: Could not create sweep thread.\n");
1968                         exit (1);
1969                 }
1970         }
1971 }
1972
1973 void
1974 #ifdef SGEN_PARALLEL_MARK
1975 #ifdef FIXED_HEAP
1976 mono_sgen_marksweep_fixed_par_init
1977 #else
1978 mono_sgen_marksweep_par_init
1979 #endif
1980 #else
1981 #ifdef FIXED_HEAP
1982 mono_sgen_marksweep_fixed_init
1983 #else
1984 mono_sgen_marksweep_init
1985 #endif
1986 #endif
1987         (SgenMajorCollector *collector)
1988 {
1989         int i;
1990
1991 #ifndef FIXED_HEAP
1992         mono_sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
1993 #endif
1994
1995         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
1996         block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1997         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
1998
1999         evacuate_block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
2000         for (i = 0; i < num_block_obj_sizes; ++i)
2001                 evacuate_block_obj_sizes [i] = FALSE;
2002
2003         /*
2004         {
2005                 int i;
2006                 g_print ("block object sizes:\n");
2007                 for (i = 0; i < num_block_obj_sizes; ++i)
2008                         g_print ("%d\n", block_obj_sizes [i]);
2009         }
2010         */
2011
2012         alloc_free_block_lists (free_block_lists);
2013
2014         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2015                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2016         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2017                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2018
2019         LOCK_INIT (ms_block_list_mutex);
2020
2021         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_alloced);
2022         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_freed);
2023         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_objects_evacuated);
2024         mono_counters_register ("Wait for sweep time", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_time_wait_for_sweep);
2025 #ifdef SGEN_PARALLEL_MARK
2026         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
2027
2028 #ifndef HAVE_KW_THREAD
2029         pthread_key_create (&workers_free_block_lists_key, NULL);
2030 #endif
2031 #endif
2032
2033         /*
2034          * FIXME: These are superfluous if concurrent sweep is
2035          * disabled.  We might want to create them lazily.
2036          */
2037         MONO_SEM_INIT (&ms_sweep_cmd_semaphore, 0);
2038         MONO_SEM_INIT (&ms_sweep_done_semaphore, 0);
2039
2040         collector->section_size = MAJOR_SECTION_SIZE;
2041 #ifdef SGEN_PARALLEL_MARK
2042         collector->is_parallel = TRUE;
2043         collector->alloc_worker_data = major_alloc_worker_data;
2044         collector->init_worker_thread = major_init_worker_thread;
2045         collector->reset_worker_data = major_reset_worker_data;
2046 #else
2047         collector->is_parallel = FALSE;
2048 #endif
2049         collector->supports_cardtable = TRUE;
2050
2051         collector->have_swept = &have_swept;
2052
2053         collector->alloc_heap = major_alloc_heap;
2054         collector->is_object_live = major_is_object_live;
2055         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2056         collector->alloc_degraded = major_alloc_degraded;
2057         collector->copy_or_mark_object = major_copy_or_mark_object;
2058         collector->alloc_object = major_alloc_object;
2059         collector->free_pinned_object = free_pinned_object;
2060         collector->iterate_objects = major_iterate_objects;
2061         collector->free_non_pinned_object = major_free_non_pinned_object;
2062         collector->find_pin_queue_start_ends = major_find_pin_queue_start_ends;
2063         collector->pin_objects = major_pin_objects;
2064 #ifdef SGEN_HAVE_CARDTABLE
2065         collector->scan_card_table = major_scan_card_table;
2066         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2067 #endif
2068         collector->init_to_space = major_init_to_space;
2069         collector->sweep = major_sweep;
2070         collector->check_scan_starts = major_check_scan_starts;
2071         collector->dump_heap = major_dump_heap;
2072         collector->get_used_size = major_get_used_size;
2073         collector->start_nursery_collection = major_start_nursery_collection;
2074         collector->finish_nursery_collection = major_finish_nursery_collection;
2075         collector->start_major_collection = major_start_major_collection;
2076         collector->finish_major_collection = major_finish_major_collection;
2077         collector->have_computed_minor_collection_allowance = major_have_computer_minor_collection_allowance;
2078         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2079         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2080         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2081         collector->get_num_major_sections = get_num_major_sections;
2082         collector->handle_gc_param = major_handle_gc_param;
2083         collector->print_gc_param_usage = major_print_gc_param_usage;
2084         collector->is_worker_thread = major_is_worker_thread;
2085         collector->post_param_init = post_param_init;
2086
2087         FILL_COLLECTOR_COPY_OBJECT (collector);
2088         FILL_COLLECTOR_SCAN_OBJECT (collector);
2089
2090 #ifdef SGEN_HAVE_CARDTABLE
2091         /*cardtable requires major pages to be 8 cards aligned*/
2092         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2093 #endif
2094 }
2095
2096 #endif