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