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