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