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