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