Added time format with only offset. Fixes #22558.
[mono.git] / mono / metadata / sgen-gc.c
1 /*
2  * sgen-gc.c: Simple generational GC.
3  *
4  * Author:
5  *      Paolo Molaro (lupus@ximian.com)
6  *  Rodrigo Kumpera (kumpera@gmail.com)
7  *
8  * Copyright 2005-2011 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  *
11  * Thread start/stop adapted from Boehm's GC:
12  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
13  * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
14  * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
15  * Copyright (c) 2000-2004 by Hewlett-Packard Company.  All rights reserved.
16  * Copyright 2001-2003 Ximian, Inc
17  * Copyright 2003-2010 Novell, Inc.
18  * Copyright 2011 Xamarin, Inc.
19  * Copyright (C) 2012 Xamarin Inc
20  *
21  * This library is free software; you can redistribute it and/or
22  * modify it under the terms of the GNU Library General Public
23  * License 2.0 as published by the Free Software Foundation;
24  *
25  * This library is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28  * Library General Public License for more details.
29  *
30  * You should have received a copy of the GNU Library General Public
31  * License 2.0 along with this library; if not, write to the Free
32  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33  *
34  * Important: allocation provides always zeroed memory, having to do
35  * a memset after allocation is deadly for performance.
36  * Memory usage at startup is currently as follows:
37  * 64 KB pinned space
38  * 64 KB internal space
39  * size of nursery
40  * We should provide a small memory config with half the sizes
41  *
42  * We currently try to make as few mono assumptions as possible:
43  * 1) 2-word header with no GC pointers in it (first vtable, second to store the
44  *    forwarding ptr)
45  * 2) gc descriptor is the second word in the vtable (first word in the class)
46  * 3) 8 byte alignment is the minimum and enough (not true for special structures (SIMD), FIXME)
47  * 4) there is a function to get an object's size and the number of
48  *    elements in an array.
49  * 5) we know the special way bounds are allocated for complex arrays
50  * 6) we know about proxies and how to treat them when domains are unloaded
51  *
52  * Always try to keep stack usage to a minimum: no recursive behaviour
53  * and no large stack allocs.
54  *
55  * General description.
56  * Objects are initially allocated in a nursery using a fast bump-pointer technique.
57  * When the nursery is full we start a nursery collection: this is performed with a
58  * copying GC.
59  * When the old generation is full we start a copying GC of the old generation as well:
60  * this will be changed to mark&sweep with copying when fragmentation becomes to severe
61  * in the future.  Maybe we'll even do both during the same collection like IMMIX.
62  *
63  * The things that complicate this description are:
64  * *) pinned objects: we can't move them so we need to keep track of them
65  * *) no precise info of the thread stacks and registers: we need to be able to
66  *    quickly find the objects that may be referenced conservatively and pin them
67  *    (this makes the first issues more important)
68  * *) large objects are too expensive to be dealt with using copying GC: we handle them
69  *    with mark/sweep during major collections
70  * *) some objects need to not move even if they are small (interned strings, Type handles):
71  *    we use mark/sweep for them, too: they are not allocated in the nursery, but inside
72  *    PinnedChunks regions
73  */
74
75 /*
76  * TODO:
77
78  *) we could have a function pointer in MonoClass to implement
79   customized write barriers for value types
80
81  *) investigate the stuff needed to advance a thread to a GC-safe
82   point (single-stepping, read from unmapped memory etc) and implement it.
83   This would enable us to inline allocations and write barriers, for example,
84   or at least parts of them, like the write barrier checks.
85   We may need this also for handling precise info on stacks, even simple things
86   as having uninitialized data on the stack and having to wait for the prolog
87   to zero it. Not an issue for the last frame that we scan conservatively.
88   We could always not trust the value in the slots anyway.
89
90  *) modify the jit to save info about references in stack locations:
91   this can be done just for locals as a start, so that at least
92   part of the stack is handled precisely.
93
94  *) test/fix endianess issues
95
96  *) Implement a card table as the write barrier instead of remembered
97     sets?  Card tables are not easy to implement with our current
98     memory layout.  We have several different kinds of major heap
99     objects: Small objects in regular blocks, small objects in pinned
100     chunks and LOS objects.  If we just have a pointer we have no way
101     to tell which kind of object it points into, therefore we cannot
102     know where its card table is.  The least we have to do to make
103     this happen is to get rid of write barriers for indirect stores.
104     (See next item)
105
106  *) Get rid of write barriers for indirect stores.  We can do this by
107     telling the GC to wbarrier-register an object once we do an ldloca
108     or ldelema on it, and to unregister it once it's not used anymore
109     (it can only travel downwards on the stack).  The problem with
110     unregistering is that it needs to happen eventually no matter
111     what, even if exceptions are thrown, the thread aborts, etc.
112     Rodrigo suggested that we could do only the registering part and
113     let the collector find out (pessimistically) when it's safe to
114     unregister, namely when the stack pointer of the thread that
115     registered the object is higher than it was when the registering
116     happened.  This might make for a good first implementation to get
117     some data on performance.
118
119  *) Some sort of blacklist support?  Blacklists is a concept from the
120     Boehm GC: if during a conservative scan we find pointers to an
121     area which we might use as heap, we mark that area as unusable, so
122     pointer retention by random pinning pointers is reduced.
123
124  *) experiment with max small object size (very small right now - 2kb,
125     because it's tied to the max freelist size)
126
127   *) add an option to mmap the whole heap in one chunk: it makes for many
128      simplifications in the checks (put the nursery at the top and just use a single
129      check for inclusion/exclusion): the issue this has is that on 32 bit systems it's
130      not flexible (too much of the address space may be used by default or we can't
131      increase the heap as needed) and we'd need a race-free mechanism to return memory
132      back to the system (mprotect(PROT_NONE) will still keep the memory allocated if it
133      was written to, munmap is needed, but the following mmap may not find the same segment
134      free...)
135
136  *) memzero the major fragments after restarting the world and optionally a smaller
137     chunk at a time
138
139  *) investigate having fragment zeroing threads
140
141  *) separate locks for finalization and other minor stuff to reduce
142     lock contention
143
144  *) try a different copying order to improve memory locality
145
146  *) a thread abort after a store but before the write barrier will
147     prevent the write barrier from executing
148
149  *) specialized dynamically generated markers/copiers
150
151  *) Dynamically adjust TLAB size to the number of threads.  If we have
152     too many threads that do allocation, we might need smaller TLABs,
153     and we might get better performance with larger TLABs if we only
154     have a handful of threads.  We could sum up the space left in all
155     assigned TLABs and if that's more than some percentage of the
156     nursery size, reduce the TLAB size.
157
158  *) Explore placing unreachable objects on unused nursery memory.
159         Instead of memset'ng a region to zero, place an int[] covering it.
160         A good place to start is add_nursery_frag. The tricky thing here is
161         placing those objects atomically outside of a collection.
162
163  *) Allocation should use asymmetric Dekker synchronization:
164         http://blogs.oracle.com/dave/resource/Asymmetric-Dekker-Synchronization.txt
165         This should help weak consistency archs.
166  */
167 #include "config.h"
168 #ifdef HAVE_SGEN_GC
169
170 #ifdef __MACH__
171 #undef _XOPEN_SOURCE
172 #define _XOPEN_SOURCE
173 #define _DARWIN_C_SOURCE
174 #endif
175
176 #ifdef HAVE_UNISTD_H
177 #include <unistd.h>
178 #endif
179 #ifdef HAVE_PTHREAD_H
180 #include <pthread.h>
181 #endif
182 #ifdef HAVE_PTHREAD_NP_H
183 #include <pthread_np.h>
184 #endif
185 #ifdef HAVE_SEMAPHORE_H
186 #include <semaphore.h>
187 #endif
188 #include <stdio.h>
189 #include <string.h>
190 #include <signal.h>
191 #include <errno.h>
192 #include <assert.h>
193
194 #include "metadata/sgen-gc.h"
195 #include "metadata/metadata-internals.h"
196 #include "metadata/class-internals.h"
197 #include "metadata/gc-internal.h"
198 #include "metadata/object-internals.h"
199 #include "metadata/threads.h"
200 #include "metadata/sgen-cardtable.h"
201 #include "metadata/sgen-protocol.h"
202 #include "metadata/sgen-archdep.h"
203 #include "metadata/sgen-bridge.h"
204 #include "metadata/sgen-memory-governor.h"
205 #include "metadata/sgen-hash-table.h"
206 #include "metadata/mono-gc.h"
207 #include "metadata/method-builder.h"
208 #include "metadata/profiler-private.h"
209 #include "metadata/monitor.h"
210 #include "metadata/mempool-internals.h"
211 #include "metadata/marshal.h"
212 #include "metadata/runtime.h"
213 #include "metadata/sgen-cardtable.h"
214 #include "metadata/sgen-pinning.h"
215 #include "metadata/sgen-workers.h"
216 #include "metadata/sgen-layout-stats.h"
217 #include "utils/mono-mmap.h"
218 #include "utils/mono-time.h"
219 #include "utils/mono-semaphore.h"
220 #include "utils/mono-counters.h"
221 #include "utils/mono-proclib.h"
222 #include "utils/mono-memory-model.h"
223 #include "utils/mono-logger-internal.h"
224 #include "utils/dtrace.h"
225
226 #include <mono/utils/mono-logger-internal.h>
227 #include <mono/utils/memcheck.h>
228
229 #if defined(__MACH__)
230 #include "utils/mach-support.h"
231 #endif
232
233 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
234         a = i,
235
236 enum {
237 #include "mono/cil/opcode.def"
238         CEE_LAST
239 };
240
241 #undef OPDEF
242
243 #undef pthread_create
244 #undef pthread_join
245 #undef pthread_detach
246
247 /*
248  * ######################################################################
249  * ########  Types and constants used by the GC.
250  * ######################################################################
251  */
252
253 /* 0 means not initialized, 1 is initialized, -1 means in progress */
254 static int gc_initialized = 0;
255 /* If set, check if we need to do something every X allocations */
256 gboolean has_per_allocation_action;
257 /* If set, do a heap check every X allocation */
258 guint32 verify_before_allocs = 0;
259 /* If set, do a minor collection before every X allocation */
260 guint32 collect_before_allocs = 0;
261 /* If set, do a whole heap check before each collection */
262 static gboolean whole_heap_check_before_collection = FALSE;
263 /* If set, do a heap consistency check before each minor collection */
264 static gboolean consistency_check_at_minor_collection = FALSE;
265 /* If set, do a mod union consistency check before each finishing collection pause */
266 static gboolean mod_union_consistency_check = FALSE;
267 /* If set, check whether mark bits are consistent after major collections */
268 static gboolean check_mark_bits_after_major_collection = FALSE;
269 /* If set, check that all nursery objects are pinned/not pinned, depending on context */
270 static gboolean check_nursery_objects_pinned = FALSE;
271 /* If set, do a few checks when the concurrent collector is used */
272 static gboolean do_concurrent_checks = FALSE;
273 /* If set, check that there are no references to the domain left at domain unload */
274 static gboolean xdomain_checks = FALSE;
275 /* If not null, dump the heap after each collection into this file */
276 static FILE *heap_dump_file = NULL;
277 /* If set, mark stacks conservatively, even if precise marking is possible */
278 static gboolean conservative_stack_mark = FALSE;
279 /* If set, do a plausibility check on the scan_starts before and after
280    each collection */
281 static gboolean do_scan_starts_check = FALSE;
282 /*
283  * If the major collector is concurrent and this is FALSE, we will
284  * never initiate a synchronous major collection, unless requested via
285  * GC.Collect().
286  */
287 static gboolean allow_synchronous_major = TRUE;
288 static gboolean nursery_collection_is_parallel = FALSE;
289 static gboolean disable_minor_collections = FALSE;
290 static gboolean disable_major_collections = FALSE;
291 gboolean do_pin_stats = FALSE;
292 static gboolean do_verify_nursery = FALSE;
293 static gboolean do_dump_nursery_content = FALSE;
294
295 #ifdef HEAVY_STATISTICS
296 long long stat_objects_alloced_degraded = 0;
297 long long stat_bytes_alloced_degraded = 0;
298
299 long long stat_copy_object_called_nursery = 0;
300 long long stat_objects_copied_nursery = 0;
301 long long stat_copy_object_called_major = 0;
302 long long stat_objects_copied_major = 0;
303
304 long long stat_scan_object_called_nursery = 0;
305 long long stat_scan_object_called_major = 0;
306
307 long long stat_slots_allocated_in_vain;
308
309 long long stat_nursery_copy_object_failed_from_space = 0;
310 long long stat_nursery_copy_object_failed_forwarded = 0;
311 long long stat_nursery_copy_object_failed_pinned = 0;
312 long long stat_nursery_copy_object_failed_to_space = 0;
313
314 static int stat_wbarrier_add_to_global_remset = 0;
315 static int stat_wbarrier_set_field = 0;
316 static int stat_wbarrier_set_arrayref = 0;
317 static int stat_wbarrier_arrayref_copy = 0;
318 static int stat_wbarrier_generic_store = 0;
319 static int stat_wbarrier_generic_store_atomic = 0;
320 static int stat_wbarrier_set_root = 0;
321 static int stat_wbarrier_value_copy = 0;
322 static int stat_wbarrier_object_copy = 0;
323 #endif
324
325 static long long stat_pinned_objects = 0;
326
327 static long long time_minor_pre_collection_fragment_clear = 0;
328 static long long time_minor_pinning = 0;
329 static long long time_minor_scan_remsets = 0;
330 static long long time_minor_scan_pinned = 0;
331 static long long time_minor_scan_registered_roots = 0;
332 static long long time_minor_scan_thread_data = 0;
333 static long long time_minor_finish_gray_stack = 0;
334 static long long time_minor_fragment_creation = 0;
335
336 static long long time_major_pre_collection_fragment_clear = 0;
337 static long long time_major_pinning = 0;
338 static long long time_major_scan_pinned = 0;
339 static long long time_major_scan_registered_roots = 0;
340 static long long time_major_scan_thread_data = 0;
341 static long long time_major_scan_alloc_pinned = 0;
342 static long long time_major_scan_finalized = 0;
343 static long long time_major_scan_big_objects = 0;
344 static long long time_major_finish_gray_stack = 0;
345 static long long time_major_free_bigobjs = 0;
346 static long long time_major_los_sweep = 0;
347 static long long time_major_sweep = 0;
348 static long long time_major_fragment_creation = 0;
349
350 int gc_debug_level = 0;
351 FILE* gc_debug_file;
352
353 static MonoGCFinalizerCallbacks fin_callbacks;
354
355 /*
356 void
357 mono_gc_flush_info (void)
358 {
359         fflush (gc_debug_file);
360 }
361 */
362
363 #define TV_DECLARE SGEN_TV_DECLARE
364 #define TV_GETTIME SGEN_TV_GETTIME
365 #define TV_ELAPSED SGEN_TV_ELAPSED
366 #define TV_ELAPSED_MS SGEN_TV_ELAPSED_MS
367
368 SGEN_TV_DECLARE (sgen_init_timestamp);
369
370 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
371
372 NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
373
374 #define object_is_forwarded     SGEN_OBJECT_IS_FORWARDED
375 #define object_is_pinned        SGEN_OBJECT_IS_PINNED
376 #define pin_object              SGEN_PIN_OBJECT
377 #define unpin_object            SGEN_UNPIN_OBJECT
378
379 #define ptr_in_nursery sgen_ptr_in_nursery
380
381 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
382
383 static const char*
384 safe_name (void* obj)
385 {
386         MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
387         return vt->klass->name;
388 }
389
390 #define safe_object_get_size    sgen_safe_object_get_size
391
392 const char*
393 sgen_safe_name (void* obj)
394 {
395         return safe_name (obj);
396 }
397
398 /*
399  * ######################################################################
400  * ########  Global data.
401  * ######################################################################
402  */
403 LOCK_DECLARE (gc_mutex);
404 gboolean sgen_try_free_some_memory;
405
406 #define SCAN_START_SIZE SGEN_SCAN_START_SIZE
407
408 static mword pagesize = 4096;
409 size_t degraded_mode = 0;
410
411 static mword bytes_pinned_from_failed_allocation = 0;
412
413 GCMemSection *nursery_section = NULL;
414 static mword lowest_heap_address = ~(mword)0;
415 static mword highest_heap_address = 0;
416
417 LOCK_DECLARE (sgen_interruption_mutex);
418 static LOCK_DECLARE (pin_queue_mutex);
419
420 #define LOCK_PIN_QUEUE mono_mutex_lock (&pin_queue_mutex)
421 #define UNLOCK_PIN_QUEUE mono_mutex_unlock (&pin_queue_mutex)
422
423 typedef struct _FinalizeReadyEntry FinalizeReadyEntry;
424 struct _FinalizeReadyEntry {
425         FinalizeReadyEntry *next;
426         void *object;
427 };
428
429 typedef struct _EphemeronLinkNode EphemeronLinkNode;
430
431 struct _EphemeronLinkNode {
432         EphemeronLinkNode *next;
433         char *array;
434 };
435
436 typedef struct {
437        void *key;
438        void *value;
439 } Ephemeron;
440
441 int current_collection_generation = -1;
442 volatile gboolean concurrent_collection_in_progress = FALSE;
443
444 /* objects that are ready to be finalized */
445 static FinalizeReadyEntry *fin_ready_list = NULL;
446 static FinalizeReadyEntry *critical_fin_list = NULL;
447
448 static EphemeronLinkNode *ephemeron_list;
449
450 /* registered roots: the key to the hash is the root start address */
451 /* 
452  * Different kinds of roots are kept separate to speed up pin_from_roots () for example.
453  */
454 SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
455         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
456         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL),
457         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), mono_aligned_addr_hash, NULL)
458 };
459 static mword roots_size = 0; /* amount of memory in the root set */
460
461 #define GC_ROOT_NUM 32
462 typedef struct {
463         int count;              /* must be the first field */
464         void *objects [GC_ROOT_NUM];
465         int root_types [GC_ROOT_NUM];
466         uintptr_t extra_info [GC_ROOT_NUM];
467 } GCRootReport;
468
469 static void
470 notify_gc_roots (GCRootReport *report)
471 {
472         if (!report->count)
473                 return;
474         mono_profiler_gc_roots (report->count, report->objects, report->root_types, report->extra_info);
475         report->count = 0;
476 }
477
478 static void
479 add_profile_gc_root (GCRootReport *report, void *object, int rtype, uintptr_t extra_info)
480 {
481         if (report->count == GC_ROOT_NUM)
482                 notify_gc_roots (report);
483         report->objects [report->count] = object;
484         report->root_types [report->count] = rtype;
485         report->extra_info [report->count++] = (uintptr_t)((MonoVTable*)LOAD_VTABLE (object))->klass;
486 }
487
488 MonoNativeTlsKey thread_info_key;
489
490 #ifdef HAVE_KW_THREAD
491 __thread SgenThreadInfo *sgen_thread_info;
492 __thread char *stack_end;
493 #endif
494
495 /* The size of a TLAB */
496 /* The bigger the value, the less often we have to go to the slow path to allocate a new 
497  * one, but the more space is wasted by threads not allocating much memory.
498  * FIXME: Tune this.
499  * FIXME: Make this self-tuning for each thread.
500  */
501 guint32 tlab_size = (1024 * 4);
502
503 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
504
505 /* Functions supplied by the runtime to be called by the GC */
506 static MonoGCCallbacks gc_callbacks;
507
508 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
509 #define ALLOC_ALIGN_BITS        SGEN_ALLOC_ALIGN_BITS
510
511 #define ALIGN_UP                SGEN_ALIGN_UP
512
513 #define MOVED_OBJECTS_NUM 64
514 static void *moved_objects [MOVED_OBJECTS_NUM];
515 static int moved_objects_idx = 0;
516
517 /* Vtable of the objects used to fill out nursery fragments before a collection */
518 static MonoVTable *array_fill_vtable;
519
520 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
521 MonoNativeThreadId main_gc_thread = NULL;
522 #endif
523
524 /*Object was pinned during the current collection*/
525 static mword objects_pinned;
526
527 /*
528  * ######################################################################
529  * ########  Macros and function declarations.
530  * ######################################################################
531  */
532
533 inline static void*
534 align_pointer (void *ptr)
535 {
536         mword p = (mword)ptr;
537         p += sizeof (gpointer) - 1;
538         p &= ~ (sizeof (gpointer) - 1);
539         return (void*)p;
540 }
541
542 typedef SgenGrayQueue GrayQueue;
543
544 /* forward declarations */
545 static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue);
546 static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
547 static void scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx);
548 static void report_finalizer_roots (void);
549 static void report_registered_roots (void);
550
551 static void pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue);
552 static void finish_gray_stack (int generation, GrayQueue *queue);
553
554 void mono_gc_scan_for_specific_ref (MonoObject *key, gboolean precise);
555
556
557 static void init_stats (void);
558
559 static int mark_ephemerons_in_range (ScanCopyContext ctx);
560 static void clear_unreachable_ephemerons (ScanCopyContext ctx);
561 static void null_ephemerons_for_domain (MonoDomain *domain);
562
563 static gboolean major_update_or_finish_concurrent_collection (gboolean force_finish);
564
565 SgenObjectOperations current_object_ops;
566 SgenMajorCollector major_collector;
567 SgenMinorCollector sgen_minor_collector;
568 static GrayQueue gray_queue;
569
570 static SgenRemeberedSet remset;
571
572 /* The gray queue to use from the main collection thread. */
573 #define WORKERS_DISTRIBUTE_GRAY_QUEUE   (&gray_queue)
574
575 /*
576  * The gray queue a worker job must use.  If we're not parallel or
577  * concurrent, we use the main gray queue.
578  */
579 static SgenGrayQueue*
580 sgen_workers_get_job_gray_queue (WorkerData *worker_data)
581 {
582         return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
583 }
584
585 static void
586 gray_queue_redirect (SgenGrayQueue *queue)
587 {
588         gboolean wake = FALSE;
589
590
591         for (;;) {
592                 GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
593                 if (!section)
594                         break;
595                 sgen_section_gray_queue_enqueue (queue->alloc_prepare_data, section);
596                 wake = TRUE;
597         }
598
599         if (wake) {
600                 g_assert (concurrent_collection_in_progress ||
601                                 (current_collection_generation == GENERATION_OLD && major_collector.is_parallel));
602                 if (sgen_workers_have_started ()) {
603                         sgen_workers_wake_up_all ();
604                 } else {
605                         if (concurrent_collection_in_progress)
606                                 g_assert (current_collection_generation == -1);
607                 }
608         }
609 }
610
611 void
612 sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags)
613 {
614         while (start < end) {
615                 size_t size;
616                 char *obj;
617
618                 if (!*(void**)start) {
619                         start += sizeof (void*); /* should be ALLOC_ALIGN, really */
620                         continue;
621                 }
622
623                 if (allow_flags) {
624                         if (!(obj = SGEN_OBJECT_IS_FORWARDED (start)))
625                                 obj = start;
626                 } else {
627                         obj = start;
628                 }
629
630                 size = ALIGN_UP (safe_object_get_size ((MonoObject*)obj));
631
632                 if ((MonoVTable*)SGEN_LOAD_VTABLE (obj) != array_fill_vtable)
633                         callback (obj, size, data);
634
635                 start += size;
636         }
637 }
638
639 static gboolean
640 need_remove_object_for_domain (char *start, MonoDomain *domain)
641 {
642         if (mono_object_domain (start) == domain) {
643                 SGEN_LOG (4, "Need to cleanup object %p", start);
644                 binary_protocol_cleanup (start, (gpointer)LOAD_VTABLE (start), safe_object_get_size ((MonoObject*)start));
645                 return TRUE;
646         }
647         return FALSE;
648 }
649
650 static void
651 process_object_for_domain_clearing (char *start, MonoDomain *domain)
652 {
653         GCVTable *vt = (GCVTable*)LOAD_VTABLE (start);
654         if (vt->klass == mono_defaults.internal_thread_class)
655                 g_assert (mono_object_domain (start) == mono_get_root_domain ());
656         /* The object could be a proxy for an object in the domain
657            we're deleting. */
658 #ifndef DISABLE_REMOTING
659         if (mono_defaults.real_proxy_class->supertypes && mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
660                 MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
661
662                 /* The server could already have been zeroed out, so
663                    we need to check for that, too. */
664                 if (server && (!LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
665                         SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
666                         ((MonoRealProxy*)start)->unwrapped_server = NULL;
667                 }
668         }
669 #endif
670 }
671
672 static gboolean
673 clear_domain_process_object (char *obj, MonoDomain *domain)
674 {
675         gboolean remove;
676
677         process_object_for_domain_clearing (obj, domain);
678         remove = need_remove_object_for_domain (obj, domain);
679
680         if (remove && ((MonoObject*)obj)->synchronisation) {
681                 void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)obj);
682                 if (dislink)
683                         sgen_register_disappearing_link (NULL, dislink, FALSE, TRUE);
684         }
685
686         return remove;
687 }
688
689 static void
690 clear_domain_process_minor_object_callback (char *obj, size_t size, MonoDomain *domain)
691 {
692         if (clear_domain_process_object (obj, domain))
693                 memset (obj, 0, size);
694 }
695
696 static void
697 clear_domain_process_major_object_callback (char *obj, size_t size, MonoDomain *domain)
698 {
699         clear_domain_process_object (obj, domain);
700 }
701
702 static void
703 clear_domain_free_major_non_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
704 {
705         if (need_remove_object_for_domain (obj, domain))
706                 major_collector.free_non_pinned_object (obj, size);
707 }
708
709 static void
710 clear_domain_free_major_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
711 {
712         if (need_remove_object_for_domain (obj, domain))
713                 major_collector.free_pinned_object (obj, size);
714 }
715
716 /*
717  * When appdomains are unloaded we can easily remove objects that have finalizers,
718  * but all the others could still be present in random places on the heap.
719  * We need a sweep to get rid of them even though it's going to be costly
720  * with big heaps.
721  * The reason we need to remove them is because we access the vtable and class
722  * structures to know the object size and the reference bitmap: once the domain is
723  * unloaded the point to random memory.
724  */
725 void
726 mono_gc_clear_domain (MonoDomain * domain)
727 {
728         LOSObject *bigobj, *prev;
729         int i;
730
731         LOCK_GC;
732
733         binary_protocol_domain_unload_begin (domain);
734
735         sgen_stop_world (0);
736
737         if (concurrent_collection_in_progress)
738                 sgen_perform_collection (0, GENERATION_OLD, "clear domain", TRUE);
739         g_assert (!concurrent_collection_in_progress);
740
741         sgen_process_fin_stage_entries ();
742         sgen_process_dislink_stage_entries ();
743
744         sgen_clear_nursery_fragments ();
745
746         if (xdomain_checks && domain != mono_get_root_domain ()) {
747                 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
748                 sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_WBARRIER);
749                 sgen_check_for_xdomain_refs ();
750         }
751
752         /*Ephemerons and dislinks must be processed before LOS since they might end up pointing
753         to memory returned to the OS.*/
754         null_ephemerons_for_domain (domain);
755
756         for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
757                 sgen_null_links_for_domain (domain, i);
758
759         for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
760                 sgen_remove_finalizers_for_domain (domain, i);
761
762         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
763                         (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain, FALSE);
764
765         /* We need two passes over major and large objects because
766            freeing such objects might give their memory back to the OS
767            (in the case of large objects) or obliterate its vtable
768            (pinned objects with major-copying or pinned and non-pinned
769            objects with major-mark&sweep), but we might need to
770            dereference a pointer from an object to another object if
771            the first object is a proxy. */
772         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
773         for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
774                 clear_domain_process_object (bigobj->data, domain);
775
776         prev = NULL;
777         for (bigobj = los_object_list; bigobj;) {
778                 if (need_remove_object_for_domain (bigobj->data, domain)) {
779                         LOSObject *to_free = bigobj;
780                         if (prev)
781                                 prev->next = bigobj->next;
782                         else
783                                 los_object_list = bigobj->next;
784                         bigobj = bigobj->next;
785                         SGEN_LOG (4, "Freeing large object %p", bigobj->data);
786                         sgen_los_free_object (to_free);
787                         continue;
788                 }
789                 prev = bigobj;
790                 bigobj = bigobj->next;
791         }
792         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
793         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
794
795         if (domain == mono_get_root_domain ()) {
796                 if (G_UNLIKELY (do_pin_stats))
797                         sgen_pin_stats_print_class_stats ();
798                 sgen_object_layout_dump (stdout);
799         }
800
801         sgen_restart_world (0, NULL);
802
803         binary_protocol_domain_unload_end (domain);
804
805         UNLOCK_GC;
806 }
807
808 /*
809  * sgen_add_to_global_remset:
810  *
811  *   The global remset contains locations which point into newspace after
812  * a minor collection. This can happen if the objects they point to are pinned.
813  *
814  * LOCKING: If called from a parallel collector, the global remset
815  * lock must be held.  For serial collectors that is not necessary.
816  */
817 void
818 sgen_add_to_global_remset (gpointer ptr, gpointer obj)
819 {
820         SGEN_ASSERT (5, sgen_ptr_in_nursery (obj), "Target pointer of global remset must be in the nursery");
821
822         HEAVY_STAT (++stat_wbarrier_add_to_global_remset);
823
824         if (!major_collector.is_concurrent) {
825                 SGEN_ASSERT (5, current_collection_generation != -1, "Global remsets can only be added during collections");
826         } else {
827                 if (current_collection_generation == -1)
828                         SGEN_ASSERT (5, sgen_concurrent_collection_in_progress (), "Global remsets outside of collection pauses can only be added by the concurrent collector");
829         }
830
831         if (!object_is_pinned (obj))
832                 SGEN_ASSERT (5, sgen_minor_collector.is_split || sgen_concurrent_collection_in_progress (), "Non-pinned objects can only remain in nursery if it is a split nursery");
833         else if (sgen_cement_lookup_or_register (obj))
834                 return;
835
836         remset.record_pointer (ptr);
837
838         if (G_UNLIKELY (do_pin_stats))
839                 sgen_pin_stats_register_global_remset (obj);
840
841         SGEN_LOG (8, "Adding global remset for %p", ptr);
842         binary_protocol_global_remset (ptr, obj, (gpointer)SGEN_LOAD_VTABLE (obj));
843
844
845 #ifdef ENABLE_DTRACE
846         if (G_UNLIKELY (MONO_GC_GLOBAL_REMSET_ADD_ENABLED ())) {
847                 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
848                 MONO_GC_GLOBAL_REMSET_ADD ((mword)ptr, (mword)obj, sgen_safe_object_get_size (obj),
849                                 vt->klass->name_space, vt->klass->name);
850         }
851 #endif
852 }
853
854 /*
855  * sgen_drain_gray_stack:
856  *
857  *   Scan objects in the gray stack until the stack is empty. This should be called
858  * frequently after each object is copied, to achieve better locality and cache
859  * usage.
860  */
861 gboolean
862 sgen_drain_gray_stack (int max_objs, ScanCopyContext ctx)
863 {
864         char *obj;
865         ScanObjectFunc scan_func = ctx.scan_func;
866         GrayQueue *queue = ctx.queue;
867
868         if (max_objs == -1) {
869                 for (;;) {
870                         GRAY_OBJECT_DEQUEUE (queue, &obj);
871                         if (!obj)
872                                 return TRUE;
873                         SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
874                         scan_func (obj, queue);
875                 }
876         } else {
877                 int i;
878
879                 do {
880                         for (i = 0; i != max_objs; ++i) {
881                                 GRAY_OBJECT_DEQUEUE (queue, &obj);
882                                 if (!obj)
883                                         return TRUE;
884                                 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, safe_name (obj));
885                                 scan_func (obj, queue);
886                         }
887                 } while (max_objs < 0);
888                 return FALSE;
889         }
890 }
891
892 /*
893  * Addresses in the pin queue are already sorted. This function finds
894  * the object header for each address and pins the object. The
895  * addresses must be inside the nursery section.  The (start of the)
896  * address array is overwritten with the addresses of the actually
897  * pinned objects.  Return the number of pinned objects.
898  */
899 static int
900 pin_objects_from_nursery_pin_queue (ScanCopyContext ctx)
901 {
902         GCMemSection *section = nursery_section;
903         void **start = section->pin_queue_start;
904         void **end = start + section->pin_queue_num_entries;
905         void *start_nursery = section->data;
906         void *end_nursery = section->next_data;
907         void *last = NULL;
908         int count = 0;
909         void *search_start;
910         void *addr;
911         void *pinning_front = start_nursery;
912         size_t idx;
913         void **definitely_pinned = start;
914         ScanObjectFunc scan_func = ctx.scan_func;
915         SgenGrayQueue *queue = ctx.queue;
916
917         sgen_nursery_allocator_prepare_for_pinning ();
918
919         while (start < end) {
920                 void *obj_to_pin = NULL;
921                 size_t obj_to_pin_size = 0;
922
923                 addr = *start;
924
925                 SGEN_ASSERT (0, addr >= start_nursery && addr < end_nursery, "Potential pinning address out of range");
926                 SGEN_ASSERT (0, addr >= last, "Pin queue not sorted");
927
928                 if (addr == last) {
929                         ++start;
930                         continue;
931                 }
932
933                 SGEN_LOG (5, "Considering pinning addr %p", addr);
934                 /* We've already processed everything up to pinning_front. */
935                 if (addr < pinning_front) {
936                         start++;
937                         continue;
938                 }
939
940                 /*
941                  * Find the closest scan start <= addr.  We might search backward in the
942                  * scan_starts array because entries might be NULL.  In the worst case we
943                  * start at start_nursery.
944                  */
945                 idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
946                 SGEN_ASSERT (0, idx < section->num_scan_start, "Scan start index out of range");
947                 search_start = (void*)section->scan_starts [idx];
948                 if (!search_start || search_start > addr) {
949                         while (idx) {
950                                 --idx;
951                                 search_start = section->scan_starts [idx];
952                                 if (search_start && search_start <= addr)
953                                         break;
954                         }
955                         if (!search_start || search_start > addr)
956                                 search_start = start_nursery;
957                 }
958
959                 /*
960                  * If the pinning front is closer than the scan start we found, start
961                  * searching at the front.
962                  */
963                 if (search_start < pinning_front)
964                         search_start = pinning_front;
965
966                 /*
967                  * Now addr should be in an object a short distance from search_start.
968                  *
969                  * search_start must point to zeroed mem or point to an object.
970                  */
971                 do {
972                         size_t obj_size;
973
974                         /* Skip zeros. */
975                         if (!*(void**)search_start) {
976                                 search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
977                                 /* The loop condition makes sure we don't overrun addr. */
978                                 continue;
979                         }
980
981                         obj_size = ALIGN_UP (safe_object_get_size ((MonoObject*)search_start));
982
983                         if (addr >= search_start && (char*)addr < (char*)search_start + obj_size) {
984                                 /* This is the object we're looking for. */
985                                 obj_to_pin = search_start;
986                                 obj_to_pin_size = obj_size;
987                                 break;
988                         }
989
990                         /* Skip to the next object */
991                         search_start = (void*)((char*)search_start + obj_size);
992                 } while (search_start <= addr);
993
994                 /* We've searched past the address we were looking for. */
995                 if (!obj_to_pin) {
996                         pinning_front = search_start;
997                         goto next_pin_queue_entry;
998                 }
999
1000                 /*
1001                  * We've found an object to pin.  It might still be a dummy array, but we
1002                  * can advance the pinning front in any case.
1003                  */
1004                 pinning_front = (char*)obj_to_pin + obj_to_pin_size;
1005
1006                 /*
1007                  * If this is a dummy array marking the beginning of a nursery
1008                  * fragment, we don't pin it.
1009                  */
1010                 if (((MonoObject*)obj_to_pin)->synchronisation == GINT_TO_POINTER (-1))
1011                         goto next_pin_queue_entry;
1012
1013                 /*
1014                  * Finally - pin the object!
1015                  */
1016                 if (scan_func) {
1017                         scan_func (obj_to_pin, queue);
1018                 } else {
1019                         SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
1020                                         obj_to_pin, *(void**)obj_to_pin, safe_name (obj_to_pin), count);
1021                         binary_protocol_pin (obj_to_pin,
1022                                         (gpointer)LOAD_VTABLE (obj_to_pin),
1023                                         safe_object_get_size (obj_to_pin));
1024
1025 #ifdef ENABLE_DTRACE
1026                         if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1027                                 int gen = sgen_ptr_in_nursery (obj_to_pin) ? GENERATION_NURSERY : GENERATION_OLD;
1028                                 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj_to_pin);
1029                                 MONO_GC_OBJ_PINNED ((mword)obj_to_pin,
1030                                                 sgen_safe_object_get_size (obj_to_pin),
1031                                                 vt->klass->name_space, vt->klass->name, gen);
1032                         }
1033 #endif
1034
1035                         pin_object (obj_to_pin);
1036                         GRAY_OBJECT_ENQUEUE (queue, obj_to_pin);
1037                         if (G_UNLIKELY (do_pin_stats))
1038                                 sgen_pin_stats_register_object (obj_to_pin, obj_to_pin_size);
1039                         definitely_pinned [count] = obj_to_pin;
1040                         count++;
1041                 }
1042
1043         next_pin_queue_entry:
1044                 last = addr;
1045                 ++start;
1046         }
1047         //printf ("effective pinned: %d (at the end: %d)\n", count, (char*)end_nursery - (char*)last);
1048         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS) {
1049                 GCRootReport report;
1050                 report.count = 0;
1051                 for (idx = 0; idx < count; ++idx)
1052                         add_profile_gc_root (&report, definitely_pinned [idx], MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
1053                 notify_gc_roots (&report);
1054         }
1055         stat_pinned_objects += count;
1056         return count;
1057 }
1058
1059 static void
1060 pin_objects_in_nursery (ScanCopyContext ctx)
1061 {
1062         size_t reduced_to;
1063
1064         if (!nursery_section->pin_queue_num_entries)
1065                 return;
1066
1067         reduced_to = pin_objects_from_nursery_pin_queue (ctx);
1068         nursery_section->pin_queue_num_entries = reduced_to;
1069         if (!reduced_to)
1070                 nursery_section->pin_queue_start = NULL;
1071 }
1072
1073
1074 void
1075 sgen_pin_object (void *object, GrayQueue *queue)
1076 {
1077         g_assert (!concurrent_collection_in_progress);
1078
1079         if (sgen_collection_is_parallel ()) {
1080                 LOCK_PIN_QUEUE;
1081                 /*object arrives pinned*/
1082                 sgen_pin_stage_ptr (object);
1083                 ++objects_pinned ;
1084                 UNLOCK_PIN_QUEUE;
1085         } else {
1086                 SGEN_PIN_OBJECT (object);
1087                 sgen_pin_stage_ptr (object);
1088                 ++objects_pinned;
1089                 if (G_UNLIKELY (do_pin_stats))
1090                         sgen_pin_stats_register_object (object, safe_object_get_size (object));
1091         }
1092         GRAY_OBJECT_ENQUEUE (queue, object);
1093         binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
1094
1095 #ifdef ENABLE_DTRACE
1096         if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
1097                 int gen = sgen_ptr_in_nursery (object) ? GENERATION_NURSERY : GENERATION_OLD;
1098                 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (object);
1099                 MONO_GC_OBJ_PINNED ((mword)object, sgen_safe_object_get_size (object), vt->klass->name_space, vt->klass->name, gen);
1100         }
1101 #endif
1102 }
1103
1104 void
1105 sgen_parallel_pin_or_update (void **ptr, void *obj, MonoVTable *vt, SgenGrayQueue *queue)
1106 {
1107         for (;;) {
1108                 mword vtable_word;
1109                 gboolean major_pinned = FALSE;
1110
1111                 if (sgen_ptr_in_nursery (obj)) {
1112                         if (SGEN_CAS_PTR (obj, (void*)((mword)vt | SGEN_PINNED_BIT), vt) == vt) {
1113                                 sgen_pin_object (obj, queue);
1114                                 break;
1115                         }
1116                 } else {
1117                         major_collector.pin_major_object (obj, queue);
1118                         major_pinned = TRUE;
1119                 }
1120
1121                 vtable_word = *(mword*)obj;
1122                 /*someone else forwarded it, update the pointer and bail out*/
1123                 if (vtable_word & SGEN_FORWARDED_BIT) {
1124                         *ptr = (void*)(vtable_word & ~SGEN_VTABLE_BITS_MASK);
1125                         break;
1126                 }
1127
1128                 /*someone pinned it, nothing to do.*/
1129                 if (vtable_word & SGEN_PINNED_BIT || major_pinned)
1130                         break;
1131         }
1132 }
1133
1134 /* Sort the addresses in array in increasing order.
1135  * Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
1136  */
1137 void
1138 sgen_sort_addresses (void **array, size_t size)
1139 {
1140         size_t i;
1141         void *tmp;
1142
1143         for (i = 1; i < size; ++i) {
1144                 size_t child = i;
1145                 while (child > 0) {
1146                         size_t parent = (child - 1) / 2;
1147
1148                         if (array [parent] >= array [child])
1149                                 break;
1150
1151                         tmp = array [parent];
1152                         array [parent] = array [child];
1153                         array [child] = tmp;
1154
1155                         child = parent;
1156                 }
1157         }
1158
1159         for (i = size - 1; i > 0; --i) {
1160                 size_t end, root;
1161                 tmp = array [i];
1162                 array [i] = array [0];
1163                 array [0] = tmp;
1164
1165                 end = i - 1;
1166                 root = 0;
1167
1168                 while (root * 2 + 1 <= end) {
1169                         size_t child = root * 2 + 1;
1170
1171                         if (child < end && array [child] < array [child + 1])
1172                                 ++child;
1173                         if (array [root] >= array [child])
1174                                 break;
1175
1176                         tmp = array [root];
1177                         array [root] = array [child];
1178                         array [child] = tmp;
1179
1180                         root = child;
1181                 }
1182         }
1183 }
1184
1185 /* 
1186  * Scan the memory between start and end and queue values which could be pointers
1187  * to the area between start_nursery and end_nursery for later consideration.
1188  * Typically used for thread stacks.
1189  */
1190 static void
1191 conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
1192 {
1193         int count = 0;
1194
1195 #ifdef VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE
1196         VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
1197 #endif
1198
1199         while (start < end) {
1200                 if (*start >= start_nursery && *start < end_nursery) {
1201                         /*
1202                          * *start can point to the middle of an object
1203                          * note: should we handle pointing at the end of an object?
1204                          * pinning in C# code disallows pointing at the end of an object
1205                          * but there is some small chance that an optimizing C compiler
1206                          * may keep the only reference to an object by pointing
1207                          * at the end of it. We ignore this small chance for now.
1208                          * Pointers to the end of an object are indistinguishable
1209                          * from pointers to the start of the next object in memory
1210                          * so if we allow that we'd need to pin two objects...
1211                          * We queue the pointer in an array, the
1212                          * array will then be sorted and uniqued. This way
1213                          * we can coalesce several pinning pointers and it should
1214                          * be faster since we'd do a memory scan with increasing
1215                          * addresses. Note: we can align the address to the allocation
1216                          * alignment, so the unique process is more effective.
1217                          */
1218                         mword addr = (mword)*start;
1219                         addr &= ~(ALLOC_ALIGN - 1);
1220                         if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
1221                                 SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
1222                                 sgen_pin_stage_ptr ((void*)addr);
1223                                 count++;
1224                         }
1225                         if (G_UNLIKELY (do_pin_stats)) { 
1226                                 if (ptr_in_nursery ((void*)addr))
1227                                         sgen_pin_stats_register_address ((char*)addr, pin_type);
1228                         }
1229                 }
1230                 start++;
1231         }
1232         if (count)
1233                 SGEN_LOG (7, "found %d potential pinned heap pointers", count);
1234 }
1235
1236 /*
1237  * The first thing we do in a collection is to identify pinned objects.
1238  * This function considers all the areas of memory that need to be
1239  * conservatively scanned.
1240  */
1241 static void
1242 pin_from_roots (void *start_nursery, void *end_nursery, GrayQueue *queue)
1243 {
1244         void **start_root;
1245         RootRecord *root;
1246         SGEN_LOG (2, "Scanning pinned roots (%d bytes, %d/%d entries)", (int)roots_size, roots_hash [ROOT_TYPE_NORMAL].num_entries, roots_hash [ROOT_TYPE_PINNED].num_entries);
1247         /* objects pinned from the API are inside these roots */
1248         SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], start_root, root) {
1249                 SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
1250                 conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
1251         } SGEN_HASH_TABLE_FOREACH_END;
1252         /* now deal with the thread stacks
1253          * in the future we should be able to conservatively scan only:
1254          * *) the cpu registers
1255          * *) the unmanaged stack frames
1256          * *) the _last_ managed stack frame
1257          * *) pointers slots in managed frames
1258          */
1259         scan_thread_data (start_nursery, end_nursery, FALSE, queue);
1260 }
1261
1262 static void
1263 unpin_objects_from_queue (SgenGrayQueue *queue)
1264 {
1265         for (;;) {
1266                 char *addr;
1267                 GRAY_OBJECT_DEQUEUE (queue, &addr);
1268                 if (!addr)
1269                         break;
1270                 g_assert (SGEN_OBJECT_IS_PINNED (addr));
1271                 SGEN_UNPIN_OBJECT (addr);
1272         }
1273 }
1274
1275 typedef struct {
1276         CopyOrMarkObjectFunc func;
1277         GrayQueue *queue;
1278 } UserCopyOrMarkData;
1279
1280 static void
1281 single_arg_user_copy_or_mark (void **obj, void *gc_data)
1282 {
1283         UserCopyOrMarkData *data = gc_data;
1284
1285         data->func (obj, data->queue);
1286 }
1287
1288 /*
1289  * The memory area from start_root to end_root contains pointers to objects.
1290  * Their position is precisely described by @desc (this means that the pointer
1291  * can be either NULL or the pointer to the start of an object).
1292  * This functions copies them to to_space updates them.
1293  *
1294  * This function is not thread-safe!
1295  */
1296 static void
1297 precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, mword desc, ScanCopyContext ctx)
1298 {
1299         CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1300         SgenGrayQueue *queue = ctx.queue;
1301
1302         switch (desc & ROOT_DESC_TYPE_MASK) {
1303         case ROOT_DESC_BITMAP:
1304                 desc >>= ROOT_DESC_TYPE_SHIFT;
1305                 while (desc) {
1306                         if ((desc & 1) && *start_root) {
1307                                 copy_func (start_root, queue);
1308                                 SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
1309                                 sgen_drain_gray_stack (-1, ctx);
1310                         }
1311                         desc >>= 1;
1312                         start_root++;
1313                 }
1314                 return;
1315         case ROOT_DESC_COMPLEX: {
1316                 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1317                 gsize bwords = (*bitmap_data) - 1;
1318                 void **start_run = start_root;
1319                 bitmap_data++;
1320                 while (bwords-- > 0) {
1321                         gsize bmap = *bitmap_data++;
1322                         void **objptr = start_run;
1323                         while (bmap) {
1324                                 if ((bmap & 1) && *objptr) {
1325                                         copy_func (objptr, queue);
1326                                         SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
1327                                         sgen_drain_gray_stack (-1, ctx);
1328                                 }
1329                                 bmap >>= 1;
1330                                 ++objptr;
1331                         }
1332                         start_run += GC_BITS_PER_WORD;
1333                 }
1334                 break;
1335         }
1336         case ROOT_DESC_USER: {
1337                 UserCopyOrMarkData data = { copy_func, queue };
1338                 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1339                 marker (start_root, single_arg_user_copy_or_mark, &data);
1340                 break;
1341         }
1342         case ROOT_DESC_RUN_LEN:
1343                 g_assert_not_reached ();
1344         default:
1345                 g_assert_not_reached ();
1346         }
1347 }
1348
1349 static void
1350 reset_heap_boundaries (void)
1351 {
1352         lowest_heap_address = ~(mword)0;
1353         highest_heap_address = 0;
1354 }
1355
1356 void
1357 sgen_update_heap_boundaries (mword low, mword high)
1358 {
1359         mword old;
1360
1361         do {
1362                 old = lowest_heap_address;
1363                 if (low >= old)
1364                         break;
1365         } while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
1366
1367         do {
1368                 old = highest_heap_address;
1369                 if (high <= old)
1370                         break;
1371         } while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
1372 }
1373
1374 /*
1375  * Allocate and setup the data structures needed to be able to allocate objects
1376  * in the nursery. The nursery is stored in nursery_section.
1377  */
1378 static void
1379 alloc_nursery (void)
1380 {
1381         GCMemSection *section;
1382         char *data;
1383         size_t scan_starts;
1384         size_t alloc_size;
1385
1386         if (nursery_section)
1387                 return;
1388         SGEN_LOG (2, "Allocating nursery size: %zu", (size_t)sgen_nursery_size);
1389         /* later we will alloc a larger area for the nursery but only activate
1390          * what we need. The rest will be used as expansion if we have too many pinned
1391          * objects in the existing nursery.
1392          */
1393         /* FIXME: handle OOM */
1394         section = sgen_alloc_internal (INTERNAL_MEM_SECTION);
1395
1396         alloc_size = sgen_nursery_size;
1397
1398         /* If there isn't enough space even for the nursery we should simply abort. */
1399         g_assert (sgen_memgov_try_alloc_space (alloc_size, SPACE_NURSERY));
1400
1401 #ifdef SGEN_ALIGN_NURSERY
1402         data = major_collector.alloc_heap (alloc_size, alloc_size, DEFAULT_NURSERY_BITS);
1403 #else
1404         data = major_collector.alloc_heap (alloc_size, 0, DEFAULT_NURSERY_BITS);
1405 #endif
1406         sgen_update_heap_boundaries ((mword)data, (mword)(data + sgen_nursery_size));
1407         SGEN_LOG (4, "Expanding nursery size (%p-%p): %lu, total: %lu", data, data + alloc_size, (unsigned long)sgen_nursery_size, (unsigned long)mono_gc_get_heap_size ());
1408         section->data = section->next_data = data;
1409         section->size = alloc_size;
1410         section->end_data = data + sgen_nursery_size;
1411         scan_starts = (alloc_size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
1412         section->scan_starts = sgen_alloc_internal_dynamic (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS, TRUE);
1413         section->num_scan_start = scan_starts;
1414
1415         nursery_section = section;
1416
1417         sgen_nursery_allocator_set_nursery_bounds (data, data + sgen_nursery_size);
1418 }
1419
1420 void*
1421 mono_gc_get_nursery (int *shift_bits, size_t *size)
1422 {
1423         *size = sgen_nursery_size;
1424 #ifdef SGEN_ALIGN_NURSERY
1425         *shift_bits = DEFAULT_NURSERY_BITS;
1426 #else
1427         *shift_bits = -1;
1428 #endif
1429         return sgen_get_nursery_start ();
1430 }
1431
1432 void
1433 mono_gc_set_current_thread_appdomain (MonoDomain *domain)
1434 {
1435         SgenThreadInfo *info = mono_thread_info_current ();
1436
1437         /* Could be called from sgen_thread_unregister () with a NULL info */
1438         if (domain) {
1439                 g_assert (info);
1440                 info->stopped_domain = domain;
1441         }
1442 }
1443
1444 gboolean
1445 mono_gc_precise_stack_mark_enabled (void)
1446 {
1447         return !conservative_stack_mark;
1448 }
1449
1450 FILE *
1451 mono_gc_get_logfile (void)
1452 {
1453         return gc_debug_file;
1454 }
1455
1456 static void
1457 report_finalizer_roots_list (FinalizeReadyEntry *list)
1458 {
1459         GCRootReport report;
1460         FinalizeReadyEntry *fin;
1461
1462         report.count = 0;
1463         for (fin = list; fin; fin = fin->next) {
1464                 if (!fin->object)
1465                         continue;
1466                 add_profile_gc_root (&report, fin->object, MONO_PROFILE_GC_ROOT_FINALIZER, 0);
1467         }
1468         notify_gc_roots (&report);
1469 }
1470
1471 static void
1472 report_finalizer_roots (void)
1473 {
1474         report_finalizer_roots_list (fin_ready_list);
1475         report_finalizer_roots_list (critical_fin_list);
1476 }
1477
1478 static GCRootReport *root_report;
1479
1480 static void
1481 single_arg_report_root (void **obj, void *gc_data)
1482 {
1483         if (*obj)
1484                 add_profile_gc_root (root_report, *obj, MONO_PROFILE_GC_ROOT_OTHER, 0);
1485 }
1486
1487 static void
1488 precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
1489 {
1490         switch (desc & ROOT_DESC_TYPE_MASK) {
1491         case ROOT_DESC_BITMAP:
1492                 desc >>= ROOT_DESC_TYPE_SHIFT;
1493                 while (desc) {
1494                         if ((desc & 1) && *start_root) {
1495                                 add_profile_gc_root (report, *start_root, MONO_PROFILE_GC_ROOT_OTHER, 0);
1496                         }
1497                         desc >>= 1;
1498                         start_root++;
1499                 }
1500                 return;
1501         case ROOT_DESC_COMPLEX: {
1502                 gsize *bitmap_data = sgen_get_complex_descriptor_bitmap (desc);
1503                 gsize bwords = (*bitmap_data) - 1;
1504                 void **start_run = start_root;
1505                 bitmap_data++;
1506                 while (bwords-- > 0) {
1507                         gsize bmap = *bitmap_data++;
1508                         void **objptr = start_run;
1509                         while (bmap) {
1510                                 if ((bmap & 1) && *objptr) {
1511                                         add_profile_gc_root (report, *objptr, MONO_PROFILE_GC_ROOT_OTHER, 0);
1512                                 }
1513                                 bmap >>= 1;
1514                                 ++objptr;
1515                         }
1516                         start_run += GC_BITS_PER_WORD;
1517                 }
1518                 break;
1519         }
1520         case ROOT_DESC_USER: {
1521                 MonoGCRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
1522                 root_report = report;
1523                 marker (start_root, single_arg_report_root, NULL);
1524                 break;
1525         }
1526         case ROOT_DESC_RUN_LEN:
1527                 g_assert_not_reached ();
1528         default:
1529                 g_assert_not_reached ();
1530         }
1531 }
1532
1533 static void
1534 report_registered_roots_by_type (int root_type)
1535 {
1536         GCRootReport report;
1537         void **start_root;
1538         RootRecord *root;
1539         report.count = 0;
1540         SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1541                 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1542                 precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
1543         } SGEN_HASH_TABLE_FOREACH_END;
1544         notify_gc_roots (&report);
1545 }
1546
1547 static void
1548 report_registered_roots (void)
1549 {
1550         report_registered_roots_by_type (ROOT_TYPE_NORMAL);
1551         report_registered_roots_by_type (ROOT_TYPE_WBARRIER);
1552 }
1553
1554 static void
1555 scan_finalizer_entries (FinalizeReadyEntry *list, ScanCopyContext ctx)
1556 {
1557         CopyOrMarkObjectFunc copy_func = ctx.copy_func;
1558         SgenGrayQueue *queue = ctx.queue;
1559         FinalizeReadyEntry *fin;
1560
1561         for (fin = list; fin; fin = fin->next) {
1562                 if (!fin->object)
1563                         continue;
1564                 SGEN_LOG (5, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object));
1565                 copy_func (&fin->object, queue);
1566         }
1567 }
1568
1569 static const char*
1570 generation_name (int generation)
1571 {
1572         switch (generation) {
1573         case GENERATION_NURSERY: return "nursery";
1574         case GENERATION_OLD: return "old";
1575         default: g_assert_not_reached ();
1576         }
1577 }
1578
1579 const char*
1580 sgen_generation_name (int generation)
1581 {
1582         return generation_name (generation);
1583 }
1584
1585 SgenObjectOperations *
1586 sgen_get_current_object_ops (void){
1587         return &current_object_ops;
1588 }
1589
1590
1591 static void
1592 finish_gray_stack (int generation, GrayQueue *queue)
1593 {
1594         TV_DECLARE (atv);
1595         TV_DECLARE (btv);
1596         int done_with_ephemerons, ephemeron_rounds = 0;
1597         CopyOrMarkObjectFunc copy_func = current_object_ops.copy_or_mark_object;
1598         ScanObjectFunc scan_func = current_object_ops.scan_object;
1599         ScanCopyContext ctx = { scan_func, copy_func, queue };
1600         char *start_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_start () : NULL;
1601         char *end_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_end () : (char*)-1;
1602
1603         /*
1604          * We copied all the reachable objects. Now it's the time to copy
1605          * the objects that were not referenced by the roots, but by the copied objects.
1606          * we built a stack of objects pointed to by gray_start: they are
1607          * additional roots and we may add more items as we go.
1608          * We loop until gray_start == gray_objects which means no more objects have
1609          * been added. Note this is iterative: no recursion is involved.
1610          * We need to walk the LO list as well in search of marked big objects
1611          * (use a flag since this is needed only on major collections). We need to loop
1612          * here as well, so keep a counter of marked LO (increasing it in copy_object).
1613          *   To achieve better cache locality and cache usage, we drain the gray stack 
1614          * frequently, after each object is copied, and just finish the work here.
1615          */
1616         sgen_drain_gray_stack (-1, ctx);
1617         TV_GETTIME (atv);
1618         SGEN_LOG (2, "%s generation done", generation_name (generation));
1619
1620         /*
1621         Reset bridge data, we might have lingering data from a previous collection if this is a major
1622         collection trigged by minor overflow.
1623
1624         We must reset the gathered bridges since their original block might be evacuated due to major
1625         fragmentation in the meanwhile and the bridge code should not have to deal with that.
1626         */
1627         if (sgen_need_bridge_processing ())
1628                 sgen_bridge_reset_data ();
1629
1630         /*
1631          * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
1632          * before processing finalizable objects and non-tracking weak links to avoid finalizing/clearing
1633          * objects that are in fact reachable.
1634          */
1635         done_with_ephemerons = 0;
1636         do {
1637                 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1638                 sgen_drain_gray_stack (-1, ctx);
1639                 ++ephemeron_rounds;
1640         } while (!done_with_ephemerons);
1641
1642         sgen_mark_togglerefs (start_addr, end_addr, ctx);
1643
1644         if (sgen_need_bridge_processing ()) {
1645                 /*Make sure the gray stack is empty before we process bridge objects so we get liveness right*/
1646                 sgen_drain_gray_stack (-1, ctx);
1647                 sgen_collect_bridge_objects (generation, ctx);
1648                 if (generation == GENERATION_OLD)
1649                         sgen_collect_bridge_objects (GENERATION_NURSERY, ctx);
1650
1651                 /*
1652                 Do the first bridge step here, as the collector liveness state will become useless after that.
1653
1654                 An important optimization is to only proccess the possibly dead part of the object graph and skip
1655                 over all live objects as we transitively know everything they point must be alive too.
1656
1657                 The above invariant is completely wrong if we let the gray queue be drained and mark/copy everything.
1658
1659                 This has the unfortunate side effect of making overflow collections perform the first step twice, but
1660                 given we now have heuristics that perform major GC in anticipation of minor overflows this should not
1661                 be a big deal.
1662                 */
1663                 sgen_bridge_processing_stw_step ();
1664         }
1665
1666         /*
1667         Make sure we drain the gray stack before processing disappearing links and finalizers.
1668         If we don't make sure it is empty we might wrongly see a live object as dead.
1669         */
1670         sgen_drain_gray_stack (-1, ctx);
1671
1672         /*
1673         We must clear weak links that don't track resurrection before processing object ready for
1674         finalization so they can be cleared before that.
1675         */
1676         sgen_null_link_in_range (generation, TRUE, ctx);
1677         if (generation == GENERATION_OLD)
1678                 sgen_null_link_in_range (GENERATION_NURSERY, TRUE, ctx);
1679
1680
1681         /* walk the finalization queue and move also the objects that need to be
1682          * finalized: use the finalized objects as new roots so the objects they depend
1683          * on are also not reclaimed. As with the roots above, only objects in the nursery
1684          * are marked/copied.
1685          */
1686         sgen_finalize_in_range (generation, ctx);
1687         if (generation == GENERATION_OLD)
1688                 sgen_finalize_in_range (GENERATION_NURSERY, ctx);
1689         /* drain the new stack that might have been created */
1690         SGEN_LOG (6, "Precise scan of gray area post fin");
1691         sgen_drain_gray_stack (-1, ctx);
1692
1693         /*
1694          * This must be done again after processing finalizable objects since CWL slots are cleared only after the key is finalized.
1695          */
1696         done_with_ephemerons = 0;
1697         do {
1698                 done_with_ephemerons = mark_ephemerons_in_range (ctx);
1699                 sgen_drain_gray_stack (-1, ctx);
1700                 ++ephemeron_rounds;
1701         } while (!done_with_ephemerons);
1702
1703         /*
1704          * Clear ephemeron pairs with unreachable keys.
1705          * We pass the copy func so we can figure out if an array was promoted or not.
1706          */
1707         clear_unreachable_ephemerons (ctx);
1708
1709         /*
1710          * We clear togglerefs only after all possible chances of revival are done. 
1711          * This is semantically more inline with what users expect and it allows for
1712          * user finalizers to correctly interact with TR objects.
1713         */
1714         sgen_clear_togglerefs (start_addr, end_addr, ctx);
1715
1716         TV_GETTIME (btv);
1717         SGEN_LOG (2, "Finalize queue handling scan for %s generation: %d usecs %d ephemeron rounds", generation_name (generation), TV_ELAPSED (atv, btv), ephemeron_rounds);
1718
1719         /*
1720          * handle disappearing links
1721          * Note we do this after checking the finalization queue because if an object
1722          * survives (at least long enough to be finalized) we don't clear the link.
1723          * This also deals with a possible issue with the monitor reclamation: with the Boehm
1724          * GC a finalized object my lose the monitor because it is cleared before the finalizer is
1725          * called.
1726          */
1727         g_assert (sgen_gray_object_queue_is_empty (queue));
1728         for (;;) {
1729                 sgen_null_link_in_range (generation, FALSE, ctx);
1730                 if (generation == GENERATION_OLD)
1731                         sgen_null_link_in_range (GENERATION_NURSERY, FALSE, ctx);
1732                 if (sgen_gray_object_queue_is_empty (queue))
1733                         break;
1734                 sgen_drain_gray_stack (-1, ctx);
1735         }
1736
1737         g_assert (sgen_gray_object_queue_is_empty (queue));
1738 }
1739
1740 void
1741 sgen_check_section_scan_starts (GCMemSection *section)
1742 {
1743         size_t i;
1744         for (i = 0; i < section->num_scan_start; ++i) {
1745                 if (section->scan_starts [i]) {
1746                         mword size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
1747                         g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
1748                 }
1749         }
1750 }
1751
1752 static void
1753 check_scan_starts (void)
1754 {
1755         if (!do_scan_starts_check)
1756                 return;
1757         sgen_check_section_scan_starts (nursery_section);
1758         major_collector.check_scan_starts ();
1759 }
1760
1761 static void
1762 scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx)
1763 {
1764         void **start_root;
1765         RootRecord *root;
1766         SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], start_root, root) {
1767                 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1768                 precisely_scan_objects_from (start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc, ctx);
1769         } SGEN_HASH_TABLE_FOREACH_END;
1770 }
1771
1772 void
1773 sgen_dump_occupied (char *start, char *end, char *section_start)
1774 {
1775         fprintf (heap_dump_file, "<occupied offset=\"%td\" size=\"%td\"/>\n", start - section_start, end - start);
1776 }
1777
1778 void
1779 sgen_dump_section (GCMemSection *section, const char *type)
1780 {
1781         char *start = section->data;
1782         char *end = section->data + section->size;
1783         char *occ_start = NULL;
1784         GCVTable *vt;
1785         char *old_start = NULL; /* just for debugging */
1786
1787         fprintf (heap_dump_file, "<section type=\"%s\" size=\"%lu\">\n", type, (unsigned long)section->size);
1788
1789         while (start < end) {
1790                 guint size;
1791                 MonoClass *class;
1792
1793                 if (!*(void**)start) {
1794                         if (occ_start) {
1795                                 sgen_dump_occupied (occ_start, start, section->data);
1796                                 occ_start = NULL;
1797                         }
1798                         start += sizeof (void*); /* should be ALLOC_ALIGN, really */
1799                         continue;
1800                 }
1801                 g_assert (start < section->next_data);
1802
1803                 if (!occ_start)
1804                         occ_start = start;
1805
1806                 vt = (GCVTable*)LOAD_VTABLE (start);
1807                 class = vt->klass;
1808
1809                 size = ALIGN_UP (safe_object_get_size ((MonoObject*) start));
1810
1811                 /*
1812                 fprintf (heap_dump_file, "<object offset=\"%d\" class=\"%s.%s\" size=\"%d\"/>\n",
1813                                 start - section->data,
1814                                 vt->klass->name_space, vt->klass->name,
1815                                 size);
1816                 */
1817
1818                 old_start = start;
1819                 start += size;
1820         }
1821         if (occ_start)
1822                 sgen_dump_occupied (occ_start, start, section->data);
1823
1824         fprintf (heap_dump_file, "</section>\n");
1825 }
1826
1827 static void
1828 dump_object (MonoObject *obj, gboolean dump_location)
1829 {
1830         static char class_name [1024];
1831
1832         MonoClass *class = mono_object_class (obj);
1833         int i, j;
1834
1835         /*
1836          * Python's XML parser is too stupid to parse angle brackets
1837          * in strings, so we just ignore them;
1838          */
1839         i = j = 0;
1840         while (class->name [i] && j < sizeof (class_name) - 1) {
1841                 if (!strchr ("<>\"", class->name [i]))
1842                         class_name [j++] = class->name [i];
1843                 ++i;
1844         }
1845         g_assert (j < sizeof (class_name));
1846         class_name [j] = 0;
1847
1848         fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%zd\"",
1849                         class->name_space, class_name,
1850                         safe_object_get_size (obj));
1851         if (dump_location) {
1852                 const char *location;
1853                 if (ptr_in_nursery (obj))
1854                         location = "nursery";
1855                 else if (safe_object_get_size (obj) <= MAX_SMALL_OBJ_SIZE)
1856                         location = "major";
1857                 else
1858                         location = "LOS";
1859                 fprintf (heap_dump_file, " location=\"%s\"", location);
1860         }
1861         fprintf (heap_dump_file, "/>\n");
1862 }
1863
1864 static void
1865 dump_heap (const char *type, int num, const char *reason)
1866 {
1867         ObjectList *list;
1868         LOSObject *bigobj;
1869
1870         fprintf (heap_dump_file, "<collection type=\"%s\" num=\"%d\"", type, num);
1871         if (reason)
1872                 fprintf (heap_dump_file, " reason=\"%s\"", reason);
1873         fprintf (heap_dump_file, ">\n");
1874         fprintf (heap_dump_file, "<other-mem-usage type=\"mempools\" size=\"%ld\"/>\n", mono_mempool_get_bytes_allocated ());
1875         sgen_dump_internal_mem_usage (heap_dump_file);
1876         fprintf (heap_dump_file, "<pinned type=\"stack\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_STACK));
1877         /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */
1878         fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%zu\"/>\n", sgen_pin_stats_get_pinned_byte_count (PIN_TYPE_OTHER));
1879
1880         fprintf (heap_dump_file, "<pinned-objects>\n");
1881         for (list = sgen_pin_stats_get_object_list (); list; list = list->next)
1882                 dump_object (list->obj, TRUE);
1883         fprintf (heap_dump_file, "</pinned-objects>\n");
1884
1885         sgen_dump_section (nursery_section, "nursery");
1886
1887         major_collector.dump_heap (heap_dump_file);
1888
1889         fprintf (heap_dump_file, "<los>\n");
1890         for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
1891                 dump_object ((MonoObject*)bigobj->data, FALSE);
1892         fprintf (heap_dump_file, "</los>\n");
1893
1894         fprintf (heap_dump_file, "</collection>\n");
1895 }
1896
1897 void
1898 sgen_register_moved_object (void *obj, void *destination)
1899 {
1900         g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
1901
1902         /* FIXME: handle this for parallel collector */
1903         g_assert (!sgen_collection_is_parallel ());
1904
1905         if (moved_objects_idx == MOVED_OBJECTS_NUM) {
1906                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
1907                 moved_objects_idx = 0;
1908         }
1909         moved_objects [moved_objects_idx++] = obj;
1910         moved_objects [moved_objects_idx++] = destination;
1911 }
1912
1913 static void
1914 init_stats (void)
1915 {
1916         static gboolean inited = FALSE;
1917
1918         if (inited)
1919                 return;
1920
1921         mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_pre_collection_fragment_clear);
1922         mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_pinning);
1923         mono_counters_register ("Minor scan remembered set", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_remsets);
1924         mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_pinned);
1925         mono_counters_register ("Minor scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_registered_roots);
1926         mono_counters_register ("Minor scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_scan_thread_data);
1927         mono_counters_register ("Minor finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_finish_gray_stack);
1928         mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_minor_fragment_creation);
1929
1930         mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_pre_collection_fragment_clear);
1931         mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_pinning);
1932         mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_pinned);
1933         mono_counters_register ("Major scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_registered_roots);
1934         mono_counters_register ("Major scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_thread_data);
1935         mono_counters_register ("Major scan alloc_pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_alloc_pinned);
1936         mono_counters_register ("Major scan finalized", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_finalized);
1937         mono_counters_register ("Major scan big objects", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_scan_big_objects);
1938         mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_finish_gray_stack);
1939         mono_counters_register ("Major free big objects", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_free_bigobjs);
1940         mono_counters_register ("Major LOS sweep", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_los_sweep);
1941         mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_sweep);
1942         mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &time_major_fragment_creation);
1943
1944         mono_counters_register ("Number of pinned objects", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_pinned_objects);
1945
1946 #ifdef HEAVY_STATISTICS
1947         mono_counters_register ("WBarrier remember pointer", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_add_to_global_remset);
1948         mono_counters_register ("WBarrier set field", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_field);
1949         mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_arrayref);
1950         mono_counters_register ("WBarrier arrayref copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_arrayref_copy);
1951         mono_counters_register ("WBarrier generic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store);
1952         mono_counters_register ("WBarrier generic atomic store called", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_generic_store_atomic);
1953         mono_counters_register ("WBarrier set root", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_root);
1954         mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_value_copy);
1955         mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_object_copy);
1956
1957         mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced_degraded);
1958         mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_degraded);
1959
1960         mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_nursery);
1961         mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_nursery);
1962         mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_major);
1963         mono_counters_register ("# objects copied (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_major);
1964
1965         mono_counters_register ("# scan_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_nursery);
1966         mono_counters_register ("# scan_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_scan_object_called_major);
1967
1968         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_slots_allocated_in_vain);
1969
1970         mono_counters_register ("# nursery copy_object() failed from space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_from_space);
1971         mono_counters_register ("# nursery copy_object() failed forwarded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_forwarded);
1972         mono_counters_register ("# nursery copy_object() failed pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_pinned);
1973         mono_counters_register ("# nursery copy_object() failed to space", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_nursery_copy_object_failed_to_space);
1974
1975         sgen_nursery_allocator_init_heavy_stats ();
1976         sgen_alloc_init_heavy_stats ();
1977 #endif
1978
1979         inited = TRUE;
1980 }
1981
1982
1983 static void
1984 reset_pinned_from_failed_allocation (void)
1985 {
1986         bytes_pinned_from_failed_allocation = 0;
1987 }
1988
1989 void
1990 sgen_set_pinned_from_failed_allocation (mword objsize)
1991 {
1992         bytes_pinned_from_failed_allocation += objsize;
1993 }
1994
1995 gboolean
1996 sgen_collection_is_parallel (void)
1997 {
1998         switch (current_collection_generation) {
1999         case GENERATION_NURSERY:
2000                 return nursery_collection_is_parallel;
2001         case GENERATION_OLD:
2002                 return major_collector.is_parallel;
2003         default:
2004                 g_error ("Invalid current generation %d", current_collection_generation);
2005         }
2006 }
2007
2008 gboolean
2009 sgen_collection_is_concurrent (void)
2010 {
2011         switch (current_collection_generation) {
2012         case GENERATION_NURSERY:
2013                 return FALSE;
2014         case GENERATION_OLD:
2015                 return concurrent_collection_in_progress;
2016         default:
2017                 g_error ("Invalid current generation %d", current_collection_generation);
2018         }
2019 }
2020
2021 gboolean
2022 sgen_concurrent_collection_in_progress (void)
2023 {
2024         return concurrent_collection_in_progress;
2025 }
2026
2027 typedef struct
2028 {
2029         char *heap_start;
2030         char *heap_end;
2031 } FinishRememberedSetScanJobData;
2032
2033 static void
2034 job_finish_remembered_set_scan (WorkerData *worker_data, void *job_data_untyped)
2035 {
2036         FinishRememberedSetScanJobData *job_data = job_data_untyped;
2037
2038         remset.finish_scan_remsets (job_data->heap_start, job_data->heap_end, sgen_workers_get_job_gray_queue (worker_data));
2039         sgen_free_internal_dynamic (job_data, sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2040 }
2041
2042 typedef struct
2043 {
2044         CopyOrMarkObjectFunc copy_or_mark_func;
2045         ScanObjectFunc scan_func;
2046         char *heap_start;
2047         char *heap_end;
2048         int root_type;
2049 } ScanFromRegisteredRootsJobData;
2050
2051 static void
2052 job_scan_from_registered_roots (WorkerData *worker_data, void *job_data_untyped)
2053 {
2054         ScanFromRegisteredRootsJobData *job_data = job_data_untyped;
2055         ScanCopyContext ctx = { job_data->scan_func, job_data->copy_or_mark_func,
2056                 sgen_workers_get_job_gray_queue (worker_data) };
2057
2058         scan_from_registered_roots (job_data->heap_start, job_data->heap_end, job_data->root_type, ctx);
2059         sgen_free_internal_dynamic (job_data, sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2060 }
2061
2062 typedef struct
2063 {
2064         char *heap_start;
2065         char *heap_end;
2066 } ScanThreadDataJobData;
2067
2068 static void
2069 job_scan_thread_data (WorkerData *worker_data, void *job_data_untyped)
2070 {
2071         ScanThreadDataJobData *job_data = job_data_untyped;
2072
2073         scan_thread_data (job_data->heap_start, job_data->heap_end, TRUE,
2074                         sgen_workers_get_job_gray_queue (worker_data));
2075         sgen_free_internal_dynamic (job_data, sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2076 }
2077
2078 typedef struct
2079 {
2080         FinalizeReadyEntry *list;
2081 } ScanFinalizerEntriesJobData;
2082
2083 static void
2084 job_scan_finalizer_entries (WorkerData *worker_data, void *job_data_untyped)
2085 {
2086         ScanFinalizerEntriesJobData *job_data = job_data_untyped;
2087         ScanCopyContext ctx = { NULL, current_object_ops.copy_or_mark_object, sgen_workers_get_job_gray_queue (worker_data) };
2088
2089         scan_finalizer_entries (job_data->list, ctx);
2090         sgen_free_internal_dynamic (job_data, sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA);
2091 }
2092
2093 static void
2094 job_scan_major_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2095 {
2096         g_assert (concurrent_collection_in_progress);
2097         major_collector.scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2098 }
2099
2100 static void
2101 job_scan_los_mod_union_cardtable (WorkerData *worker_data, void *job_data_untyped)
2102 {
2103         g_assert (concurrent_collection_in_progress);
2104         sgen_los_scan_card_table (TRUE, sgen_workers_get_job_gray_queue (worker_data));
2105 }
2106
2107 static void
2108 verify_scan_starts (char *start, char *end)
2109 {
2110         size_t i;
2111
2112         for (i = 0; i < nursery_section->num_scan_start; ++i) {
2113                 char *addr = nursery_section->scan_starts [i];
2114                 if (addr > start && addr < end)
2115                         SGEN_LOG (1, "NFC-BAD SCAN START [%zu] %p for obj [%p %p]", i, addr, start, end);
2116         }
2117 }
2118
2119 static void
2120 verify_nursery (void)
2121 {
2122         char *start, *end, *cur, *hole_start;
2123
2124         if (!do_verify_nursery)
2125                 return;
2126
2127         /*This cleans up unused fragments */
2128         sgen_nursery_allocator_prepare_for_pinning ();
2129
2130         hole_start = start = cur = sgen_get_nursery_start ();
2131         end = sgen_get_nursery_end ();
2132
2133         while (cur < end) {
2134                 size_t ss, size;
2135
2136                 if (!*(void**)cur) {
2137                         cur += sizeof (void*);
2138                         continue;
2139                 }
2140
2141                 if (object_is_forwarded (cur))
2142                         SGEN_LOG (1, "FORWARDED OBJ %p", cur);
2143                 else if (object_is_pinned (cur))
2144                         SGEN_LOG (1, "PINNED OBJ %p", cur);
2145
2146                 ss = safe_object_get_size ((MonoObject*)cur);
2147                 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2148                 verify_scan_starts (cur, cur + size);
2149                 if (do_dump_nursery_content) {
2150                         if (cur > hole_start)
2151                                 SGEN_LOG (1, "HOLE [%p %p %d]", hole_start, cur, (int)(cur - hole_start));
2152                         SGEN_LOG (1, "OBJ  [%p %p %d %d %s %d]", cur, cur + size, (int)size, (int)ss, sgen_safe_name ((MonoObject*)cur), (gpointer)LOAD_VTABLE (cur) == sgen_get_array_fill_vtable ());
2153                 }
2154                 cur += size;
2155                 hole_start = cur;
2156         }
2157 }
2158
2159 /*
2160  * Checks that no objects in the nursery are fowarded or pinned.  This
2161  * is a precondition to restarting the mutator while doing a
2162  * concurrent collection.  Note that we don't clear fragments because
2163  * we depend on that having happened earlier.
2164  */
2165 static void
2166 check_nursery_is_clean (void)
2167 {
2168         char *start, *end, *cur;
2169
2170         start = cur = sgen_get_nursery_start ();
2171         end = sgen_get_nursery_end ();
2172
2173         while (cur < end) {
2174                 size_t ss, size;
2175
2176                 if (!*(void**)cur) {
2177                         cur += sizeof (void*);
2178                         continue;
2179                 }
2180
2181                 g_assert (!object_is_forwarded (cur));
2182                 g_assert (!object_is_pinned (cur));
2183
2184                 ss = safe_object_get_size ((MonoObject*)cur);
2185                 size = ALIGN_UP (safe_object_get_size ((MonoObject*)cur));
2186                 verify_scan_starts (cur, cur + size);
2187
2188                 cur += size;
2189         }
2190 }
2191
2192 static void
2193 init_gray_queue (void)
2194 {
2195         if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ()) {
2196                 sgen_workers_init_distribute_gray_queue ();
2197                 sgen_gray_object_queue_init_with_alloc_prepare (&gray_queue, NULL,
2198                                 gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
2199         } else {
2200                 sgen_gray_object_queue_init (&gray_queue, NULL);
2201         }
2202 }
2203
2204 static void
2205 pin_stage_object_callback (char *obj, size_t size, void *data)
2206 {
2207         sgen_pin_stage_ptr (obj);
2208         /* FIXME: do pin stats if enabled */
2209 }
2210
2211 /*
2212  * Collect objects in the nursery.  Returns whether to trigger a major
2213  * collection.
2214  */
2215 static gboolean
2216 collect_nursery (SgenGrayQueue *unpin_queue, gboolean finish_up_concurrent_mark)
2217 {
2218         gboolean needs_major;
2219         size_t max_garbage_amount;
2220         char *nursery_next;
2221         FinishRememberedSetScanJobData *frssjd;
2222         ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2223         ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2224         ScanThreadDataJobData *stdjd;
2225         mword fragment_total;
2226         ScanCopyContext ctx;
2227         TV_DECLARE (all_atv);
2228         TV_DECLARE (all_btv);
2229         TV_DECLARE (atv);
2230         TV_DECLARE (btv);
2231
2232         if (disable_minor_collections)
2233                 return TRUE;
2234
2235         MONO_GC_BEGIN (GENERATION_NURSERY);
2236         binary_protocol_collection_begin (gc_stats.minor_gc_count, GENERATION_NURSERY);
2237
2238         verify_nursery ();
2239
2240 #ifndef DISABLE_PERFCOUNTERS
2241         mono_perfcounters->gc_collections0++;
2242 #endif
2243
2244         current_collection_generation = GENERATION_NURSERY;
2245         if (sgen_collection_is_parallel ())
2246                 current_object_ops = sgen_minor_collector.parallel_ops;
2247         else
2248                 current_object_ops = sgen_minor_collector.serial_ops;
2249         
2250         reset_pinned_from_failed_allocation ();
2251
2252         check_scan_starts ();
2253
2254         sgen_nursery_alloc_prepare_for_minor ();
2255
2256         degraded_mode = 0;
2257         objects_pinned = 0;
2258         nursery_next = sgen_nursery_alloc_get_upper_alloc_bound ();
2259         /* FIXME: optimize later to use the higher address where an object can be present */
2260         nursery_next = MAX (nursery_next, sgen_get_nursery_end ());
2261
2262         SGEN_LOG (1, "Start nursery collection %d %p-%p, size: %d", gc_stats.minor_gc_count, sgen_get_nursery_start (), nursery_next, (int)(nursery_next - sgen_get_nursery_start ()));
2263         max_garbage_amount = nursery_next - sgen_get_nursery_start ();
2264         g_assert (nursery_section->size >= max_garbage_amount);
2265
2266         /* world must be stopped already */
2267         TV_GETTIME (all_atv);
2268         atv = all_atv;
2269
2270         TV_GETTIME (btv);
2271         time_minor_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2272
2273         if (xdomain_checks) {
2274                 sgen_clear_nursery_fragments ();
2275                 sgen_check_for_xdomain_refs ();
2276         }
2277
2278         nursery_section->next_data = nursery_next;
2279
2280         major_collector.start_nursery_collection ();
2281
2282         sgen_memgov_minor_collection_start ();
2283
2284         init_gray_queue ();
2285
2286         gc_stats.minor_gc_count ++;
2287
2288         MONO_GC_CHECKPOINT_1 (GENERATION_NURSERY);
2289
2290         sgen_process_fin_stage_entries ();
2291         sgen_process_dislink_stage_entries ();
2292
2293         MONO_GC_CHECKPOINT_2 (GENERATION_NURSERY);
2294
2295         /* pin from pinned handles */
2296         sgen_init_pinning ();
2297         mono_profiler_gc_event (MONO_GC_EVENT_MARK_START, 0);
2298         pin_from_roots (sgen_get_nursery_start (), nursery_next, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2299         /* pin cemented objects */
2300         sgen_cement_iterate (pin_stage_object_callback, NULL);
2301         /* identify pinned objects */
2302         sgen_optimize_pin_queue (0);
2303         sgen_pinning_setup_section (nursery_section);
2304         ctx.scan_func = NULL;
2305         ctx.copy_func = NULL;
2306         ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2307         pin_objects_in_nursery (ctx);
2308         sgen_pinning_trim_queue_to_section (nursery_section);
2309
2310         TV_GETTIME (atv);
2311         time_minor_pinning += TV_ELAPSED (btv, atv);
2312         SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (btv, atv));
2313         SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
2314
2315         MONO_GC_CHECKPOINT_3 (GENERATION_NURSERY);
2316
2317         if (whole_heap_check_before_collection) {
2318                 sgen_clear_nursery_fragments ();
2319                 sgen_check_whole_heap (finish_up_concurrent_mark);
2320         }
2321         if (consistency_check_at_minor_collection)
2322                 sgen_check_consistency ();
2323
2324         sgen_workers_start_all_workers ();
2325         sgen_workers_start_marking ();
2326
2327         frssjd = sgen_alloc_internal_dynamic (sizeof (FinishRememberedSetScanJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2328         frssjd->heap_start = sgen_get_nursery_start ();
2329         frssjd->heap_end = nursery_next;
2330         sgen_workers_enqueue_job (job_finish_remembered_set_scan, frssjd);
2331
2332         /* we don't have complete write barrier yet, so we scan all the old generation sections */
2333         TV_GETTIME (btv);
2334         time_minor_scan_remsets += TV_ELAPSED (atv, btv);
2335         SGEN_LOG (2, "Old generation scan: %d usecs", TV_ELAPSED (atv, btv));
2336
2337         MONO_GC_CHECKPOINT_4 (GENERATION_NURSERY);
2338
2339         if (!sgen_collection_is_parallel ()) {
2340                 ctx.scan_func = current_object_ops.scan_object;
2341                 ctx.copy_func = NULL;
2342                 ctx.queue = &gray_queue;
2343                 sgen_drain_gray_stack (-1, ctx);
2344         }
2345
2346         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2347                 report_registered_roots ();
2348         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2349                 report_finalizer_roots ();
2350         TV_GETTIME (atv);
2351         time_minor_scan_pinned += TV_ELAPSED (btv, atv);
2352
2353         MONO_GC_CHECKPOINT_5 (GENERATION_NURSERY);
2354
2355         /* registered roots, this includes static fields */
2356         scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2357         scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2358         scrrjd_normal->scan_func = current_object_ops.scan_object;
2359         scrrjd_normal->heap_start = sgen_get_nursery_start ();
2360         scrrjd_normal->heap_end = nursery_next;
2361         scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2362         sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2363
2364         scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2365         scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2366         scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2367         scrrjd_wbarrier->heap_start = sgen_get_nursery_start ();
2368         scrrjd_wbarrier->heap_end = nursery_next;
2369         scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2370         sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2371
2372         TV_GETTIME (btv);
2373         time_minor_scan_registered_roots += TV_ELAPSED (atv, btv);
2374
2375         MONO_GC_CHECKPOINT_6 (GENERATION_NURSERY);
2376
2377         /* thread data */
2378         stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2379         stdjd->heap_start = sgen_get_nursery_start ();
2380         stdjd->heap_end = nursery_next;
2381         sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2382
2383         TV_GETTIME (atv);
2384         time_minor_scan_thread_data += TV_ELAPSED (btv, atv);
2385         btv = atv;
2386
2387         MONO_GC_CHECKPOINT_7 (GENERATION_NURSERY);
2388
2389         g_assert (!sgen_collection_is_parallel () && !sgen_collection_is_concurrent ());
2390
2391         if (sgen_collection_is_parallel () || sgen_collection_is_concurrent ())
2392                 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2393
2394         /* Scan the list of objects ready for finalization. If */
2395         sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2396         sfejd_fin_ready->list = fin_ready_list;
2397         sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2398
2399         sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2400         sfejd_critical_fin->list = critical_fin_list;
2401         sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2402
2403         MONO_GC_CHECKPOINT_8 (GENERATION_NURSERY);
2404
2405         finish_gray_stack (GENERATION_NURSERY, &gray_queue);
2406         TV_GETTIME (atv);
2407         time_minor_finish_gray_stack += TV_ELAPSED (btv, atv);
2408         mono_profiler_gc_event (MONO_GC_EVENT_MARK_END, 0);
2409
2410         MONO_GC_CHECKPOINT_9 (GENERATION_NURSERY);
2411
2412         /*
2413          * The (single-threaded) finalization code might have done
2414          * some copying/marking so we can only reset the GC thread's
2415          * worker data here instead of earlier when we joined the
2416          * workers.
2417          */
2418         sgen_workers_reset_data ();
2419
2420         if (objects_pinned) {
2421                 sgen_optimize_pin_queue (0);
2422                 sgen_pinning_setup_section (nursery_section);
2423         }
2424
2425         /* walk the pin_queue, build up the fragment list of free memory, unmark
2426          * pinned objects as we go, memzero() the empty fragments so they are ready for the
2427          * next allocations.
2428          */
2429         mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_START, 0);
2430         fragment_total = sgen_build_nursery_fragments (nursery_section,
2431                         nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries,
2432                         unpin_queue);
2433         if (!fragment_total)
2434                 degraded_mode = 1;
2435
2436         /* Clear TLABs for all threads */
2437         sgen_clear_tlabs ();
2438
2439         mono_profiler_gc_event (MONO_GC_EVENT_RECLAIM_END, 0);
2440         TV_GETTIME (btv);
2441         time_minor_fragment_creation += TV_ELAPSED (atv, btv);
2442         SGEN_LOG (2, "Fragment creation: %d usecs, %lu bytes available", TV_ELAPSED (atv, btv), (unsigned long)fragment_total);
2443
2444         if (consistency_check_at_minor_collection)
2445                 sgen_check_major_refs ();
2446
2447         major_collector.finish_nursery_collection ();
2448
2449         TV_GETTIME (all_btv);
2450         gc_stats.minor_gc_time += TV_ELAPSED (all_atv, all_btv);
2451
2452         if (heap_dump_file)
2453                 dump_heap ("minor", gc_stats.minor_gc_count - 1, NULL);
2454
2455         /* prepare the pin queue for the next collection */
2456         sgen_finish_pinning ();
2457         if (fin_ready_list || critical_fin_list) {
2458                 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2459                 mono_gc_finalize_notify ();
2460         }
2461         sgen_pin_stats_reset ();
2462         /* clear cemented hash */
2463         sgen_cement_clear_below_threshold ();
2464
2465         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2466
2467         remset.finish_minor_collection ();
2468
2469         check_scan_starts ();
2470
2471         binary_protocol_flush_buffers (FALSE);
2472
2473         sgen_memgov_minor_collection_end ();
2474
2475         /*objects are late pinned because of lack of memory, so a major is a good call*/
2476         needs_major = objects_pinned > 0;
2477         current_collection_generation = -1;
2478         objects_pinned = 0;
2479
2480         MONO_GC_END (GENERATION_NURSERY);
2481         binary_protocol_collection_end (gc_stats.minor_gc_count - 1, GENERATION_NURSERY);
2482
2483         if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2484                 sgen_check_nursery_objects_pinned (unpin_queue != NULL);
2485
2486         return needs_major;
2487 }
2488
2489 static void
2490 scan_nursery_objects_callback (char *obj, size_t size, ScanCopyContext *ctx)
2491 {
2492         ctx->scan_func (obj, ctx->queue);
2493 }
2494
2495 static void
2496 scan_nursery_objects (ScanCopyContext ctx)
2497 {
2498         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
2499                         (IterateObjectCallbackFunc)scan_nursery_objects_callback, (void*)&ctx, FALSE);
2500 }
2501
2502 static void
2503 major_copy_or_mark_from_roots (size_t *old_next_pin_slot, gboolean finish_up_concurrent_mark, gboolean scan_mod_union)
2504 {
2505         LOSObject *bigobj;
2506         TV_DECLARE (atv);
2507         TV_DECLARE (btv);
2508         /* FIXME: only use these values for the precise scan
2509          * note that to_space pointers should be excluded anyway...
2510          */
2511         char *heap_start = NULL;
2512         char *heap_end = (char*)-1;
2513         gboolean profile_roots = mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS;
2514         GCRootReport root_report = { 0 };
2515         ScanFromRegisteredRootsJobData *scrrjd_normal, *scrrjd_wbarrier;
2516         ScanThreadDataJobData *stdjd;
2517         ScanFinalizerEntriesJobData *sfejd_fin_ready, *sfejd_critical_fin;
2518         ScanCopyContext ctx;
2519
2520         if (concurrent_collection_in_progress) {
2521                 /*This cleans up unused fragments */
2522                 sgen_nursery_allocator_prepare_for_pinning ();
2523
2524                 if (do_concurrent_checks)
2525                         check_nursery_is_clean ();
2526         } else {
2527                 /* The concurrent collector doesn't touch the nursery. */
2528                 sgen_nursery_alloc_prepare_for_major ();
2529         }
2530
2531         init_gray_queue ();
2532
2533         TV_GETTIME (atv);
2534
2535         /* Pinning depends on this */
2536         sgen_clear_nursery_fragments ();
2537
2538         if (whole_heap_check_before_collection)
2539                 sgen_check_whole_heap (finish_up_concurrent_mark);
2540
2541         TV_GETTIME (btv);
2542         time_major_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
2543
2544         if (!sgen_collection_is_concurrent ())
2545                 nursery_section->next_data = sgen_get_nursery_end ();
2546         /* we should also coalesce scanning from sections close to each other
2547          * and deal with pointers outside of the sections later.
2548          */
2549
2550         objects_pinned = 0;
2551         *major_collector.have_swept = FALSE;
2552
2553         if (xdomain_checks) {
2554                 sgen_clear_nursery_fragments ();
2555                 sgen_check_for_xdomain_refs ();
2556         }
2557
2558         if (!concurrent_collection_in_progress) {
2559                 /* Remsets are not useful for a major collection */
2560                 remset.prepare_for_major_collection ();
2561         }
2562
2563         sgen_process_fin_stage_entries ();
2564         sgen_process_dislink_stage_entries ();
2565
2566         TV_GETTIME (atv);
2567         sgen_init_pinning ();
2568         SGEN_LOG (6, "Collecting pinned addresses");
2569         pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address, WORKERS_DISTRIBUTE_GRAY_QUEUE);
2570
2571         if (!concurrent_collection_in_progress || finish_up_concurrent_mark) {
2572                 if (major_collector.is_concurrent) {
2573                         /*
2574                          * The concurrent major collector cannot evict
2575                          * yet, so we need to pin cemented objects to
2576                          * not break some asserts.
2577                          *
2578                          * FIXME: We could evict now!
2579                          */
2580                         sgen_cement_iterate (pin_stage_object_callback, NULL);
2581                 }
2582
2583                 if (!concurrent_collection_in_progress)
2584                         sgen_cement_reset ();
2585         }
2586
2587         sgen_optimize_pin_queue (0);
2588
2589         /*
2590          * The concurrent collector doesn't move objects, neither on
2591          * the major heap nor in the nursery, so we can mark even
2592          * before pinning has finished.  For the non-concurrent
2593          * collector we start the workers after pinning.
2594          */
2595         if (concurrent_collection_in_progress) {
2596                 sgen_workers_start_all_workers ();
2597                 sgen_workers_start_marking ();
2598         }
2599
2600         /*
2601          * pin_queue now contains all candidate pointers, sorted and
2602          * uniqued.  We must do two passes now to figure out which
2603          * objects are pinned.
2604          *
2605          * The first is to find within the pin_queue the area for each
2606          * section.  This requires that the pin_queue be sorted.  We
2607          * also process the LOS objects and pinned chunks here.
2608          *
2609          * The second, destructive, pass is to reduce the section
2610          * areas to pointers to the actually pinned objects.
2611          */
2612         SGEN_LOG (6, "Pinning from sections");
2613         /* first pass for the sections */
2614         sgen_find_section_pin_queue_start_end (nursery_section);
2615         major_collector.find_pin_queue_start_ends (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2616         /* identify possible pointers to the insize of large objects */
2617         SGEN_LOG (6, "Pinning from large objects");
2618         for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
2619                 size_t dummy;
2620                 if (sgen_find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + sgen_los_object_size (bigobj), &dummy)) {
2621                         binary_protocol_pin (bigobj->data, (gpointer)LOAD_VTABLE (bigobj->data), safe_object_get_size (((MonoObject*)(bigobj->data))));
2622
2623 #ifdef ENABLE_DTRACE
2624                         if (G_UNLIKELY (MONO_GC_OBJ_PINNED_ENABLED ())) {
2625                                 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (bigobj->data);
2626                                 MONO_GC_OBJ_PINNED ((mword)bigobj->data, sgen_safe_object_get_size ((MonoObject*)bigobj->data), vt->klass->name_space, vt->klass->name, GENERATION_OLD);
2627                         }
2628 #endif
2629
2630                         if (sgen_los_object_is_pinned (bigobj->data)) {
2631                                 g_assert (finish_up_concurrent_mark);
2632                                 continue;
2633                         }
2634                         sgen_los_pin_object (bigobj->data);
2635                         if (SGEN_OBJECT_HAS_REFERENCES (bigobj->data))
2636                                 GRAY_OBJECT_ENQUEUE (WORKERS_DISTRIBUTE_GRAY_QUEUE, bigobj->data);
2637                         if (G_UNLIKELY (do_pin_stats))
2638                                 sgen_pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
2639                         SGEN_LOG (6, "Marked large object %p (%s) size: %lu from roots", bigobj->data, safe_name (bigobj->data), (unsigned long)sgen_los_object_size (bigobj));
2640
2641                         if (profile_roots)
2642                                 add_profile_gc_root (&root_report, bigobj->data, MONO_PROFILE_GC_ROOT_PINNING | MONO_PROFILE_GC_ROOT_MISC, 0);
2643                 }
2644         }
2645         if (profile_roots)
2646                 notify_gc_roots (&root_report);
2647         /* second pass for the sections */
2648         ctx.scan_func = concurrent_collection_in_progress ? current_object_ops.scan_object : NULL;
2649         ctx.copy_func = NULL;
2650         ctx.queue = WORKERS_DISTRIBUTE_GRAY_QUEUE;
2651
2652         /*
2653          * Concurrent mark never follows references into the nursery.
2654          * In the start and finish pauses we must scan live nursery
2655          * objects, though.  We could simply scan all nursery objects,
2656          * but that would be conservative.  The easiest way is to do a
2657          * nursery collection, which copies all live nursery objects
2658          * (except pinned ones, with the simple nursery) to the major
2659          * heap.  Scanning the mod union table later will then scan
2660          * those promoted objects, provided they're reachable.  Pinned
2661          * objects in the nursery - which we can trivially find in the
2662          * pinning queue - are treated as roots in the mark pauses.
2663          *
2664          * The split nursery complicates the latter part because
2665          * non-pinned objects can survive in the nursery.  That's why
2666          * we need to do a full front-to-back scan of the nursery,
2667          * marking all objects.
2668          *
2669          * Non-concurrent mark evacuates from the nursery, so it's
2670          * sufficient to just scan pinned nursery objects.
2671          */
2672         if (concurrent_collection_in_progress && sgen_minor_collector.is_split) {
2673                 scan_nursery_objects (ctx);
2674         } else {
2675                 pin_objects_in_nursery (ctx);
2676                 if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
2677                         sgen_check_nursery_objects_pinned (!concurrent_collection_in_progress || finish_up_concurrent_mark);
2678         }
2679
2680         major_collector.pin_objects (WORKERS_DISTRIBUTE_GRAY_QUEUE);
2681         if (old_next_pin_slot)
2682                 *old_next_pin_slot = sgen_get_pinned_count ();
2683
2684         TV_GETTIME (btv);
2685         time_major_pinning += TV_ELAPSED (atv, btv);
2686         SGEN_LOG (2, "Finding pinned pointers: %zd in %d usecs", sgen_get_pinned_count (), TV_ELAPSED (atv, btv));
2687         SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
2688
2689         major_collector.init_to_space ();
2690
2691 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2692         main_gc_thread = mono_native_thread_self ();
2693 #endif
2694
2695         if (!concurrent_collection_in_progress && major_collector.is_parallel) {
2696                 sgen_workers_start_all_workers ();
2697                 sgen_workers_start_marking ();
2698         }
2699
2700         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2701                 report_registered_roots ();
2702         TV_GETTIME (atv);
2703         time_major_scan_pinned += TV_ELAPSED (btv, atv);
2704
2705         /* registered roots, this includes static fields */
2706         scrrjd_normal = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2707         scrrjd_normal->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2708         scrrjd_normal->scan_func = current_object_ops.scan_object;
2709         scrrjd_normal->heap_start = heap_start;
2710         scrrjd_normal->heap_end = heap_end;
2711         scrrjd_normal->root_type = ROOT_TYPE_NORMAL;
2712         sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_normal);
2713
2714         scrrjd_wbarrier = sgen_alloc_internal_dynamic (sizeof (ScanFromRegisteredRootsJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2715         scrrjd_wbarrier->copy_or_mark_func = current_object_ops.copy_or_mark_object;
2716         scrrjd_wbarrier->scan_func = current_object_ops.scan_object;
2717         scrrjd_wbarrier->heap_start = heap_start;
2718         scrrjd_wbarrier->heap_end = heap_end;
2719         scrrjd_wbarrier->root_type = ROOT_TYPE_WBARRIER;
2720         sgen_workers_enqueue_job (job_scan_from_registered_roots, scrrjd_wbarrier);
2721
2722         TV_GETTIME (btv);
2723         time_major_scan_registered_roots += TV_ELAPSED (atv, btv);
2724
2725         /* Threads */
2726         stdjd = sgen_alloc_internal_dynamic (sizeof (ScanThreadDataJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2727         stdjd->heap_start = heap_start;
2728         stdjd->heap_end = heap_end;
2729         sgen_workers_enqueue_job (job_scan_thread_data, stdjd);
2730
2731         TV_GETTIME (atv);
2732         time_major_scan_thread_data += TV_ELAPSED (btv, atv);
2733
2734         TV_GETTIME (btv);
2735         time_major_scan_alloc_pinned += TV_ELAPSED (atv, btv);
2736
2737         if (mono_profiler_get_events () & MONO_PROFILE_GC_ROOTS)
2738                 report_finalizer_roots ();
2739
2740         /* scan the list of objects ready for finalization */
2741         sfejd_fin_ready = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2742         sfejd_fin_ready->list = fin_ready_list;
2743         sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_fin_ready);
2744
2745         sfejd_critical_fin = sgen_alloc_internal_dynamic (sizeof (ScanFinalizerEntriesJobData), INTERNAL_MEM_WORKER_JOB_DATA, TRUE);
2746         sfejd_critical_fin->list = critical_fin_list;
2747         sgen_workers_enqueue_job (job_scan_finalizer_entries, sfejd_critical_fin);
2748
2749         if (scan_mod_union) {
2750                 g_assert (finish_up_concurrent_mark);
2751
2752                 /* Mod union card table */
2753                 sgen_workers_enqueue_job (job_scan_major_mod_union_cardtable, NULL);
2754                 sgen_workers_enqueue_job (job_scan_los_mod_union_cardtable, NULL);
2755         }
2756
2757         TV_GETTIME (atv);
2758         time_major_scan_finalized += TV_ELAPSED (btv, atv);
2759         SGEN_LOG (2, "Root scan: %d usecs", TV_ELAPSED (btv, atv));
2760
2761         TV_GETTIME (btv);
2762         time_major_scan_big_objects += TV_ELAPSED (atv, btv);
2763
2764         if (concurrent_collection_in_progress) {
2765                 /* prepare the pin queue for the next collection */
2766                 sgen_finish_pinning ();
2767
2768                 sgen_pin_stats_reset ();
2769
2770                 if (do_concurrent_checks)
2771                         check_nursery_is_clean ();
2772         }
2773 }
2774
2775 static void
2776 major_start_collection (gboolean concurrent, size_t *old_next_pin_slot)
2777 {
2778         MONO_GC_BEGIN (GENERATION_OLD);
2779         binary_protocol_collection_begin (gc_stats.major_gc_count, GENERATION_OLD);
2780
2781         current_collection_generation = GENERATION_OLD;
2782 #ifndef DISABLE_PERFCOUNTERS
2783         mono_perfcounters->gc_collections1++;
2784 #endif
2785
2786         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2787
2788         if (concurrent) {
2789                 g_assert (major_collector.is_concurrent);
2790                 concurrent_collection_in_progress = TRUE;
2791
2792                 sgen_cement_concurrent_start ();
2793
2794                 current_object_ops = major_collector.major_concurrent_ops;
2795         } else {
2796                 current_object_ops = major_collector.major_ops;
2797         }
2798
2799         reset_pinned_from_failed_allocation ();
2800
2801         sgen_memgov_major_collection_start ();
2802
2803         //count_ref_nonref_objs ();
2804         //consistency_check ();
2805
2806         check_scan_starts ();
2807
2808         degraded_mode = 0;
2809         SGEN_LOG (1, "Start major collection %d", gc_stats.major_gc_count);
2810         gc_stats.major_gc_count ++;
2811
2812         if (major_collector.start_major_collection)
2813                 major_collector.start_major_collection ();
2814
2815         major_copy_or_mark_from_roots (old_next_pin_slot, FALSE, FALSE);
2816 }
2817
2818 static void
2819 wait_for_workers_to_finish (void)
2820 {
2821         while (!sgen_workers_all_done ())
2822                 g_usleep (200);
2823 }
2824
2825 static void
2826 join_workers (void)
2827 {
2828         if (concurrent_collection_in_progress || major_collector.is_parallel) {
2829                 gray_queue_redirect (&gray_queue);
2830                 sgen_workers_join ();
2831         }
2832
2833         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2834
2835 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
2836         main_gc_thread = NULL;
2837 #endif
2838 }
2839
2840 static void
2841 major_finish_collection (const char *reason, size_t old_next_pin_slot, gboolean scan_mod_union)
2842 {
2843         LOSObject *bigobj, *prevbo;
2844         TV_DECLARE (atv);
2845         TV_DECLARE (btv);
2846
2847         TV_GETTIME (btv);
2848
2849         if (concurrent_collection_in_progress || major_collector.is_parallel)
2850                 join_workers ();
2851
2852         if (concurrent_collection_in_progress) {
2853                 current_object_ops = major_collector.major_concurrent_ops;
2854
2855                 major_copy_or_mark_from_roots (NULL, TRUE, scan_mod_union);
2856                 join_workers ();
2857
2858                 g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2859
2860                 if (do_concurrent_checks)
2861                         check_nursery_is_clean ();
2862         } else {
2863                 current_object_ops = major_collector.major_ops;
2864         }
2865
2866         /*
2867          * The workers have stopped so we need to finish gray queue
2868          * work that might result from finalization in the main GC
2869          * thread.  Redirection must therefore be turned off.
2870          */
2871         sgen_gray_object_queue_disable_alloc_prepare (&gray_queue);
2872         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2873
2874         /* all the objects in the heap */
2875         finish_gray_stack (GENERATION_OLD, &gray_queue);
2876         TV_GETTIME (atv);
2877         time_major_finish_gray_stack += TV_ELAPSED (btv, atv);
2878
2879         /*
2880          * The (single-threaded) finalization code might have done
2881          * some copying/marking so we can only reset the GC thread's
2882          * worker data here instead of earlier when we joined the
2883          * workers.
2884          */
2885         sgen_workers_reset_data ();
2886
2887         if (objects_pinned) {
2888                 g_assert (!concurrent_collection_in_progress);
2889
2890                 /*This is slow, but we just OOM'd*/
2891                 sgen_pin_queue_clear_discarded_entries (nursery_section, old_next_pin_slot);
2892                 sgen_optimize_pin_queue (0);
2893                 sgen_find_section_pin_queue_start_end (nursery_section);
2894                 objects_pinned = 0;
2895         }
2896
2897         reset_heap_boundaries ();
2898         sgen_update_heap_boundaries ((mword)sgen_get_nursery_start (), (mword)sgen_get_nursery_end ());
2899
2900         if (check_mark_bits_after_major_collection)
2901                 sgen_check_major_heap_marked ();
2902
2903         MONO_GC_SWEEP_BEGIN (GENERATION_OLD, !major_collector.sweeps_lazily);
2904
2905         /* sweep the big objects list */
2906         prevbo = NULL;
2907         for (bigobj = los_object_list; bigobj;) {
2908                 g_assert (!object_is_pinned (bigobj->data));
2909                 if (sgen_los_object_is_pinned (bigobj->data)) {
2910                         sgen_los_unpin_object (bigobj->data);
2911                         sgen_update_heap_boundaries ((mword)bigobj->data, (mword)bigobj->data + sgen_los_object_size (bigobj));
2912                 } else {
2913                         LOSObject *to_free;
2914                         /* not referenced anywhere, so we can free it */
2915                         if (prevbo)
2916                                 prevbo->next = bigobj->next;
2917                         else
2918                                 los_object_list = bigobj->next;
2919                         to_free = bigobj;
2920                         bigobj = bigobj->next;
2921                         sgen_los_free_object (to_free);
2922                         continue;
2923                 }
2924                 prevbo = bigobj;
2925                 bigobj = bigobj->next;
2926         }
2927
2928         TV_GETTIME (btv);
2929         time_major_free_bigobjs += TV_ELAPSED (atv, btv);
2930
2931         sgen_los_sweep ();
2932
2933         TV_GETTIME (atv);
2934         time_major_los_sweep += TV_ELAPSED (btv, atv);
2935
2936         major_collector.sweep ();
2937
2938         MONO_GC_SWEEP_END (GENERATION_OLD, !major_collector.sweeps_lazily);
2939
2940         TV_GETTIME (btv);
2941         time_major_sweep += TV_ELAPSED (atv, btv);
2942
2943         if (!concurrent_collection_in_progress) {
2944                 /* walk the pin_queue, build up the fragment list of free memory, unmark
2945                  * pinned objects as we go, memzero() the empty fragments so they are ready for the
2946                  * next allocations.
2947                  */
2948                 if (!sgen_build_nursery_fragments (nursery_section, nursery_section->pin_queue_start, nursery_section->pin_queue_num_entries, NULL))
2949                         degraded_mode = 1;
2950
2951                 /* prepare the pin queue for the next collection */
2952                 sgen_finish_pinning ();
2953
2954                 /* Clear TLABs for all threads */
2955                 sgen_clear_tlabs ();
2956
2957                 sgen_pin_stats_reset ();
2958         }
2959
2960         if (concurrent_collection_in_progress)
2961                 sgen_cement_concurrent_finish ();
2962         sgen_cement_clear_below_threshold ();
2963
2964         TV_GETTIME (atv);
2965         time_major_fragment_creation += TV_ELAPSED (btv, atv);
2966
2967         if (heap_dump_file)
2968                 dump_heap ("major", gc_stats.major_gc_count - 1, reason);
2969
2970         if (fin_ready_list || critical_fin_list) {
2971                 SGEN_LOG (4, "Finalizer-thread wakeup: ready %d", num_ready_finalizers);
2972                 mono_gc_finalize_notify ();
2973         }
2974
2975         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2976
2977         sgen_memgov_major_collection_end ();
2978         current_collection_generation = -1;
2979
2980         major_collector.finish_major_collection ();
2981
2982         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2983
2984         if (concurrent_collection_in_progress)
2985                 concurrent_collection_in_progress = FALSE;
2986
2987         check_scan_starts ();
2988
2989         binary_protocol_flush_buffers (FALSE);
2990
2991         //consistency_check ();
2992
2993         MONO_GC_END (GENERATION_OLD);
2994         binary_protocol_collection_end (gc_stats.major_gc_count - 1, GENERATION_OLD);
2995 }
2996
2997 static gboolean
2998 major_do_collection (const char *reason)
2999 {
3000         TV_DECLARE (all_atv);
3001         TV_DECLARE (all_btv);
3002         size_t old_next_pin_slot;
3003
3004         if (disable_major_collections)
3005                 return FALSE;
3006
3007         if (major_collector.get_and_reset_num_major_objects_marked) {
3008                 long long num_marked = major_collector.get_and_reset_num_major_objects_marked ();
3009                 g_assert (!num_marked);
3010         }
3011
3012         /* world must be stopped already */
3013         TV_GETTIME (all_atv);
3014
3015         major_start_collection (FALSE, &old_next_pin_slot);
3016         major_finish_collection (reason, old_next_pin_slot, FALSE);
3017
3018         TV_GETTIME (all_btv);
3019         gc_stats.major_gc_time += TV_ELAPSED (all_atv, all_btv);
3020
3021         /* FIXME: also report this to the user, preferably in gc-end. */
3022         if (major_collector.get_and_reset_num_major_objects_marked)
3023                 major_collector.get_and_reset_num_major_objects_marked ();
3024
3025         return bytes_pinned_from_failed_allocation > 0;
3026 }
3027
3028 static void
3029 major_start_concurrent_collection (const char *reason)
3030 {
3031         long long num_objects_marked;
3032
3033         if (disable_major_collections)
3034                 return;
3035
3036         num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3037         g_assert (num_objects_marked == 0);
3038
3039         MONO_GC_CONCURRENT_START_BEGIN (GENERATION_OLD);
3040         binary_protocol_concurrent_start ();
3041
3042         // FIXME: store reason and pass it when finishing
3043         major_start_collection (TRUE, NULL);
3044
3045         gray_queue_redirect (&gray_queue);
3046         sgen_workers_wait_for_jobs ();
3047
3048         num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
3049         MONO_GC_CONCURRENT_START_END (GENERATION_OLD, num_objects_marked);
3050
3051         current_collection_generation = -1;
3052 }
3053
3054 static gboolean
3055 major_update_or_finish_concurrent_collection (gboolean force_finish)
3056 {
3057         SgenGrayQueue unpin_queue;
3058         memset (&unpin_queue, 0, sizeof (unpin_queue));
3059
3060         MONO_GC_CONCURRENT_UPDATE_FINISH_BEGIN (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3061         binary_protocol_concurrent_update_finish ();
3062
3063         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3064
3065         if (!force_finish && !sgen_workers_all_done ()) {
3066                 major_collector.update_cardtable_mod_union ();
3067                 sgen_los_update_cardtable_mod_union ();
3068
3069                 MONO_GC_CONCURRENT_UPDATE_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3070                 return FALSE;
3071         }
3072
3073         /*
3074          * The major collector can add global remsets which are processed in the finishing
3075          * nursery collection, below.  That implies that the workers must have finished
3076          * marking before the nursery collection is allowed to run, otherwise we might miss
3077          * some remsets.
3078          */
3079         wait_for_workers_to_finish ();
3080
3081         major_collector.update_cardtable_mod_union ();
3082         sgen_los_update_cardtable_mod_union ();
3083
3084         collect_nursery (&unpin_queue, TRUE);
3085
3086         if (mod_union_consistency_check)
3087                 sgen_check_mod_union_consistency ();
3088
3089         current_collection_generation = GENERATION_OLD;
3090         major_finish_collection ("finishing", -1, TRUE);
3091
3092         if (whole_heap_check_before_collection)
3093                 sgen_check_whole_heap (FALSE);
3094
3095         unpin_objects_from_queue (&unpin_queue);
3096         sgen_gray_object_queue_deinit (&unpin_queue);
3097
3098         MONO_GC_CONCURRENT_FINISH_END (GENERATION_OLD, major_collector.get_and_reset_num_major_objects_marked ());
3099
3100         current_collection_generation = -1;
3101
3102         return TRUE;
3103 }
3104
3105 /*
3106  * Ensure an allocation request for @size will succeed by freeing enough memory.
3107  *
3108  * LOCKING: The GC lock MUST be held.
3109  */
3110 void
3111 sgen_ensure_free_space (size_t size)
3112 {
3113         int generation_to_collect = -1;
3114         const char *reason = NULL;
3115
3116
3117         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
3118                 if (sgen_need_major_collection (size)) {
3119                         reason = "LOS overflow";
3120                         generation_to_collect = GENERATION_OLD;
3121                 }
3122         } else {
3123                 if (degraded_mode) {
3124                         if (sgen_need_major_collection (size)) {
3125                                 reason = "Degraded mode overflow";
3126                                 generation_to_collect = GENERATION_OLD;
3127                         }
3128                 } else if (sgen_need_major_collection (size)) {
3129                         reason = "Minor allowance";
3130                         generation_to_collect = GENERATION_OLD;
3131                 } else {
3132                         generation_to_collect = GENERATION_NURSERY;
3133                         reason = "Nursery full";                        
3134                 }
3135         }
3136
3137         if (generation_to_collect == -1) {
3138                 if (concurrent_collection_in_progress && sgen_workers_all_done ()) {
3139                         generation_to_collect = GENERATION_OLD;
3140                         reason = "Finish concurrent collection";
3141                 }
3142         }
3143
3144         if (generation_to_collect == -1)
3145                 return;
3146         sgen_perform_collection (size, generation_to_collect, reason, FALSE);
3147 }
3148
3149 /*
3150  * LOCKING: Assumes the GC lock is held.
3151  */
3152 void
3153 sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish)
3154 {
3155         TV_DECLARE (gc_end);
3156         GGTimingInfo infos [2];
3157         int overflow_generation_to_collect = -1;
3158         int oldest_generation_collected = generation_to_collect;
3159         const char *overflow_reason = NULL;
3160
3161         MONO_GC_REQUESTED (generation_to_collect, requested_size, wait_to_finish ? 1 : 0);
3162         if (wait_to_finish)
3163                 binary_protocol_collection_force (generation_to_collect);
3164
3165         g_assert (generation_to_collect == GENERATION_NURSERY || generation_to_collect == GENERATION_OLD);
3166
3167         memset (infos, 0, sizeof (infos));
3168         mono_profiler_gc_event (MONO_GC_EVENT_START, generation_to_collect);
3169
3170         infos [0].generation = generation_to_collect;
3171         infos [0].reason = reason;
3172         infos [0].is_overflow = FALSE;
3173         TV_GETTIME (infos [0].total_time);
3174         infos [1].generation = -1;
3175
3176         sgen_stop_world (generation_to_collect);
3177
3178         if (concurrent_collection_in_progress) {
3179                 if (major_update_or_finish_concurrent_collection (wait_to_finish && generation_to_collect == GENERATION_OLD)) {
3180                         oldest_generation_collected = GENERATION_OLD;
3181                         goto done;
3182                 }
3183                 if (generation_to_collect == GENERATION_OLD)
3184                         goto done;
3185         } else {
3186                 if (generation_to_collect == GENERATION_OLD &&
3187                                 allow_synchronous_major &&
3188                                 major_collector.want_synchronous_collection &&
3189                                 *major_collector.want_synchronous_collection) {
3190                         wait_to_finish = TRUE;
3191                 }
3192         }
3193
3194         //FIXME extract overflow reason
3195         if (generation_to_collect == GENERATION_NURSERY) {
3196                 if (collect_nursery (NULL, FALSE)) {
3197                         overflow_generation_to_collect = GENERATION_OLD;
3198                         overflow_reason = "Minor overflow";
3199                 }
3200         } else {
3201                 if (major_collector.is_concurrent) {
3202                         g_assert (!concurrent_collection_in_progress);
3203                         if (!wait_to_finish)
3204                                 collect_nursery (NULL, FALSE);
3205                 }
3206
3207                 if (major_collector.is_concurrent && !wait_to_finish) {
3208                         major_start_concurrent_collection (reason);
3209                         // FIXME: set infos[0] properly
3210                         goto done;
3211                 } else {
3212                         if (major_do_collection (reason)) {
3213                                 overflow_generation_to_collect = GENERATION_NURSERY;
3214                                 overflow_reason = "Excessive pinning";
3215                         }
3216                 }
3217         }
3218
3219         TV_GETTIME (gc_end);
3220         infos [0].total_time = SGEN_TV_ELAPSED (infos [0].total_time, gc_end);
3221
3222
3223         if (!major_collector.is_concurrent && overflow_generation_to_collect != -1) {
3224                 mono_profiler_gc_event (MONO_GC_EVENT_START, overflow_generation_to_collect);
3225                 infos [1].generation = overflow_generation_to_collect;
3226                 infos [1].reason = overflow_reason;
3227                 infos [1].is_overflow = TRUE;
3228                 infos [1].total_time = gc_end;
3229
3230                 if (overflow_generation_to_collect == GENERATION_NURSERY)
3231                         collect_nursery (NULL, FALSE);
3232                 else
3233                         major_do_collection (overflow_reason);
3234
3235                 TV_GETTIME (gc_end);
3236                 infos [1].total_time = SGEN_TV_ELAPSED (infos [1].total_time, gc_end);
3237
3238                 /* keep events symmetric */
3239                 mono_profiler_gc_event (MONO_GC_EVENT_END, overflow_generation_to_collect);
3240
3241                 oldest_generation_collected = MAX (oldest_generation_collected, overflow_generation_to_collect);
3242         }
3243
3244         SGEN_LOG (2, "Heap size: %lu, LOS size: %lu", (unsigned long)mono_gc_get_heap_size (), (unsigned long)los_memory_usage);
3245
3246         /* this also sets the proper pointers for the next allocation */
3247         if (generation_to_collect == GENERATION_NURSERY && !sgen_can_alloc_size (requested_size)) {
3248                 /* TypeBuilder and MonoMethod are killing mcs with fragmentation */
3249                 SGEN_LOG (1, "nursery collection didn't find enough room for %zd alloc (%zd pinned)", requested_size, sgen_get_pinned_count ());
3250                 sgen_dump_pin_queue ();
3251                 degraded_mode = 1;
3252         }
3253
3254  done:
3255         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
3256
3257         sgen_restart_world (oldest_generation_collected, infos);
3258
3259         mono_profiler_gc_event (MONO_GC_EVENT_END, generation_to_collect);
3260 }
3261
3262 /*
3263  * ######################################################################
3264  * ########  Memory allocation from the OS
3265  * ######################################################################
3266  * This section of code deals with getting memory from the OS and
3267  * allocating memory for GC-internal data structures.
3268  * Internal memory can be handled with a freelist for small objects.
3269  */
3270
3271 /*
3272  * Debug reporting.
3273  */
3274 G_GNUC_UNUSED static void
3275 report_internal_mem_usage (void)
3276 {
3277         printf ("Internal memory usage:\n");
3278         sgen_report_internal_mem_usage ();
3279         printf ("Pinned memory usage:\n");
3280         major_collector.report_pinned_memory_usage ();
3281 }
3282
3283 /*
3284  * ######################################################################
3285  * ########  Finalization support
3286  * ######################################################################
3287  */
3288
3289 static inline gboolean
3290 sgen_major_is_object_alive (void *object)
3291 {
3292         mword objsize;
3293
3294         /* Oldgen objects can be pinned and forwarded too */
3295         if (SGEN_OBJECT_IS_PINNED (object) || SGEN_OBJECT_IS_FORWARDED (object))
3296                 return TRUE;
3297
3298         /*
3299          * FIXME: major_collector.is_object_live() also calculates the
3300          * size.  Avoid the double calculation.
3301          */
3302         objsize = SGEN_ALIGN_UP (sgen_safe_object_get_size ((MonoObject*)object));
3303         if (objsize > SGEN_MAX_SMALL_OBJ_SIZE)
3304                 return sgen_los_object_is_pinned (object);
3305
3306         return major_collector.is_object_live (object);
3307 }
3308
3309 /*
3310  * If the object has been forwarded it means it's still referenced from a root. 
3311  * If it is pinned it's still alive as well.
3312  * A LOS object is only alive if we have pinned it.
3313  * Return TRUE if @obj is ready to be finalized.
3314  */
3315 static inline gboolean
3316 sgen_is_object_alive (void *object)
3317 {
3318         if (ptr_in_nursery (object))
3319                 return sgen_nursery_is_object_alive (object);
3320
3321         return sgen_major_is_object_alive (object);
3322 }
3323
3324 /*
3325  * This function returns true if @object is either alive or it belongs to the old gen
3326  * and we're currently doing a minor collection.
3327  */
3328 static inline int
3329 sgen_is_object_alive_for_current_gen (char *object)
3330 {
3331         if (ptr_in_nursery (object))
3332                 return sgen_nursery_is_object_alive (object);
3333
3334         if (current_collection_generation == GENERATION_NURSERY)
3335                 return TRUE;
3336
3337         return sgen_major_is_object_alive (object);
3338 }
3339
3340 /*
3341  * This function returns true if @object is either alive and belongs to the
3342  * current collection - major collections are full heap, so old gen objects
3343  * are never alive during a minor collection.
3344  */
3345 static inline int
3346 sgen_is_object_alive_and_on_current_collection (char *object)
3347 {
3348         if (ptr_in_nursery (object))
3349                 return sgen_nursery_is_object_alive (object);
3350
3351         if (current_collection_generation == GENERATION_NURSERY)
3352                 return FALSE;
3353
3354         return sgen_major_is_object_alive (object);
3355 }
3356
3357
3358 gboolean
3359 sgen_gc_is_object_ready_for_finalization (void *object)
3360 {
3361         return !sgen_is_object_alive (object);
3362 }
3363
3364 static gboolean
3365 has_critical_finalizer (MonoObject *obj)
3366 {
3367         MonoClass *class;
3368
3369         if (!mono_defaults.critical_finalizer_object)
3370                 return FALSE;
3371
3372         class = ((MonoVTable*)LOAD_VTABLE (obj))->klass;
3373
3374         return mono_class_has_parent_fast (class, mono_defaults.critical_finalizer_object);
3375 }
3376
3377 static gboolean
3378 is_finalization_aware (MonoObject *obj)
3379 {
3380         MonoVTable *vt = ((MonoVTable*)LOAD_VTABLE (obj));
3381         return (vt->gc_bits & SGEN_GC_BIT_FINALIZER_AWARE) == SGEN_GC_BIT_FINALIZER_AWARE;
3382 }
3383
3384 void
3385 sgen_queue_finalization_entry (MonoObject *obj)
3386 {
3387         FinalizeReadyEntry *entry = sgen_alloc_internal (INTERNAL_MEM_FINALIZE_READY_ENTRY);
3388         gboolean critical = has_critical_finalizer (obj);
3389         entry->object = obj;
3390         if (critical) {
3391                 entry->next = critical_fin_list;
3392                 critical_fin_list = entry;
3393         } else {
3394                 entry->next = fin_ready_list;
3395                 fin_ready_list = entry;
3396         }
3397
3398         if (fin_callbacks.object_queued_for_finalization && is_finalization_aware (obj))
3399                 fin_callbacks.object_queued_for_finalization (obj);
3400
3401 #ifdef ENABLE_DTRACE
3402         if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
3403                 int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
3404                 MonoVTable *vt = (MonoVTable*)LOAD_VTABLE (obj);
3405                 MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
3406                                 vt->klass->name_space, vt->klass->name, gen, critical);
3407         }
3408 #endif
3409 }
3410
3411 gboolean
3412 sgen_object_is_live (void *obj)
3413 {
3414         return sgen_is_object_alive_and_on_current_collection (obj);
3415 }
3416
3417 /* LOCKING: requires that the GC lock is held */
3418 static void
3419 null_ephemerons_for_domain (MonoDomain *domain)
3420 {
3421         EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3422
3423         while (current) {
3424                 MonoObject *object = (MonoObject*)current->array;
3425
3426                 if (object && !object->vtable) {
3427                         EphemeronLinkNode *tmp = current;
3428
3429                         if (prev)
3430                                 prev->next = current->next;
3431                         else
3432                                 ephemeron_list = current->next;
3433
3434                         current = current->next;
3435                         sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3436                 } else {
3437                         prev = current;
3438                         current = current->next;
3439                 }
3440         }
3441 }
3442
3443 /* LOCKING: requires that the GC lock is held */
3444 static void
3445 clear_unreachable_ephemerons (ScanCopyContext ctx)
3446 {
3447         CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3448         GrayQueue *queue = ctx.queue;
3449         EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
3450         MonoArray *array;
3451         Ephemeron *cur, *array_end;
3452         char *tombstone;
3453
3454         while (current) {
3455                 char *object = current->array;
3456
3457                 if (!sgen_is_object_alive_for_current_gen (object)) {
3458                         EphemeronLinkNode *tmp = current;
3459
3460                         SGEN_LOG (5, "Dead Ephemeron array at %p", object);
3461
3462                         if (prev)
3463                                 prev->next = current->next;
3464                         else
3465                                 ephemeron_list = current->next;
3466
3467                         current = current->next;
3468                         sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
3469
3470                         continue;
3471                 }
3472
3473                 copy_func ((void**)&object, queue);
3474                 current->array = object;
3475
3476                 SGEN_LOG (5, "Clearing unreachable entries for ephemeron array at %p", object);
3477
3478                 array = (MonoArray*)object;
3479                 cur = mono_array_addr (array, Ephemeron, 0);
3480                 array_end = cur + mono_array_length_fast (array);
3481                 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3482
3483                 for (; cur < array_end; ++cur) {
3484                         char *key = (char*)cur->key;
3485
3486                         if (!key || key == tombstone)
3487                                 continue;
3488
3489                         SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3490                                 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3491                                 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3492
3493                         if (!sgen_is_object_alive_for_current_gen (key)) {
3494                                 cur->key = tombstone;
3495                                 cur->value = NULL;
3496                                 continue;
3497                         }
3498                 }
3499                 prev = current;
3500                 current = current->next;
3501         }
3502 }
3503
3504 /*
3505 LOCKING: requires that the GC lock is held
3506
3507 Limitations: We scan all ephemerons on every collection since the current design doesn't allow for a simple nursery/mature split.
3508 */
3509 static int
3510 mark_ephemerons_in_range (ScanCopyContext ctx)
3511 {
3512         CopyOrMarkObjectFunc copy_func = ctx.copy_func;
3513         GrayQueue *queue = ctx.queue;
3514         int nothing_marked = 1;
3515         EphemeronLinkNode *current = ephemeron_list;
3516         MonoArray *array;
3517         Ephemeron *cur, *array_end;
3518         char *tombstone;
3519
3520         for (current = ephemeron_list; current; current = current->next) {
3521                 char *object = current->array;
3522                 SGEN_LOG (5, "Ephemeron array at %p", object);
3523
3524                 /*It has to be alive*/
3525                 if (!sgen_is_object_alive_for_current_gen (object)) {
3526                         SGEN_LOG (5, "\tnot reachable");
3527                         continue;
3528                 }
3529
3530                 copy_func ((void**)&object, queue);
3531
3532                 array = (MonoArray*)object;
3533                 cur = mono_array_addr (array, Ephemeron, 0);
3534                 array_end = cur + mono_array_length_fast (array);
3535                 tombstone = (char*)((MonoVTable*)LOAD_VTABLE (object))->domain->ephemeron_tombstone;
3536
3537                 for (; cur < array_end; ++cur) {
3538                         char *key = cur->key;
3539
3540                         if (!key || key == tombstone)
3541                                 continue;
3542
3543                         SGEN_LOG (5, "[%td] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
3544                                 key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
3545                                 cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
3546
3547                         if (sgen_is_object_alive_for_current_gen (key)) {
3548                                 char *value = cur->value;
3549
3550                                 copy_func ((void**)&cur->key, queue);
3551                                 if (value) {
3552                                         if (!sgen_is_object_alive_for_current_gen (value))
3553                                                 nothing_marked = 0;
3554                                         copy_func ((void**)&cur->value, queue);
3555                                 }
3556                         }
3557                 }
3558         }
3559
3560         SGEN_LOG (5, "Ephemeron run finished. Is it done %d", nothing_marked);
3561         return nothing_marked;
3562 }
3563
3564 int
3565 mono_gc_invoke_finalizers (void)
3566 {
3567         FinalizeReadyEntry *entry = NULL;
3568         gboolean entry_is_critical = FALSE;
3569         int count = 0;
3570         void *obj;
3571         /* FIXME: batch to reduce lock contention */
3572         while (fin_ready_list || critical_fin_list) {
3573                 LOCK_GC;
3574
3575                 if (entry) {
3576                         FinalizeReadyEntry **list = entry_is_critical ? &critical_fin_list : &fin_ready_list;
3577
3578                         /* We have finalized entry in the last
3579                            interation, now we need to remove it from
3580                            the list. */
3581                         if (*list == entry)
3582                                 *list = entry->next;
3583                         else {
3584                                 FinalizeReadyEntry *e = *list;
3585                                 while (e->next != entry)
3586                                         e = e->next;
3587                                 e->next = entry->next;
3588                         }
3589                         sgen_free_internal (entry, INTERNAL_MEM_FINALIZE_READY_ENTRY);
3590                         entry = NULL;
3591                 }
3592
3593                 /* Now look for the first non-null entry. */
3594                 for (entry = fin_ready_list; entry && !entry->object; entry = entry->next)
3595                         ;
3596                 if (entry) {
3597                         entry_is_critical = FALSE;
3598                 } else {
3599                         entry_is_critical = TRUE;
3600                         for (entry = critical_fin_list; entry && !entry->object; entry = entry->next)
3601                                 ;
3602                 }
3603
3604                 if (entry) {
3605                         g_assert (entry->object);
3606                         num_ready_finalizers--;
3607                         obj = entry->object;
3608                         entry->object = NULL;
3609                         SGEN_LOG (7, "Finalizing object %p (%s)", obj, safe_name (obj));
3610                 }
3611
3612                 UNLOCK_GC;
3613
3614                 if (!entry)
3615                         break;
3616
3617                 g_assert (entry->object == NULL);
3618                 count++;
3619                 /* the object is on the stack so it is pinned */
3620                 /*g_print ("Calling finalizer for object: %p (%s)\n", entry->object, safe_name (entry->object));*/
3621                 mono_gc_run_finalize (obj, NULL);
3622         }
3623         g_assert (!entry);
3624         return count;
3625 }
3626
3627 gboolean
3628 mono_gc_pending_finalizers (void)
3629 {
3630         return fin_ready_list || critical_fin_list;
3631 }
3632
3633 /*
3634  * ######################################################################
3635  * ########  registered roots support
3636  * ######################################################################
3637  */
3638
3639 /*
3640  * We do not coalesce roots.
3641  */
3642 static int
3643 mono_gc_register_root_inner (char *start, size_t size, void *descr, int root_type)
3644 {
3645         RootRecord new_root;
3646         int i;
3647         LOCK_GC;
3648         for (i = 0; i < ROOT_TYPE_NUM; ++i) {
3649                 RootRecord *root = sgen_hash_table_lookup (&roots_hash [i], start);
3650                 /* we allow changing the size and the descriptor (for thread statics etc) */
3651                 if (root) {
3652                         size_t old_size = root->end_root - start;
3653                         root->end_root = start + size;
3654                         g_assert (((root->root_desc != 0) && (descr != NULL)) ||
3655                                           ((root->root_desc == 0) && (descr == NULL)));
3656                         root->root_desc = (mword)descr;
3657                         roots_size += size;
3658                         roots_size -= old_size;
3659                         UNLOCK_GC;
3660                         return TRUE;
3661                 }
3662         }
3663
3664         new_root.end_root = start + size;
3665         new_root.root_desc = (mword)descr;
3666
3667         sgen_hash_table_replace (&roots_hash [root_type], start, &new_root, NULL);
3668         roots_size += size;
3669
3670         SGEN_LOG (3, "Added root for range: %p-%p, descr: %p  (%d/%d bytes)", start, new_root.end_root, descr, (int)size, (int)roots_size);
3671
3672         UNLOCK_GC;
3673         return TRUE;
3674 }
3675
3676 int
3677 mono_gc_register_root (char *start, size_t size, void *descr)
3678 {
3679         return mono_gc_register_root_inner (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED);
3680 }
3681
3682 int
3683 mono_gc_register_root_wbarrier (char *start, size_t size, void *descr)
3684 {
3685         return mono_gc_register_root_inner (start, size, descr, ROOT_TYPE_WBARRIER);
3686 }
3687
3688 void
3689 mono_gc_deregister_root (char* addr)
3690 {
3691         int root_type;
3692         RootRecord root;
3693
3694         LOCK_GC;
3695         for (root_type = 0; root_type < ROOT_TYPE_NUM; ++root_type) {
3696                 if (sgen_hash_table_remove (&roots_hash [root_type], addr, &root))
3697                         roots_size -= (root.end_root - addr);
3698         }
3699         UNLOCK_GC;
3700 }
3701
3702 /*
3703  * ######################################################################
3704  * ########  Thread handling (stop/start code)
3705  * ######################################################################
3706  */
3707
3708 unsigned int sgen_global_stop_count = 0;
3709
3710 int
3711 sgen_get_current_collection_generation (void)
3712 {
3713         return current_collection_generation;
3714 }
3715
3716 void
3717 mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
3718 {
3719         gc_callbacks = *callbacks;
3720 }
3721
3722 MonoGCCallbacks *
3723 mono_gc_get_gc_callbacks ()
3724 {
3725         return &gc_callbacks;
3726 }
3727
3728 /* Variables holding start/end nursery so it won't have to be passed at every call */
3729 static void *scan_area_arg_start, *scan_area_arg_end;
3730
3731 void
3732 mono_gc_conservatively_scan_area (void *start, void *end)
3733 {
3734         conservatively_pin_objects_from (start, end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
3735 }
3736
3737 void*
3738 mono_gc_scan_object (void *obj, void *gc_data)
3739 {
3740         UserCopyOrMarkData *data = gc_data;
3741         current_object_ops.copy_or_mark_object (&obj, data->queue);
3742         return obj;
3743 }
3744
3745 /*
3746  * Mark from thread stacks and registers.
3747  */
3748 static void
3749 scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, GrayQueue *queue)
3750 {
3751         SgenThreadInfo *info;
3752
3753         scan_area_arg_start = start_nursery;
3754         scan_area_arg_end = end_nursery;
3755
3756         FOREACH_THREAD (info) {
3757                 if (info->skip) {
3758                         SGEN_LOG (3, "Skipping dead thread %p, range: %p-%p, size: %td", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start);
3759                         continue;
3760                 }
3761                 if (info->gc_disabled) {
3762                         SGEN_LOG (3, "GC disabled for thread %p, range: %p-%p, size: %td", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start);
3763                         continue;
3764                 }
3765                 if (mono_thread_info_run_state (info) != STATE_RUNNING) {
3766                         SGEN_LOG (3, "Skipping non-running thread %p, range: %p-%p, size: %td (state %d)", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, mono_thread_info_run_state (info));
3767                         continue;
3768                 }
3769                 SGEN_LOG (3, "Scanning thread %p, range: %p-%p, size: %td, pinned=%zd", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, sgen_get_pinned_count ());
3770                 if (gc_callbacks.thread_mark_func && !conservative_stack_mark) {
3771                         UserCopyOrMarkData data = { NULL, queue };
3772                         gc_callbacks.thread_mark_func (info->runtime_data, info->stack_start, info->stack_end, precise, &data);
3773                 } else if (!precise) {
3774                         if (!conservative_stack_mark) {
3775                                 fprintf (stderr, "Precise stack mark not supported - disabling.\n");
3776                                 conservative_stack_mark = TRUE;
3777                         }
3778                         conservatively_pin_objects_from (info->stack_start, info->stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
3779                 }
3780
3781                 if (!precise) {
3782 #ifdef USE_MONO_CTX
3783                         conservatively_pin_objects_from ((void**)&info->ctx, (void**)&info->ctx + ARCH_NUM_REGS,
3784                                 start_nursery, end_nursery, PIN_TYPE_STACK);
3785 #else
3786                         conservatively_pin_objects_from ((void**)&info->regs, (void**)&info->regs + ARCH_NUM_REGS,
3787                                         start_nursery, end_nursery, PIN_TYPE_STACK);
3788 #endif
3789                 }
3790         } END_FOREACH_THREAD
3791 }
3792
3793 static gboolean
3794 ptr_on_stack (void *ptr)
3795 {
3796         gpointer stack_start = &stack_start;
3797         SgenThreadInfo *info = mono_thread_info_current ();
3798
3799         if (ptr >= stack_start && ptr < (gpointer)info->stack_end)
3800                 return TRUE;
3801         return FALSE;
3802 }
3803
3804 static void*
3805 sgen_thread_register (SgenThreadInfo* info, void *addr)
3806 {
3807         size_t stsize = 0;
3808         guint8 *staddr = NULL;
3809
3810 #ifndef HAVE_KW_THREAD
3811         info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
3812
3813         g_assert (!mono_native_tls_get_value (thread_info_key));
3814         mono_native_tls_set_value (thread_info_key, info);
3815 #else
3816         sgen_thread_info = info;
3817 #endif
3818
3819 #ifdef SGEN_POSIX_STW
3820         info->stop_count = -1;
3821         info->signal = 0;
3822 #endif
3823         info->skip = 0;
3824         info->stack_start = NULL;
3825         info->stopped_ip = NULL;
3826         info->stopped_domain = NULL;
3827 #ifdef USE_MONO_CTX
3828         memset (&info->ctx, 0, sizeof (MonoContext));
3829 #else
3830         memset (&info->regs, 0, sizeof (info->regs));
3831 #endif
3832
3833         sgen_init_tlab_info (info);
3834
3835         binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
3836
3837         /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
3838 #ifndef HOST_WIN32
3839         mono_thread_info_get_stack_bounds (&staddr, &stsize);
3840 #endif
3841         if (staddr) {
3842                 info->stack_start_limit = staddr;
3843                 info->stack_end = staddr + stsize;
3844         } else {
3845                 gsize stack_bottom = (gsize)addr;
3846                 stack_bottom += 4095;
3847                 stack_bottom &= ~4095;
3848                 info->stack_end = (char*)stack_bottom;
3849         }
3850
3851 #ifdef HAVE_KW_THREAD
3852         stack_end = info->stack_end;
3853 #endif
3854
3855         SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->stack_end);
3856
3857         if (gc_callbacks.thread_attach_func)
3858                 info->runtime_data = gc_callbacks.thread_attach_func ();
3859         return info;
3860 }
3861
3862 static void
3863 sgen_thread_detach (SgenThreadInfo *p)
3864 {
3865         /* If a delegate is passed to native code and invoked on a thread we dont
3866          * know about, the jit will register it with mono_jit_thread_attach, but
3867          * we have no way of knowing when that thread goes away.  SGen has a TSD
3868          * so we assume that if the domain is still registered, we can detach
3869          * the thread
3870          */
3871         if (mono_domain_get ())
3872                 mono_thread_detach_internal (mono_thread_internal_current ());
3873 }
3874
3875 static void
3876 sgen_thread_unregister (SgenThreadInfo *p)
3877 {
3878         MonoNativeThreadId tid;
3879
3880         tid = mono_thread_info_get_tid (p);
3881         binary_protocol_thread_unregister ((gpointer)tid);
3882         SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
3883
3884 #ifndef HAVE_KW_THREAD
3885         mono_native_tls_set_value (thread_info_key, NULL);
3886 #else
3887         sgen_thread_info = NULL;
3888 #endif
3889
3890         if (p->info.runtime_thread)
3891                 mono_threads_add_joinable_thread ((gpointer)tid);
3892
3893         if (gc_callbacks.thread_detach_func) {
3894                 gc_callbacks.thread_detach_func (p->runtime_data);
3895                 p->runtime_data = NULL;
3896         }
3897 }
3898
3899
3900 static void
3901 sgen_thread_attach (SgenThreadInfo *info)
3902 {
3903         LOCK_GC;
3904         /*this is odd, can we get attached before the gc is inited?*/
3905         init_stats ();
3906         UNLOCK_GC;
3907         
3908         if (gc_callbacks.thread_attach_func && !info->runtime_data)
3909                 info->runtime_data = gc_callbacks.thread_attach_func ();
3910 }
3911 gboolean
3912 mono_gc_register_thread (void *baseptr)
3913 {
3914         return mono_thread_info_attach (baseptr) != NULL;
3915 }
3916
3917 /*
3918  * mono_gc_set_stack_end:
3919  *
3920  *   Set the end of the current threads stack to STACK_END. The stack space between 
3921  * STACK_END and the real end of the threads stack will not be scanned during collections.
3922  */
3923 void
3924 mono_gc_set_stack_end (void *stack_end)
3925 {
3926         SgenThreadInfo *info;
3927
3928         LOCK_GC;
3929         info = mono_thread_info_current ();
3930         if (info) {
3931                 g_assert (stack_end < info->stack_end);
3932                 info->stack_end = stack_end;
3933         }
3934         UNLOCK_GC;
3935 }
3936
3937 #if USE_PTHREAD_INTERCEPT
3938
3939
3940 int
3941 mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
3942 {
3943         return pthread_create (new_thread, attr, start_routine, arg);
3944 }
3945
3946 int
3947 mono_gc_pthread_join (pthread_t thread, void **retval)
3948 {
3949         return pthread_join (thread, retval);
3950 }
3951
3952 int
3953 mono_gc_pthread_detach (pthread_t thread)
3954 {
3955         return pthread_detach (thread);
3956 }
3957
3958 void
3959 mono_gc_pthread_exit (void *retval) 
3960 {
3961         mono_thread_info_detach ();
3962         pthread_exit (retval);
3963         g_assert_not_reached ();
3964 }
3965
3966 #endif /* USE_PTHREAD_INTERCEPT */
3967
3968 /*
3969  * ######################################################################
3970  * ########  Write barriers
3971  * ######################################################################
3972  */
3973
3974 /*
3975  * Note: the write barriers first do the needed GC work and then do the actual store:
3976  * this way the value is visible to the conservative GC scan after the write barrier
3977  * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
3978  * the conservative scan, otherwise by the remembered set scan.
3979  */
3980 void
3981 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
3982 {
3983         HEAVY_STAT (++stat_wbarrier_set_field);
3984         if (ptr_in_nursery (field_ptr)) {
3985                 *(void**)field_ptr = value;
3986                 return;
3987         }
3988         SGEN_LOG (8, "Adding remset at %p", field_ptr);
3989         if (value)
3990                 binary_protocol_wbarrier (field_ptr, value, value->vtable);
3991
3992         remset.wbarrier_set_field (obj, field_ptr, value);
3993 }
3994
3995 void
3996 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
3997 {
3998         HEAVY_STAT (++stat_wbarrier_set_arrayref);
3999         if (ptr_in_nursery (slot_ptr)) {
4000                 *(void**)slot_ptr = value;
4001                 return;
4002         }
4003         SGEN_LOG (8, "Adding remset at %p", slot_ptr);
4004         if (value)
4005                 binary_protocol_wbarrier (slot_ptr, value, value->vtable);
4006
4007         remset.wbarrier_set_arrayref (arr, slot_ptr, value);
4008 }
4009
4010 void
4011 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
4012 {
4013         HEAVY_STAT (++stat_wbarrier_arrayref_copy);
4014         /*This check can be done without taking a lock since dest_ptr array is pinned*/
4015         if (ptr_in_nursery (dest_ptr) || count <= 0) {
4016                 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
4017                 return;
4018         }
4019
4020 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4021         if (binary_protocol_is_heavy_enabled ()) {
4022                 int i;
4023                 for (i = 0; i < count; ++i) {
4024                         gpointer dest = (gpointer*)dest_ptr + i;
4025                         gpointer obj = *((gpointer*)src_ptr + i);
4026                         if (obj)
4027                                 binary_protocol_wbarrier (dest, obj, (gpointer)LOAD_VTABLE (obj));
4028                 }
4029         }
4030 #endif
4031
4032         remset.wbarrier_arrayref_copy (dest_ptr, src_ptr, count);
4033 }
4034
4035 static char *found_obj;
4036
4037 static void
4038 find_object_for_ptr_callback (char *obj, size_t size, void *user_data)
4039 {
4040         char *ptr = user_data;
4041
4042         if (ptr >= obj && ptr < obj + size) {
4043                 g_assert (!found_obj);
4044                 found_obj = obj;
4045         }
4046 }
4047
4048 /* for use in the debugger */
4049 char* find_object_for_ptr (char *ptr);
4050 char*
4051 find_object_for_ptr (char *ptr)
4052 {
4053         if (ptr >= nursery_section->data && ptr < nursery_section->end_data) {
4054                 found_obj = NULL;
4055                 sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
4056                                 find_object_for_ptr_callback, ptr, TRUE);
4057                 if (found_obj)
4058                         return found_obj;
4059         }
4060
4061         found_obj = NULL;
4062         sgen_los_iterate_objects (find_object_for_ptr_callback, ptr);
4063         if (found_obj)
4064                 return found_obj;
4065
4066         /*
4067          * Very inefficient, but this is debugging code, supposed to
4068          * be called from gdb, so we don't care.
4069          */
4070         found_obj = NULL;
4071         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, find_object_for_ptr_callback, ptr);
4072         return found_obj;
4073 }
4074
4075 void
4076 mono_gc_wbarrier_generic_nostore (gpointer ptr)
4077 {
4078         gpointer obj;
4079
4080         HEAVY_STAT (++stat_wbarrier_generic_store);
4081
4082 #ifdef XDOMAIN_CHECKS_IN_WBARRIER
4083         /* FIXME: ptr_in_heap must be called with the GC lock held */
4084         if (xdomain_checks && *(MonoObject**)ptr && ptr_in_heap (ptr)) {
4085                 char *start = find_object_for_ptr (ptr);
4086                 MonoObject *value = *(MonoObject**)ptr;
4087                 LOCK_GC;
4088                 g_assert (start);
4089                 if (start) {
4090                         MonoObject *obj = (MonoObject*)start;
4091                         if (obj->vtable->domain != value->vtable->domain)
4092                                 g_assert (is_xdomain_ref_allowed (ptr, start, obj->vtable->domain));
4093                 }
4094                 UNLOCK_GC;
4095         }
4096 #endif
4097
4098         obj = *(gpointer*)ptr;
4099         if (obj)
4100                 binary_protocol_wbarrier (ptr, obj, (gpointer)LOAD_VTABLE (obj));
4101
4102         if (ptr_in_nursery (ptr) || ptr_on_stack (ptr)) {
4103                 SGEN_LOG (8, "Skipping remset at %p", ptr);
4104                 return;
4105         }
4106
4107         /*
4108          * We need to record old->old pointer locations for the
4109          * concurrent collector.
4110          */
4111         if (!ptr_in_nursery (obj) && !concurrent_collection_in_progress) {
4112                 SGEN_LOG (8, "Skipping remset at %p", ptr);
4113                 return;
4114         }
4115
4116         SGEN_LOG (8, "Adding remset at %p", ptr);
4117
4118         remset.wbarrier_generic_nostore (ptr);
4119 }
4120
4121 void
4122 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
4123 {
4124         SGEN_LOG (8, "Wbarrier store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
4125         *(void**)ptr = value;
4126         if (ptr_in_nursery (value))
4127                 mono_gc_wbarrier_generic_nostore (ptr);
4128         sgen_dummy_use (value);
4129 }
4130
4131 /* Same as mono_gc_wbarrier_generic_store () but performs the store
4132  * as an atomic operation with release semantics.
4133  */
4134 void
4135 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, MonoObject *value)
4136 {
4137         HEAVY_STAT (++stat_wbarrier_generic_store_atomic);
4138
4139         SGEN_LOG (8, "Wbarrier atomic store at %p to %p (%s)", ptr, value, value ? safe_name (value) : "null");
4140
4141         InterlockedWritePointer (ptr, value);
4142
4143         if (ptr_in_nursery (value))
4144                 mono_gc_wbarrier_generic_nostore (ptr);
4145
4146         sgen_dummy_use (value);
4147 }
4148
4149 void mono_gc_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
4150 {
4151         mword *dest = _dest;
4152         mword *src = _src;
4153
4154         while (size) {
4155                 if (bitmap & 0x1)
4156                         mono_gc_wbarrier_generic_store (dest, (MonoObject*)*src);
4157                 else
4158                         *dest = *src;
4159                 ++src;
4160                 ++dest;
4161                 size -= SIZEOF_VOID_P;
4162                 bitmap >>= 1;
4163         }
4164 }
4165
4166 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4167 #undef HANDLE_PTR
4168 #define HANDLE_PTR(ptr,obj) do {                                        \
4169                 gpointer o = *(gpointer*)(ptr);                         \
4170                 if ((o)) {                                              \
4171                         gpointer d = ((char*)dest) + ((char*)(ptr) - (char*)(obj)); \
4172                         binary_protocol_wbarrier (d, o, (gpointer) LOAD_VTABLE (o)); \
4173                 }                                                       \
4174         } while (0)
4175
4176 static void
4177 scan_object_for_binary_protocol_copy_wbarrier (gpointer dest, char *start, mword desc)
4178 {
4179 #define SCAN_OBJECT_NOVTABLE
4180 #include "sgen-scan-object.h"
4181 }
4182 #endif
4183
4184 void
4185 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
4186 {
4187         HEAVY_STAT (++stat_wbarrier_value_copy);
4188         g_assert (klass->valuetype);
4189
4190         SGEN_LOG (8, "Adding value remset at %p, count %d, descr %p for class %s (%p)", dest, count, klass->gc_descr, klass->name, klass);
4191
4192         if (ptr_in_nursery (dest) || ptr_on_stack (dest) || !SGEN_CLASS_HAS_REFERENCES (klass)) {
4193                 size_t element_size = mono_class_value_size (klass, NULL);
4194                 size_t size = count * element_size;
4195                 mono_gc_memmove_atomic (dest, src, size);               
4196                 return;
4197         }
4198
4199 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4200         if (binary_protocol_is_heavy_enabled ()) {
4201                 size_t element_size = mono_class_value_size (klass, NULL);
4202                 int i;
4203                 for (i = 0; i < count; ++i) {
4204                         scan_object_for_binary_protocol_copy_wbarrier ((char*)dest + i * element_size,
4205                                         (char*)src + i * element_size - sizeof (MonoObject),
4206                                         (mword) klass->gc_descr);
4207                 }
4208         }
4209 #endif
4210
4211         remset.wbarrier_value_copy (dest, src, count, klass);
4212 }
4213
4214 /**
4215  * mono_gc_wbarrier_object_copy:
4216  *
4217  * Write barrier to call when obj is the result of a clone or copy of an object.
4218  */
4219 void
4220 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
4221 {
4222         int size;
4223
4224         HEAVY_STAT (++stat_wbarrier_object_copy);
4225
4226         if (ptr_in_nursery (obj) || ptr_on_stack (obj)) {
4227                 size = mono_object_class (obj)->instance_size;
4228                 mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
4229                                 size - sizeof (MonoObject));
4230                 return; 
4231         }
4232
4233 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
4234         if (binary_protocol_is_heavy_enabled ())
4235                 scan_object_for_binary_protocol_copy_wbarrier (obj, (char*)src, (mword) src->vtable->gc_descr);
4236 #endif
4237
4238         remset.wbarrier_object_copy (obj, src);
4239 }
4240
4241
4242 /*
4243  * ######################################################################
4244  * ########  Other mono public interface functions.
4245  * ######################################################################
4246  */
4247
4248 #define REFS_SIZE 128
4249 typedef struct {
4250         void *data;
4251         MonoGCReferences callback;
4252         int flags;
4253         int count;
4254         int called;
4255         MonoObject *refs [REFS_SIZE];
4256         uintptr_t offsets [REFS_SIZE];
4257 } HeapWalkInfo;
4258
4259 #undef HANDLE_PTR
4260 #define HANDLE_PTR(ptr,obj)     do {    \
4261                 if (*(ptr)) {   \
4262                         if (hwi->count == REFS_SIZE) {  \
4263                                 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);    \
4264                                 hwi->count = 0; \
4265                                 hwi->called = 1;        \
4266                         }       \
4267                         hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start;  \
4268                         hwi->refs [hwi->count++] = *(ptr);      \
4269                 }       \
4270         } while (0)
4271
4272 static void
4273 collect_references (HeapWalkInfo *hwi, char *start, size_t size)
4274 {
4275 #include "sgen-scan-object.h"
4276 }
4277
4278 static void
4279 walk_references (char *start, size_t size, void *data)
4280 {
4281         HeapWalkInfo *hwi = data;
4282         hwi->called = 0;
4283         hwi->count = 0;
4284         collect_references (hwi, start, size);
4285         if (hwi->count || !hwi->called)
4286                 hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
4287 }
4288
4289 /**
4290  * mono_gc_walk_heap:
4291  * @flags: flags for future use
4292  * @callback: a function pointer called for each object in the heap
4293  * @data: a user data pointer that is passed to callback
4294  *
4295  * This function can be used to iterate over all the live objects in the heap:
4296  * for each object, @callback is invoked, providing info about the object's
4297  * location in memory, its class, its size and the objects it references.
4298  * For each referenced object it's offset from the object address is
4299  * reported in the offsets array.
4300  * The object references may be buffered, so the callback may be invoked
4301  * multiple times for the same object: in all but the first call, the size
4302  * argument will be zero.
4303  * Note that this function can be only called in the #MONO_GC_EVENT_PRE_START_WORLD
4304  * profiler event handler.
4305  *
4306  * Returns: a non-zero value if the GC doesn't support heap walking
4307  */
4308 int
4309 mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
4310 {
4311         HeapWalkInfo hwi;
4312
4313         hwi.flags = flags;
4314         hwi.callback = callback;
4315         hwi.data = data;
4316
4317         sgen_clear_nursery_fragments ();
4318         sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE);
4319
4320         major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
4321         sgen_los_iterate_objects (walk_references, &hwi);
4322
4323         return 0;
4324 }
4325
4326 void
4327 mono_gc_collect (int generation)
4328 {
4329         LOCK_GC;
4330         if (generation > 1)
4331                 generation = 1;
4332         sgen_perform_collection (0, generation, "user request", TRUE);
4333         UNLOCK_GC;
4334 }
4335
4336 int
4337 mono_gc_max_generation (void)
4338 {
4339         return 1;
4340 }
4341
4342 int
4343 mono_gc_collection_count (int generation)
4344 {
4345         if (generation == 0)
4346                 return gc_stats.minor_gc_count;
4347         return gc_stats.major_gc_count;
4348 }
4349
4350 int64_t
4351 mono_gc_get_used_size (void)
4352 {
4353         gint64 tot = 0;
4354         LOCK_GC;
4355         tot = los_memory_usage;
4356         tot += nursery_section->next_data - nursery_section->data;
4357         tot += major_collector.get_used_size ();
4358         /* FIXME: account for pinned objects */
4359         UNLOCK_GC;
4360         return tot;
4361 }
4362
4363 int
4364 mono_gc_get_los_limit (void)
4365 {
4366         return MAX_SMALL_OBJ_SIZE;
4367 }
4368
4369 gboolean
4370 mono_gc_user_markers_supported (void)
4371 {
4372         return TRUE;
4373 }
4374
4375 gboolean
4376 mono_object_is_alive (MonoObject* o)
4377 {
4378         return TRUE;
4379 }
4380
4381 int
4382 mono_gc_get_generation (MonoObject *obj)
4383 {
4384         if (ptr_in_nursery (obj))
4385                 return 0;
4386         return 1;
4387 }
4388
4389 void
4390 mono_gc_enable_events (void)
4391 {
4392 }
4393
4394 void
4395 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
4396 {
4397         sgen_register_disappearing_link (obj, link_addr, track, FALSE);
4398 }
4399
4400 void
4401 mono_gc_weak_link_remove (void **link_addr, gboolean track)
4402 {
4403         sgen_register_disappearing_link (NULL, link_addr, track, FALSE);
4404 }
4405
4406 MonoObject*
4407 mono_gc_weak_link_get (void **link_addr)
4408 {
4409         void * volatile *link_addr_volatile;
4410         void *ptr;
4411         MonoObject *obj;
4412  retry:
4413         link_addr_volatile = link_addr;
4414         ptr = (void*)*link_addr_volatile;
4415         /*
4416          * At this point we have a hidden pointer.  If the GC runs
4417          * here, it will not recognize the hidden pointer as a
4418          * reference, and if the object behind it is not referenced
4419          * elsewhere, it will be freed.  Once the world is restarted
4420          * we reveal the pointer, giving us a pointer to a freed
4421          * object.  To make sure we don't return it, we load the
4422          * hidden pointer again.  If it's still the same, we can be
4423          * sure the object reference is valid.
4424          */
4425         if (ptr)
4426                 obj = (MonoObject*) REVEAL_POINTER (ptr);
4427         else
4428                 return NULL;
4429
4430         mono_memory_barrier ();
4431
4432         /*
4433          * During the second bridge processing step the world is
4434          * running again.  That step processes all weak links once
4435          * more to null those that refer to dead objects.  Before that
4436          * is completed, those links must not be followed, so we
4437          * conservatively wait for bridge processing when any weak
4438          * link is dereferenced.
4439          */
4440         if (G_UNLIKELY (bridge_processing_in_progress))
4441                 mono_gc_wait_for_bridge_processing ();
4442
4443         if ((void*)*link_addr_volatile != ptr)
4444                 goto retry;
4445
4446         return obj;
4447 }
4448
4449 gboolean
4450 mono_gc_ephemeron_array_add (MonoObject *obj)
4451 {
4452         EphemeronLinkNode *node;
4453
4454         LOCK_GC;
4455
4456         node = sgen_alloc_internal (INTERNAL_MEM_EPHEMERON_LINK);
4457         if (!node) {
4458                 UNLOCK_GC;
4459                 return FALSE;
4460         }
4461         node->array = (char*)obj;
4462         node->next = ephemeron_list;
4463         ephemeron_list = node;
4464
4465         SGEN_LOG (5, "Registered ephemeron array %p", obj);
4466
4467         UNLOCK_GC;
4468         return TRUE;
4469 }
4470
4471 gboolean
4472 mono_gc_set_allow_synchronous_major (gboolean flag)
4473 {
4474         if (!major_collector.is_concurrent)
4475                 return flag;
4476
4477         allow_synchronous_major = flag;
4478         return TRUE;
4479 }
4480
4481 void*
4482 mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
4483 {
4484         void *result;
4485         LOCK_INTERRUPTION;
4486         result = func (data);
4487         UNLOCK_INTERRUPTION;
4488         return result;
4489 }
4490
4491 gboolean
4492 mono_gc_is_gc_thread (void)
4493 {
4494         gboolean result;
4495         LOCK_GC;
4496         result = mono_thread_info_current () != NULL;
4497         UNLOCK_GC;
4498         return result;
4499 }
4500
4501 static gboolean
4502 is_critical_method (MonoMethod *method)
4503 {
4504         return mono_runtime_is_critical_method (method) || sgen_is_critical_method (method);
4505 }
4506
4507 void
4508 sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...)
4509 {
4510         va_list ap;
4511
4512         va_start (ap, description_format);
4513
4514         fprintf (stderr, "Warning: In environment variable `%s': ", env_var);
4515         vfprintf (stderr, description_format, ap);
4516         if (fallback)
4517                 fprintf (stderr, " - %s", fallback);
4518         fprintf (stderr, "\n");
4519
4520         va_end (ap);
4521 }
4522
4523 static gboolean
4524 parse_double_in_interval (const char *env_var, const char *opt_name, const char *opt, double min, double max, double *result)
4525 {
4526         char *endptr;
4527         double val = strtod (opt, &endptr);
4528         if (endptr == opt) {
4529                 sgen_env_var_error (env_var, "Using default value.", "`%s` must be a number.", opt_name);
4530                 return FALSE;
4531         }
4532         else if (val < min || val > max) {
4533                 sgen_env_var_error (env_var, "Using default value.", "`%s` must be between %.2f - %.2f.", opt_name, min, max);
4534                 return FALSE;
4535         }
4536         *result = val;
4537         return TRUE;
4538 }
4539
4540 void
4541 mono_gc_base_init (void)
4542 {
4543         MonoThreadInfoCallbacks cb;
4544         const char *env;
4545         char **opts, **ptr;
4546         char *major_collector_opt = NULL;
4547         char *minor_collector_opt = NULL;
4548         size_t max_heap = 0;
4549         size_t soft_limit = 0;
4550         int num_workers;
4551         int result;
4552         int dummy;
4553         gboolean debug_print_allowance = FALSE;
4554         double allowance_ratio = 0, save_target = 0;
4555         gboolean have_split_nursery = FALSE;
4556         gboolean cement_enabled = TRUE;
4557
4558         do {
4559                 result = InterlockedCompareExchange (&gc_initialized, -1, 0);
4560                 switch (result) {
4561                 case 1:
4562                         /* already inited */
4563                         return;
4564                 case -1:
4565                         /* being inited by another thread */
4566                         g_usleep (1000);
4567                         break;
4568                 case 0:
4569                         /* we will init it */
4570                         break;
4571                 default:
4572                         g_assert_not_reached ();
4573                 }
4574         } while (result != 0);
4575
4576         SGEN_TV_GETTIME (sgen_init_timestamp);
4577
4578         LOCK_INIT (gc_mutex);
4579
4580         pagesize = mono_pagesize ();
4581         gc_debug_file = stderr;
4582
4583         cb.thread_register = sgen_thread_register;
4584         cb.thread_detach = sgen_thread_detach;
4585         cb.thread_unregister = sgen_thread_unregister;
4586         cb.thread_attach = sgen_thread_attach;
4587         cb.mono_method_is_critical = (gpointer)is_critical_method;
4588 #ifndef HOST_WIN32
4589         cb.thread_exit = mono_gc_pthread_exit;
4590         cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
4591 #endif
4592
4593         mono_threads_init (&cb, sizeof (SgenThreadInfo));
4594
4595         LOCK_INIT (sgen_interruption_mutex);
4596         LOCK_INIT (pin_queue_mutex);
4597
4598         if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
4599                 opts = g_strsplit (env, ",", -1);
4600                 for (ptr = opts; *ptr; ++ptr) {
4601                         char *opt = *ptr;
4602                         if (g_str_has_prefix (opt, "major=")) {
4603                                 opt = strchr (opt, '=') + 1;
4604                                 major_collector_opt = g_strdup (opt);
4605                         } else if (g_str_has_prefix (opt, "minor=")) {
4606                                 opt = strchr (opt, '=') + 1;
4607                                 minor_collector_opt = g_strdup (opt);
4608                         }
4609                 }
4610         } else {
4611                 opts = NULL;
4612         }
4613
4614         init_stats ();
4615         sgen_init_internal_allocator ();
4616         sgen_init_nursery_allocator ();
4617         sgen_init_fin_weak_hash ();
4618         sgen_init_stw ();
4619         sgen_init_hash_table ();
4620
4621         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_SECTION, SGEN_SIZEOF_GC_MEM_SECTION);
4622         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_FINALIZE_READY_ENTRY, sizeof (FinalizeReadyEntry));
4623         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_GRAY_QUEUE, sizeof (GrayQueueSection));
4624         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
4625
4626 #ifndef HAVE_KW_THREAD
4627         mono_native_tls_alloc (&thread_info_key, NULL);
4628 #if defined(__APPLE__) || defined (HOST_WIN32)
4629         /* 
4630          * CEE_MONO_TLS requires the tls offset, not the key, so the code below only works on darwin,
4631          * where the two are the same.
4632          */
4633         mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, thread_info_key);
4634 #endif
4635 #else
4636         {
4637                 int tls_offset = -1;
4638                 MONO_THREAD_VAR_OFFSET (sgen_thread_info, tls_offset);
4639                 mono_tls_key_set_offset (TLS_KEY_SGEN_THREAD_INFO, tls_offset);
4640         }
4641 #endif
4642
4643         /*
4644          * This needs to happen before any internal allocations because
4645          * it inits the small id which is required for hazard pointer
4646          * operations.
4647          */
4648         sgen_os_init ();
4649
4650         mono_thread_info_attach (&dummy);
4651
4652         if (!minor_collector_opt) {
4653                 sgen_simple_nursery_init (&sgen_minor_collector);
4654         } else {
4655                 if (!strcmp (minor_collector_opt, "simple")) {
4656                 use_simple_nursery:
4657                         sgen_simple_nursery_init (&sgen_minor_collector);
4658                 } else if (!strcmp (minor_collector_opt, "split")) {
4659                         sgen_split_nursery_init (&sgen_minor_collector);
4660                         have_split_nursery = TRUE;
4661                 } else {
4662                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `simple` instead.", "Unknown minor collector `%s'.", minor_collector_opt);
4663                         goto use_simple_nursery;
4664                 }
4665         }
4666
4667         if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep")) {
4668         use_marksweep_major:
4669                 sgen_marksweep_init (&major_collector);
4670         } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed")) {
4671                 sgen_marksweep_fixed_init (&major_collector);
4672         } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-par")) {
4673                 sgen_marksweep_par_init (&major_collector);
4674         } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-fixed-par")) {
4675                 sgen_marksweep_fixed_par_init (&major_collector);
4676         } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-conc")) {
4677                 sgen_marksweep_conc_init (&major_collector);
4678         } else {
4679                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `marksweep` instead.", "Unknown major collector `%s'.", major_collector_opt);
4680                 goto use_marksweep_major;
4681         }
4682
4683         if (have_split_nursery && major_collector.is_parallel) {
4684                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Disabling split minor collector.", "`minor=split` is not supported with the parallel collector yet.");
4685                 have_split_nursery = FALSE;
4686         }
4687
4688         num_workers = mono_cpu_count ();
4689         g_assert (num_workers > 0);
4690         if (num_workers > 16)
4691                 num_workers = 16;
4692
4693         ///* Keep this the default for now */
4694         /* Precise marking is broken on all supported targets. Disable until fixed. */
4695         conservative_stack_mark = TRUE;
4696
4697         sgen_nursery_size = DEFAULT_NURSERY_SIZE;
4698
4699         if (opts) {
4700                 gboolean usage_printed = FALSE;
4701
4702                 for (ptr = opts; *ptr; ++ptr) {
4703                         char *opt = *ptr;
4704                         if (!strcmp (opt, ""))
4705                                 continue;
4706                         if (g_str_has_prefix (opt, "major="))
4707                                 continue;
4708                         if (g_str_has_prefix (opt, "minor="))
4709                                 continue;
4710                         if (g_str_has_prefix (opt, "max-heap-size=")) {
4711                                 size_t max_heap_candidate = 0;
4712                                 opt = strchr (opt, '=') + 1;
4713                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap_candidate)) {
4714                                         max_heap = (max_heap_candidate + mono_pagesize () - 1) & ~(size_t)(mono_pagesize () - 1);
4715                                         if (max_heap != max_heap_candidate)
4716                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Rounding up.", "`max-heap-size` size must be a multiple of %d.", mono_pagesize ());
4717                                 } else {
4718                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`max-heap-size` must be an integer.");
4719                                 }
4720                                 continue;
4721                         }
4722                         if (g_str_has_prefix (opt, "soft-heap-limit=")) {
4723                                 opt = strchr (opt, '=') + 1;
4724                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &soft_limit)) {
4725                                         if (soft_limit <= 0) {
4726                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be positive.");
4727                                                 soft_limit = 0;
4728                                         }
4729                                 } else {
4730                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be an integer.");
4731                                 }
4732                                 continue;
4733                         }
4734                         if (g_str_has_prefix (opt, "workers=")) {
4735                                 long val;
4736                                 char *endptr;
4737                                 if (!major_collector.is_parallel) {
4738                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "The `workers` option can only be used for parallel collectors.");
4739                                         continue;
4740                                 }
4741                                 opt = strchr (opt, '=') + 1;
4742                                 val = strtol (opt, &endptr, 10);
4743                                 if (!*opt || *endptr) {
4744                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Cannot parse the `workers` option value.");
4745                                         continue;
4746                                 }
4747                                 if (val <= 0 || val > 16) {
4748                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "The number of `workers` must be in the range 1 to 16.");
4749                                         continue;
4750                                 }
4751                                 num_workers = (int)val;
4752                                 continue;
4753                         }
4754                         if (g_str_has_prefix (opt, "stack-mark=")) {
4755                                 opt = strchr (opt, '=') + 1;
4756                                 if (!strcmp (opt, "precise")) {
4757                                         conservative_stack_mark = FALSE;
4758                                 } else if (!strcmp (opt, "conservative")) {
4759                                         conservative_stack_mark = TRUE;
4760                                 } else {
4761                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
4762                                                         "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
4763                                 }
4764                                 continue;
4765                         }
4766                         if (g_str_has_prefix (opt, "bridge-implementation=")) {
4767                                 opt = strchr (opt, '=') + 1;
4768                                 sgen_set_bridge_implementation (opt);
4769                                 continue;
4770                         }
4771                         if (g_str_has_prefix (opt, "toggleref-test")) {
4772                                 sgen_register_test_toggleref_callback ();
4773                                 continue;
4774                         }
4775
4776 #ifdef USER_CONFIG
4777                         if (g_str_has_prefix (opt, "nursery-size=")) {
4778                                 size_t val;
4779                                 opt = strchr (opt, '=') + 1;
4780                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &val)) {
4781 #ifdef SGEN_ALIGN_NURSERY
4782                                         if ((val & (val - 1))) {
4783                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be a power of two.");
4784                                                 continue;
4785                                         }
4786
4787                                         if (val < SGEN_MAX_NURSERY_WASTE) {
4788                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.",
4789                                                                 "`nursery-size` must be at least %d bytes.", SGEN_MAX_NURSERY_WASTE);
4790                                                 continue;
4791                                         }
4792
4793                                         sgen_nursery_size = val;
4794                                         sgen_nursery_bits = 0;
4795                                         while (ONE_P << (++ sgen_nursery_bits) != sgen_nursery_size)
4796                                                 ;
4797 #else
4798                                         sgen_nursery_size = val;
4799 #endif
4800                                 } else {
4801                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be an integer.");
4802                                         continue;
4803                                 }
4804                                 continue;
4805                         }
4806 #endif
4807                         if (g_str_has_prefix (opt, "save-target-ratio=")) {
4808                                 double val;
4809                                 opt = strchr (opt, '=') + 1;
4810                                 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "save-target-ratio", opt,
4811                                                 SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO, &val)) {
4812                                         save_target = val;
4813                                 }
4814                                 continue;
4815                         }
4816                         if (g_str_has_prefix (opt, "default-allowance-ratio=")) {
4817                                 double val;
4818                                 opt = strchr (opt, '=') + 1;
4819                                 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "default-allowance-ratio", opt,
4820                                                 SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, &val)) {
4821                                         allowance_ratio = val;
4822                                 }
4823                                 continue;
4824                         }
4825                         if (g_str_has_prefix (opt, "allow-synchronous-major=")) {
4826                                 if (!major_collector.is_concurrent) {
4827                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`allow-synchronous-major` is only valid for the concurrent major collector.");
4828                                         continue;
4829                                 }
4830
4831                                 opt = strchr (opt, '=') + 1;
4832
4833                                 if (!strcmp (opt, "yes")) {
4834                                         allow_synchronous_major = TRUE;
4835                                 } else if (!strcmp (opt, "no")) {
4836                                         allow_synchronous_major = FALSE;
4837                                 } else {
4838                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`allow-synchronous-major` must be either `yes' or `no'.");
4839                                         continue;
4840                                 }
4841                         }
4842
4843                         if (!strcmp (opt, "cementing")) {
4844                                 if (major_collector.is_parallel) {
4845                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "`cementing` is not supported for the parallel major collector.");
4846                                         continue;
4847                                 }
4848                                 cement_enabled = TRUE;
4849                                 continue;
4850                         }
4851                         if (!strcmp (opt, "no-cementing")) {
4852                                 cement_enabled = FALSE;
4853                                 continue;
4854                         }
4855
4856                         if (major_collector.handle_gc_param && major_collector.handle_gc_param (opt))
4857                                 continue;
4858
4859                         if (sgen_minor_collector.handle_gc_param && sgen_minor_collector.handle_gc_param (opt))
4860                                 continue;
4861
4862                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Unknown option `%s`.", opt);
4863
4864                         if (usage_printed)
4865                                 continue;
4866
4867                         fprintf (stderr, "\n%s must be a comma-delimited list of one or more of the following:\n", MONO_GC_PARAMS_NAME);
4868                         fprintf (stderr, "  max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4869                         fprintf (stderr, "  soft-heap-limit=n (where N is an integer, possibly with a k, m or a g suffix)\n");
4870                         fprintf (stderr, "  nursery-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
4871                         fprintf (stderr, "  major=COLLECTOR (where COLLECTOR is `marksweep', `marksweep-conc', `marksweep-par', 'marksweep-fixed' or 'marksweep-fixed-par')\n");
4872                         fprintf (stderr, "  minor=COLLECTOR (where COLLECTOR is `simple' or `split')\n");
4873                         fprintf (stderr, "  wbarrier=WBARRIER (where WBARRIER is `remset' or `cardtable')\n");
4874                         fprintf (stderr, "  stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
4875                         fprintf (stderr, "  [no-]cementing\n");
4876                         if (major_collector.is_concurrent)
4877                                 fprintf (stderr, "  allow-synchronous-major=FLAG (where FLAG is `yes' or `no')\n");
4878                         if (major_collector.print_gc_param_usage)
4879                                 major_collector.print_gc_param_usage ();
4880                         if (sgen_minor_collector.print_gc_param_usage)
4881                                 sgen_minor_collector.print_gc_param_usage ();
4882                         fprintf (stderr, " Experimental options:\n");
4883                         fprintf (stderr, "  save-target-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
4884                         fprintf (stderr, "  default-allowance-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MAX_ALLOWANCE_NURSERY_SIZE_RATIO);
4885                         fprintf (stderr, "\n");
4886
4887                         usage_printed = TRUE;
4888                 }
4889                 g_strfreev (opts);
4890         }
4891
4892         if (major_collector.is_parallel) {
4893                 cement_enabled = FALSE;
4894                 sgen_workers_init (num_workers);
4895         } else if (major_collector.is_concurrent) {
4896                 sgen_workers_init (1);
4897         }
4898
4899         if (major_collector_opt)
4900                 g_free (major_collector_opt);
4901
4902         if (minor_collector_opt)
4903                 g_free (minor_collector_opt);
4904
4905         alloc_nursery ();
4906
4907         sgen_cement_init (cement_enabled);
4908
4909         if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
4910                 gboolean usage_printed = FALSE;
4911
4912                 opts = g_strsplit (env, ",", -1);
4913                 for (ptr = opts; ptr && *ptr; ptr ++) {
4914                         char *opt = *ptr;
4915                         if (!strcmp (opt, ""))
4916                                 continue;
4917                         if (opt [0] >= '0' && opt [0] <= '9') {
4918                                 gc_debug_level = atoi (opt);
4919                                 opt++;
4920                                 if (opt [0] == ':')
4921                                         opt++;
4922                                 if (opt [0]) {
4923 #ifdef HOST_WIN32
4924                                         char *rf = g_strdup_printf ("%s.%d", opt, GetCurrentProcessId ());
4925 #else
4926                                         char *rf = g_strdup_printf ("%s.%d", opt, getpid ());
4927 #endif
4928                                         gc_debug_file = fopen (rf, "wb");
4929                                         if (!gc_debug_file)
4930                                                 gc_debug_file = stderr;
4931                                         g_free (rf);
4932                                 }
4933                         } else if (!strcmp (opt, "print-allowance")) {
4934                                 debug_print_allowance = TRUE;
4935                         } else if (!strcmp (opt, "print-pinning")) {
4936                                 do_pin_stats = TRUE;
4937                         } else if (!strcmp (opt, "verify-before-allocs")) {
4938                                 verify_before_allocs = 1;
4939                                 has_per_allocation_action = TRUE;
4940                         } else if (g_str_has_prefix (opt, "verify-before-allocs=")) {
4941                                 char *arg = strchr (opt, '=') + 1;
4942                                 verify_before_allocs = atoi (arg);
4943                                 has_per_allocation_action = TRUE;
4944                         } else if (!strcmp (opt, "collect-before-allocs")) {
4945                                 collect_before_allocs = 1;
4946                                 has_per_allocation_action = TRUE;
4947                         } else if (g_str_has_prefix (opt, "collect-before-allocs=")) {
4948                                 char *arg = strchr (opt, '=') + 1;
4949                                 has_per_allocation_action = TRUE;
4950                                 collect_before_allocs = atoi (arg);
4951                         } else if (!strcmp (opt, "verify-before-collections")) {
4952                                 whole_heap_check_before_collection = TRUE;
4953                         } else if (!strcmp (opt, "check-at-minor-collections")) {
4954                                 consistency_check_at_minor_collection = TRUE;
4955                                 nursery_clear_policy = CLEAR_AT_GC;
4956                         } else if (!strcmp (opt, "mod-union-consistency-check")) {
4957                                 if (!major_collector.is_concurrent) {
4958                                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`mod-union-consistency-check` only works with concurrent major collector.");
4959                                         continue;
4960                                 }
4961                                 mod_union_consistency_check = TRUE;
4962                         } else if (!strcmp (opt, "check-mark-bits")) {
4963                                 check_mark_bits_after_major_collection = TRUE;
4964                         } else if (!strcmp (opt, "check-nursery-pinned")) {
4965                                 check_nursery_objects_pinned = TRUE;
4966                         } else if (!strcmp (opt, "xdomain-checks")) {
4967                                 xdomain_checks = TRUE;
4968                         } else if (!strcmp (opt, "clear-at-gc")) {
4969                                 nursery_clear_policy = CLEAR_AT_GC;
4970                         } else if (!strcmp (opt, "clear-nursery-at-gc")) {
4971                                 nursery_clear_policy = CLEAR_AT_GC;
4972                         } else if (!strcmp (opt, "clear-at-tlab-creation")) {
4973                                 nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
4974                         } else if (!strcmp (opt, "debug-clear-at-tlab-creation")) {
4975                                 nursery_clear_policy = CLEAR_AT_TLAB_CREATION_DEBUG;
4976                         } else if (!strcmp (opt, "check-scan-starts")) {
4977                                 do_scan_starts_check = TRUE;
4978                         } else if (!strcmp (opt, "verify-nursery-at-minor-gc")) {
4979                                 do_verify_nursery = TRUE;
4980                         } else if (!strcmp (opt, "check-concurrent")) {
4981                                 if (!major_collector.is_concurrent) {
4982                                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`check-concurrent` only works with concurrent major collectors.");
4983                                         continue;
4984                                 }
4985                                 do_concurrent_checks = TRUE;
4986                         } else if (!strcmp (opt, "dump-nursery-at-minor-gc")) {
4987                                 do_dump_nursery_content = TRUE;
4988                         } else if (!strcmp (opt, "no-managed-allocator")) {
4989                                 sgen_set_use_managed_allocator (FALSE);
4990                         } else if (!strcmp (opt, "disable-minor")) {
4991                                 disable_minor_collections = TRUE;
4992                         } else if (!strcmp (opt, "disable-major")) {
4993                                 disable_major_collections = TRUE;
4994                         } else if (g_str_has_prefix (opt, "heap-dump=")) {
4995                                 char *filename = strchr (opt, '=') + 1;
4996                                 nursery_clear_policy = CLEAR_AT_GC;
4997                                 heap_dump_file = fopen (filename, "w");
4998                                 if (heap_dump_file) {
4999                                         fprintf (heap_dump_file, "<sgen-dump>\n");
5000                                         do_pin_stats = TRUE;
5001                                 }
5002                         } else if (g_str_has_prefix (opt, "binary-protocol=")) {
5003                                 char *filename = strchr (opt, '=') + 1;
5004                                 char *colon = strrchr (filename, ':');
5005                                 size_t limit = -1;
5006                                 if (colon) {
5007                                         if (!mono_gc_parse_environment_string_extract_number (colon + 1, &limit)) {
5008                                                 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring limit.", "Binary protocol file size limit must be an integer.");
5009                                                 limit = -1;
5010                                         }
5011                                         *colon = '\0';
5012                                 }
5013                                 binary_protocol_init (filename, (long long)limit);
5014                         } else if (!sgen_bridge_handle_gc_debug (opt)) {
5015                                 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "Unknown option `%s`.", opt);
5016
5017                                 if (usage_printed)
5018                                         continue;
5019
5020                                 fprintf (stderr, "\n%s must be of the format [<l>[:<filename>]|<option>]+ where <l> is a debug level 0-9.\n", MONO_GC_DEBUG_NAME);
5021                                 fprintf (stderr, "Valid <option>s are:\n");
5022                                 fprintf (stderr, "  collect-before-allocs[=<n>]\n");
5023                                 fprintf (stderr, "  verify-before-allocs[=<n>]\n");
5024                                 fprintf (stderr, "  check-at-minor-collections\n");
5025                                 fprintf (stderr, "  check-mark-bits\n");
5026                                 fprintf (stderr, "  check-nursery-pinned\n");
5027                                 fprintf (stderr, "  verify-before-collections\n");
5028                                 fprintf (stderr, "  verify-nursery-at-minor-gc\n");
5029                                 fprintf (stderr, "  dump-nursery-at-minor-gc\n");
5030                                 fprintf (stderr, "  disable-minor\n");
5031                                 fprintf (stderr, "  disable-major\n");
5032                                 fprintf (stderr, "  xdomain-checks\n");
5033                                 fprintf (stderr, "  check-concurrent\n");
5034                                 fprintf (stderr, "  clear-[nursery-]at-gc\n");
5035                                 fprintf (stderr, "  clear-at-tlab-creation\n");
5036                                 fprintf (stderr, "  debug-clear-at-tlab-creation\n");
5037                                 fprintf (stderr, "  check-scan-starts\n");
5038                                 fprintf (stderr, "  no-managed-allocator\n");
5039                                 fprintf (stderr, "  print-allowance\n");
5040                                 fprintf (stderr, "  print-pinning\n");
5041                                 fprintf (stderr, "  heap-dump=<filename>\n");
5042                                 fprintf (stderr, "  binary-protocol=<filename>[:<file-size-limit>]\n");
5043                                 sgen_bridge_print_gc_debug_usage ();
5044                                 fprintf (stderr, "\n");
5045
5046                                 usage_printed = TRUE;
5047                         }
5048                 }
5049                 g_strfreev (opts);
5050         }
5051
5052         if (major_collector.is_parallel) {
5053                 if (heap_dump_file) {
5054                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Disabling.", "Cannot do `heap-dump` with the parallel collector.");
5055                         fclose (heap_dump_file);
5056                         heap_dump_file = NULL;
5057                 }
5058                 if (do_pin_stats) {
5059                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Disabling.", "`print-pinning` is not supported with the parallel collector.");
5060                         do_pin_stats = FALSE;
5061                 }
5062         }
5063
5064         if (major_collector.post_param_init)
5065                 major_collector.post_param_init (&major_collector);
5066
5067         sgen_memgov_init (max_heap, soft_limit, debug_print_allowance, allowance_ratio, save_target);
5068
5069         memset (&remset, 0, sizeof (remset));
5070
5071         sgen_card_table_init (&remset);
5072
5073         gc_initialized = 1;
5074 }
5075
5076 const char *
5077 mono_gc_get_gc_name (void)
5078 {
5079         return "sgen";
5080 }
5081
5082 static MonoMethod *write_barrier_method;
5083
5084 gboolean
5085 sgen_is_critical_method (MonoMethod *method)
5086 {
5087         return (method == write_barrier_method || sgen_is_managed_allocator (method));
5088 }
5089
5090 gboolean
5091 sgen_has_critical_method (void)
5092 {
5093         return write_barrier_method || sgen_has_managed_allocator ();
5094 }
5095
5096 #ifndef DISABLE_JIT
5097
5098 static void
5099 emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels)
5100 {
5101         memset (nursery_check_return_labels, 0, sizeof (int) * 3);
5102 #ifdef SGEN_ALIGN_NURSERY
5103         // if (ptr_in_nursery (ptr)) return;
5104         /*
5105          * Masking out the bits might be faster, but we would have to use 64 bit
5106          * immediates, which might be slower.
5107          */
5108         mono_mb_emit_ldarg (mb, 0);
5109         mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5110         mono_mb_emit_byte (mb, CEE_SHR_UN);
5111         mono_mb_emit_ptr (mb, (gpointer)((mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS));
5112         nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
5113
5114         if (!major_collector.is_concurrent) {
5115                 // if (!ptr_in_nursery (*ptr)) return;
5116                 mono_mb_emit_ldarg (mb, 0);
5117                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5118                 mono_mb_emit_icon (mb, DEFAULT_NURSERY_BITS);
5119                 mono_mb_emit_byte (mb, CEE_SHR_UN);
5120                 mono_mb_emit_ptr (mb, (gpointer)((mword)sgen_get_nursery_start () >> DEFAULT_NURSERY_BITS));
5121                 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
5122         }
5123 #else
5124         int label_continue1, label_continue2;
5125         int dereferenced_var;
5126
5127         // if (ptr < (sgen_get_nursery_start ())) goto continue;
5128         mono_mb_emit_ldarg (mb, 0);
5129         mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5130         label_continue_1 = mono_mb_emit_branch (mb, CEE_BLT);
5131
5132         // if (ptr >= sgen_get_nursery_end ())) goto continue;
5133         mono_mb_emit_ldarg (mb, 0);
5134         mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5135         label_continue_2 = mono_mb_emit_branch (mb, CEE_BGE);
5136
5137         // Otherwise return
5138         nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BR);
5139
5140         // continue:
5141         mono_mb_patch_branch (mb, label_continue_1);
5142         mono_mb_patch_branch (mb, label_continue_2);
5143
5144         // Dereference and store in local var
5145         dereferenced_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5146         mono_mb_emit_ldarg (mb, 0);
5147         mono_mb_emit_byte (mb, CEE_LDIND_I);
5148         mono_mb_emit_stloc (mb, dereferenced_var);
5149
5150         if (!major_collector.is_concurrent) {
5151                 // if (*ptr < sgen_get_nursery_start ()) return;
5152                 mono_mb_emit_ldloc (mb, dereferenced_var);
5153                 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_start ());
5154                 nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BLT);
5155
5156                 // if (*ptr >= sgen_get_nursery_end ()) return;
5157                 mono_mb_emit_ldloc (mb, dereferenced_var);
5158                 mono_mb_emit_ptr (mb, (gpointer) sgen_get_nursery_end ());
5159                 nursery_check_return_labels [2] = mono_mb_emit_branch (mb, CEE_BGE);
5160         }
5161 #endif  
5162 }
5163 #endif
5164
5165 MonoMethod*
5166 mono_gc_get_write_barrier (void)
5167 {
5168         MonoMethod *res;
5169         MonoMethodBuilder *mb;
5170         MonoMethodSignature *sig;
5171 #ifdef MANAGED_WBARRIER
5172         int i, nursery_check_labels [3];
5173
5174 #ifdef HAVE_KW_THREAD
5175         int stack_end_offset = -1;
5176
5177         MONO_THREAD_VAR_OFFSET (stack_end, stack_end_offset);
5178         g_assert (stack_end_offset != -1);
5179 #endif
5180 #endif
5181
5182         // FIXME: Maybe create a separate version for ctors (the branch would be
5183         // correctly predicted more times)
5184         if (write_barrier_method)
5185                 return write_barrier_method;
5186
5187         /* Create the IL version of mono_gc_barrier_generic_store () */
5188         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5189         sig->ret = &mono_defaults.void_class->byval_arg;
5190         sig->params [0] = &mono_defaults.int_class->byval_arg;
5191
5192         mb = mono_mb_new (mono_defaults.object_class, "wbarrier", MONO_WRAPPER_WRITE_BARRIER);
5193
5194 #ifndef DISABLE_JIT
5195 #ifdef MANAGED_WBARRIER
5196         emit_nursery_check (mb, nursery_check_labels);
5197         /*
5198         addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
5199         *addr = 1;
5200
5201         sgen_cardtable:
5202                 LDC_PTR sgen_cardtable
5203
5204         address >> CARD_BITS
5205                 LDARG_0
5206                 LDC_I4 CARD_BITS
5207                 SHR_UN
5208         if (SGEN_HAVE_OVERLAPPING_CARDS) {
5209                 LDC_PTR card_table_mask
5210                 AND
5211         }
5212         AND
5213         ldc_i4_1
5214         stind_i1
5215         */
5216         mono_mb_emit_ptr (mb, sgen_cardtable);
5217         mono_mb_emit_ldarg (mb, 0);
5218         mono_mb_emit_icon (mb, CARD_BITS);
5219         mono_mb_emit_byte (mb, CEE_SHR_UN);
5220 #ifdef SGEN_HAVE_OVERLAPPING_CARDS
5221         mono_mb_emit_ptr (mb, (gpointer)CARD_MASK);
5222         mono_mb_emit_byte (mb, CEE_AND);
5223 #endif
5224         mono_mb_emit_byte (mb, CEE_ADD);
5225         mono_mb_emit_icon (mb, 1);
5226         mono_mb_emit_byte (mb, CEE_STIND_I1);
5227
5228         // return;
5229         for (i = 0; i < 3; ++i) {
5230                 if (nursery_check_labels [i])
5231                         mono_mb_patch_branch (mb, nursery_check_labels [i]);
5232         }
5233         mono_mb_emit_byte (mb, CEE_RET);
5234 #else
5235         mono_mb_emit_ldarg (mb, 0);
5236         mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
5237         mono_mb_emit_byte (mb, CEE_RET);
5238 #endif
5239 #endif
5240         res = mono_mb_create_method (mb, sig, 16);
5241         mono_mb_free (mb);
5242
5243         LOCK_GC;
5244         if (write_barrier_method) {
5245                 /* Already created */
5246                 mono_free_method (res);
5247         } else {
5248                 /* double-checked locking */
5249                 mono_memory_barrier ();
5250                 write_barrier_method = res;
5251         }
5252         UNLOCK_GC;
5253
5254         return write_barrier_method;
5255 }
5256
5257 char*
5258 mono_gc_get_description (void)
5259 {
5260         return g_strdup ("sgen");
5261 }
5262
5263 void
5264 mono_gc_set_desktop_mode (void)
5265 {
5266 }
5267
5268 gboolean
5269 mono_gc_is_moving (void)
5270 {
5271         return TRUE;
5272 }
5273
5274 gboolean
5275 mono_gc_is_disabled (void)
5276 {
5277         return FALSE;
5278 }
5279
5280 #ifdef HOST_WIN32
5281 BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
5282 {
5283         return TRUE;
5284 }
5285 #endif
5286
5287 NurseryClearPolicy
5288 sgen_get_nursery_clear_policy (void)
5289 {
5290         return nursery_clear_policy;
5291 }
5292
5293 MonoVTable*
5294 sgen_get_array_fill_vtable (void)
5295 {
5296         if (!array_fill_vtable) {
5297                 static MonoClass klass;
5298                 static MonoVTable vtable;
5299                 gsize bmap;
5300
5301                 MonoDomain *domain = mono_get_root_domain ();
5302                 g_assert (domain);
5303
5304                 klass.element_class = mono_defaults.byte_class;
5305                 klass.rank = 1;
5306                 klass.instance_size = sizeof (MonoArray);
5307                 klass.sizes.element_size = 1;
5308                 klass.name = "array_filler_type";
5309
5310                 vtable.klass = &klass;
5311                 bmap = 0;
5312                 vtable.gc_descr = mono_gc_make_descr_for_array (TRUE, &bmap, 0, 1);
5313                 vtable.rank = 1;
5314
5315                 array_fill_vtable = &vtable;
5316         }
5317         return array_fill_vtable;
5318 }
5319
5320 void
5321 sgen_gc_lock (void)
5322 {
5323         LOCK_GC;
5324 }
5325
5326 void
5327 sgen_gc_unlock (void)
5328 {
5329         gboolean try_free = sgen_try_free_some_memory;
5330         sgen_try_free_some_memory = FALSE;
5331         mono_mutex_unlock (&gc_mutex);
5332         MONO_GC_UNLOCKED ();
5333         if (try_free)
5334                 mono_thread_hazardous_try_free_some ();
5335 }
5336
5337 void
5338 sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
5339 {
5340         major_collector.iterate_live_block_ranges (callback);
5341 }
5342
5343 void
5344 sgen_major_collector_scan_card_table (SgenGrayQueue *queue)
5345 {
5346         major_collector.scan_card_table (FALSE, queue);
5347 }
5348
5349 SgenMajorCollector*
5350 sgen_get_major_collector (void)
5351 {
5352         return &major_collector;
5353 }
5354
5355 void mono_gc_set_skip_thread (gboolean skip)
5356 {
5357         SgenThreadInfo *info = mono_thread_info_current ();
5358
5359         LOCK_GC;
5360         info->gc_disabled = skip;
5361         UNLOCK_GC;
5362 }
5363
5364 SgenRemeberedSet*
5365 sgen_get_remset (void)
5366 {
5367         return &remset;
5368 }
5369
5370 guint
5371 mono_gc_get_vtable_bits (MonoClass *class)
5372 {
5373         guint res = 0;
5374         /* FIXME move this to the bridge code */
5375         if (sgen_need_bridge_processing ()) {
5376                 switch (sgen_bridge_class_kind (class)) {
5377                 case GC_BRIDGE_TRANSPARENT_BRIDGE_CLASS:
5378                 case GC_BRIDGE_OPAQUE_BRIDGE_CLASS:
5379                         res = SGEN_GC_BIT_BRIDGE_OBJECT;
5380                         break;
5381                 case GC_BRIDGE_OPAQUE_CLASS:
5382                         res = SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT;
5383                         break;
5384                 }
5385         }
5386         if (fin_callbacks.is_class_finalization_aware) {
5387                 if (fin_callbacks.is_class_finalization_aware (class))
5388                         res |= SGEN_GC_BIT_FINALIZER_AWARE;
5389         }
5390         return res;
5391 }
5392
5393 void
5394 mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
5395 {
5396         // FIXME:
5397 }
5398
5399
5400 void
5401 sgen_check_whole_heap_stw (void)
5402 {
5403         sgen_stop_world (0);
5404         sgen_clear_nursery_fragments ();
5405         sgen_check_whole_heap (FALSE);
5406         sgen_restart_world (0, NULL);
5407 }
5408
5409 void
5410 sgen_gc_event_moves (void)
5411 {
5412         if (moved_objects_idx) {
5413                 mono_profiler_gc_moves (moved_objects, moved_objects_idx);
5414                 moved_objects_idx = 0;
5415         }
5416 }
5417
5418 gint64
5419 sgen_timestamp (void)
5420 {
5421         SGEN_TV_DECLARE (timestamp);
5422         SGEN_TV_GETTIME (timestamp);
5423         return SGEN_TV_ELAPSED (sgen_init_timestamp, timestamp);
5424 }
5425
5426 void
5427 mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
5428 {
5429         if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
5430                 g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
5431
5432         fin_callbacks = *callbacks;
5433 }
5434
5435 #endif /* HAVE_SGEN_GC */