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