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