Merge pull request #2799 from BrzVlad/fix-conc-card-clean
[mono.git] / mono / sgen / sgen-gc.c
1 /*
2  * sgen-gc.c: Simple generational GC.
3  *
4  * Author:
5  *      Paolo Molaro (lupus@ximian.com)
6  *  Rodrigo Kumpera (kumpera@gmail.com)
7  *
8  * Copyright 2005-2011 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  *
11  * Thread start/stop adapted from Boehm's GC:
12  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
13  * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
14  * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
15  * Copyright (c) 2000-2004 by Hewlett-Packard Company.  All rights reserved.
16  * Copyright 2001-2003 Ximian, Inc
17  * Copyright 2003-2010 Novell, Inc.
18  * Copyright 2011 Xamarin, Inc.
19  * Copyright (C) 2012 Xamarin Inc
20  *
21  * This library is free software; you can redistribute it and/or
22  * modify it under the terms of the GNU Library General Public
23  * License 2.0 as published by the Free Software Foundation;
24  *
25  * This library is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28  * Library General Public License for more details.
29  *
30  * You should have received a copy of the GNU Library General Public
31  * License 2.0 along with this library; if not, write to the Free
32  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33  *
34  * Important: allocation provides always zeroed memory, having to do
35  * a memset after allocation is deadly for performance.
36  * Memory usage at startup is currently as follows:
37  * 64 KB pinned space
38  * 64 KB internal space
39  * size of nursery
40  * We should provide a small memory config with half the sizes
41  *
42  * We currently try to make as few mono assumptions as possible:
43  * 1) 2-word header with no GC pointers in it (first vtable, second to store the
44  *    forwarding ptr)
45  * 2) gc descriptor is the second word in the vtable (first word in the class)
46  * 3) 8 byte alignment is the minimum and enough (not true for special structures (SIMD), FIXME)
47  * 4) there is a function to get an object's size and the number of
48  *    elements in an array.
49  * 5) we know the special way bounds are allocated for complex arrays
50  * 6) we know about proxies and how to treat them when domains are unloaded
51  *
52  * Always try to keep stack usage to a minimum: no recursive behaviour
53  * and no large stack allocs.
54  *
55  * General description.
56  * Objects are initially allocated in a nursery using a fast bump-pointer technique.
57  * When the nursery is full we start a nursery collection: this is performed with a
58  * copying GC.
59  * When the old generation is full we start a copying GC of the old generation as well:
60  * this will be changed to mark&sweep with copying when fragmentation becomes to severe
61  * in the future.  Maybe we'll even do both during the same collection like IMMIX.
62  *
63  * The things that complicate this description are:
64  * *) pinned objects: we can't move them so we need to keep track of them
65  * *) no precise info of the thread stacks and registers: we need to be able to
66  *    quickly find the objects that may be referenced conservatively and pin them
67  *    (this makes the first issues more important)
68  * *) large objects are too expensive to be dealt with using copying GC: we handle them
69  *    with mark/sweep during major collections
70  * *) some objects need to not move even if they are small (interned strings, Type handles):
71  *    we use mark/sweep for them, too: they are not allocated in the nursery, but inside
72  *    PinnedChunks regions
73  */
74
75 /*
76  * TODO:
77
78  *) we could have a function pointer in MonoClass to implement
79   customized write barriers for value types
80
81  *) investigate the stuff needed to advance a thread to a GC-safe
82   point (single-stepping, read from unmapped memory etc) and implement it.
83   This would enable us to inline allocations and write barriers, for example,
84   or at least parts of them, like the write barrier checks.
85   We may need this also for handling precise info on stacks, even simple things
86   as having uninitialized data on the stack and having to wait for the prolog
87   to zero it. Not an issue for the last frame that we scan conservatively.
88   We could always not trust the value in the slots anyway.
89
90  *) modify the jit to save info about references in stack locations:
91   this can be done just for locals as a start, so that at least
92   part of the stack is handled precisely.
93
94  *) test/fix endianess issues
95
96  *) Implement a card table as the write barrier instead of remembered
97     sets?  Card tables are not easy to implement with our current
98     memory layout.  We have several different kinds of major heap
99     objects: Small objects in regular blocks, small objects in pinned
100     chunks and LOS objects.  If we just have a pointer we have no way
101     to tell which kind of object it points into, therefore we cannot
102     know where its card table is.  The least we have to do to make
103     this happen is to get rid of write barriers for indirect stores.
104     (See next item)
105
106  *) Get rid of write barriers for indirect stores.  We can do this by
107     telling the GC to wbarrier-register an object once we do an ldloca
108     or ldelema on it, and to unregister it once it's not used anymore
109     (it can only travel downwards on the stack).  The problem with
110     unregistering is that it needs to happen eventually no matter
111     what, even if exceptions are thrown, the thread aborts, etc.
112     Rodrigo suggested that we could do only the registering part and
113     let the collector find out (pessimistically) when it's safe to
114     unregister, namely when the stack pointer of the thread that
115     registered the object is higher than it was when the registering
116     happened.  This might make for a good first implementation to get
117     some data on performance.
118
119  *) Some sort of blacklist support?  Blacklists is a concept from the
120     Boehm GC: if during a conservative scan we find pointers to an
121     area which we might use as heap, we mark that area as unusable, so
122     pointer retention by random pinning pointers is reduced.
123
124  *) experiment with max small object size (very small right now - 2kb,
125     because it's tied to the max freelist size)
126
127   *) add an option to mmap the whole heap in one chunk: it makes for many
128      simplifications in the checks (put the nursery at the top and just use a single
129      check for inclusion/exclusion): the issue this has is that on 32 bit systems it's
130      not flexible (too much of the address space may be used by default or we can't
131      increase the heap as needed) and we'd need a race-free mechanism to return memory
132      back to the system (mprotect(PROT_NONE) will still keep the memory allocated if it
133      was written to, munmap is needed, but the following mmap may not find the same segment
134      free...)
135
136  *) memzero the major fragments after restarting the world and optionally a smaller
137     chunk at a time
138
139  *) investigate having fragment zeroing threads
140
141  *) separate locks for finalization and other minor stuff to reduce
142     lock contention
143
144  *) try a different copying order to improve memory locality
145
146  *) a thread abort after a store but before the write barrier will
147     prevent the write barrier from executing
148
149  *) specialized dynamically generated markers/copiers
150
151  *) Dynamically adjust TLAB size to the number of threads.  If we have
152     too many threads that do allocation, we might need smaller TLABs,
153     and we might get better performance with larger TLABs if we only
154     have a handful of threads.  We could sum up the space left in all
155     assigned TLABs and if that's more than some percentage of the
156     nursery size, reduce the TLAB size.
157
158  *) Explore placing unreachable objects on unused nursery memory.
159         Instead of memset'ng a region to zero, place an int[] covering it.
160         A good place to start is add_nursery_frag. The tricky thing here is
161         placing those objects atomically outside of a collection.
162
163  *) Allocation should use asymmetric Dekker synchronization:
164         http://blogs.oracle.com/dave/resource/Asymmetric-Dekker-Synchronization.txt
165         This should help weak consistency archs.
166  */
167 #include "config.h"
168 #ifdef HAVE_SGEN_GC
169
170 #ifdef __MACH__
171 #undef _XOPEN_SOURCE
172 #define _XOPEN_SOURCE
173 #define _DARWIN_C_SOURCE
174 #endif
175
176 #ifdef HAVE_UNISTD_H
177 #include <unistd.h>
178 #endif
179 #ifdef HAVE_PTHREAD_H
180 #include <pthread.h>
181 #endif
182 #ifdef HAVE_PTHREAD_NP_H
183 #include <pthread_np.h>
184 #endif
185 #include <stdio.h>
186 #include <string.h>
187 #include <errno.h>
188 #include <assert.h>
189 #include <stdlib.h>
190
191 #include "mono/sgen/sgen-gc.h"
192 #include "mono/sgen/sgen-cardtable.h"
193 #include "mono/sgen/sgen-protocol.h"
194 #include "mono/sgen/sgen-memory-governor.h"
195 #include "mono/sgen/sgen-hash-table.h"
196 #include "mono/sgen/sgen-cardtable.h"
197 #include "mono/sgen/sgen-pinning.h"
198 #include "mono/sgen/sgen-workers.h"
199 #include "mono/sgen/sgen-client.h"
200 #include "mono/sgen/sgen-pointer-queue.h"
201 #include "mono/sgen/gc-internal-agnostic.h"
202 #include "mono/utils/mono-proclib.h"
203 #include "mono/utils/mono-memory-model.h"
204 #include "mono/utils/hazard-pointer.h"
205
206 #include <mono/utils/memcheck.h>
207
208 #undef pthread_create
209 #undef pthread_join
210 #undef pthread_detach
211
212 /*
213  * ######################################################################
214  * ########  Types and constants used by the GC.
215  * ######################################################################
216  */
217
218 /* 0 means not initialized, 1 is initialized, -1 means in progress */
219 static int gc_initialized = 0;
220 /* If set, check if we need to do something every X allocations */
221 gboolean has_per_allocation_action;
222 /* If set, do a heap check every X allocation */
223 guint32 verify_before_allocs = 0;
224 /* If set, do a minor collection before every X allocation */
225 guint32 collect_before_allocs = 0;
226 /* If set, do a whole heap check before each collection */
227 static gboolean whole_heap_check_before_collection = FALSE;
228 /* If set, do a heap consistency check before each minor collection */
229 static gboolean consistency_check_at_minor_collection = FALSE;
230 /* If set, do a mod union consistency check before each finishing collection pause */
231 static gboolean mod_union_consistency_check = FALSE;
232 /* If set, check whether mark bits are consistent after major collections */
233 static gboolean check_mark_bits_after_major_collection = FALSE;
234 /* If set, check that all nursery objects are pinned/not pinned, depending on context */
235 static gboolean check_nursery_objects_pinned = FALSE;
236 /* If set, do a few checks when the concurrent collector is used */
237 static gboolean do_concurrent_checks = FALSE;
238 /* If set, do a plausibility check on the scan_starts before and after
239    each collection */
240 static gboolean do_scan_starts_check = FALSE;
241
242 static gboolean disable_minor_collections = FALSE;
243 static gboolean disable_major_collections = FALSE;
244 static gboolean do_verify_nursery = FALSE;
245 static gboolean do_dump_nursery_content = FALSE;
246 static gboolean enable_nursery_canaries = FALSE;
247
248 static gboolean precleaning_enabled = TRUE;
249
250 #ifdef HEAVY_STATISTICS
251 guint64 stat_objects_alloced_degraded = 0;
252 guint64 stat_bytes_alloced_degraded = 0;
253
254 guint64 stat_copy_object_called_nursery = 0;
255 guint64 stat_objects_copied_nursery = 0;
256 guint64 stat_copy_object_called_major = 0;
257 guint64 stat_objects_copied_major = 0;
258
259 guint64 stat_scan_object_called_nursery = 0;
260 guint64 stat_scan_object_called_major = 0;
261
262 guint64 stat_slots_allocated_in_vain;
263
264 guint64 stat_nursery_copy_object_failed_from_space = 0;
265 guint64 stat_nursery_copy_object_failed_forwarded = 0;
266 guint64 stat_nursery_copy_object_failed_pinned = 0;
267 guint64 stat_nursery_copy_object_failed_to_space = 0;
268
269 static guint64 stat_wbarrier_add_to_global_remset = 0;
270 static guint64 stat_wbarrier_arrayref_copy = 0;
271 static guint64 stat_wbarrier_generic_store = 0;
272 static guint64 stat_wbarrier_generic_store_atomic = 0;
273 static guint64 stat_wbarrier_set_root = 0;
274 #endif
275
276 static guint64 stat_pinned_objects = 0;
277
278 static guint64 time_minor_pre_collection_fragment_clear = 0;
279 static guint64 time_minor_pinning = 0;
280 static guint64 time_minor_scan_remsets = 0;
281 static guint64 time_minor_scan_pinned = 0;
282 static guint64 time_minor_scan_roots = 0;
283 static guint64 time_minor_finish_gray_stack = 0;
284 static guint64 time_minor_fragment_creation = 0;
285
286 static guint64 time_major_pre_collection_fragment_clear = 0;
287 static guint64 time_major_pinning = 0;
288 static guint64 time_major_scan_pinned = 0;
289 static guint64 time_major_scan_roots = 0;
290 static guint64 time_major_scan_mod_union = 0;
291 static guint64 time_major_finish_gray_stack = 0;
292 static guint64 time_major_free_bigobjs = 0;
293 static guint64 time_major_los_sweep = 0;
294 static guint64 time_major_sweep = 0;
295 static guint64 time_major_fragment_creation = 0;
296
297 static guint64 time_max = 0;
298
299 static SGEN_TV_DECLARE (time_major_conc_collection_start);
300 static SGEN_TV_DECLARE (time_major_conc_collection_end);
301
302 static SGEN_TV_DECLARE (last_minor_collection_start_tv);
303 static SGEN_TV_DECLARE (last_minor_collection_end_tv);
304
305 int gc_debug_level = 0;
306 FILE* gc_debug_file;
307
308 /*
309 void
310 mono_gc_flush_info (void)
311 {
312         fflush (gc_debug_file);
313 }
314 */
315
316 #define TV_DECLARE SGEN_TV_DECLARE
317 #define TV_GETTIME SGEN_TV_GETTIME
318 #define TV_ELAPSED SGEN_TV_ELAPSED
319
320 static SGEN_TV_DECLARE (sgen_init_timestamp);
321
322 NurseryClearPolicy nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
323
324 #define object_is_forwarded     SGEN_OBJECT_IS_FORWARDED
325 #define object_is_pinned        SGEN_OBJECT_IS_PINNED
326 #define pin_object              SGEN_PIN_OBJECT
327
328 #define ptr_in_nursery sgen_ptr_in_nursery
329
330 #define LOAD_VTABLE     SGEN_LOAD_VTABLE
331
332 gboolean
333 nursery_canaries_enabled (void)
334 {
335         return enable_nursery_canaries;
336 }
337
338 #define safe_object_get_size    sgen_safe_object_get_size
339
340 /*
341  * ######################################################################
342  * ########  Global data.
343  * ######################################################################
344  */
345 MonoCoopMutex gc_mutex;
346 gboolean sgen_try_free_some_memory;
347
348 #define SCAN_START_SIZE SGEN_SCAN_START_SIZE
349
350 size_t degraded_mode = 0;
351
352 static mword bytes_pinned_from_failed_allocation = 0;
353
354 GCMemSection *nursery_section = NULL;
355 static volatile mword lowest_heap_address = ~(mword)0;
356 static volatile mword highest_heap_address = 0;
357
358 MonoCoopMutex sgen_interruption_mutex;
359
360 int current_collection_generation = -1;
361 static volatile gboolean concurrent_collection_in_progress = FALSE;
362
363 /* objects that are ready to be finalized */
364 static SgenPointerQueue fin_ready_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_FINALIZE_READY);
365 static SgenPointerQueue critical_fin_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_FINALIZE_READY);
366
367 /* registered roots: the key to the hash is the root start address */
368 /* 
369  * Different kinds of roots are kept separate to speed up pin_from_roots () for example.
370  */
371 SgenHashTable roots_hash [ROOT_TYPE_NUM] = {
372         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL),
373         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL),
374         SGEN_HASH_TABLE_INIT (INTERNAL_MEM_ROOTS_TABLE, INTERNAL_MEM_ROOT_RECORD, sizeof (RootRecord), sgen_aligned_addr_hash, NULL)
375 };
376 static mword roots_size = 0; /* amount of memory in the root set */
377
378 /* The size of a TLAB */
379 /* The bigger the value, the less often we have to go to the slow path to allocate a new 
380  * one, but the more space is wasted by threads not allocating much memory.
381  * FIXME: Tune this.
382  * FIXME: Make this self-tuning for each thread.
383  */
384 guint32 tlab_size = (1024 * 4);
385
386 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
387
388 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
389
390 #define ALIGN_UP                SGEN_ALIGN_UP
391
392 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
393 MonoNativeThreadId main_gc_thread = NULL;
394 #endif
395
396 /*Object was pinned during the current collection*/
397 static mword objects_pinned;
398
399 /*
400  * ######################################################################
401  * ########  Macros and function declarations.
402  * ######################################################################
403  */
404
405 typedef SgenGrayQueue GrayQueue;
406
407 /* forward declarations */
408 static void scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx);
409
410 static void pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx);
411 static void finish_gray_stack (int generation, ScanCopyContext ctx);
412
413
414 SgenMajorCollector major_collector;
415 SgenMinorCollector sgen_minor_collector;
416 /* FIXME: get rid of this */
417 static GrayQueue gray_queue;
418
419 static SgenRememberedSet remset;
420
421 /* The gray queue to use from the main collection thread. */
422 #define WORKERS_DISTRIBUTE_GRAY_QUEUE   (&gray_queue)
423
424 /*
425  * The gray queue a worker job must use.  If we're not parallel or
426  * concurrent, we use the main gray queue.
427  */
428 static SgenGrayQueue*
429 sgen_workers_get_job_gray_queue (WorkerData *worker_data)
430 {
431         return worker_data ? &worker_data->private_gray_queue : WORKERS_DISTRIBUTE_GRAY_QUEUE;
432 }
433
434 static void
435 gray_queue_redirect (SgenGrayQueue *queue)
436 {
437         gboolean wake = FALSE;
438
439         for (;;) {
440                 GrayQueueSection *section = sgen_gray_object_dequeue_section (queue);
441                 if (!section)
442                         break;
443                 sgen_section_gray_queue_enqueue ((SgenSectionGrayQueue *)queue->alloc_prepare_data, section);
444                 wake = TRUE;
445         }
446
447         if (wake) {
448                 g_assert (concurrent_collection_in_progress);
449                 sgen_workers_ensure_awake ();
450         }
451 }
452
453 static void
454 gray_queue_enable_redirect (SgenGrayQueue *queue)
455 {
456         if (!concurrent_collection_in_progress)
457                 return;
458
459         sgen_gray_queue_set_alloc_prepare (queue, gray_queue_redirect, sgen_workers_get_distribute_section_gray_queue ());
460         gray_queue_redirect (queue);
461 }
462
463 void
464 sgen_scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data, gboolean allow_flags, gboolean fail_on_canaries)
465 {
466         while (start < end) {
467                 size_t size;
468                 char *obj;
469
470                 if (!*(void**)start) {
471                         start += sizeof (void*); /* should be ALLOC_ALIGN, really */
472                         continue;
473                 }
474
475                 if (allow_flags) {
476                         if (!(obj = (char *)SGEN_OBJECT_IS_FORWARDED (start)))
477                                 obj = start;
478                 } else {
479                         obj = start;
480                 }
481
482                 if (!sgen_client_object_is_array_fill ((GCObject*)obj)) {
483                         CHECK_CANARY_FOR_OBJECT ((GCObject*)obj, fail_on_canaries);
484                         size = ALIGN_UP (safe_object_get_size ((GCObject*)obj));
485                         callback ((GCObject*)obj, size, data);
486                         CANARIFY_SIZE (size);
487                 } else {
488                         size = ALIGN_UP (safe_object_get_size ((GCObject*)obj));
489                 }
490
491                 start += size;
492         }
493 }
494
495 /*
496  * sgen_add_to_global_remset:
497  *
498  *   The global remset contains locations which point into newspace after
499  * a minor collection. This can happen if the objects they point to are pinned.
500  *
501  * LOCKING: If called from a parallel collector, the global remset
502  * lock must be held.  For serial collectors that is not necessary.
503  */
504 void
505 sgen_add_to_global_remset (gpointer ptr, GCObject *obj)
506 {
507         SGEN_ASSERT (5, sgen_ptr_in_nursery (obj), "Target pointer of global remset must be in the nursery");
508
509         HEAVY_STAT (++stat_wbarrier_add_to_global_remset);
510
511         if (!major_collector.is_concurrent) {
512                 SGEN_ASSERT (5, current_collection_generation != -1, "Global remsets can only be added during collections");
513         } else {
514                 if (current_collection_generation == -1)
515                         SGEN_ASSERT (5, sgen_concurrent_collection_in_progress (), "Global remsets outside of collection pauses can only be added by the concurrent collector");
516         }
517
518         if (!object_is_pinned (obj))
519                 SGEN_ASSERT (5, sgen_minor_collector.is_split || sgen_concurrent_collection_in_progress (), "Non-pinned objects can only remain in nursery if it is a split nursery");
520         else if (sgen_cement_lookup_or_register (obj))
521                 return;
522
523         remset.record_pointer (ptr);
524
525         sgen_pin_stats_register_global_remset (obj);
526
527         SGEN_LOG (8, "Adding global remset for %p", ptr);
528         binary_protocol_global_remset (ptr, obj, (gpointer)SGEN_LOAD_VTABLE (obj));
529 }
530
531 /*
532  * sgen_drain_gray_stack:
533  *
534  *   Scan objects in the gray stack until the stack is empty. This should be called
535  * frequently after each object is copied, to achieve better locality and cache
536  * usage.
537  *
538  */
539 gboolean
540 sgen_drain_gray_stack (ScanCopyContext ctx)
541 {
542         ScanObjectFunc scan_func = ctx.ops->scan_object;
543         GrayQueue *queue = ctx.queue;
544
545         if (ctx.ops->drain_gray_stack)
546                 return ctx.ops->drain_gray_stack (queue);
547
548         for (;;) {
549                 GCObject *obj;
550                 SgenDescriptor desc;
551                 GRAY_OBJECT_DEQUEUE (queue, &obj, &desc);
552                 if (!obj)
553                         return TRUE;
554                 SGEN_LOG (9, "Precise gray object scan %p (%s)", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
555                 scan_func (obj, desc, queue);
556         }
557         return FALSE;
558 }
559
560 /*
561  * Addresses in the pin queue are already sorted. This function finds
562  * the object header for each address and pins the object. The
563  * addresses must be inside the nursery section.  The (start of the)
564  * address array is overwritten with the addresses of the actually
565  * pinned objects.  Return the number of pinned objects.
566  */
567 static int
568 pin_objects_from_nursery_pin_queue (gboolean do_scan_objects, ScanCopyContext ctx)
569 {
570         GCMemSection *section = nursery_section;
571         void **start =  sgen_pinning_get_entry (section->pin_queue_first_entry);
572         void **end = sgen_pinning_get_entry (section->pin_queue_last_entry);
573         void *start_nursery = section->data;
574         void *end_nursery = section->next_data;
575         void *last = NULL;
576         int count = 0;
577         void *search_start;
578         void *addr;
579         void *pinning_front = start_nursery;
580         size_t idx;
581         void **definitely_pinned = start;
582         ScanObjectFunc scan_func = ctx.ops->scan_object;
583         SgenGrayQueue *queue = ctx.queue;
584
585         sgen_nursery_allocator_prepare_for_pinning ();
586
587         while (start < end) {
588                 GCObject *obj_to_pin = NULL;
589                 size_t obj_to_pin_size = 0;
590                 SgenDescriptor desc;
591
592                 addr = *start;
593
594                 SGEN_ASSERT (0, addr >= start_nursery && addr < end_nursery, "Potential pinning address out of range");
595                 SGEN_ASSERT (0, addr >= last, "Pin queue not sorted");
596
597                 if (addr == last) {
598                         ++start;
599                         continue;
600                 }
601
602                 SGEN_LOG (5, "Considering pinning addr %p", addr);
603                 /* We've already processed everything up to pinning_front. */
604                 if (addr < pinning_front) {
605                         start++;
606                         continue;
607                 }
608
609                 /*
610                  * Find the closest scan start <= addr.  We might search backward in the
611                  * scan_starts array because entries might be NULL.  In the worst case we
612                  * start at start_nursery.
613                  */
614                 idx = ((char*)addr - (char*)section->data) / SCAN_START_SIZE;
615                 SGEN_ASSERT (0, idx < section->num_scan_start, "Scan start index out of range");
616                 search_start = (void*)section->scan_starts [idx];
617                 if (!search_start || search_start > addr) {
618                         while (idx) {
619                                 --idx;
620                                 search_start = section->scan_starts [idx];
621                                 if (search_start && search_start <= addr)
622                                         break;
623                         }
624                         if (!search_start || search_start > addr)
625                                 search_start = start_nursery;
626                 }
627
628                 /*
629                  * If the pinning front is closer than the scan start we found, start
630                  * searching at the front.
631                  */
632                 if (search_start < pinning_front)
633                         search_start = pinning_front;
634
635                 /*
636                  * Now addr should be in an object a short distance from search_start.
637                  *
638                  * search_start must point to zeroed mem or point to an object.
639                  */
640                 do {
641                         size_t obj_size, canarified_obj_size;
642
643                         /* Skip zeros. */
644                         if (!*(void**)search_start) {
645                                 search_start = (void*)ALIGN_UP ((mword)search_start + sizeof (gpointer));
646                                 /* The loop condition makes sure we don't overrun addr. */
647                                 continue;
648                         }
649
650                         canarified_obj_size = obj_size = ALIGN_UP (safe_object_get_size ((GCObject*)search_start));
651
652                         /*
653                          * Filler arrays are marked by an invalid sync word.  We don't
654                          * consider them for pinning.  They are not delimited by canaries,
655                          * either.
656                          */
657                         if (!sgen_client_object_is_array_fill ((GCObject*)search_start)) {
658                                 CHECK_CANARY_FOR_OBJECT (search_start, TRUE);
659                                 CANARIFY_SIZE (canarified_obj_size);
660
661                                 if (addr >= search_start && (char*)addr < (char*)search_start + obj_size) {
662                                         /* This is the object we're looking for. */
663                                         obj_to_pin = (GCObject*)search_start;
664                                         obj_to_pin_size = canarified_obj_size;
665                                         break;
666                                 }
667                         }
668
669                         /* Skip to the next object */
670                         search_start = (void*)((char*)search_start + canarified_obj_size);
671                 } while (search_start <= addr);
672
673                 /* We've searched past the address we were looking for. */
674                 if (!obj_to_pin) {
675                         pinning_front = search_start;
676                         goto next_pin_queue_entry;
677                 }
678
679                 /*
680                  * We've found an object to pin.  It might still be a dummy array, but we
681                  * can advance the pinning front in any case.
682                  */
683                 pinning_front = (char*)obj_to_pin + obj_to_pin_size;
684
685                 /*
686                  * If this is a dummy array marking the beginning of a nursery
687                  * fragment, we don't pin it.
688                  */
689                 if (sgen_client_object_is_array_fill (obj_to_pin))
690                         goto next_pin_queue_entry;
691
692                 /*
693                  * Finally - pin the object!
694                  */
695                 desc = sgen_obj_get_descriptor_safe (obj_to_pin);
696                 if (do_scan_objects) {
697                         scan_func (obj_to_pin, desc, queue);
698                 } else {
699                         SGEN_LOG (4, "Pinned object %p, vtable %p (%s), count %d\n",
700                                         obj_to_pin, *(void**)obj_to_pin, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj_to_pin)), count);
701                         binary_protocol_pin (obj_to_pin,
702                                         (gpointer)LOAD_VTABLE (obj_to_pin),
703                                         safe_object_get_size (obj_to_pin));
704
705                         pin_object (obj_to_pin);
706                         GRAY_OBJECT_ENQUEUE (queue, obj_to_pin, desc);
707                         sgen_pin_stats_register_object (obj_to_pin, obj_to_pin_size);
708                         definitely_pinned [count] = obj_to_pin;
709                         count++;
710                 }
711
712         next_pin_queue_entry:
713                 last = addr;
714                 ++start;
715         }
716         sgen_client_nursery_objects_pinned (definitely_pinned, count);
717         stat_pinned_objects += count;
718         return count;
719 }
720
721 static void
722 pin_objects_in_nursery (gboolean do_scan_objects, ScanCopyContext ctx)
723 {
724         size_t reduced_to;
725
726         if (nursery_section->pin_queue_first_entry == nursery_section->pin_queue_last_entry)
727                 return;
728
729         reduced_to = pin_objects_from_nursery_pin_queue (do_scan_objects, ctx);
730         nursery_section->pin_queue_last_entry = nursery_section->pin_queue_first_entry + reduced_to;
731 }
732
733 /*
734  * This function is only ever called (via `collector_pin_object()` in `sgen-copy-object.h`)
735  * when we can't promote an object because we're out of memory.
736  */
737 void
738 sgen_pin_object (GCObject *object, GrayQueue *queue)
739 {
740         /*
741          * All pinned objects are assumed to have been staged, so we need to stage as well.
742          * Also, the count of staged objects shows that "late pinning" happened.
743          */
744         sgen_pin_stage_ptr (object);
745
746         SGEN_PIN_OBJECT (object);
747         binary_protocol_pin (object, (gpointer)LOAD_VTABLE (object), safe_object_get_size (object));
748
749         ++objects_pinned;
750         sgen_pin_stats_register_object (object, safe_object_get_size (object));
751
752         GRAY_OBJECT_ENQUEUE (queue, object, sgen_obj_get_descriptor_safe (object));
753 }
754
755 /* Sort the addresses in array in increasing order.
756  * Done using a by-the book heap sort. Which has decent and stable performance, is pretty cache efficient.
757  */
758 void
759 sgen_sort_addresses (void **array, size_t size)
760 {
761         size_t i;
762         void *tmp;
763
764         for (i = 1; i < size; ++i) {
765                 size_t child = i;
766                 while (child > 0) {
767                         size_t parent = (child - 1) / 2;
768
769                         if (array [parent] >= array [child])
770                                 break;
771
772                         tmp = array [parent];
773                         array [parent] = array [child];
774                         array [child] = tmp;
775
776                         child = parent;
777                 }
778         }
779
780         for (i = size - 1; i > 0; --i) {
781                 size_t end, root;
782                 tmp = array [i];
783                 array [i] = array [0];
784                 array [0] = tmp;
785
786                 end = i - 1;
787                 root = 0;
788
789                 while (root * 2 + 1 <= end) {
790                         size_t child = root * 2 + 1;
791
792                         if (child < end && array [child] < array [child + 1])
793                                 ++child;
794                         if (array [root] >= array [child])
795                                 break;
796
797                         tmp = array [root];
798                         array [root] = array [child];
799                         array [child] = tmp;
800
801                         root = child;
802                 }
803         }
804 }
805
806 /* 
807  * Scan the memory between start and end and queue values which could be pointers
808  * to the area between start_nursery and end_nursery for later consideration.
809  * Typically used for thread stacks.
810  */
811 void
812 sgen_conservatively_pin_objects_from (void **start, void **end, void *start_nursery, void *end_nursery, int pin_type)
813 {
814         int count = 0;
815
816         SGEN_ASSERT (0, ((mword)start & (SIZEOF_VOID_P - 1)) == 0, "Why are we scanning for references in unaligned memory ?");
817
818 #if defined(VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE) && !defined(_WIN64)
819         VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE (start, (char*)end - (char*)start);
820 #endif
821
822         while (start < end) {
823                 /*
824                  * *start can point to the middle of an object
825                  * note: should we handle pointing at the end of an object?
826                  * pinning in C# code disallows pointing at the end of an object
827                  * but there is some small chance that an optimizing C compiler
828                  * may keep the only reference to an object by pointing
829                  * at the end of it. We ignore this small chance for now.
830                  * Pointers to the end of an object are indistinguishable
831                  * from pointers to the start of the next object in memory
832                  * so if we allow that we'd need to pin two objects...
833                  * We queue the pointer in an array, the
834                  * array will then be sorted and uniqued. This way
835                  * we can coalesce several pinning pointers and it should
836                  * be faster since we'd do a memory scan with increasing
837                  * addresses. Note: we can align the address to the allocation
838                  * alignment, so the unique process is more effective.
839                  */
840                 mword addr = (mword)*start;
841                 addr &= ~(ALLOC_ALIGN - 1);
842                 if (addr >= (mword)start_nursery && addr < (mword)end_nursery) {
843                         SGEN_LOG (6, "Pinning address %p from %p", (void*)addr, start);
844                         sgen_pin_stage_ptr ((void*)addr);
845                         binary_protocol_pin_stage (start, (void*)addr);
846                         sgen_pin_stats_register_address ((char*)addr, pin_type);
847                         count++;
848                 }
849                 start++;
850         }
851         if (count)
852                 SGEN_LOG (7, "found %d potential pinned heap pointers", count);
853 }
854
855 /*
856  * The first thing we do in a collection is to identify pinned objects.
857  * This function considers all the areas of memory that need to be
858  * conservatively scanned.
859  */
860 static void
861 pin_from_roots (void *start_nursery, void *end_nursery, ScanCopyContext ctx)
862 {
863         void **start_root;
864         RootRecord *root;
865         SGEN_LOG (2, "Scanning pinned roots (%d bytes, %d/%d entries)", (int)roots_size, roots_hash [ROOT_TYPE_NORMAL].num_entries, roots_hash [ROOT_TYPE_PINNED].num_entries);
866         /* objects pinned from the API are inside these roots */
867         SGEN_HASH_TABLE_FOREACH (&roots_hash [ROOT_TYPE_PINNED], void **, start_root, RootRecord *, root) {
868                 SGEN_LOG (6, "Pinned roots %p-%p", start_root, root->end_root);
869                 sgen_conservatively_pin_objects_from (start_root, (void**)root->end_root, start_nursery, end_nursery, PIN_TYPE_OTHER);
870         } SGEN_HASH_TABLE_FOREACH_END;
871         /* now deal with the thread stacks
872          * in the future we should be able to conservatively scan only:
873          * *) the cpu registers
874          * *) the unmanaged stack frames
875          * *) the _last_ managed stack frame
876          * *) pointers slots in managed frames
877          */
878         sgen_client_scan_thread_data (start_nursery, end_nursery, FALSE, ctx);
879 }
880
881 static void
882 single_arg_user_copy_or_mark (GCObject **obj, void *gc_data)
883 {
884         ScanCopyContext *ctx = (ScanCopyContext *)gc_data;
885         ctx->ops->copy_or_mark_object (obj, ctx->queue);
886 }
887
888 /*
889  * The memory area from start_root to end_root contains pointers to objects.
890  * Their position is precisely described by @desc (this means that the pointer
891  * can be either NULL or the pointer to the start of an object).
892  * This functions copies them to to_space updates them.
893  *
894  * This function is not thread-safe!
895  */
896 static void
897 precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, SgenDescriptor desc, ScanCopyContext ctx)
898 {
899         CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
900         SgenGrayQueue *queue = ctx.queue;
901
902         switch (desc & ROOT_DESC_TYPE_MASK) {
903         case ROOT_DESC_BITMAP:
904                 desc >>= ROOT_DESC_TYPE_SHIFT;
905                 while (desc) {
906                         if ((desc & 1) && *start_root) {
907                                 copy_func ((GCObject**)start_root, queue);
908                                 SGEN_LOG (9, "Overwrote root at %p with %p", start_root, *start_root);
909                         }
910                         desc >>= 1;
911                         start_root++;
912                 }
913                 return;
914         case ROOT_DESC_COMPLEX: {
915                 gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc);
916                 gsize bwords = (*bitmap_data) - 1;
917                 void **start_run = start_root;
918                 bitmap_data++;
919                 while (bwords-- > 0) {
920                         gsize bmap = *bitmap_data++;
921                         void **objptr = start_run;
922                         while (bmap) {
923                                 if ((bmap & 1) && *objptr) {
924                                         copy_func ((GCObject**)objptr, queue);
925                                         SGEN_LOG (9, "Overwrote root at %p with %p", objptr, *objptr);
926                                 }
927                                 bmap >>= 1;
928                                 ++objptr;
929                         }
930                         start_run += GC_BITS_PER_WORD;
931                 }
932                 break;
933         }
934         case ROOT_DESC_USER: {
935                 SgenUserRootMarkFunc marker = sgen_get_user_descriptor_func (desc);
936                 marker (start_root, single_arg_user_copy_or_mark, &ctx);
937                 break;
938         }
939         case ROOT_DESC_RUN_LEN:
940                 g_assert_not_reached ();
941         default:
942                 g_assert_not_reached ();
943         }
944 }
945
946 static void
947 reset_heap_boundaries (void)
948 {
949         lowest_heap_address = ~(mword)0;
950         highest_heap_address = 0;
951 }
952
953 void
954 sgen_update_heap_boundaries (mword low, mword high)
955 {
956         mword old;
957
958         do {
959                 old = lowest_heap_address;
960                 if (low >= old)
961                         break;
962         } while (SGEN_CAS_PTR ((gpointer*)&lowest_heap_address, (gpointer)low, (gpointer)old) != (gpointer)old);
963
964         do {
965                 old = highest_heap_address;
966                 if (high <= old)
967                         break;
968         } while (SGEN_CAS_PTR ((gpointer*)&highest_heap_address, (gpointer)high, (gpointer)old) != (gpointer)old);
969 }
970
971 /*
972  * Allocate and setup the data structures needed to be able to allocate objects
973  * in the nursery. The nursery is stored in nursery_section.
974  */
975 static void
976 alloc_nursery (void)
977 {
978         GCMemSection *section;
979         char *data;
980         size_t scan_starts;
981         size_t alloc_size;
982
983         if (nursery_section)
984                 return;
985         SGEN_LOG (2, "Allocating nursery size: %zu", (size_t)sgen_nursery_size);
986         /* later we will alloc a larger area for the nursery but only activate
987          * what we need. The rest will be used as expansion if we have too many pinned
988          * objects in the existing nursery.
989          */
990         /* FIXME: handle OOM */
991         section = (GCMemSection *)sgen_alloc_internal (INTERNAL_MEM_SECTION);
992
993         alloc_size = sgen_nursery_size;
994
995         /* If there isn't enough space even for the nursery we should simply abort. */
996         g_assert (sgen_memgov_try_alloc_space (alloc_size, SPACE_NURSERY));
997
998         data = (char *)major_collector.alloc_heap (alloc_size, alloc_size, DEFAULT_NURSERY_BITS);
999         sgen_update_heap_boundaries ((mword)data, (mword)(data + sgen_nursery_size));
1000         SGEN_LOG (4, "Expanding nursery size (%p-%p): %lu, total: %lu", data, data + alloc_size, (unsigned long)sgen_nursery_size, (unsigned long)sgen_gc_get_total_heap_allocation ());
1001         section->data = section->next_data = data;
1002         section->size = alloc_size;
1003         section->end_data = data + sgen_nursery_size;
1004         scan_starts = (alloc_size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
1005         section->scan_starts = (char **)sgen_alloc_internal_dynamic (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS, TRUE);
1006         section->num_scan_start = scan_starts;
1007
1008         nursery_section = section;
1009
1010         sgen_nursery_allocator_set_nursery_bounds (data, data + sgen_nursery_size);
1011 }
1012
1013 FILE *
1014 mono_gc_get_logfile (void)
1015 {
1016         return gc_debug_file;
1017 }
1018
1019 static void
1020 scan_finalizer_entries (SgenPointerQueue *fin_queue, ScanCopyContext ctx)
1021 {
1022         CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
1023         SgenGrayQueue *queue = ctx.queue;
1024         size_t i;
1025
1026         for (i = 0; i < fin_queue->next_slot; ++i) {
1027                 GCObject *obj = (GCObject *)fin_queue->data [i];
1028                 if (!obj)
1029                         continue;
1030                 SGEN_LOG (5, "Scan of fin ready object: %p (%s)\n", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
1031                 copy_func ((GCObject**)&fin_queue->data [i], queue);
1032         }
1033 }
1034
1035 static const char*
1036 generation_name (int generation)
1037 {
1038         switch (generation) {
1039         case GENERATION_NURSERY: return "nursery";
1040         case GENERATION_OLD: return "old";
1041         default: g_assert_not_reached ();
1042         }
1043 }
1044
1045 const char*
1046 sgen_generation_name (int generation)
1047 {
1048         return generation_name (generation);
1049 }
1050
1051 static void
1052 finish_gray_stack (int generation, ScanCopyContext ctx)
1053 {
1054         TV_DECLARE (atv);
1055         TV_DECLARE (btv);
1056         int done_with_ephemerons, ephemeron_rounds = 0;
1057         char *start_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_start () : NULL;
1058         char *end_addr = generation == GENERATION_NURSERY ? sgen_get_nursery_end () : (char*)-1;
1059         SgenGrayQueue *queue = ctx.queue;
1060
1061         binary_protocol_finish_gray_stack_start (sgen_timestamp (), generation);
1062         /*
1063          * We copied all the reachable objects. Now it's the time to copy
1064          * the objects that were not referenced by the roots, but by the copied objects.
1065          * we built a stack of objects pointed to by gray_start: they are
1066          * additional roots and we may add more items as we go.
1067          * We loop until gray_start == gray_objects which means no more objects have
1068          * been added. Note this is iterative: no recursion is involved.
1069          * We need to walk the LO list as well in search of marked big objects
1070          * (use a flag since this is needed only on major collections). We need to loop
1071          * here as well, so keep a counter of marked LO (increasing it in copy_object).
1072          *   To achieve better cache locality and cache usage, we drain the gray stack 
1073          * frequently, after each object is copied, and just finish the work here.
1074          */
1075         sgen_drain_gray_stack (ctx);
1076         TV_GETTIME (atv);
1077         SGEN_LOG (2, "%s generation done", generation_name (generation));
1078
1079         /*
1080         Reset bridge data, we might have lingering data from a previous collection if this is a major
1081         collection trigged by minor overflow.
1082
1083         We must reset the gathered bridges since their original block might be evacuated due to major
1084         fragmentation in the meanwhile and the bridge code should not have to deal with that.
1085         */
1086         if (sgen_client_bridge_need_processing ())
1087                 sgen_client_bridge_reset_data ();
1088
1089         /*
1090          * Walk the ephemeron tables marking all values with reachable keys. This must be completely done
1091          * before processing finalizable objects and non-tracking weak links to avoid finalizing/clearing
1092          * objects that are in fact reachable.
1093          */
1094         done_with_ephemerons = 0;
1095         do {
1096                 done_with_ephemerons = sgen_client_mark_ephemerons (ctx);
1097                 sgen_drain_gray_stack (ctx);
1098                 ++ephemeron_rounds;
1099         } while (!done_with_ephemerons);
1100
1101         sgen_client_mark_togglerefs (start_addr, end_addr, ctx);
1102
1103         if (sgen_client_bridge_need_processing ()) {
1104                 /*Make sure the gray stack is empty before we process bridge objects so we get liveness right*/
1105                 sgen_drain_gray_stack (ctx);
1106                 sgen_collect_bridge_objects (generation, ctx);
1107                 if (generation == GENERATION_OLD)
1108                         sgen_collect_bridge_objects (GENERATION_NURSERY, ctx);
1109
1110                 /*
1111                 Do the first bridge step here, as the collector liveness state will become useless after that.
1112
1113                 An important optimization is to only proccess the possibly dead part of the object graph and skip
1114                 over all live objects as we transitively know everything they point must be alive too.
1115
1116                 The above invariant is completely wrong if we let the gray queue be drained and mark/copy everything.
1117
1118                 This has the unfortunate side effect of making overflow collections perform the first step twice, but
1119                 given we now have heuristics that perform major GC in anticipation of minor overflows this should not
1120                 be a big deal.
1121                 */
1122                 sgen_client_bridge_processing_stw_step ();
1123         }
1124
1125         /*
1126         Make sure we drain the gray stack before processing disappearing links and finalizers.
1127         If we don't make sure it is empty we might wrongly see a live object as dead.
1128         */
1129         sgen_drain_gray_stack (ctx);
1130
1131         /*
1132         We must clear weak links that don't track resurrection before processing object ready for
1133         finalization so they can be cleared before that.
1134         */
1135         sgen_null_link_in_range (generation, ctx, FALSE);
1136         if (generation == GENERATION_OLD)
1137                 sgen_null_link_in_range (GENERATION_NURSERY, ctx, FALSE);
1138
1139
1140         /* walk the finalization queue and move also the objects that need to be
1141          * finalized: use the finalized objects as new roots so the objects they depend
1142          * on are also not reclaimed. As with the roots above, only objects in the nursery
1143          * are marked/copied.
1144          */
1145         sgen_finalize_in_range (generation, ctx);
1146         if (generation == GENERATION_OLD)
1147                 sgen_finalize_in_range (GENERATION_NURSERY, ctx);
1148         /* drain the new stack that might have been created */
1149         SGEN_LOG (6, "Precise scan of gray area post fin");
1150         sgen_drain_gray_stack (ctx);
1151
1152         /*
1153          * This must be done again after processing finalizable objects since CWL slots are cleared only after the key is finalized.
1154          */
1155         done_with_ephemerons = 0;
1156         do {
1157                 done_with_ephemerons = sgen_client_mark_ephemerons (ctx);
1158                 sgen_drain_gray_stack (ctx);
1159                 ++ephemeron_rounds;
1160         } while (!done_with_ephemerons);
1161
1162         sgen_client_clear_unreachable_ephemerons (ctx);
1163
1164         /*
1165          * We clear togglerefs only after all possible chances of revival are done. 
1166          * This is semantically more inline with what users expect and it allows for
1167          * user finalizers to correctly interact with TR objects.
1168         */
1169         sgen_client_clear_togglerefs (start_addr, end_addr, ctx);
1170
1171         TV_GETTIME (btv);
1172         SGEN_LOG (2, "Finalize queue handling scan for %s generation: %lld usecs %d ephemeron rounds", generation_name (generation), TV_ELAPSED (atv, btv), ephemeron_rounds);
1173
1174         /*
1175          * handle disappearing links
1176          * Note we do this after checking the finalization queue because if an object
1177          * survives (at least long enough to be finalized) we don't clear the link.
1178          * This also deals with a possible issue with the monitor reclamation: with the Boehm
1179          * GC a finalized object my lose the monitor because it is cleared before the finalizer is
1180          * called.
1181          */
1182         g_assert (sgen_gray_object_queue_is_empty (queue));
1183         for (;;) {
1184                 sgen_null_link_in_range (generation, ctx, TRUE);
1185                 if (generation == GENERATION_OLD)
1186                         sgen_null_link_in_range (GENERATION_NURSERY, ctx, TRUE);
1187                 if (sgen_gray_object_queue_is_empty (queue))
1188                         break;
1189                 sgen_drain_gray_stack (ctx);
1190         }
1191
1192         g_assert (sgen_gray_object_queue_is_empty (queue));
1193
1194         sgen_gray_object_queue_trim_free_list (queue);
1195         binary_protocol_finish_gray_stack_end (sgen_timestamp (), generation);
1196 }
1197
1198 void
1199 sgen_check_section_scan_starts (GCMemSection *section)
1200 {
1201         size_t i;
1202         for (i = 0; i < section->num_scan_start; ++i) {
1203                 if (section->scan_starts [i]) {
1204                         mword size = safe_object_get_size ((GCObject*) section->scan_starts [i]);
1205                         SGEN_ASSERT (0, size >= SGEN_CLIENT_MINIMUM_OBJECT_SIZE && size <= MAX_SMALL_OBJ_SIZE, "Weird object size at scan starts.");
1206                 }
1207         }
1208 }
1209
1210 static void
1211 check_scan_starts (void)
1212 {
1213         if (!do_scan_starts_check)
1214                 return;
1215         sgen_check_section_scan_starts (nursery_section);
1216         major_collector.check_scan_starts ();
1217 }
1218
1219 static void
1220 scan_from_registered_roots (char *addr_start, char *addr_end, int root_type, ScanCopyContext ctx)
1221 {
1222         void **start_root;
1223         RootRecord *root;
1224         SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], void **, start_root, RootRecord *, root) {
1225                 SGEN_LOG (6, "Precise root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
1226                 precisely_scan_objects_from (start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc, ctx);
1227         } SGEN_HASH_TABLE_FOREACH_END;
1228 }
1229
1230 static void
1231 init_stats (void)
1232 {
1233         static gboolean inited = FALSE;
1234
1235         if (inited)
1236                 return;
1237
1238         mono_counters_register ("Collection max time",  MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME | MONO_COUNTER_MONOTONIC, &time_max);
1239
1240         mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_pre_collection_fragment_clear);
1241         mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_pinning);
1242         mono_counters_register ("Minor scan remembered set", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_remsets);
1243         mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_pinned);
1244         mono_counters_register ("Minor scan roots", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_scan_roots);
1245         mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_minor_fragment_creation);
1246
1247         mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_pre_collection_fragment_clear);
1248         mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_pinning);
1249         mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_pinned);
1250         mono_counters_register ("Major scan roots", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_roots);
1251         mono_counters_register ("Major scan mod union", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_scan_mod_union);
1252         mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_finish_gray_stack);
1253         mono_counters_register ("Major free big objects", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_free_bigobjs);
1254         mono_counters_register ("Major LOS sweep", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_los_sweep);
1255         mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_sweep);
1256         mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &time_major_fragment_creation);
1257
1258         mono_counters_register ("Number of pinned objects", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_pinned_objects);
1259
1260 #ifdef HEAVY_STATISTICS
1261         mono_counters_register ("WBarrier remember pointer", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_add_to_global_remset);
1262         mono_counters_register ("WBarrier arrayref copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_arrayref_copy);
1263         mono_counters_register ("WBarrier generic store called", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_generic_store);
1264         mono_counters_register ("WBarrier generic atomic store called", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_generic_store_atomic);
1265         mono_counters_register ("WBarrier set root", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_set_root);
1266
1267         mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_alloced_degraded);
1268         mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_bytes_alloced_degraded);
1269
1270         mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_copy_object_called_nursery);
1271         mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_copied_nursery);
1272         mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_copy_object_called_major);
1273         mono_counters_register ("# objects copied (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_copied_major);
1274
1275         mono_counters_register ("# scan_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_scan_object_called_nursery);
1276         mono_counters_register ("# scan_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_scan_object_called_major);
1277
1278         mono_counters_register ("Slots allocated in vain", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_slots_allocated_in_vain);
1279
1280         mono_counters_register ("# nursery copy_object() failed from space", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_from_space);
1281         mono_counters_register ("# nursery copy_object() failed forwarded", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_forwarded);
1282         mono_counters_register ("# nursery copy_object() failed pinned", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_pinned);
1283         mono_counters_register ("# nursery copy_object() failed to space", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_nursery_copy_object_failed_to_space);
1284
1285         sgen_nursery_allocator_init_heavy_stats ();
1286 #endif
1287
1288         inited = TRUE;
1289 }
1290
1291
1292 static void
1293 reset_pinned_from_failed_allocation (void)
1294 {
1295         bytes_pinned_from_failed_allocation = 0;
1296 }
1297
1298 void
1299 sgen_set_pinned_from_failed_allocation (mword objsize)
1300 {
1301         bytes_pinned_from_failed_allocation += objsize;
1302 }
1303
1304 gboolean
1305 sgen_collection_is_concurrent (void)
1306 {
1307         switch (current_collection_generation) {
1308         case GENERATION_NURSERY:
1309                 return FALSE;
1310         case GENERATION_OLD:
1311                 return concurrent_collection_in_progress;
1312         default:
1313                 g_error ("Invalid current generation %d", current_collection_generation);
1314         }
1315         return FALSE;
1316 }
1317
1318 gboolean
1319 sgen_concurrent_collection_in_progress (void)
1320 {
1321         return concurrent_collection_in_progress;
1322 }
1323
1324 typedef struct {
1325         SgenThreadPoolJob job;
1326         SgenObjectOperations *ops;
1327 } ScanJob;
1328
1329 static void
1330 job_remembered_set_scan (void *worker_data_untyped, SgenThreadPoolJob *job)
1331 {
1332         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1333         ScanJob *job_data = (ScanJob*)job;
1334         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1335         remset.scan_remsets (ctx);
1336 }
1337
1338 typedef struct {
1339         SgenThreadPoolJob job;
1340         SgenObjectOperations *ops;
1341         char *heap_start;
1342         char *heap_end;
1343         int root_type;
1344 } ScanFromRegisteredRootsJob;
1345
1346 static void
1347 job_scan_from_registered_roots (void *worker_data_untyped, SgenThreadPoolJob *job)
1348 {
1349         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1350         ScanFromRegisteredRootsJob *job_data = (ScanFromRegisteredRootsJob*)job;
1351         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1352
1353         scan_from_registered_roots (job_data->heap_start, job_data->heap_end, job_data->root_type, ctx);
1354 }
1355
1356 typedef struct {
1357         SgenThreadPoolJob job;
1358         SgenObjectOperations *ops;
1359         char *heap_start;
1360         char *heap_end;
1361 } ScanThreadDataJob;
1362
1363 static void
1364 job_scan_thread_data (void *worker_data_untyped, SgenThreadPoolJob *job)
1365 {
1366         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1367         ScanThreadDataJob *job_data = (ScanThreadDataJob*)job;
1368         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1369
1370         sgen_client_scan_thread_data (job_data->heap_start, job_data->heap_end, TRUE, ctx);
1371 }
1372
1373 typedef struct {
1374         SgenThreadPoolJob job;
1375         SgenObjectOperations *ops;
1376         SgenPointerQueue *queue;
1377 } ScanFinalizerEntriesJob;
1378
1379 static void
1380 job_scan_finalizer_entries (void *worker_data_untyped, SgenThreadPoolJob *job)
1381 {
1382         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1383         ScanFinalizerEntriesJob *job_data = (ScanFinalizerEntriesJob*)job;
1384         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1385
1386         scan_finalizer_entries (job_data->queue, ctx);
1387 }
1388
1389 static void
1390 job_scan_major_mod_union_card_table (void *worker_data_untyped, SgenThreadPoolJob *job)
1391 {
1392         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1393         ScanJob *job_data = (ScanJob*)job;
1394         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1395
1396         g_assert (concurrent_collection_in_progress);
1397         major_collector.scan_card_table (CARDTABLE_SCAN_MOD_UNION, ctx);
1398 }
1399
1400 static void
1401 job_scan_los_mod_union_card_table (void *worker_data_untyped, SgenThreadPoolJob *job)
1402 {
1403         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1404         ScanJob *job_data = (ScanJob*)job;
1405         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1406
1407         g_assert (concurrent_collection_in_progress);
1408         sgen_los_scan_card_table (CARDTABLE_SCAN_MOD_UNION, ctx);
1409 }
1410
1411 static void
1412 job_mod_union_preclean (void *worker_data_untyped, SgenThreadPoolJob *job)
1413 {
1414         WorkerData *worker_data = (WorkerData *)worker_data_untyped;
1415         ScanJob *job_data = (ScanJob*)job;
1416         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (job_data->ops, sgen_workers_get_job_gray_queue (worker_data));
1417
1418         g_assert (concurrent_collection_in_progress);
1419
1420         major_collector.scan_card_table (CARDTABLE_SCAN_MOD_UNION_PRECLEAN, ctx);
1421         sgen_los_scan_card_table (CARDTABLE_SCAN_MOD_UNION_PRECLEAN, ctx);
1422 }
1423
1424 static void
1425 init_gray_queue (gboolean use_workers)
1426 {
1427         if (use_workers)
1428                 sgen_workers_init_distribute_gray_queue ();
1429         sgen_gray_object_queue_init (&gray_queue, NULL);
1430 }
1431
1432 static void
1433 enqueue_scan_from_roots_jobs (char *heap_start, char *heap_end, SgenObjectOperations *ops, gboolean enqueue)
1434 {
1435         ScanFromRegisteredRootsJob *scrrj;
1436         ScanThreadDataJob *stdj;
1437         ScanFinalizerEntriesJob *sfej;
1438
1439         /* registered roots, this includes static fields */
1440
1441         scrrj = (ScanFromRegisteredRootsJob*)sgen_thread_pool_job_alloc ("scan from registered roots normal", job_scan_from_registered_roots, sizeof (ScanFromRegisteredRootsJob));
1442         scrrj->ops = ops;
1443         scrrj->heap_start = heap_start;
1444         scrrj->heap_end = heap_end;
1445         scrrj->root_type = ROOT_TYPE_NORMAL;
1446         sgen_workers_enqueue_job (&scrrj->job, enqueue);
1447
1448         scrrj = (ScanFromRegisteredRootsJob*)sgen_thread_pool_job_alloc ("scan from registered roots wbarrier", job_scan_from_registered_roots, sizeof (ScanFromRegisteredRootsJob));
1449         scrrj->ops = ops;
1450         scrrj->heap_start = heap_start;
1451         scrrj->heap_end = heap_end;
1452         scrrj->root_type = ROOT_TYPE_WBARRIER;
1453         sgen_workers_enqueue_job (&scrrj->job, enqueue);
1454
1455         /* Threads */
1456
1457         stdj = (ScanThreadDataJob*)sgen_thread_pool_job_alloc ("scan thread data", job_scan_thread_data, sizeof (ScanThreadDataJob));
1458         stdj->heap_start = heap_start;
1459         stdj->heap_end = heap_end;
1460         sgen_workers_enqueue_job (&stdj->job, enqueue);
1461
1462         /* Scan the list of objects ready for finalization. */
1463
1464         sfej = (ScanFinalizerEntriesJob*)sgen_thread_pool_job_alloc ("scan finalizer entries", job_scan_finalizer_entries, sizeof (ScanFinalizerEntriesJob));
1465         sfej->queue = &fin_ready_queue;
1466         sfej->ops = ops;
1467         sgen_workers_enqueue_job (&sfej->job, enqueue);
1468
1469         sfej = (ScanFinalizerEntriesJob*)sgen_thread_pool_job_alloc ("scan critical finalizer entries", job_scan_finalizer_entries, sizeof (ScanFinalizerEntriesJob));
1470         sfej->queue = &critical_fin_queue;
1471         sfej->ops = ops;
1472         sgen_workers_enqueue_job (&sfej->job, enqueue);
1473 }
1474
1475 /*
1476  * Perform a nursery collection.
1477  *
1478  * Return whether any objects were late-pinned due to being out of memory.
1479  */
1480 static gboolean
1481 collect_nursery (SgenGrayQueue *unpin_queue, gboolean finish_up_concurrent_mark)
1482 {
1483         gboolean needs_major;
1484         size_t max_garbage_amount;
1485         char *nursery_next;
1486         mword fragment_total;
1487         ScanJob *sj;
1488         SgenObjectOperations *object_ops = &sgen_minor_collector.serial_ops;
1489         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, &gray_queue);
1490         TV_DECLARE (atv);
1491         TV_DECLARE (btv);
1492
1493         if (disable_minor_collections)
1494                 return TRUE;
1495
1496         TV_GETTIME (last_minor_collection_start_tv);
1497         atv = last_minor_collection_start_tv;
1498
1499         binary_protocol_collection_begin (gc_stats.minor_gc_count, GENERATION_NURSERY);
1500
1501         if (do_verify_nursery || do_dump_nursery_content)
1502                 sgen_debug_verify_nursery (do_dump_nursery_content);
1503
1504         current_collection_generation = GENERATION_NURSERY;
1505
1506         SGEN_ASSERT (0, !sgen_collection_is_concurrent (), "Why is the nursery collection concurrent?");
1507
1508         reset_pinned_from_failed_allocation ();
1509
1510         check_scan_starts ();
1511
1512         sgen_nursery_alloc_prepare_for_minor ();
1513
1514         degraded_mode = 0;
1515         objects_pinned = 0;
1516         nursery_next = sgen_nursery_alloc_get_upper_alloc_bound ();
1517         /* FIXME: optimize later to use the higher address where an object can be present */
1518         nursery_next = MAX (nursery_next, sgen_get_nursery_end ());
1519
1520         SGEN_LOG (1, "Start nursery collection %d %p-%p, size: %d", gc_stats.minor_gc_count, sgen_get_nursery_start (), nursery_next, (int)(nursery_next - sgen_get_nursery_start ()));
1521         max_garbage_amount = nursery_next - sgen_get_nursery_start ();
1522         g_assert (nursery_section->size >= max_garbage_amount);
1523
1524         /* world must be stopped already */
1525         TV_GETTIME (btv);
1526         time_minor_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
1527
1528         sgen_client_pre_collection_checks ();
1529
1530         nursery_section->next_data = nursery_next;
1531
1532         major_collector.start_nursery_collection ();
1533
1534         sgen_memgov_minor_collection_start ();
1535
1536         init_gray_queue (FALSE);
1537
1538         gc_stats.minor_gc_count ++;
1539
1540         if (whole_heap_check_before_collection) {
1541                 sgen_clear_nursery_fragments ();
1542                 sgen_check_whole_heap (finish_up_concurrent_mark);
1543         }
1544         if (consistency_check_at_minor_collection)
1545                 sgen_check_consistency ();
1546
1547         sgen_process_fin_stage_entries ();
1548
1549         /* pin from pinned handles */
1550         sgen_init_pinning ();
1551         sgen_client_binary_protocol_mark_start (GENERATION_NURSERY);
1552         pin_from_roots (sgen_get_nursery_start (), nursery_next, ctx);
1553         /* pin cemented objects */
1554         sgen_pin_cemented_objects ();
1555         /* identify pinned objects */
1556         sgen_optimize_pin_queue ();
1557         sgen_pinning_setup_section (nursery_section);
1558
1559         pin_objects_in_nursery (FALSE, ctx);
1560         sgen_pinning_trim_queue_to_section (nursery_section);
1561
1562         TV_GETTIME (atv);
1563         time_minor_pinning += TV_ELAPSED (btv, atv);
1564         SGEN_LOG (2, "Finding pinned pointers: %zd in %lld usecs", sgen_get_pinned_count (), TV_ELAPSED (btv, atv));
1565         SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
1566
1567         sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan remset", job_remembered_set_scan, sizeof (ScanJob));
1568         sj->ops = object_ops;
1569         sgen_workers_enqueue_job (&sj->job, FALSE);
1570
1571         /* we don't have complete write barrier yet, so we scan all the old generation sections */
1572         TV_GETTIME (btv);
1573         time_minor_scan_remsets += TV_ELAPSED (atv, btv);
1574         SGEN_LOG (2, "Old generation scan: %lld usecs", TV_ELAPSED (atv, btv));
1575
1576         sgen_pin_stats_print_class_stats ();
1577
1578         /* FIXME: Why do we do this at this specific, seemingly random, point? */
1579         sgen_client_collecting_minor (&fin_ready_queue, &critical_fin_queue);
1580
1581         TV_GETTIME (atv);
1582         time_minor_scan_pinned += TV_ELAPSED (btv, atv);
1583
1584         enqueue_scan_from_roots_jobs (sgen_get_nursery_start (), nursery_next, object_ops, FALSE);
1585
1586         TV_GETTIME (btv);
1587         time_minor_scan_roots += TV_ELAPSED (atv, btv);
1588
1589         finish_gray_stack (GENERATION_NURSERY, ctx);
1590
1591         TV_GETTIME (atv);
1592         time_minor_finish_gray_stack += TV_ELAPSED (btv, atv);
1593         sgen_client_binary_protocol_mark_end (GENERATION_NURSERY);
1594
1595         if (objects_pinned) {
1596                 sgen_optimize_pin_queue ();
1597                 sgen_pinning_setup_section (nursery_section);
1598         }
1599
1600         /* walk the pin_queue, build up the fragment list of free memory, unmark
1601          * pinned objects as we go, memzero() the empty fragments so they are ready for the
1602          * next allocations.
1603          */
1604         sgen_client_binary_protocol_reclaim_start (GENERATION_NURSERY);
1605         fragment_total = sgen_build_nursery_fragments (nursery_section, unpin_queue);
1606         if (!fragment_total)
1607                 degraded_mode = 1;
1608
1609         /* Clear TLABs for all threads */
1610         sgen_clear_tlabs ();
1611
1612         sgen_client_binary_protocol_reclaim_end (GENERATION_NURSERY);
1613         TV_GETTIME (btv);
1614         time_minor_fragment_creation += TV_ELAPSED (atv, btv);
1615         SGEN_LOG (2, "Fragment creation: %lld usecs, %lu bytes available", TV_ELAPSED (atv, btv), (unsigned long)fragment_total);
1616
1617         if (consistency_check_at_minor_collection)
1618                 sgen_check_major_refs ();
1619
1620         major_collector.finish_nursery_collection ();
1621
1622         TV_GETTIME (last_minor_collection_end_tv);
1623         gc_stats.minor_gc_time += TV_ELAPSED (last_minor_collection_start_tv, last_minor_collection_end_tv);
1624
1625         sgen_debug_dump_heap ("minor", gc_stats.minor_gc_count - 1, NULL);
1626
1627         /* prepare the pin queue for the next collection */
1628         sgen_finish_pinning ();
1629         if (sgen_have_pending_finalizers ()) {
1630                 SGEN_LOG (4, "Finalizer-thread wakeup");
1631                 sgen_client_finalize_notify ();
1632         }
1633         sgen_pin_stats_reset ();
1634         /* clear cemented hash */
1635         sgen_cement_clear_below_threshold ();
1636
1637         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
1638
1639         remset.finish_minor_collection ();
1640
1641         check_scan_starts ();
1642
1643         binary_protocol_flush_buffers (FALSE);
1644
1645         sgen_memgov_minor_collection_end ();
1646
1647         /*objects are late pinned because of lack of memory, so a major is a good call*/
1648         needs_major = objects_pinned > 0;
1649         current_collection_generation = -1;
1650         objects_pinned = 0;
1651
1652         binary_protocol_collection_end (gc_stats.minor_gc_count - 1, GENERATION_NURSERY, 0, 0);
1653
1654         if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
1655                 sgen_check_nursery_objects_pinned (unpin_queue != NULL);
1656
1657         return needs_major;
1658 }
1659
1660 typedef enum {
1661         COPY_OR_MARK_FROM_ROOTS_SERIAL,
1662         COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT,
1663         COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT
1664 } CopyOrMarkFromRootsMode;
1665
1666 static void
1667 major_copy_or_mark_from_roots (size_t *old_next_pin_slot, CopyOrMarkFromRootsMode mode, SgenObjectOperations *object_ops)
1668 {
1669         LOSObject *bigobj;
1670         TV_DECLARE (atv);
1671         TV_DECLARE (btv);
1672         /* FIXME: only use these values for the precise scan
1673          * note that to_space pointers should be excluded anyway...
1674          */
1675         char *heap_start = NULL;
1676         char *heap_end = (char*)-1;
1677         ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, WORKERS_DISTRIBUTE_GRAY_QUEUE);
1678         gboolean concurrent = mode != COPY_OR_MARK_FROM_ROOTS_SERIAL;
1679
1680         SGEN_ASSERT (0, !!concurrent == !!concurrent_collection_in_progress, "We've been called with the wrong mode.");
1681
1682         if (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
1683                 /*This cleans up unused fragments */
1684                 sgen_nursery_allocator_prepare_for_pinning ();
1685
1686                 if (do_concurrent_checks)
1687                         sgen_debug_check_nursery_is_clean ();
1688         } else {
1689                 /* The concurrent collector doesn't touch the nursery. */
1690                 sgen_nursery_alloc_prepare_for_major ();
1691         }
1692
1693         init_gray_queue (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT);
1694
1695         TV_GETTIME (atv);
1696
1697         /* Pinning depends on this */
1698         sgen_clear_nursery_fragments ();
1699
1700         if (whole_heap_check_before_collection)
1701                 sgen_check_whole_heap (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT);
1702
1703         TV_GETTIME (btv);
1704         time_major_pre_collection_fragment_clear += TV_ELAPSED (atv, btv);
1705
1706         if (!sgen_collection_is_concurrent ())
1707                 nursery_section->next_data = sgen_get_nursery_end ();
1708         /* we should also coalesce scanning from sections close to each other
1709          * and deal with pointers outside of the sections later.
1710          */
1711
1712         objects_pinned = 0;
1713
1714         sgen_client_pre_collection_checks ();
1715
1716         if (mode != COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
1717                 /* Remsets are not useful for a major collection */
1718                 remset.clear_cards ();
1719         }
1720
1721         sgen_process_fin_stage_entries ();
1722
1723         TV_GETTIME (atv);
1724         sgen_init_pinning ();
1725         SGEN_LOG (6, "Collecting pinned addresses");
1726         pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address, ctx);
1727         if (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT) {
1728                 /* Pin cemented objects that were forced */
1729                 sgen_pin_cemented_objects ();
1730         }
1731         sgen_optimize_pin_queue ();
1732         if (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
1733                 /*
1734                  * Cemented objects that are in the pinned list will be marked. When
1735                  * marking concurrently we won't mark mod-union cards for these objects.
1736                  * Instead they will remain cemented until the next major collection,
1737                  * when we will recheck if they are still pinned in the roots.
1738                  */
1739                 sgen_cement_force_pinned ();
1740         }
1741
1742         sgen_client_collecting_major_1 ();
1743
1744         /*
1745          * pin_queue now contains all candidate pointers, sorted and
1746          * uniqued.  We must do two passes now to figure out which
1747          * objects are pinned.
1748          *
1749          * The first is to find within the pin_queue the area for each
1750          * section.  This requires that the pin_queue be sorted.  We
1751          * also process the LOS objects and pinned chunks here.
1752          *
1753          * The second, destructive, pass is to reduce the section
1754          * areas to pointers to the actually pinned objects.
1755          */
1756         SGEN_LOG (6, "Pinning from sections");
1757         /* first pass for the sections */
1758         sgen_find_section_pin_queue_start_end (nursery_section);
1759         /* identify possible pointers to the insize of large objects */
1760         SGEN_LOG (6, "Pinning from large objects");
1761         for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
1762                 size_t dummy;
1763                 if (sgen_find_optimized_pin_queue_area ((char*)bigobj->data, (char*)bigobj->data + sgen_los_object_size (bigobj), &dummy, &dummy)) {
1764                         binary_protocol_pin (bigobj->data, (gpointer)LOAD_VTABLE (bigobj->data), safe_object_get_size (bigobj->data));
1765
1766                         if (sgen_los_object_is_pinned (bigobj->data)) {
1767                                 SGEN_ASSERT (0, mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT, "LOS objects can only be pinned here after concurrent marking.");
1768                                 continue;
1769                         }
1770                         sgen_los_pin_object (bigobj->data);
1771                         if (SGEN_OBJECT_HAS_REFERENCES (bigobj->data))
1772                                 GRAY_OBJECT_ENQUEUE (WORKERS_DISTRIBUTE_GRAY_QUEUE, bigobj->data, sgen_obj_get_descriptor ((GCObject*)bigobj->data));
1773                         sgen_pin_stats_register_object (bigobj->data, safe_object_get_size (bigobj->data));
1774                         SGEN_LOG (6, "Marked large object %p (%s) size: %lu from roots", bigobj->data,
1775                                         sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (bigobj->data)),
1776                                         (unsigned long)sgen_los_object_size (bigobj));
1777
1778                         sgen_client_pinned_los_object (bigobj->data);
1779                 }
1780         }
1781
1782         pin_objects_in_nursery (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT, ctx);
1783         if (check_nursery_objects_pinned && !sgen_minor_collector.is_split)
1784                 sgen_check_nursery_objects_pinned (mode != COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT);
1785
1786         major_collector.pin_objects (WORKERS_DISTRIBUTE_GRAY_QUEUE);
1787         if (old_next_pin_slot)
1788                 *old_next_pin_slot = sgen_get_pinned_count ();
1789
1790         TV_GETTIME (btv);
1791         time_major_pinning += TV_ELAPSED (atv, btv);
1792         SGEN_LOG (2, "Finding pinned pointers: %zd in %lld usecs", sgen_get_pinned_count (), TV_ELAPSED (atv, btv));
1793         SGEN_LOG (4, "Start scan with %zd pinned objects", sgen_get_pinned_count ());
1794
1795         major_collector.init_to_space ();
1796
1797         SGEN_ASSERT (0, sgen_workers_all_done (), "Why are the workers not done when we start or finish a major collection?");
1798         if (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT) {
1799                 if (sgen_workers_have_idle_work ()) {
1800                         /*
1801                          * We force the finish of the worker with the new object ops context
1802                          * which can also do copying. We need to have finished pinning.
1803                          */
1804                         sgen_workers_start_all_workers (object_ops, NULL);
1805                         sgen_workers_join ();
1806                 }
1807         }
1808
1809 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
1810         main_gc_thread = mono_native_thread_self ();
1811 #endif
1812
1813         sgen_client_collecting_major_2 ();
1814
1815         TV_GETTIME (atv);
1816         time_major_scan_pinned += TV_ELAPSED (btv, atv);
1817
1818         sgen_client_collecting_major_3 (&fin_ready_queue, &critical_fin_queue);
1819
1820         enqueue_scan_from_roots_jobs (heap_start, heap_end, object_ops, FALSE);
1821
1822         TV_GETTIME (btv);
1823         time_major_scan_roots += TV_ELAPSED (atv, btv);
1824
1825         /*
1826          * We start the concurrent worker after pinning and after we scanned the roots
1827          * in order to make sure that the worker does not finish before handling all
1828          * the roots.
1829          */
1830         if (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
1831                 if (precleaning_enabled) {
1832                         ScanJob *sj;
1833                         /* Mod union preclean job */
1834                         sj = (ScanJob*)sgen_thread_pool_job_alloc ("preclean mod union cardtable", job_mod_union_preclean, sizeof (ScanJob));
1835                         sj->ops = object_ops;
1836                         sgen_workers_start_all_workers (object_ops, &sj->job);
1837                 } else {
1838                         sgen_workers_start_all_workers (object_ops, NULL);
1839                 }
1840                 gray_queue_enable_redirect (WORKERS_DISTRIBUTE_GRAY_QUEUE);
1841         }
1842
1843         if (mode == COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT) {
1844                 ScanJob *sj;
1845
1846                 /* Mod union card table */
1847                 sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan mod union cardtable", job_scan_major_mod_union_card_table, sizeof (ScanJob));
1848                 sj->ops = object_ops;
1849                 sgen_workers_enqueue_job (&sj->job, FALSE);
1850
1851                 sj = (ScanJob*)sgen_thread_pool_job_alloc ("scan LOS mod union cardtable", job_scan_los_mod_union_card_table, sizeof (ScanJob));
1852                 sj->ops = object_ops;
1853                 sgen_workers_enqueue_job (&sj->job, FALSE);
1854
1855                 TV_GETTIME (atv);
1856                 time_major_scan_mod_union += TV_ELAPSED (btv, atv);
1857         }
1858
1859         sgen_pin_stats_print_class_stats ();
1860 }
1861
1862 static void
1863 major_finish_copy_or_mark (CopyOrMarkFromRootsMode mode)
1864 {
1865         if (mode == COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT) {
1866                 sgen_finish_pinning ();
1867
1868                 sgen_pin_stats_reset ();
1869
1870                 if (do_concurrent_checks)
1871                         sgen_debug_check_nursery_is_clean ();
1872         }
1873 }
1874
1875 static void
1876 major_start_collection (gboolean concurrent, size_t *old_next_pin_slot)
1877 {
1878         SgenObjectOperations *object_ops;
1879
1880         binary_protocol_collection_begin (gc_stats.major_gc_count, GENERATION_OLD);
1881
1882         current_collection_generation = GENERATION_OLD;
1883
1884         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
1885
1886         if (!concurrent)
1887                 sgen_cement_reset ();
1888
1889         if (concurrent) {
1890                 g_assert (major_collector.is_concurrent);
1891                 concurrent_collection_in_progress = TRUE;
1892
1893                 object_ops = &major_collector.major_ops_concurrent_start;
1894         } else {
1895                 object_ops = &major_collector.major_ops_serial;
1896         }
1897
1898         reset_pinned_from_failed_allocation ();
1899
1900         sgen_memgov_major_collection_start ();
1901
1902         //count_ref_nonref_objs ();
1903         //consistency_check ();
1904
1905         check_scan_starts ();
1906
1907         degraded_mode = 0;
1908         SGEN_LOG (1, "Start major collection %d", gc_stats.major_gc_count);
1909         gc_stats.major_gc_count ++;
1910
1911         if (major_collector.start_major_collection)
1912                 major_collector.start_major_collection ();
1913
1914         major_copy_or_mark_from_roots (old_next_pin_slot, concurrent ? COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT : COPY_OR_MARK_FROM_ROOTS_SERIAL, object_ops);
1915         major_finish_copy_or_mark (concurrent ? COPY_OR_MARK_FROM_ROOTS_START_CONCURRENT : COPY_OR_MARK_FROM_ROOTS_SERIAL);
1916 }
1917
1918 static void
1919 major_finish_collection (const char *reason, size_t old_next_pin_slot, gboolean forced)
1920 {
1921         ScannedObjectCounts counts;
1922         SgenObjectOperations *object_ops;
1923         mword fragment_total;
1924         TV_DECLARE (atv);
1925         TV_DECLARE (btv);
1926
1927         TV_GETTIME (btv);
1928
1929         if (concurrent_collection_in_progress) {
1930                 object_ops = &major_collector.major_ops_concurrent_finish;
1931
1932                 major_copy_or_mark_from_roots (NULL, COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT, object_ops);
1933
1934                 major_finish_copy_or_mark (COPY_OR_MARK_FROM_ROOTS_FINISH_CONCURRENT);
1935
1936 #ifdef SGEN_DEBUG_INTERNAL_ALLOC
1937                 main_gc_thread = NULL;
1938 #endif
1939         } else {
1940                 object_ops = &major_collector.major_ops_serial;
1941         }
1942
1943         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
1944
1945         /* all the objects in the heap */
1946         finish_gray_stack (GENERATION_OLD, CONTEXT_FROM_OBJECT_OPERATIONS (object_ops, &gray_queue));
1947         TV_GETTIME (atv);
1948         time_major_finish_gray_stack += TV_ELAPSED (btv, atv);
1949
1950         SGEN_ASSERT (0, sgen_workers_all_done (), "Can't have workers working after joining");
1951
1952         if (objects_pinned) {
1953                 g_assert (!concurrent_collection_in_progress);
1954
1955                 /*
1956                  * This is slow, but we just OOM'd.
1957                  *
1958                  * See comment at `sgen_pin_queue_clear_discarded_entries` for how the pin
1959                  * queue is laid out at this point.
1960                  */
1961                 sgen_pin_queue_clear_discarded_entries (nursery_section, old_next_pin_slot);
1962                 /*
1963                  * We need to reestablish all pinned nursery objects in the pin queue
1964                  * because they're needed for fragment creation.  Unpinning happens by
1965                  * walking the whole queue, so it's not necessary to reestablish where major
1966                  * heap block pins are - all we care is that they're still in there
1967                  * somewhere.
1968                  */
1969                 sgen_optimize_pin_queue ();
1970                 sgen_find_section_pin_queue_start_end (nursery_section);
1971                 objects_pinned = 0;
1972         }
1973
1974         reset_heap_boundaries ();
1975         sgen_update_heap_boundaries ((mword)sgen_get_nursery_start (), (mword)sgen_get_nursery_end ());
1976
1977         /* walk the pin_queue, build up the fragment list of free memory, unmark
1978          * pinned objects as we go, memzero() the empty fragments so they are ready for the
1979          * next allocations.
1980          */
1981         fragment_total = sgen_build_nursery_fragments (nursery_section, NULL);
1982         if (!fragment_total)
1983                 degraded_mode = 1;
1984         SGEN_LOG (4, "Free space in nursery after major %ld", (long)fragment_total);
1985
1986         if (do_concurrent_checks && concurrent_collection_in_progress)
1987                 sgen_debug_check_nursery_is_clean ();
1988
1989         /* prepare the pin queue for the next collection */
1990         sgen_finish_pinning ();
1991
1992         /* Clear TLABs for all threads */
1993         sgen_clear_tlabs ();
1994
1995         sgen_pin_stats_reset ();
1996
1997         sgen_cement_clear_below_threshold ();
1998
1999         if (check_mark_bits_after_major_collection)
2000                 sgen_check_heap_marked (concurrent_collection_in_progress);
2001
2002         TV_GETTIME (btv);
2003         time_major_fragment_creation += TV_ELAPSED (atv, btv);
2004
2005         binary_protocol_sweep_begin (GENERATION_OLD, !major_collector.sweeps_lazily);
2006         sgen_memgov_major_pre_sweep ();
2007
2008         TV_GETTIME (atv);
2009         time_major_free_bigobjs += TV_ELAPSED (btv, atv);
2010
2011         sgen_los_sweep ();
2012
2013         TV_GETTIME (btv);
2014         time_major_los_sweep += TV_ELAPSED (atv, btv);
2015
2016         major_collector.sweep ();
2017
2018         binary_protocol_sweep_end (GENERATION_OLD, !major_collector.sweeps_lazily);
2019
2020         TV_GETTIME (atv);
2021         time_major_sweep += TV_ELAPSED (btv, atv);
2022
2023         sgen_debug_dump_heap ("major", gc_stats.major_gc_count - 1, reason);
2024
2025         if (sgen_have_pending_finalizers ()) {
2026                 SGEN_LOG (4, "Finalizer-thread wakeup");
2027                 sgen_client_finalize_notify ();
2028         }
2029
2030         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2031
2032         sgen_memgov_major_collection_end (forced);
2033         current_collection_generation = -1;
2034
2035         memset (&counts, 0, sizeof (ScannedObjectCounts));
2036         major_collector.finish_major_collection (&counts);
2037
2038         g_assert (sgen_section_gray_queue_is_empty (sgen_workers_get_distribute_section_gray_queue ()));
2039
2040         SGEN_ASSERT (0, sgen_workers_all_done (), "Can't have workers working after major collection has finished");
2041         if (concurrent_collection_in_progress)
2042                 concurrent_collection_in_progress = FALSE;
2043
2044         check_scan_starts ();
2045
2046         binary_protocol_flush_buffers (FALSE);
2047
2048         //consistency_check ();
2049
2050         binary_protocol_collection_end (gc_stats.major_gc_count - 1, GENERATION_OLD, counts.num_scanned_objects, counts.num_unique_scanned_objects);
2051 }
2052
2053 static gboolean
2054 major_do_collection (const char *reason, gboolean forced)
2055 {
2056         TV_DECLARE (time_start);
2057         TV_DECLARE (time_end);
2058         size_t old_next_pin_slot;
2059
2060         if (disable_major_collections)
2061                 return FALSE;
2062
2063         if (major_collector.get_and_reset_num_major_objects_marked) {
2064                 long long num_marked = major_collector.get_and_reset_num_major_objects_marked ();
2065                 g_assert (!num_marked);
2066         }
2067
2068         /* world must be stopped already */
2069         TV_GETTIME (time_start);
2070
2071         major_start_collection (FALSE, &old_next_pin_slot);
2072         major_finish_collection (reason, old_next_pin_slot, forced);
2073
2074         TV_GETTIME (time_end);
2075         gc_stats.major_gc_time += TV_ELAPSED (time_start, time_end);
2076
2077         /* FIXME: also report this to the user, preferably in gc-end. */
2078         if (major_collector.get_and_reset_num_major_objects_marked)
2079                 major_collector.get_and_reset_num_major_objects_marked ();
2080
2081         return bytes_pinned_from_failed_allocation > 0;
2082 }
2083
2084 static void
2085 major_start_concurrent_collection (const char *reason)
2086 {
2087         TV_DECLARE (time_start);
2088         TV_DECLARE (time_end);
2089         long long num_objects_marked;
2090
2091         if (disable_major_collections)
2092                 return;
2093
2094         TV_GETTIME (time_start);
2095         SGEN_TV_GETTIME (time_major_conc_collection_start);
2096
2097         num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
2098         g_assert (num_objects_marked == 0);
2099
2100         binary_protocol_concurrent_start ();
2101
2102         // FIXME: store reason and pass it when finishing
2103         major_start_collection (TRUE, NULL);
2104
2105         gray_queue_redirect (&gray_queue);
2106
2107         num_objects_marked = major_collector.get_and_reset_num_major_objects_marked ();
2108
2109         TV_GETTIME (time_end);
2110         gc_stats.major_gc_time += TV_ELAPSED (time_start, time_end);
2111
2112         current_collection_generation = -1;
2113 }
2114
2115 /*
2116  * Returns whether the major collection has finished.
2117  */
2118 static gboolean
2119 major_should_finish_concurrent_collection (void)
2120 {
2121         SGEN_ASSERT (0, sgen_gray_object_queue_is_empty (&gray_queue), "Why is the gray queue not empty before we have started doing anything?");
2122         return sgen_workers_all_done ();
2123 }
2124
2125 static void
2126 major_update_concurrent_collection (void)
2127 {
2128         TV_DECLARE (total_start);
2129         TV_DECLARE (total_end);
2130
2131         TV_GETTIME (total_start);
2132
2133         binary_protocol_concurrent_update ();
2134
2135         major_collector.update_cardtable_mod_union ();
2136         sgen_los_update_cardtable_mod_union ();
2137
2138         TV_GETTIME (total_end);
2139         gc_stats.major_gc_time += TV_ELAPSED (total_start, total_end);
2140 }
2141
2142 static void
2143 major_finish_concurrent_collection (gboolean forced)
2144 {
2145         TV_DECLARE (total_start);
2146         TV_DECLARE (total_end);
2147
2148         TV_GETTIME (total_start);
2149
2150         binary_protocol_concurrent_finish ();
2151
2152         /*
2153          * We need to stop all workers since we're updating the cardtable below.
2154          * The workers will be resumed with a finishing pause context to avoid
2155          * additional cardtable and object scanning.
2156          */
2157         sgen_workers_stop_all_workers ();
2158
2159         SGEN_TV_GETTIME (time_major_conc_collection_end);
2160         gc_stats.major_gc_time_concurrent += SGEN_TV_ELAPSED (time_major_conc_collection_start, time_major_conc_collection_end);
2161
2162         major_collector.update_cardtable_mod_union ();
2163         sgen_los_update_cardtable_mod_union ();
2164
2165         if (mod_union_consistency_check)
2166                 sgen_check_mod_union_consistency ();
2167
2168         current_collection_generation = GENERATION_OLD;
2169         sgen_cement_reset ();
2170         major_finish_collection ("finishing", -1, forced);
2171
2172         if (whole_heap_check_before_collection)
2173                 sgen_check_whole_heap (FALSE);
2174
2175         TV_GETTIME (total_end);
2176         gc_stats.major_gc_time += TV_ELAPSED (total_start, total_end) - TV_ELAPSED (last_minor_collection_start_tv, last_minor_collection_end_tv);
2177
2178         current_collection_generation = -1;
2179 }
2180
2181 /*
2182  * Ensure an allocation request for @size will succeed by freeing enough memory.
2183  *
2184  * LOCKING: The GC lock MUST be held.
2185  */
2186 void
2187 sgen_ensure_free_space (size_t size, int generation)
2188 {
2189         int generation_to_collect = -1;
2190         const char *reason = NULL;
2191
2192         if (generation == GENERATION_OLD) {
2193                 if (sgen_need_major_collection (size)) {
2194                         reason = "LOS overflow";
2195                         generation_to_collect = GENERATION_OLD;
2196                 }
2197         } else {
2198                 if (degraded_mode) {
2199                         if (sgen_need_major_collection (size)) {
2200                                 reason = "Degraded mode overflow";
2201                                 generation_to_collect = GENERATION_OLD;
2202                         }
2203                 } else if (sgen_need_major_collection (size)) {
2204                         reason = concurrent_collection_in_progress ? "Forced finish concurrent collection" : "Minor allowance";
2205                         generation_to_collect = GENERATION_OLD;
2206                 } else {
2207                         generation_to_collect = GENERATION_NURSERY;
2208                         reason = "Nursery full";                        
2209                 }
2210         }
2211
2212         if (generation_to_collect == -1) {
2213                 if (concurrent_collection_in_progress && sgen_workers_all_done ()) {
2214                         generation_to_collect = GENERATION_OLD;
2215                         reason = "Finish concurrent collection";
2216                 }
2217         }
2218
2219         if (generation_to_collect == -1)
2220                 return;
2221         sgen_perform_collection (size, generation_to_collect, reason, FALSE);
2222 }
2223
2224 /*
2225  * LOCKING: Assumes the GC lock is held.
2226  */
2227 void
2228 sgen_perform_collection (size_t requested_size, int generation_to_collect, const char *reason, gboolean wait_to_finish)
2229 {
2230         TV_DECLARE (gc_start);
2231         TV_DECLARE (gc_end);
2232         TV_DECLARE (gc_total_start);
2233         TV_DECLARE (gc_total_end);
2234         GGTimingInfo infos [2];
2235         int overflow_generation_to_collect = -1;
2236         int oldest_generation_collected = generation_to_collect;
2237         const char *overflow_reason = NULL;
2238
2239         binary_protocol_collection_requested (generation_to_collect, requested_size, wait_to_finish ? 1 : 0);
2240
2241         SGEN_ASSERT (0, generation_to_collect == GENERATION_NURSERY || generation_to_collect == GENERATION_OLD, "What generation is this?");
2242
2243         TV_GETTIME (gc_start);
2244
2245         sgen_stop_world (generation_to_collect);
2246
2247         TV_GETTIME (gc_total_start);
2248
2249         if (concurrent_collection_in_progress) {
2250                 /*
2251                  * If the concurrent worker is finished or we are asked to do a major collection
2252                  * then we finish the concurrent collection.
2253                  */
2254                 gboolean finish = major_should_finish_concurrent_collection () || generation_to_collect == GENERATION_OLD;
2255
2256                 if (finish) {
2257                         major_finish_concurrent_collection (wait_to_finish);
2258                         oldest_generation_collected = GENERATION_OLD;
2259                 } else {
2260                         SGEN_ASSERT (0, generation_to_collect == GENERATION_NURSERY, "Why aren't we finishing the concurrent collection?");
2261                         major_update_concurrent_collection ();
2262                         collect_nursery (NULL, FALSE);
2263                 }
2264
2265                 goto done;
2266         }
2267
2268         SGEN_ASSERT (0, !concurrent_collection_in_progress, "Why did this not get handled above?");
2269
2270         /*
2271          * There's no concurrent collection in progress.  Collect the generation we're asked
2272          * to collect.  If the major collector is concurrent and we're not forced to wait,
2273          * start a concurrent collection.
2274          */
2275         // FIXME: extract overflow reason
2276         if (generation_to_collect == GENERATION_NURSERY) {
2277                 if (collect_nursery (NULL, FALSE)) {
2278                         overflow_generation_to_collect = GENERATION_OLD;
2279                         overflow_reason = "Minor overflow";
2280                 }
2281         } else {
2282                 if (major_collector.is_concurrent && !wait_to_finish) {
2283                         collect_nursery (NULL, FALSE);
2284                         major_start_concurrent_collection (reason);
2285                         // FIXME: set infos[0] properly
2286                         goto done;
2287                 }
2288
2289                 if (major_do_collection (reason, wait_to_finish)) {
2290                         overflow_generation_to_collect = GENERATION_NURSERY;
2291                         overflow_reason = "Excessive pinning";
2292                 }
2293         }
2294
2295         TV_GETTIME (gc_end);
2296
2297         memset (infos, 0, sizeof (infos));
2298         infos [0].generation = generation_to_collect;
2299         infos [0].reason = reason;
2300         infos [0].is_overflow = FALSE;
2301         infos [1].generation = -1;
2302         infos [0].total_time = SGEN_TV_ELAPSED (gc_start, gc_end);
2303
2304         SGEN_ASSERT (0, !concurrent_collection_in_progress, "Why did this not get handled above?");
2305
2306         if (overflow_generation_to_collect != -1) {
2307                 /*
2308                  * We need to do an overflow collection, either because we ran out of memory
2309                  * or the nursery is fully pinned.
2310                  */
2311
2312                 infos [1].generation = overflow_generation_to_collect;
2313                 infos [1].reason = overflow_reason;
2314                 infos [1].is_overflow = TRUE;
2315                 gc_start = gc_end;
2316
2317                 if (overflow_generation_to_collect == GENERATION_NURSERY)
2318                         collect_nursery (NULL, FALSE);
2319                 else
2320                         major_do_collection (overflow_reason, wait_to_finish);
2321
2322                 TV_GETTIME (gc_end);
2323                 infos [1].total_time = SGEN_TV_ELAPSED (gc_start, gc_end);
2324
2325                 oldest_generation_collected = MAX (oldest_generation_collected, overflow_generation_to_collect);
2326         }
2327
2328         SGEN_LOG (2, "Heap size: %lu, LOS size: %lu", (unsigned long)sgen_gc_get_total_heap_allocation (), (unsigned long)los_memory_usage);
2329
2330         /* this also sets the proper pointers for the next allocation */
2331         if (generation_to_collect == GENERATION_NURSERY && !sgen_can_alloc_size (requested_size)) {
2332                 /* TypeBuilder and MonoMethod are killing mcs with fragmentation */
2333                 SGEN_LOG (1, "nursery collection didn't find enough room for %zd alloc (%zd pinned)", requested_size, sgen_get_pinned_count ());
2334                 sgen_dump_pin_queue ();
2335                 degraded_mode = 1;
2336         }
2337
2338  done:
2339         g_assert (sgen_gray_object_queue_is_empty (&gray_queue));
2340
2341         TV_GETTIME (gc_total_end);
2342         time_max = MAX (time_max, TV_ELAPSED (gc_total_start, gc_total_end));
2343
2344         sgen_restart_world (oldest_generation_collected, infos);
2345 }
2346
2347 /*
2348  * ######################################################################
2349  * ########  Memory allocation from the OS
2350  * ######################################################################
2351  * This section of code deals with getting memory from the OS and
2352  * allocating memory for GC-internal data structures.
2353  * Internal memory can be handled with a freelist for small objects.
2354  */
2355
2356 /*
2357  * Debug reporting.
2358  */
2359 G_GNUC_UNUSED static void
2360 report_internal_mem_usage (void)
2361 {
2362         printf ("Internal memory usage:\n");
2363         sgen_report_internal_mem_usage ();
2364         printf ("Pinned memory usage:\n");
2365         major_collector.report_pinned_memory_usage ();
2366 }
2367
2368 /*
2369  * ######################################################################
2370  * ########  Finalization support
2371  * ######################################################################
2372  */
2373
2374 /*
2375  * If the object has been forwarded it means it's still referenced from a root. 
2376  * If it is pinned it's still alive as well.
2377  * A LOS object is only alive if we have pinned it.
2378  * Return TRUE if @obj is ready to be finalized.
2379  */
2380 static inline gboolean
2381 sgen_is_object_alive (GCObject *object)
2382 {
2383         if (ptr_in_nursery (object))
2384                 return sgen_nursery_is_object_alive (object);
2385
2386         return sgen_major_is_object_alive (object);
2387 }
2388
2389 /*
2390  * This function returns true if @object is either alive and belongs to the
2391  * current collection - major collections are full heap, so old gen objects
2392  * are never alive during a minor collection.
2393  */
2394 static inline int
2395 sgen_is_object_alive_and_on_current_collection (GCObject *object)
2396 {
2397         if (ptr_in_nursery (object))
2398                 return sgen_nursery_is_object_alive (object);
2399
2400         if (current_collection_generation == GENERATION_NURSERY)
2401                 return FALSE;
2402
2403         return sgen_major_is_object_alive (object);
2404 }
2405
2406
2407 gboolean
2408 sgen_gc_is_object_ready_for_finalization (GCObject *object)
2409 {
2410         return !sgen_is_object_alive (object);
2411 }
2412
2413 void
2414 sgen_queue_finalization_entry (GCObject *obj)
2415 {
2416         gboolean critical = sgen_client_object_has_critical_finalizer (obj);
2417
2418         sgen_pointer_queue_add (critical ? &critical_fin_queue : &fin_ready_queue, obj);
2419
2420         sgen_client_object_queued_for_finalization (obj);
2421 }
2422
2423 gboolean
2424 sgen_object_is_live (GCObject *obj)
2425 {
2426         return sgen_is_object_alive_and_on_current_collection (obj);
2427 }
2428
2429 /*
2430  * `System.GC.WaitForPendingFinalizers` first checks `sgen_have_pending_finalizers()` to
2431  * determine whether it can exit quickly.  The latter must therefore only return FALSE if
2432  * all finalizers have really finished running.
2433  *
2434  * `sgen_gc_invoke_finalizers()` first dequeues a finalizable object, and then finalizes it.
2435  * This means that just checking whether the queues are empty leaves the possibility that an
2436  * object might have been dequeued but not yet finalized.  That's why we need the additional
2437  * flag `pending_unqueued_finalizer`.
2438  */
2439
2440 static volatile gboolean pending_unqueued_finalizer = FALSE;
2441
2442 int
2443 sgen_gc_invoke_finalizers (void)
2444 {
2445         int count = 0;
2446
2447         g_assert (!pending_unqueued_finalizer);
2448
2449         /* FIXME: batch to reduce lock contention */
2450         while (sgen_have_pending_finalizers ()) {
2451                 GCObject *obj;
2452
2453                 LOCK_GC;
2454
2455                 /*
2456                  * We need to set `pending_unqueued_finalizer` before dequeing the
2457                  * finalizable object.
2458                  */
2459                 if (!sgen_pointer_queue_is_empty (&fin_ready_queue)) {
2460                         pending_unqueued_finalizer = TRUE;
2461                         mono_memory_write_barrier ();
2462                         obj = (GCObject *)sgen_pointer_queue_pop (&fin_ready_queue);
2463                 } else if (!sgen_pointer_queue_is_empty (&critical_fin_queue)) {
2464                         pending_unqueued_finalizer = TRUE;
2465                         mono_memory_write_barrier ();
2466                         obj = (GCObject *)sgen_pointer_queue_pop (&critical_fin_queue);
2467                 } else {
2468                         obj = NULL;
2469                 }
2470
2471                 if (obj)
2472                         SGEN_LOG (7, "Finalizing object %p (%s)", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
2473
2474                 UNLOCK_GC;
2475
2476                 if (!obj)
2477                         break;
2478
2479                 count++;
2480                 /* the object is on the stack so it is pinned */
2481                 /*g_print ("Calling finalizer for object: %p (%s)\n", obj, sgen_client_object_safe_name (obj));*/
2482                 sgen_client_run_finalize (obj);
2483         }
2484
2485         if (pending_unqueued_finalizer) {
2486                 mono_memory_write_barrier ();
2487                 pending_unqueued_finalizer = FALSE;
2488         }
2489
2490         return count;
2491 }
2492
2493 gboolean
2494 sgen_have_pending_finalizers (void)
2495 {
2496         return pending_unqueued_finalizer || !sgen_pointer_queue_is_empty (&fin_ready_queue) || !sgen_pointer_queue_is_empty (&critical_fin_queue);
2497 }
2498
2499 /*
2500  * ######################################################################
2501  * ########  registered roots support
2502  * ######################################################################
2503  */
2504
2505 /*
2506  * We do not coalesce roots.
2507  */
2508 int
2509 sgen_register_root (char *start, size_t size, SgenDescriptor descr, int root_type, int source, const char *msg)
2510 {
2511         RootRecord new_root;
2512         int i;
2513         LOCK_GC;
2514         for (i = 0; i < ROOT_TYPE_NUM; ++i) {
2515                 RootRecord *root = (RootRecord *)sgen_hash_table_lookup (&roots_hash [i], start);
2516                 /* we allow changing the size and the descriptor (for thread statics etc) */
2517                 if (root) {
2518                         size_t old_size = root->end_root - start;
2519                         root->end_root = start + size;
2520                         SGEN_ASSERT (0, !!root->root_desc == !!descr, "Can't change whether a root is precise or conservative.");
2521                         SGEN_ASSERT (0, root->source == source, "Can't change a root's source identifier.");
2522                         SGEN_ASSERT (0, !!root->msg == !!msg, "Can't change a root's message.");
2523                         root->root_desc = descr;
2524                         roots_size += size;
2525                         roots_size -= old_size;
2526                         UNLOCK_GC;
2527                         return TRUE;
2528                 }
2529         }
2530
2531         new_root.end_root = start + size;
2532         new_root.root_desc = descr;
2533         new_root.source = source;
2534         new_root.msg = msg;
2535
2536         sgen_hash_table_replace (&roots_hash [root_type], start, &new_root, NULL);
2537         roots_size += size;
2538
2539         SGEN_LOG (3, "Added root for range: %p-%p, descr: %llx  (%d/%d bytes)", start, new_root.end_root, (long long)descr, (int)size, (int)roots_size);
2540
2541         UNLOCK_GC;
2542         return TRUE;
2543 }
2544
2545 void
2546 sgen_deregister_root (char* addr)
2547 {
2548         int root_type;
2549         RootRecord root;
2550
2551         LOCK_GC;
2552         for (root_type = 0; root_type < ROOT_TYPE_NUM; ++root_type) {
2553                 if (sgen_hash_table_remove (&roots_hash [root_type], addr, &root))
2554                         roots_size -= (root.end_root - addr);
2555         }
2556         UNLOCK_GC;
2557 }
2558
2559 /*
2560  * ######################################################################
2561  * ########  Thread handling (stop/start code)
2562  * ######################################################################
2563  */
2564
2565 int
2566 sgen_get_current_collection_generation (void)
2567 {
2568         return current_collection_generation;
2569 }
2570
2571 void*
2572 sgen_thread_register (SgenThreadInfo* info, void *stack_bottom_fallback)
2573 {
2574 #ifndef HAVE_KW_THREAD
2575         info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
2576 #endif
2577
2578         sgen_init_tlab_info (info);
2579
2580         sgen_client_thread_register (info, stack_bottom_fallback);
2581
2582         return info;
2583 }
2584
2585 void
2586 sgen_thread_unregister (SgenThreadInfo *p)
2587 {
2588         sgen_client_thread_unregister (p);
2589 }
2590
2591 /*
2592  * ######################################################################
2593  * ########  Write barriers
2594  * ######################################################################
2595  */
2596
2597 /*
2598  * Note: the write barriers first do the needed GC work and then do the actual store:
2599  * this way the value is visible to the conservative GC scan after the write barrier
2600  * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
2601  * the conservative scan, otherwise by the remembered set scan.
2602  */
2603
2604 void
2605 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
2606 {
2607         HEAVY_STAT (++stat_wbarrier_arrayref_copy);
2608         /*This check can be done without taking a lock since dest_ptr array is pinned*/
2609         if (ptr_in_nursery (dest_ptr) || count <= 0) {
2610                 mono_gc_memmove_aligned (dest_ptr, src_ptr, count * sizeof (gpointer));
2611                 return;
2612         }
2613
2614 #ifdef SGEN_HEAVY_BINARY_PROTOCOL
2615         if (binary_protocol_is_heavy_enabled ()) {
2616                 int i;
2617                 for (i = 0; i < count; ++i) {
2618                         gpointer dest = (gpointer*)dest_ptr + i;
2619                         gpointer obj = *((gpointer*)src_ptr + i);
2620                         if (obj)
2621                                 binary_protocol_wbarrier (dest, obj, (gpointer)LOAD_VTABLE (obj));
2622                 }
2623         }
2624 #endif
2625
2626         remset.wbarrier_arrayref_copy (dest_ptr, src_ptr, count);
2627 }
2628
2629 void
2630 mono_gc_wbarrier_generic_nostore (gpointer ptr)
2631 {
2632         gpointer obj;
2633
2634         HEAVY_STAT (++stat_wbarrier_generic_store);
2635
2636         sgen_client_wbarrier_generic_nostore_check (ptr);
2637
2638         obj = *(gpointer*)ptr;
2639         if (obj)
2640                 binary_protocol_wbarrier (ptr, obj, (gpointer)LOAD_VTABLE (obj));
2641
2642         /*
2643          * We need to record old->old pointer locations for the
2644          * concurrent collector.
2645          */
2646         if (!ptr_in_nursery (obj) && !concurrent_collection_in_progress) {
2647                 SGEN_LOG (8, "Skipping remset at %p", ptr);
2648                 return;
2649         }
2650
2651         SGEN_LOG (8, "Adding remset at %p", ptr);
2652
2653         remset.wbarrier_generic_nostore (ptr);
2654 }
2655
2656 void
2657 mono_gc_wbarrier_generic_store (gpointer ptr, GCObject* value)
2658 {
2659         SGEN_LOG (8, "Wbarrier store at %p to %p (%s)", ptr, value, value ? sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (value)) : "null");
2660         SGEN_UPDATE_REFERENCE_ALLOW_NULL (ptr, value);
2661         if (ptr_in_nursery (value) || concurrent_collection_in_progress)
2662                 mono_gc_wbarrier_generic_nostore (ptr);
2663         sgen_dummy_use (value);
2664 }
2665
2666 /* Same as mono_gc_wbarrier_generic_store () but performs the store
2667  * as an atomic operation with release semantics.
2668  */
2669 void
2670 mono_gc_wbarrier_generic_store_atomic (gpointer ptr, GCObject *value)
2671 {
2672         HEAVY_STAT (++stat_wbarrier_generic_store_atomic);
2673
2674         SGEN_LOG (8, "Wbarrier atomic store at %p to %p (%s)", ptr, value, value ? sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (value)) : "null");
2675
2676         InterlockedWritePointer ((volatile gpointer *)ptr, value);
2677
2678         if (ptr_in_nursery (value) || concurrent_collection_in_progress)
2679                 mono_gc_wbarrier_generic_nostore (ptr);
2680
2681         sgen_dummy_use (value);
2682 }
2683
2684 void
2685 sgen_wbarrier_value_copy_bitmap (gpointer _dest, gpointer _src, int size, unsigned bitmap)
2686 {
2687         GCObject **dest = (GCObject **)_dest;
2688         GCObject **src = (GCObject **)_src;
2689
2690         while (size) {
2691                 if (bitmap & 0x1)
2692                         mono_gc_wbarrier_generic_store (dest, *src);
2693                 else
2694                         *dest = *src;
2695                 ++src;
2696                 ++dest;
2697                 size -= SIZEOF_VOID_P;
2698                 bitmap >>= 1;
2699         }
2700 }
2701
2702 /*
2703  * ######################################################################
2704  * ########  Other mono public interface functions.
2705  * ######################################################################
2706  */
2707
2708 void
2709 sgen_gc_collect (int generation)
2710 {
2711         LOCK_GC;
2712         if (generation > 1)
2713                 generation = 1;
2714         sgen_perform_collection (0, generation, "user request", TRUE);
2715         UNLOCK_GC;
2716 }
2717
2718 int
2719 sgen_gc_collection_count (int generation)
2720 {
2721         if (generation == 0)
2722                 return gc_stats.minor_gc_count;
2723         return gc_stats.major_gc_count;
2724 }
2725
2726 size_t
2727 sgen_gc_get_used_size (void)
2728 {
2729         gint64 tot = 0;
2730         LOCK_GC;
2731         tot = los_memory_usage;
2732         tot += nursery_section->next_data - nursery_section->data;
2733         tot += major_collector.get_used_size ();
2734         /* FIXME: account for pinned objects */
2735         UNLOCK_GC;
2736         return tot;
2737 }
2738
2739 void
2740 sgen_env_var_error (const char *env_var, const char *fallback, const char *description_format, ...)
2741 {
2742         va_list ap;
2743
2744         va_start (ap, description_format);
2745
2746         fprintf (stderr, "Warning: In environment variable `%s': ", env_var);
2747         vfprintf (stderr, description_format, ap);
2748         if (fallback)
2749                 fprintf (stderr, " - %s", fallback);
2750         fprintf (stderr, "\n");
2751
2752         va_end (ap);
2753 }
2754
2755 static gboolean
2756 parse_double_in_interval (const char *env_var, const char *opt_name, const char *opt, double min, double max, double *result)
2757 {
2758         char *endptr;
2759         double val = strtod (opt, &endptr);
2760         if (endptr == opt) {
2761                 sgen_env_var_error (env_var, "Using default value.", "`%s` must be a number.", opt_name);
2762                 return FALSE;
2763         }
2764         else if (val < min || val > max) {
2765                 sgen_env_var_error (env_var, "Using default value.", "`%s` must be between %.2f - %.2f.", opt_name, min, max);
2766                 return FALSE;
2767         }
2768         *result = val;
2769         return TRUE;
2770 }
2771
2772 void
2773 sgen_gc_init (void)
2774 {
2775         const char *env;
2776         char **opts, **ptr;
2777         char *major_collector_opt = NULL;
2778         char *minor_collector_opt = NULL;
2779         size_t max_heap = 0;
2780         size_t soft_limit = 0;
2781         int result;
2782         gboolean debug_print_allowance = FALSE;
2783         double allowance_ratio = 0, save_target = 0;
2784         gboolean cement_enabled = TRUE;
2785
2786         do {
2787                 result = InterlockedCompareExchange (&gc_initialized, -1, 0);
2788                 switch (result) {
2789                 case 1:
2790                         /* already inited */
2791                         return;
2792                 case -1:
2793                         /* being inited by another thread */
2794                         mono_thread_info_usleep (1000);
2795                         break;
2796                 case 0:
2797                         /* we will init it */
2798                         break;
2799                 default:
2800                         g_assert_not_reached ();
2801                 }
2802         } while (result != 0);
2803
2804         SGEN_TV_GETTIME (sgen_init_timestamp);
2805
2806 #ifdef SGEN_WITHOUT_MONO
2807         mono_thread_smr_init ();
2808 #endif
2809
2810         mono_coop_mutex_init (&gc_mutex);
2811
2812         gc_debug_file = stderr;
2813
2814         mono_coop_mutex_init (&sgen_interruption_mutex);
2815
2816         if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
2817                 opts = g_strsplit (env, ",", -1);
2818                 for (ptr = opts; *ptr; ++ptr) {
2819                         char *opt = *ptr;
2820                         if (g_str_has_prefix (opt, "major=")) {
2821                                 opt = strchr (opt, '=') + 1;
2822                                 major_collector_opt = g_strdup (opt);
2823                         } else if (g_str_has_prefix (opt, "minor=")) {
2824                                 opt = strchr (opt, '=') + 1;
2825                                 minor_collector_opt = g_strdup (opt);
2826                         }
2827                 }
2828         } else {
2829                 opts = NULL;
2830         }
2831
2832         init_stats ();
2833         sgen_init_internal_allocator ();
2834         sgen_init_nursery_allocator ();
2835         sgen_init_fin_weak_hash ();
2836         sgen_init_hash_table ();
2837         sgen_init_descriptors ();
2838         sgen_init_gray_queues ();
2839         sgen_init_allocator ();
2840         sgen_init_gchandles ();
2841
2842         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_SECTION, SGEN_SIZEOF_GC_MEM_SECTION);
2843         sgen_register_fixed_internal_mem_type (INTERNAL_MEM_GRAY_QUEUE, sizeof (GrayQueueSection));
2844
2845         sgen_client_init ();
2846
2847         if (!minor_collector_opt) {
2848                 sgen_simple_nursery_init (&sgen_minor_collector);
2849         } else {
2850                 if (!strcmp (minor_collector_opt, "simple")) {
2851                 use_simple_nursery:
2852                         sgen_simple_nursery_init (&sgen_minor_collector);
2853                 } else if (!strcmp (minor_collector_opt, "split")) {
2854                         sgen_split_nursery_init (&sgen_minor_collector);
2855                 } else {
2856                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `simple` instead.", "Unknown minor collector `%s'.", minor_collector_opt);
2857                         goto use_simple_nursery;
2858                 }
2859         }
2860
2861         if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep")) {
2862         use_marksweep_major:
2863                 sgen_marksweep_init (&major_collector);
2864         } else if (!major_collector_opt || !strcmp (major_collector_opt, "marksweep-conc")) {
2865                 sgen_marksweep_conc_init (&major_collector);
2866         } else {
2867                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using `marksweep` instead.", "Unknown major collector `%s'.", major_collector_opt);
2868                 goto use_marksweep_major;
2869         }
2870
2871         sgen_nursery_size = DEFAULT_NURSERY_SIZE;
2872
2873         if (opts) {
2874                 gboolean usage_printed = FALSE;
2875
2876                 for (ptr = opts; *ptr; ++ptr) {
2877                         char *opt = *ptr;
2878                         if (!strcmp (opt, ""))
2879                                 continue;
2880                         if (g_str_has_prefix (opt, "major="))
2881                                 continue;
2882                         if (g_str_has_prefix (opt, "minor="))
2883                                 continue;
2884                         if (g_str_has_prefix (opt, "max-heap-size=")) {
2885                                 size_t page_size = mono_pagesize ();
2886                                 size_t max_heap_candidate = 0;
2887                                 opt = strchr (opt, '=') + 1;
2888                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap_candidate)) {
2889                                         max_heap = (max_heap_candidate + page_size - 1) & ~(size_t)(page_size - 1);
2890                                         if (max_heap != max_heap_candidate)
2891                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Rounding up.", "`max-heap-size` size must be a multiple of %d.", page_size);
2892                                 } else {
2893                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`max-heap-size` must be an integer.");
2894                                 }
2895                                 continue;
2896                         }
2897                         if (g_str_has_prefix (opt, "soft-heap-limit=")) {
2898                                 opt = strchr (opt, '=') + 1;
2899                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &soft_limit)) {
2900                                         if (soft_limit <= 0) {
2901                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be positive.");
2902                                                 soft_limit = 0;
2903                                         }
2904                                 } else {
2905                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, NULL, "`soft-heap-limit` must be an integer.");
2906                                 }
2907                                 continue;
2908                         }
2909
2910 #ifdef USER_CONFIG
2911                         if (g_str_has_prefix (opt, "nursery-size=")) {
2912                                 size_t val;
2913                                 opt = strchr (opt, '=') + 1;
2914                                 if (*opt && mono_gc_parse_environment_string_extract_number (opt, &val)) {
2915                                         if ((val & (val - 1))) {
2916                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be a power of two.");
2917                                                 continue;
2918                                         }
2919
2920                                         if (val < SGEN_MAX_NURSERY_WASTE) {
2921                                                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.",
2922                                                                 "`nursery-size` must be at least %d bytes.", SGEN_MAX_NURSERY_WASTE);
2923                                                 continue;
2924                                         }
2925
2926                                         sgen_nursery_size = val;
2927                                         sgen_nursery_bits = 0;
2928                                         while (ONE_P << (++ sgen_nursery_bits) != sgen_nursery_size)
2929                                                 ;
2930                                 } else {
2931                                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Using default value.", "`nursery-size` must be an integer.");
2932                                         continue;
2933                                 }
2934                                 continue;
2935                         }
2936 #endif
2937                         if (g_str_has_prefix (opt, "save-target-ratio=")) {
2938                                 double val;
2939                                 opt = strchr (opt, '=') + 1;
2940                                 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "save-target-ratio", opt,
2941                                                 SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO, &val)) {
2942                                         save_target = val;
2943                                 }
2944                                 continue;
2945                         }
2946                         if (g_str_has_prefix (opt, "default-allowance-ratio=")) {
2947                                 double val;
2948                                 opt = strchr (opt, '=') + 1;
2949                                 if (parse_double_in_interval (MONO_GC_PARAMS_NAME, "default-allowance-ratio", opt,
2950                                                 SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, SGEN_MIN_ALLOWANCE_NURSERY_SIZE_RATIO, &val)) {
2951                                         allowance_ratio = val;
2952                                 }
2953                                 continue;
2954                         }
2955
2956                         if (!strcmp (opt, "cementing")) {
2957                                 cement_enabled = TRUE;
2958                                 continue;
2959                         }
2960                         if (!strcmp (opt, "no-cementing")) {
2961                                 cement_enabled = FALSE;
2962                                 continue;
2963                         }
2964
2965                         if (!strcmp (opt, "precleaning")) {
2966                                 precleaning_enabled = TRUE;
2967                                 continue;
2968                         }
2969                         if (!strcmp (opt, "no-precleaning")) {
2970                                 precleaning_enabled = FALSE;
2971                                 continue;
2972                         }
2973
2974                         if (major_collector.handle_gc_param && major_collector.handle_gc_param (opt))
2975                                 continue;
2976
2977                         if (sgen_minor_collector.handle_gc_param && sgen_minor_collector.handle_gc_param (opt))
2978                                 continue;
2979
2980                         if (sgen_client_handle_gc_param (opt))
2981                                 continue;
2982
2983                         sgen_env_var_error (MONO_GC_PARAMS_NAME, "Ignoring.", "Unknown option `%s`.", opt);
2984
2985                         if (usage_printed)
2986                                 continue;
2987
2988                         fprintf (stderr, "\n%s must be a comma-delimited list of one or more of the following:\n", MONO_GC_PARAMS_NAME);
2989                         fprintf (stderr, "  max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
2990                         fprintf (stderr, "  soft-heap-limit=n (where N is an integer, possibly with a k, m or a g suffix)\n");
2991                         fprintf (stderr, "  nursery-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
2992                         fprintf (stderr, "  major=COLLECTOR (where COLLECTOR is `marksweep', `marksweep-conc', `marksweep-par')\n");
2993                         fprintf (stderr, "  minor=COLLECTOR (where COLLECTOR is `simple' or `split')\n");
2994                         fprintf (stderr, "  wbarrier=WBARRIER (where WBARRIER is `remset' or `cardtable')\n");
2995                         fprintf (stderr, "  [no-]cementing\n");
2996                         if (major_collector.print_gc_param_usage)
2997                                 major_collector.print_gc_param_usage ();
2998                         if (sgen_minor_collector.print_gc_param_usage)
2999                                 sgen_minor_collector.print_gc_param_usage ();
3000                         sgen_client_print_gc_params_usage ();
3001                         fprintf (stderr, " Experimental options:\n");
3002                         fprintf (stderr, "  save-target-ratio=R (where R must be between %.2f - %.2f).\n", SGEN_MIN_SAVE_TARGET_RATIO, SGEN_MAX_SAVE_TARGET_RATIO);
3003                         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);
3004                         fprintf (stderr, "\n");
3005
3006                         usage_printed = TRUE;
3007                 }
3008                 g_strfreev (opts);
3009         }
3010
3011         if (major_collector_opt)
3012                 g_free (major_collector_opt);
3013
3014         if (minor_collector_opt)
3015                 g_free (minor_collector_opt);
3016
3017         alloc_nursery ();
3018
3019         sgen_cement_init (cement_enabled);
3020
3021         if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
3022                 gboolean usage_printed = FALSE;
3023
3024                 opts = g_strsplit (env, ",", -1);
3025                 for (ptr = opts; ptr && *ptr; ptr ++) {
3026                         char *opt = *ptr;
3027                         if (!strcmp (opt, ""))
3028                                 continue;
3029                         if (opt [0] >= '0' && opt [0] <= '9') {
3030                                 gc_debug_level = atoi (opt);
3031                                 opt++;
3032                                 if (opt [0] == ':')
3033                                         opt++;
3034                                 if (opt [0]) {
3035                                         char *rf = g_strdup_printf ("%s.%d", opt, mono_process_current_pid ());
3036                                         gc_debug_file = fopen (rf, "wb");
3037                                         if (!gc_debug_file)
3038                                                 gc_debug_file = stderr;
3039                                         g_free (rf);
3040                                 }
3041                         } else if (!strcmp (opt, "print-allowance")) {
3042                                 debug_print_allowance = TRUE;
3043                         } else if (!strcmp (opt, "print-pinning")) {
3044                                 sgen_pin_stats_enable ();
3045                         } else if (!strcmp (opt, "verify-before-allocs")) {
3046                                 verify_before_allocs = 1;
3047                                 has_per_allocation_action = TRUE;
3048                         } else if (g_str_has_prefix (opt, "verify-before-allocs=")) {
3049                                 char *arg = strchr (opt, '=') + 1;
3050                                 verify_before_allocs = atoi (arg);
3051                                 has_per_allocation_action = TRUE;
3052                         } else if (!strcmp (opt, "collect-before-allocs")) {
3053                                 collect_before_allocs = 1;
3054                                 has_per_allocation_action = TRUE;
3055                         } else if (g_str_has_prefix (opt, "collect-before-allocs=")) {
3056                                 char *arg = strchr (opt, '=') + 1;
3057                                 has_per_allocation_action = TRUE;
3058                                 collect_before_allocs = atoi (arg);
3059                         } else if (!strcmp (opt, "verify-before-collections")) {
3060                                 whole_heap_check_before_collection = TRUE;
3061                         } else if (!strcmp (opt, "check-at-minor-collections")) {
3062                                 consistency_check_at_minor_collection = TRUE;
3063                                 nursery_clear_policy = CLEAR_AT_GC;
3064                         } else if (!strcmp (opt, "mod-union-consistency-check")) {
3065                                 if (!major_collector.is_concurrent) {
3066                                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`mod-union-consistency-check` only works with concurrent major collector.");
3067                                         continue;
3068                                 }
3069                                 mod_union_consistency_check = TRUE;
3070                         } else if (!strcmp (opt, "check-mark-bits")) {
3071                                 check_mark_bits_after_major_collection = TRUE;
3072                         } else if (!strcmp (opt, "check-nursery-pinned")) {
3073                                 check_nursery_objects_pinned = TRUE;
3074                         } else if (!strcmp (opt, "clear-at-gc")) {
3075                                 nursery_clear_policy = CLEAR_AT_GC;
3076                         } else if (!strcmp (opt, "clear-nursery-at-gc")) {
3077                                 nursery_clear_policy = CLEAR_AT_GC;
3078                         } else if (!strcmp (opt, "clear-at-tlab-creation")) {
3079                                 nursery_clear_policy = CLEAR_AT_TLAB_CREATION;
3080                         } else if (!strcmp (opt, "debug-clear-at-tlab-creation")) {
3081                                 nursery_clear_policy = CLEAR_AT_TLAB_CREATION_DEBUG;
3082                         } else if (!strcmp (opt, "check-scan-starts")) {
3083                                 do_scan_starts_check = TRUE;
3084                         } else if (!strcmp (opt, "verify-nursery-at-minor-gc")) {
3085                                 do_verify_nursery = TRUE;
3086                         } else if (!strcmp (opt, "check-concurrent")) {
3087                                 if (!major_collector.is_concurrent) {
3088                                         sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "`check-concurrent` only works with concurrent major collectors.");
3089                                         continue;
3090                                 }
3091                                 nursery_clear_policy = CLEAR_AT_GC;
3092                                 do_concurrent_checks = TRUE;
3093                         } else if (!strcmp (opt, "dump-nursery-at-minor-gc")) {
3094                                 do_dump_nursery_content = TRUE;
3095                         } else if (!strcmp (opt, "disable-minor")) {
3096                                 disable_minor_collections = TRUE;
3097                         } else if (!strcmp (opt, "disable-major")) {
3098                                 disable_major_collections = TRUE;
3099                         } else if (g_str_has_prefix (opt, "heap-dump=")) {
3100                                 char *filename = strchr (opt, '=') + 1;
3101                                 nursery_clear_policy = CLEAR_AT_GC;
3102                                 sgen_debug_enable_heap_dump (filename);
3103                         } else if (g_str_has_prefix (opt, "binary-protocol=")) {
3104                                 char *filename = strchr (opt, '=') + 1;
3105                                 char *colon = strrchr (filename, ':');
3106                                 size_t limit = 0;
3107                                 if (colon) {
3108                                         if (!mono_gc_parse_environment_string_extract_number (colon + 1, &limit)) {
3109                                                 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring limit.", "Binary protocol file size limit must be an integer.");
3110                                                 limit = -1;
3111                                         }
3112                                         *colon = '\0';
3113                                 }
3114                                 binary_protocol_init (filename, (long long)limit);
3115                         } else if (!strcmp (opt, "nursery-canaries")) {
3116                                 do_verify_nursery = TRUE;
3117                                 enable_nursery_canaries = TRUE;
3118                         } else if (!sgen_client_handle_gc_debug (opt)) {
3119                                 sgen_env_var_error (MONO_GC_DEBUG_NAME, "Ignoring.", "Unknown option `%s`.", opt);
3120
3121                                 if (usage_printed)
3122                                         continue;
3123
3124                                 fprintf (stderr, "\n%s must be of the format [<l>[:<filename>]|<option>]+ where <l> is a debug level 0-9.\n", MONO_GC_DEBUG_NAME);
3125                                 fprintf (stderr, "Valid <option>s are:\n");
3126                                 fprintf (stderr, "  collect-before-allocs[=<n>]\n");
3127                                 fprintf (stderr, "  verify-before-allocs[=<n>]\n");
3128                                 fprintf (stderr, "  check-at-minor-collections\n");
3129                                 fprintf (stderr, "  check-mark-bits\n");
3130                                 fprintf (stderr, "  check-nursery-pinned\n");
3131                                 fprintf (stderr, "  verify-before-collections\n");
3132                                 fprintf (stderr, "  verify-nursery-at-minor-gc\n");
3133                                 fprintf (stderr, "  dump-nursery-at-minor-gc\n");
3134                                 fprintf (stderr, "  disable-minor\n");
3135                                 fprintf (stderr, "  disable-major\n");
3136                                 fprintf (stderr, "  check-concurrent\n");
3137                                 fprintf (stderr, "  clear-[nursery-]at-gc\n");
3138                                 fprintf (stderr, "  clear-at-tlab-creation\n");
3139                                 fprintf (stderr, "  debug-clear-at-tlab-creation\n");
3140                                 fprintf (stderr, "  check-scan-starts\n");
3141                                 fprintf (stderr, "  print-allowance\n");
3142                                 fprintf (stderr, "  print-pinning\n");
3143                                 fprintf (stderr, "  heap-dump=<filename>\n");
3144                                 fprintf (stderr, "  binary-protocol=<filename>[:<file-size-limit>]\n");
3145                                 fprintf (stderr, "  nursery-canaries\n");
3146                                 sgen_client_print_gc_debug_usage ();
3147                                 fprintf (stderr, "\n");
3148
3149                                 usage_printed = TRUE;
3150                         }
3151                 }
3152                 g_strfreev (opts);
3153         }
3154
3155         if (check_mark_bits_after_major_collection)
3156                 nursery_clear_policy = CLEAR_AT_GC;
3157
3158         if (major_collector.post_param_init)
3159                 major_collector.post_param_init (&major_collector);
3160
3161         if (major_collector.needs_thread_pool)
3162                 sgen_workers_init (1);
3163
3164         sgen_memgov_init (max_heap, soft_limit, debug_print_allowance, allowance_ratio, save_target);
3165
3166         memset (&remset, 0, sizeof (remset));
3167
3168         sgen_card_table_init (&remset);
3169
3170         sgen_register_root (NULL, 0, sgen_make_user_root_descriptor (sgen_mark_normal_gc_handles), ROOT_TYPE_NORMAL, MONO_ROOT_SOURCE_GC_HANDLE, "normal gc handles");
3171
3172         gc_initialized = 1;
3173 }
3174
3175 NurseryClearPolicy
3176 sgen_get_nursery_clear_policy (void)
3177 {
3178         return nursery_clear_policy;
3179 }
3180
3181 void
3182 sgen_gc_lock (void)
3183 {
3184         mono_coop_mutex_lock (&gc_mutex);
3185 }
3186
3187 void
3188 sgen_gc_unlock (void)
3189 {
3190         gboolean try_free = sgen_try_free_some_memory;
3191         sgen_try_free_some_memory = FALSE;
3192         mono_coop_mutex_unlock (&gc_mutex);
3193         if (try_free)
3194                 mono_thread_hazardous_try_free_some ();
3195 }
3196
3197 void
3198 sgen_major_collector_iterate_live_block_ranges (sgen_cardtable_block_callback callback)
3199 {
3200         major_collector.iterate_live_block_ranges (callback);
3201 }
3202
3203 SgenMajorCollector*
3204 sgen_get_major_collector (void)
3205 {
3206         return &major_collector;
3207 }
3208
3209 SgenRememberedSet*
3210 sgen_get_remset (void)
3211 {
3212         return &remset;
3213 }
3214
3215 static void
3216 count_cards (long long *major_total, long long *major_marked, long long *los_total, long long *los_marked)
3217 {
3218         sgen_get_major_collector ()->count_cards (major_total, major_marked);
3219         sgen_los_count_cards (los_total, los_marked);
3220 }
3221
3222 static gboolean world_is_stopped = FALSE;
3223
3224 /* LOCKING: assumes the GC lock is held */
3225 void
3226 sgen_stop_world (int generation)
3227 {
3228         long long major_total = -1, major_marked = -1, los_total = -1, los_marked = -1;
3229
3230         SGEN_ASSERT (0, !world_is_stopped, "Why are we stopping a stopped world?");
3231
3232         binary_protocol_world_stopping (generation, sgen_timestamp (), (gpointer) (gsize) mono_native_thread_id_get ());
3233
3234         sgen_client_stop_world (generation);
3235
3236         world_is_stopped = TRUE;
3237
3238         if (binary_protocol_is_heavy_enabled ())
3239                 count_cards (&major_total, &major_marked, &los_total, &los_marked);
3240         binary_protocol_world_stopped (generation, sgen_timestamp (), major_total, major_marked, los_total, los_marked);
3241 }
3242
3243 /* LOCKING: assumes the GC lock is held */
3244 void
3245 sgen_restart_world (int generation, GGTimingInfo *timing)
3246 {
3247         long long major_total = -1, major_marked = -1, los_total = -1, los_marked = -1;
3248
3249         SGEN_ASSERT (0, world_is_stopped, "Why are we restarting a running world?");
3250
3251         if (binary_protocol_is_heavy_enabled ())
3252                 count_cards (&major_total, &major_marked, &los_total, &los_marked);
3253         binary_protocol_world_restarting (generation, sgen_timestamp (), major_total, major_marked, los_total, los_marked);
3254
3255         sgen_client_restart_world (generation, timing);
3256
3257         world_is_stopped = FALSE;
3258
3259         binary_protocol_world_restarted (generation, sgen_timestamp ());
3260
3261         sgen_try_free_some_memory = TRUE;
3262
3263         if (sgen_client_bridge_need_processing ())
3264                 sgen_client_bridge_processing_finish (generation);
3265
3266         sgen_memgov_collection_end (generation, timing, timing ? 2 : 0);
3267 }
3268
3269 gboolean
3270 sgen_is_world_stopped (void)
3271 {
3272         return world_is_stopped;
3273 }
3274
3275 void
3276 sgen_check_whole_heap_stw (void)
3277 {
3278         sgen_stop_world (0);
3279         sgen_clear_nursery_fragments ();
3280         sgen_check_whole_heap (FALSE);
3281         sgen_restart_world (0, NULL);
3282 }
3283
3284 gint64
3285 sgen_timestamp (void)
3286 {
3287         SGEN_TV_DECLARE (timestamp);
3288         SGEN_TV_GETTIME (timestamp);
3289         return SGEN_TV_ELAPSED (sgen_init_timestamp, timestamp);
3290 }
3291
3292 #endif /* HAVE_SGEN_GC */