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