[sgen] Parallel nursery collection.
[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                 if (SGEN_CAS_PTR (obj, (void*)((mword)destination | SGEN_FORWARDED_BIT), vt) == vt) {
1089                         gboolean was_marked;
1090
1091                         par_copy_object_no_checks (destination, vt, obj, objsize, has_references ? queue : NULL);
1092                         obj = destination;
1093                         *ptr = obj;
1094
1095                         /*
1096                          * FIXME: If we make major_alloc_object() give
1097                          * us the block info, too, we won't have to
1098                          * re-fetch it here.
1099                          */
1100                         block = MS_BLOCK_FOR_OBJ (obj);
1101                         MS_CALC_MARK_BIT (word, bit, obj);
1102                         DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1103                         MS_PAR_SET_MARK_BIT (was_marked, block, word, bit);
1104                 } else {
1105                         /*
1106                          * FIXME: We have allocated destination, but
1107                          * we cannot use it.  Give it back to the
1108                          * allocator.
1109                          */
1110                         *(void**)destination = NULL;
1111
1112                         vtable_word = *(mword*)obj;
1113                         g_assert (vtable_word & SGEN_FORWARDED_BIT);
1114
1115                         obj = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1116
1117                         *ptr = obj;
1118
1119                         ++stat_slots_allocated_in_vain;
1120                 }
1121         } else {
1122 #ifdef FIXED_HEAP
1123                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1124 #else
1125                 mword vtable_word = *(mword*)obj;
1126                 vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1127
1128                 /* see comment in the non-parallel version below */
1129                 if (vtable_word & SGEN_FORWARDED_BIT) {
1130                         *ptr = (void*)vt;
1131                         return;
1132                 }
1133                 objsize = SGEN_ALIGN_UP (mono_sgen_par_object_get_size (vt, (MonoObject*)obj));
1134
1135                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1136 #endif
1137                 {
1138                         int size_index;
1139
1140                         block = MS_BLOCK_FOR_OBJ (obj);
1141                         size_index = block->obj_size_index;
1142
1143                         if (!block->has_pinned && evacuate_block_obj_sizes [size_index]) {
1144                                 if (block->is_to_space)
1145                                         return;
1146
1147 #ifdef FIXED_HEAP
1148                                 {
1149                                         mword vtable_word = *(mword*)obj;
1150                                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1151
1152                                         if (vtable_word & SGEN_FORWARDED_BIT) {
1153                                                 *ptr = (void*)vt;
1154                                                 return;
1155                                         }
1156                                 }
1157 #endif
1158
1159                                 HEAVY_STAT (++stat_major_objects_evacuated);
1160                                 goto do_copy_object;
1161                         }
1162
1163                         MS_PAR_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1164                 } else {
1165 #ifdef FIXED_HEAP
1166                         mword vtable_word = *(mword*)obj;
1167                         vt = (MonoVTable*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1168 #endif
1169
1170                         if (vtable_word & SGEN_PINNED_BIT)
1171                                 return;
1172                         binary_protocol_pin (obj, vt, mono_sgen_safe_object_get_size ((MonoObject*)obj));
1173                         if (SGEN_CAS_PTR (obj, (void*)(vtable_word | SGEN_PINNED_BIT), (void*)vtable_word) == (void*)vtable_word) {
1174                                 if (SGEN_VTABLE_HAS_REFERENCES (vt))
1175                                         GRAY_OBJECT_ENQUEUE (queue, obj);
1176                         } else {
1177                                 g_assert (SGEN_OBJECT_IS_PINNED (obj));
1178                         }
1179                 }
1180         }
1181 }
1182 #else
1183 static void
1184 major_copy_or_mark_object (void **ptr, SgenGrayQueue *queue)
1185 {
1186         void *obj = *ptr;
1187         MSBlockInfo *block;
1188
1189         HEAVY_STAT (++stat_copy_object_called_major);
1190
1191         DEBUG (9, g_assert (obj));
1192         DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
1193
1194         if (ptr_in_nursery (obj)) {
1195                 int word, bit;
1196                 char *forwarded, *old_obj;
1197
1198                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1199                         *ptr = forwarded;
1200                         return;
1201                 }
1202                 if (SGEN_OBJECT_IS_PINNED (obj))
1203                         return;
1204
1205                 HEAVY_STAT (++stat_objects_copied_major);
1206
1207         do_copy_object:
1208                 old_obj = obj;
1209                 obj = copy_object_no_checks (obj, queue);
1210                 if (G_UNLIKELY (old_obj == obj)) {
1211                         /*If we fail to evacuate an object we just stop doing it for a given block size as all other will surely fail too.*/
1212                         if (!ptr_in_nursery (obj)) {
1213                                 int size_index;
1214                                 block = MS_BLOCK_FOR_OBJ (obj);
1215                                 size_index = block->obj_size_index;
1216                                 evacuate_block_obj_sizes [size_index] = FALSE;
1217                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1218                         }
1219                         return;
1220                 }
1221                 *ptr = obj;
1222
1223                 /*
1224                  * FIXME: See comment for copy_object_no_checks().  If
1225                  * we have that, we can let the allocation function
1226                  * give us the block info, too, and we won't have to
1227                  * re-fetch it.
1228                  */
1229                 block = MS_BLOCK_FOR_OBJ (obj);
1230                 MS_CALC_MARK_BIT (word, bit, obj);
1231                 DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
1232                 MS_SET_MARK_BIT (block, word, bit);
1233         } else {
1234                 char *forwarded;
1235 #ifdef FIXED_HEAP
1236                 if (MS_PTR_IN_SMALL_MAJOR_HEAP (obj))
1237 #else
1238                 mword objsize;
1239
1240                 /*
1241                  * If we have don't have a fixed heap we cannot know
1242                  * whether an object is in the LOS or in the small
1243                  * object major heap without checking its size.  To do
1244                  * that, however, we need to know that we actually
1245                  * have a valid object, not a forwarding pointer, so
1246                  * we have to do this check first.
1247                  */
1248                 if ((forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1249                         *ptr = forwarded;
1250                         return;
1251                 }
1252
1253                 objsize = SGEN_ALIGN_UP (mono_sgen_safe_object_get_size ((MonoObject*)obj));
1254
1255                 if (objsize <= SGEN_MAX_SMALL_OBJ_SIZE)
1256 #endif
1257                 {
1258                         int size_index;
1259                         gboolean evacuate;
1260
1261                         block = MS_BLOCK_FOR_OBJ (obj);
1262                         size_index = block->obj_size_index;
1263                         evacuate = evacuate_block_obj_sizes [size_index];
1264
1265 #ifdef FIXED_HEAP
1266                         /*
1267                          * We could also check for !block->has_pinned
1268                          * here, but it would only make an uncommon case
1269                          * faster, namely objects that are in blocks
1270                          * whose slot sizes are evacuated but which have
1271                          * pinned objects.
1272                          */
1273                         if (evacuate && (forwarded = SGEN_OBJECT_IS_FORWARDED (obj))) {
1274                                 *ptr = forwarded;
1275                                 return;
1276                         }
1277 #endif
1278
1279                         if (evacuate && !block->has_pinned) {
1280                                 if (block->is_to_space)
1281                                         return;
1282                                 HEAVY_STAT (++stat_major_objects_evacuated);
1283                                 goto do_copy_object;
1284                         } else {
1285                                 MS_MARK_OBJECT_AND_ENQUEUE (obj, block, queue);
1286                         }
1287                 } else {
1288                         if (SGEN_OBJECT_IS_PINNED (obj))
1289                                 return;
1290                         binary_protocol_pin (obj, (gpointer)SGEN_LOAD_VTABLE (obj), mono_sgen_safe_object_get_size ((MonoObject*)obj));
1291                         SGEN_PIN_OBJECT (obj);
1292                         /* FIXME: only enqueue if object has references */
1293                         GRAY_OBJECT_ENQUEUE (queue, obj);
1294                 }
1295         }
1296 }
1297 #endif
1298
1299 #include "sgen-major-scan-object.h"
1300
1301 static void
1302 mark_pinned_objects_in_block (MSBlockInfo *block, SgenGrayQueue *queue)
1303 {
1304         int i;
1305         int last_index = -1;
1306
1307         if (!block->pin_queue_num_entries)
1308                 return;
1309
1310         block->has_pinned = TRUE;
1311
1312         for (i = 0; i < block->pin_queue_num_entries; ++i) {
1313                 int index = MS_BLOCK_OBJ_INDEX (block->pin_queue_start [i], block);
1314                 DEBUG (9, g_assert (index >= 0 && index < MS_BLOCK_FREE / block->obj_size));
1315                 if (index == last_index)
1316                         continue;
1317                 MS_MARK_OBJECT_AND_ENQUEUE_CHECKED (MS_BLOCK_OBJ (block, index), block, queue);
1318                 last_index = index;
1319         }
1320 }
1321
1322 static void
1323 ms_sweep (void)
1324 {
1325         int i;
1326         MSBlockInfo **iter;
1327
1328         /* statistics for evacuation */
1329         int *slots_available = alloca (sizeof (int) * num_block_obj_sizes);
1330         int *slots_used = alloca (sizeof (int) * num_block_obj_sizes);
1331         int *num_blocks = alloca (sizeof (int) * num_block_obj_sizes);
1332
1333         for (i = 0; i < num_block_obj_sizes; ++i)
1334                 slots_available [i] = slots_used [i] = num_blocks [i] = 0;
1335
1336         /* clear all the free lists */
1337         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1338                 MSBlockInfo **free_blocks = free_block_lists [i];
1339                 int j;
1340                 for (j = 0; j < num_block_obj_sizes; ++j)
1341                         free_blocks [j] = NULL;
1342         }
1343
1344         /* traverse all blocks, free and zero unmarked objects */
1345         iter = &all_blocks;
1346         while (*iter) {
1347                 MSBlockInfo *block = *iter;
1348                 int count;
1349                 gboolean have_live = FALSE;
1350                 gboolean has_pinned;
1351                 int obj_index;
1352                 int obj_size_index;
1353
1354                 obj_size_index = block->obj_size_index;
1355
1356                 has_pinned = block->has_pinned;
1357                 block->has_pinned = block->pinned;
1358
1359                 block->is_to_space = FALSE;
1360
1361                 count = MS_BLOCK_FREE / block->obj_size;
1362                 block->free_list = NULL;
1363
1364                 for (obj_index = 0; obj_index < count; ++obj_index) {
1365                         int word, bit;
1366                         void *obj = MS_BLOCK_OBJ (block, obj_index);
1367
1368                         MS_CALC_MARK_BIT (word, bit, obj);
1369                         if (MS_MARK_BIT (block, word, bit)) {
1370                                 DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
1371                                 have_live = TRUE;
1372                                 if (!has_pinned)
1373                                         ++slots_used [obj_size_index];
1374                         } else {
1375                                 /* an unmarked object */
1376                                 if (MS_OBJ_ALLOCED (obj, block)) {
1377                                         binary_protocol_empty (obj, block->obj_size);
1378                                         memset (obj, 0, block->obj_size);
1379                                 }
1380                                 *(void**)obj = block->free_list;
1381                                 block->free_list = obj;
1382                         }
1383                 }
1384
1385                 /* reset mark bits */
1386                 memset (block->mark_words, 0, sizeof (mword) * MS_NUM_MARK_WORDS);
1387
1388                 /*
1389                  * FIXME: reverse free list so that it's in address
1390                  * order
1391                  */
1392
1393                 if (have_live) {
1394                         if (!has_pinned) {
1395                                 ++num_blocks [obj_size_index];
1396                                 slots_available [obj_size_index] += count;
1397                         }
1398
1399                         iter = &block->next;
1400
1401                         /*
1402                          * If there are free slots in the block, add
1403                          * the block to the corresponding free list.
1404                          */
1405                         if (block->free_list) {
1406                                 MSBlockInfo **free_blocks = FREE_BLOCKS (block->pinned, block->has_references);
1407                                 int index = MS_BLOCK_OBJ_SIZE_INDEX (block->obj_size);
1408                                 block->next_free = free_blocks [index];
1409                                 free_blocks [index] = block;
1410                         }
1411
1412                         update_heap_boundaries_for_block (block);
1413                 } else {
1414                         /*
1415                          * Blocks without live objects are removed from the
1416                          * block list and freed.
1417                          */
1418                         *iter = block->next;
1419
1420 #ifdef FIXED_HEAP
1421                         ms_free_block (block);
1422 #else
1423                         ms_free_block (block->block);
1424
1425                         mono_sgen_free_internal (block, INTERNAL_MEM_MS_BLOCK_INFO);
1426 #endif
1427
1428                         --num_major_sections;
1429                 }
1430         }
1431
1432         for (i = 0; i < num_block_obj_sizes; ++i) {
1433                 float usage = (float)slots_used [i] / (float)slots_available [i];
1434                 if (num_blocks [i] > 5 && usage < evacuation_threshold) {
1435                         evacuate_block_obj_sizes [i] = TRUE;
1436                         /*
1437                         g_print ("slot size %d - %d of %d used\n",
1438                                         block_obj_sizes [i], slots_used [i], slots_available [i]);
1439                         */
1440                 } else {
1441                         evacuate_block_obj_sizes [i] = FALSE;
1442                 }
1443         }
1444
1445         have_swept = TRUE;
1446 }
1447
1448 static void*
1449 ms_sweep_thread_func (void *dummy)
1450 {
1451         g_assert (concurrent_sweep);
1452
1453         for (;;) {
1454                 int result;
1455
1456                 while ((result = MONO_SEM_WAIT (&ms_sweep_cmd_semaphore)) != 0) {
1457                         if (errno != EINTR)
1458                                 g_error ("MONO_SEM_WAIT");
1459                 }
1460
1461                 ms_sweep ();
1462
1463                 ms_signal_sweep_done ();
1464         }
1465
1466         return NULL;
1467 }
1468
1469 static void
1470 major_sweep (void)
1471 {
1472         if (concurrent_sweep) {
1473                 g_assert (ms_sweep_thread);
1474                 ms_signal_sweep_command ();
1475         } else {
1476                 ms_sweep ();
1477         }
1478 }
1479
1480 static int count_pinned_ref;
1481 static int count_pinned_nonref;
1482 static int count_nonpinned_ref;
1483 static int count_nonpinned_nonref;
1484
1485 static void
1486 count_nonpinned_callback (char *obj, size_t size, void *data)
1487 {
1488         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1489
1490         if (vtable->klass->has_references)
1491                 ++count_nonpinned_ref;
1492         else
1493                 ++count_nonpinned_nonref;
1494 }
1495
1496 static void
1497 count_pinned_callback (char *obj, size_t size, void *data)
1498 {
1499         MonoVTable *vtable = (MonoVTable*)LOAD_VTABLE (obj);
1500
1501         if (vtable->klass->has_references)
1502                 ++count_pinned_ref;
1503         else
1504                 ++count_pinned_nonref;
1505 }
1506
1507 static void __attribute__ ((unused))
1508 count_ref_nonref_objs (void)
1509 {
1510         int total;
1511
1512         count_pinned_ref = 0;
1513         count_pinned_nonref = 0;
1514         count_nonpinned_ref = 0;
1515         count_nonpinned_nonref = 0;
1516
1517         major_iterate_objects (TRUE, FALSE, count_nonpinned_callback, NULL);
1518         major_iterate_objects (FALSE, TRUE, count_pinned_callback, NULL);
1519
1520         total = count_pinned_nonref + count_nonpinned_nonref + count_pinned_ref + count_nonpinned_ref;
1521
1522         g_print ("ref: %d pinned %d non-pinned   non-ref: %d pinned %d non-pinned  --  %.1f\n",
1523                         count_pinned_ref, count_nonpinned_ref,
1524                         count_pinned_nonref, count_nonpinned_nonref,
1525                         (count_pinned_nonref + count_nonpinned_nonref) * 100.0 / total);
1526 }
1527
1528 static int
1529 ms_calculate_block_obj_sizes (double factor, int *arr)
1530 {
1531         double target_size = sizeof (MonoObject);
1532         int num_sizes = 0;
1533         int last_size = 0;
1534
1535         do {
1536                 int target_count = ceil (MS_BLOCK_FREE / target_size);
1537                 int size = MIN ((MS_BLOCK_FREE / target_count) & ~(SGEN_ALLOC_ALIGN - 1), SGEN_MAX_SMALL_OBJ_SIZE);
1538
1539                 if (size != last_size) {
1540                         if (arr)
1541                                 arr [num_sizes] = size;
1542                         ++num_sizes;
1543                         last_size = size;
1544                 }
1545
1546                 target_size *= factor;
1547         } while (last_size < SGEN_MAX_SMALL_OBJ_SIZE);
1548
1549         return num_sizes;
1550 }
1551
1552 /* only valid during minor collections */
1553 static int old_num_major_sections;
1554
1555 static void
1556 major_start_nursery_collection (void)
1557 {
1558         ms_wait_for_sweep_done ();
1559
1560 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1561         consistency_check ();
1562 #endif
1563
1564         old_num_major_sections = num_major_sections;
1565 }
1566
1567 static void
1568 major_finish_nursery_collection (void)
1569 {
1570 #ifdef MARKSWEEP_CONSISTENCY_CHECK
1571         consistency_check ();
1572 #endif
1573         mono_sgen_register_major_sections_alloced (num_major_sections - old_num_major_sections);
1574 }
1575
1576 static void
1577 major_start_major_collection (void)
1578 {
1579         int i;
1580
1581         ms_wait_for_sweep_done ();
1582
1583         /* clear the free lists */
1584         for (i = 0; i < num_block_obj_sizes; ++i) {
1585                 if (!evacuate_block_obj_sizes [i])
1586                         continue;
1587
1588                 free_block_lists [0][i] = NULL;
1589                 free_block_lists [MS_BLOCK_FLAG_REFS][i] = NULL;
1590         }
1591 }
1592
1593 static void
1594 major_finish_major_collection (void)
1595 {
1596 }
1597
1598 static void
1599 major_have_computer_minor_collection_allowance (void)
1600 {
1601 #ifndef FIXED_HEAP
1602         int section_reserve = mono_sgen_get_minor_collection_allowance () / MS_BLOCK_SIZE;
1603
1604         g_assert (have_swept);
1605         ms_wait_for_sweep_done ();
1606         g_assert (!ms_sweep_in_progress);
1607
1608         /*
1609          * FIXME: We don't free blocks on 32 bit platforms because it
1610          * can lead to address space fragmentation, since we're
1611          * allocating blocks in larger contingents.
1612          */
1613         if (sizeof (mword) < 8)
1614                 return;
1615
1616         while (num_empty_blocks > section_reserve) {
1617                 void *next = *(void**)empty_blocks;
1618                 mono_sgen_free_os_memory (empty_blocks, MS_BLOCK_SIZE);
1619                 empty_blocks = next;
1620                 /*
1621                  * Needs not be atomic because this is running
1622                  * single-threaded.
1623                  */
1624                 --num_empty_blocks;
1625
1626                 ++stat_major_blocks_freed;
1627         }
1628 #endif
1629 }
1630
1631 static void
1632 major_find_pin_queue_start_ends (SgenGrayQueue *queue)
1633 {
1634         MSBlockInfo *block;
1635
1636         FOREACH_BLOCK (block) {
1637                 block->pin_queue_start = mono_sgen_find_optimized_pin_queue_area (block->block + MS_BLOCK_SKIP, block->block + MS_BLOCK_SIZE,
1638                                 &block->pin_queue_num_entries);
1639         } END_FOREACH_BLOCK;
1640 }
1641
1642 static void
1643 major_pin_objects (SgenGrayQueue *queue)
1644 {
1645         MSBlockInfo *block;
1646
1647         FOREACH_BLOCK (block) {
1648                 mark_pinned_objects_in_block (block, queue);
1649         } END_FOREACH_BLOCK;
1650 }
1651
1652 static void
1653 major_init_to_space (void)
1654 {
1655 }
1656
1657 static void
1658 major_report_pinned_memory_usage (void)
1659 {
1660         g_assert_not_reached ();
1661 }
1662
1663 static gint64
1664 major_get_used_size (void)
1665 {
1666         gint64 size = 0;
1667         MSBlockInfo *block;
1668
1669         FOREACH_BLOCK (block) {
1670                 int count = MS_BLOCK_FREE / block->obj_size;
1671                 void **iter;
1672                 size += count * block->obj_size;
1673                 for (iter = block->free_list; iter; iter = (void**)*iter)
1674                         size -= block->obj_size;
1675         } END_FOREACH_BLOCK;
1676
1677         return size;
1678 }
1679
1680 static int
1681 get_num_major_sections (void)
1682 {
1683         return num_major_sections;
1684 }
1685
1686 static gboolean
1687 major_handle_gc_param (const char *opt)
1688 {
1689 #ifdef FIXED_HEAP
1690         if (g_str_has_prefix (opt, "major-heap-size=")) {
1691                 const char *arg = strchr (opt, '=') + 1;
1692                 glong size;
1693                 if (!mono_gc_parse_environment_string_extract_number (arg, &size))
1694                         return FALSE;
1695                 ms_heap_num_blocks = (size + MS_BLOCK_SIZE - 1) / MS_BLOCK_SIZE;
1696                 g_assert (ms_heap_num_blocks > 0);
1697                 return TRUE;
1698         } else
1699 #endif
1700         if (g_str_has_prefix (opt, "evacuation-threshold=")) {
1701                 const char *arg = strchr (opt, '=') + 1;
1702                 int percentage = atoi (arg);
1703                 if (percentage < 0 || percentage > 100) {
1704                         fprintf (stderr, "evacuation-threshold must be an integer in the range 0-100.\n");
1705                         exit (1);
1706                 }
1707                 evacuation_threshold = (float)percentage / 100.0;
1708                 return TRUE;
1709         } else if (!strcmp (opt, "concurrent-sweep")) {
1710                 concurrent_sweep = TRUE;
1711                 return TRUE;
1712         } else if (!strcmp (opt, "no-concurrent-sweep")) {
1713                 concurrent_sweep = FALSE;
1714                 return TRUE;
1715         }
1716
1717         return FALSE;
1718 }
1719
1720 static void
1721 major_print_gc_param_usage (void)
1722 {
1723         fprintf (stderr,
1724                         ""
1725 #ifdef FIXED_HEAP
1726                         "  major-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n"
1727 #endif
1728                         "  evacuation-threshold=P (where P is a percentage, an integer in 0-100)\n"
1729                         "  (no-)concurrent-sweep\n"
1730                         );
1731 }
1732
1733 #ifdef SGEN_HAVE_CARDTABLE
1734 static void
1735 major_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
1736 {
1737         MSBlockInfo *block;
1738
1739         FOREACH_BLOCK (block) {
1740                 if (block->has_references)
1741                         callback ((mword)block->block, MS_BLOCK_SIZE);
1742         } END_FOREACH_BLOCK;
1743 }
1744
1745 #ifdef HEAVY_STATISTICS
1746 extern long long marked_cards;
1747 extern long long scanned_cards;
1748 extern long long scanned_objects;
1749
1750 #endif
1751
1752 #define CARD_WORDS_PER_BLOCK (CARDS_PER_BLOCK / SIZEOF_VOID_P)
1753 /*
1754  * MS blocks are 16K aligned.
1755  * Cardtables are 4K aligned, at least.
1756  * This means that the cardtable of a given block is 32 bytes aligned.
1757  */
1758 static guint8*
1759 initial_skip_card (guint8 *card_data)
1760 {
1761         mword *cards = (mword*)card_data;
1762         mword card;
1763         int i;
1764         for (i = 0; i < CARD_WORDS_PER_BLOCK; ++i) {
1765                 card = cards [i];
1766                 if (card)
1767                         break;
1768         }
1769
1770         if (i == CARD_WORDS_PER_BLOCK)
1771                 return card_data + CARDS_PER_BLOCK;
1772
1773 #if defined(__i386__) && defined(__GNUC__)
1774         return card_data + i * 4 +  (__builtin_ffs (card) - 1) / 8;
1775 #elif defined(__x86_64__) && defined(__GNUC__)
1776         return card_data + i * 8 +  (__builtin_ffsll (card) - 1) / 8;
1777 #else
1778         for (i = i * SIZEOF_VOID_P; i < CARDS_PER_BLOCK; ++i) {
1779                 if (card_data [i])
1780                         return &card_data [i];
1781         }
1782         return card_data;
1783 #endif
1784 }
1785
1786
1787 static G_GNUC_UNUSED guint8*
1788 skip_card (guint8 *card_data, guint8 *card_data_end)
1789 {
1790         while (card_data < card_data_end && !*card_data)
1791                 ++card_data;
1792         return card_data;
1793 }
1794
1795 #define MS_BLOCK_OBJ_INDEX_FAST(o,b,os) (((char*)(o) - ((b) + MS_BLOCK_SKIP)) / (os))
1796 #define MS_BLOCK_OBJ_FAST(b,os,i)                       ((b) + MS_BLOCK_SKIP + (os) * (i))
1797 #define MS_OBJ_ALLOCED_FAST(o,b)                (*(void**)(o) && (*(char**)(o) < (b) || *(char**)(o) >= (b) + MS_BLOCK_SIZE))
1798
1799 static void
1800 major_scan_card_table (SgenGrayQueue *queue)
1801 {
1802         MSBlockInfo *block;
1803
1804         FOREACH_BLOCK (block) {
1805                 int block_obj_size;
1806                 char *block_start;
1807
1808                 if (!block->has_references)
1809                         continue;
1810
1811                 block_obj_size = block->obj_size;
1812                 block_start = block->block;
1813
1814                 if (block_obj_size >= CARD_SIZE_IN_BYTES) {
1815                         guint8 *cards;
1816 #ifndef SGEN_HAVE_OVERLAPPING_CARDS
1817                         guint8 cards_data [CARDS_PER_BLOCK];
1818 #endif
1819                         char *obj, *end, *base;
1820
1821                         /*We can avoid the extra copy since the remark cardtable was cleaned before */
1822 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
1823                         cards = sgen_card_table_get_card_scan_address ((mword)block_start);
1824 #else
1825                         cards = cards_data;
1826                         if (!sgen_card_table_get_card_data (cards_data, (mword)block_start, CARDS_PER_BLOCK))
1827                                 continue;
1828 #endif
1829
1830                         obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, 0);
1831                         end = block_start + MS_BLOCK_SIZE;
1832                         base = sgen_card_table_align_pointer (obj);
1833
1834                         while (obj < end) {
1835                                 if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1836                                         int card_offset = (obj - base) >> CARD_BITS;
1837                                         sgen_cardtable_scan_object (obj, block_obj_size, cards + card_offset, queue);
1838                                 }
1839                                 obj += block_obj_size;
1840                         }
1841                 } else {
1842                         guint8 *card_data, *card_base;
1843                         guint8 *card_data_end;
1844
1845                         /*
1846                          * This is safe in face of card aliasing for the following reason:
1847                          *
1848                          * Major blocks are 16k aligned, or 32 cards aligned.
1849                          * Cards aliasing happens in powers of two, so as long as major blocks are aligned to their
1850                          * sizes, they won't overflow the cardtable overlap modulus.
1851                          */
1852                         card_data = card_base = sgen_card_table_get_card_scan_address ((mword)block_start);
1853                         card_data_end = card_data + CARDS_PER_BLOCK;
1854
1855                         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)) {
1856                                 int index;
1857                                 int idx = card_data - card_base;
1858                                 char *start = (char*)(block_start + idx * CARD_SIZE_IN_BYTES);
1859                                 char *end = start + CARD_SIZE_IN_BYTES;
1860                                 char *obj;
1861
1862                                 HEAVY_STAT (++scanned_cards);
1863
1864                                 if (!*card_data)
1865                                         continue;
1866
1867                                 HEAVY_STAT (++marked_cards);
1868
1869                                 sgen_card_table_prepare_card_for_scanning (card_data);
1870
1871                                 if (idx == 0)
1872                                         index = 0;
1873                                 else
1874                                         index = MS_BLOCK_OBJ_INDEX_FAST (start, block_start, block_obj_size);
1875
1876                                 obj = (char*)MS_BLOCK_OBJ_FAST (block_start, block_obj_size, index);
1877                                 while (obj < end) {
1878                                         if (MS_OBJ_ALLOCED_FAST (obj, block_start)) {
1879                                                 HEAVY_STAT (++scanned_objects);
1880                                                 minor_scan_object (obj, queue);
1881                                         }
1882                                         obj += block_obj_size;
1883                                 }
1884                         }
1885                 }
1886         } END_FOREACH_BLOCK;
1887 }
1888 #endif
1889
1890 static gboolean
1891 major_is_worker_thread (pthread_t thread)
1892 {
1893         if (concurrent_sweep)
1894                 return thread == ms_sweep_thread;
1895         else
1896                 return FALSE;
1897 }
1898
1899 static void
1900 alloc_free_block_lists (MSBlockInfo ***lists)
1901 {
1902         int i;
1903         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i)
1904                 lists [i] = mono_sgen_alloc_internal_dynamic (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1905 }
1906
1907 #ifdef SGEN_PARALLEL_MARK
1908 static void*
1909 major_alloc_worker_data (void)
1910 {
1911         /* FIXME: free this when the workers come down */
1912         MSBlockInfo ***lists = malloc (sizeof (MSBlockInfo**) * MS_BLOCK_TYPE_MAX);
1913         alloc_free_block_lists (lists);
1914         return lists;
1915 }
1916
1917 static void
1918 major_init_worker_thread (void *data)
1919 {
1920         MSBlockInfo ***lists = data;
1921         int i;
1922
1923         g_assert (lists && lists != free_block_lists);
1924         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1925                 int j;
1926                 for (j = 0; j < num_block_obj_sizes; ++j)
1927                         g_assert (!lists [i][j]);
1928         }
1929
1930 #ifdef HAVE_KW_THREAD
1931         workers_free_block_lists = data;
1932 #else
1933         pthread_setspecific (workers_free_block_lists_key, data);
1934 #endif
1935 }
1936
1937 static void
1938 major_reset_worker_data (void *data)
1939 {
1940         MSBlockInfo ***lists = data;
1941         int i;
1942         for (i = 0; i < MS_BLOCK_TYPE_MAX; ++i) {
1943                 int j;
1944                 for (j = 0; j < num_block_obj_sizes; ++j)
1945                         lists [i][j] = NULL;
1946         }
1947 }
1948 #endif
1949
1950 #undef pthread_create
1951
1952 static void
1953 post_param_init (void)
1954 {
1955         if (concurrent_sweep) {
1956                 if (pthread_create (&ms_sweep_thread, NULL, ms_sweep_thread_func, NULL)) {
1957                         fprintf (stderr, "Error: Could not create sweep thread.\n");
1958                         exit (1);
1959                 }
1960         }
1961 }
1962
1963 void
1964 #ifdef SGEN_PARALLEL_MARK
1965 #ifdef FIXED_HEAP
1966 mono_sgen_marksweep_fixed_par_init
1967 #else
1968 mono_sgen_marksweep_par_init
1969 #endif
1970 #else
1971 #ifdef FIXED_HEAP
1972 mono_sgen_marksweep_fixed_init
1973 #else
1974 mono_sgen_marksweep_init
1975 #endif
1976 #endif
1977         (SgenMajorCollector *collector)
1978 {
1979         int i;
1980
1981 #ifndef FIXED_HEAP
1982         mono_sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, sizeof (MSBlockInfo));
1983 #endif
1984
1985         num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
1986         block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1987         ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
1988
1989         evacuate_block_obj_sizes = mono_sgen_alloc_internal_dynamic (sizeof (gboolean) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
1990         for (i = 0; i < num_block_obj_sizes; ++i)
1991                 evacuate_block_obj_sizes [i] = FALSE;
1992
1993         /*
1994         {
1995                 int i;
1996                 g_print ("block object sizes:\n");
1997                 for (i = 0; i < num_block_obj_sizes; ++i)
1998                         g_print ("%d\n", block_obj_sizes [i]);
1999         }
2000         */
2001
2002         alloc_free_block_lists (free_block_lists);
2003
2004         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
2005                 fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
2006         for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
2007                 g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
2008
2009         LOCK_INIT (ms_block_list_mutex);
2010
2011         mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_alloced);
2012         mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_freed);
2013         mono_counters_register ("# major objects evacuated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_objects_evacuated);
2014         mono_counters_register ("Wait for sweep time", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_time_wait_for_sweep);
2015 #ifdef SGEN_PARALLEL_MARK
2016         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
2017
2018 #ifndef HAVE_KW_THREAD
2019         pthread_key_create (&workers_free_block_lists_key, NULL);
2020 #endif
2021 #endif
2022
2023         /*
2024          * FIXME: These are superfluous if concurrent sweep is
2025          * disabled.  We might want to create them lazily.
2026          */
2027         MONO_SEM_INIT (&ms_sweep_cmd_semaphore, 0);
2028         MONO_SEM_INIT (&ms_sweep_done_semaphore, 0);
2029
2030         collector->section_size = MAJOR_SECTION_SIZE;
2031 #ifdef SGEN_PARALLEL_MARK
2032         collector->is_parallel = TRUE;
2033         collector->alloc_worker_data = major_alloc_worker_data;
2034         collector->init_worker_thread = major_init_worker_thread;
2035         collector->reset_worker_data = major_reset_worker_data;
2036 #else
2037         collector->is_parallel = FALSE;
2038 #endif
2039         collector->supports_cardtable = TRUE;
2040
2041         collector->have_swept = &have_swept;
2042
2043         collector->alloc_heap = major_alloc_heap;
2044         collector->is_object_live = major_is_object_live;
2045         collector->alloc_small_pinned_obj = major_alloc_small_pinned_obj;
2046         collector->alloc_degraded = major_alloc_degraded;
2047         collector->copy_or_mark_object = major_copy_or_mark_object;
2048         collector->alloc_object = major_alloc_object;
2049         collector->free_pinned_object = free_pinned_object;
2050         collector->iterate_objects = major_iterate_objects;
2051         collector->free_non_pinned_object = major_free_non_pinned_object;
2052         collector->find_pin_queue_start_ends = major_find_pin_queue_start_ends;
2053         collector->pin_objects = major_pin_objects;
2054 #ifdef SGEN_HAVE_CARDTABLE
2055         collector->scan_card_table = major_scan_card_table;
2056         collector->iterate_live_block_ranges = (void*)(void*) major_iterate_live_block_ranges;
2057 #endif
2058         collector->init_to_space = major_init_to_space;
2059         collector->sweep = major_sweep;
2060         collector->check_scan_starts = major_check_scan_starts;
2061         collector->dump_heap = major_dump_heap;
2062         collector->get_used_size = major_get_used_size;
2063         collector->start_nursery_collection = major_start_nursery_collection;
2064         collector->finish_nursery_collection = major_finish_nursery_collection;
2065         collector->start_major_collection = major_start_major_collection;
2066         collector->finish_major_collection = major_finish_major_collection;
2067         collector->have_computed_minor_collection_allowance = major_have_computer_minor_collection_allowance;
2068         collector->ptr_is_in_non_pinned_space = major_ptr_is_in_non_pinned_space;
2069         collector->obj_is_from_pinned_alloc = obj_is_from_pinned_alloc;
2070         collector->report_pinned_memory_usage = major_report_pinned_memory_usage;
2071         collector->get_num_major_sections = get_num_major_sections;
2072         collector->handle_gc_param = major_handle_gc_param;
2073         collector->print_gc_param_usage = major_print_gc_param_usage;
2074         collector->is_worker_thread = major_is_worker_thread;
2075         collector->post_param_init = post_param_init;
2076
2077         FILL_COLLECTOR_COPY_OBJECT (collector);
2078         FILL_COLLECTOR_SCAN_OBJECT (collector);
2079
2080 #ifdef SGEN_HAVE_CARDTABLE
2081         /*cardtable requires major pages to be 8 cards aligned*/
2082         g_assert ((MS_BLOCK_SIZE % (8 * CARD_SIZE_IN_BYTES)) == 0);
2083 #endif
2084 }
2085
2086 #endif