Merge pull request #517 from getsometoast/master
[mono.git] / mono / metadata / sgen-memory-governor.c
1 /*
2  * sgen-memory-governor.c: When to schedule collections based on
3  * memory usage.
4  *
5  * Author:
6  *      Rodrigo Kumpera (rkumpera@novell.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc
9  * Copyright 2003-2010 Novell, Inc.
10  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11  * Copyright (C) 2012 Xamarin Inc
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Library General Public
15  * License 2.0 as published by the Free Software Foundation;
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License 2.0 along with this library; if not, write to the Free
24  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include "config.h"
28 #ifdef HAVE_SGEN_GC
29
30 #include "metadata/sgen-gc.h"
31 #include "metadata/sgen-memory-governor.h"
32 #include "metadata/mono-gc.h"
33
34 #include "utils/mono-counters.h"
35 #include "utils/mono-mmap.h"
36 #include "utils/mono-logger-internal.h"
37 #include "utils/dtrace.h"
38
39 #define MIN_MINOR_COLLECTION_ALLOWANCE  ((mword)(DEFAULT_NURSERY_SIZE * default_allowance_nursery_size_ratio))
40
41 /*Heap limits and allocation knobs*/
42 static mword max_heap_size = ((mword)0)- ((mword)1);
43 static mword soft_heap_limit = ((mword)0) - ((mword)1);
44
45 static double default_allowance_nursery_size_ratio = SGEN_DEFAULT_ALLOWANCE_NURSERY_SIZE_RATIO;
46 static double save_target_ratio = SGEN_DEFAULT_SAVE_TARGET_RATIO;
47
48 /**/
49 static mword allocated_heap;
50 static mword total_alloc = 0;
51
52 /* GC triggers. */
53
54 static gboolean debug_print_allowance = FALSE;
55
56
57 /* use this to tune when to do a major/minor collection */
58 static mword memory_pressure = 0;
59 static mword minor_collection_allowance;
60 static int minor_collection_sections_alloced = 0;
61
62 static int last_major_num_sections = 0;
63 static int last_los_memory_usage = 0;
64
65 static gboolean need_calculate_minor_collection_allowance;
66
67 static int last_collection_old_num_major_sections;
68 static mword last_collection_los_memory_usage = 0;
69 static mword last_collection_old_los_memory_usage;
70 static mword last_collection_los_memory_alloced;
71
72 static mword sgen_memgov_available_free_space (void);
73
74
75 static mword
76 double_to_mword_with_saturation (double value)
77 {
78         if (value >= (double)MWORD_MAX_VALUE)
79                 return MWORD_MAX_VALUE;
80         return (mword)value;
81 }
82
83 /* GC trigger heuristics. */
84
85 static void
86 sgen_memgov_try_calculate_minor_collection_allowance (gboolean overwrite)
87 {
88         int num_major_sections, num_major_sections_saved;
89         mword los_memory_saved, new_major, new_heap_size, save_target, allowance_target;
90
91         if (overwrite)
92                 g_assert (need_calculate_minor_collection_allowance);
93
94         if (!need_calculate_minor_collection_allowance)
95                 return;
96
97         if (!*major_collector.have_swept) {
98                 if (overwrite)
99                         minor_collection_allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
100                 return;
101         }
102
103         num_major_sections = major_collector.get_num_major_sections ();
104
105         num_major_sections_saved = MAX (last_collection_old_num_major_sections - num_major_sections, 0);
106         los_memory_saved = MAX (last_collection_old_los_memory_usage - last_collection_los_memory_usage, 1);
107
108         new_major = num_major_sections * major_collector.section_size;
109         new_heap_size = new_major + last_collection_los_memory_usage;
110
111         save_target = (mword)((new_major + last_collection_los_memory_usage) * SGEN_DEFAULT_SAVE_TARGET_RATIO);
112
113         /*
114          * We aim to allow the allocation of as many sections as is
115          * necessary to reclaim save_target sections in the next
116          * collection.  We assume the collection pattern won't change.
117          * In the last cycle, we had num_major_sections_saved for
118          * minor_collection_sections_alloced.  Assuming things won't
119          * change, this must be the same ratio as save_target for
120          * allowance_target, i.e.
121          *
122          *    num_major_sections_saved            save_target
123          * --------------------------------- == ----------------
124          * minor_collection_sections_alloced    allowance_target
125          *
126          * hence:
127          */
128         allowance_target = double_to_mword_with_saturation ((double)save_target * (double)(minor_collection_sections_alloced * major_collector.section_size + last_collection_los_memory_alloced) / (double)(num_major_sections_saved * major_collector.section_size + los_memory_saved));
129
130         minor_collection_allowance = MAX (MIN (allowance_target, num_major_sections * major_collector.section_size + los_memory_usage), MIN_MINOR_COLLECTION_ALLOWANCE);
131
132         if (new_heap_size + minor_collection_allowance > soft_heap_limit) {
133                 if (new_heap_size > soft_heap_limit)
134                         minor_collection_allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
135                 else
136                         minor_collection_allowance = MAX (soft_heap_limit - new_heap_size, MIN_MINOR_COLLECTION_ALLOWANCE);
137         }
138
139         if (debug_print_allowance) {
140                 mword old_major = last_collection_old_num_major_sections * major_collector.section_size;
141
142                 SGEN_LOG (1, "Before collection: %td bytes (%td major, %td LOS)",
143                                 old_major + last_collection_old_los_memory_usage, old_major, last_collection_old_los_memory_usage);
144                 SGEN_LOG (1, "After collection: %td bytes (%td major, %td LOS)",
145                                 new_heap_size, new_major, last_collection_los_memory_usage);
146                 SGEN_LOG (1, "Allowance: %td bytes", minor_collection_allowance);
147         }
148
149         if (major_collector.have_computed_minor_collection_allowance)
150                 major_collector.have_computed_minor_collection_allowance ();
151
152         need_calculate_minor_collection_allowance = FALSE;
153 }
154
155
156 gboolean
157 sgen_need_major_collection (mword space_needed)
158 {
159         mword los_alloced;
160         los_alloced = los_memory_usage - MIN (last_collection_los_memory_usage, los_memory_usage);
161         return (space_needed > sgen_memgov_available_free_space ()) ||
162                 minor_collection_sections_alloced * major_collector.section_size + los_alloced > minor_collection_allowance;
163 }
164
165 void
166 sgen_memgov_minor_collection_start (void)
167 {
168         sgen_memgov_try_calculate_minor_collection_allowance (FALSE);
169 }
170
171 void
172 sgen_memgov_minor_collection_end (void)
173 {
174 }
175
176 void
177 sgen_memgov_major_collection_start (void)
178 {
179         last_collection_old_num_major_sections = sgen_get_major_collector ()->get_num_major_sections ();
180
181         /*
182          * A domain could have been freed, resulting in
183          * los_memory_usage being less than last_collection_los_memory_usage.
184          */
185         last_collection_los_memory_alloced = los_memory_usage - MIN (last_collection_los_memory_usage, los_memory_usage);
186         last_collection_old_los_memory_usage = los_memory_usage;
187
188         need_calculate_minor_collection_allowance = TRUE;
189 }
190
191 void
192 sgen_memgov_major_collection_end (void)
193 {
194         sgen_memgov_try_calculate_minor_collection_allowance (TRUE);
195
196         minor_collection_sections_alloced = 0;
197         last_collection_los_memory_usage = los_memory_usage;
198 }
199
200 void
201 sgen_memgov_collection_start (int generation)
202 {
203         last_major_num_sections = major_collector.get_num_major_sections ();
204         last_los_memory_usage = los_memory_usage;
205 }
206
207 static void
208 log_timming (GGTimingInfo *info)
209 {
210         //unsigned long stw_time, unsigned long bridge_time, gboolean is_overflow
211         int num_major_sections = major_collector.get_num_major_sections ();
212         char full_timing_buff [1024];
213         full_timing_buff [0] = '\0';
214
215         if (!info->is_overflow)
216                 sprintf (full_timing_buff, "total %.2fms, bridge %.2f", info->stw_time / 1000.0f, (int)info->bridge_time / 1000.0f);
217         if (info->generation == GENERATION_OLD)
218                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) pause %.2fms, %s major %dK/%dK los %dK/%dK",
219                         info->is_overflow ? "_OVERFLOW" : "",
220                         info->reason ? info->reason : "",
221                         (int)info->total_time / 1000.0f,
222                         full_timing_buff,
223                         major_collector.section_size * num_major_sections / 1024,
224                         major_collector.section_size * last_major_num_sections / 1024,
225                         los_memory_usage / 1024,
226                         last_los_memory_usage / 1024);
227         else
228                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) pause %.2fms, %s promoted %dK major %dK los %dK",
229                                 info->is_overflow ? "_OVERFLOW" : "",
230                         info->reason ? info->reason : "",
231                         (int)info->total_time / 1000.0f,
232                         full_timing_buff,
233                         (num_major_sections - last_major_num_sections) * major_collector.section_size / 1024,
234                         major_collector.section_size * num_major_sections / 1024,
235                         los_memory_usage / 1024);       
236 }
237
238 void
239 sgen_memgov_collection_end (int generation, GGTimingInfo* info, int info_count)
240 {
241         int i;
242         for (i = 0; i < info_count; ++i) {
243                 if (info[i].generation != -1)
244                         log_timming (&info [i]);
245         }
246 }
247
248 void
249 sgen_register_major_sections_alloced (int num_sections)
250 {
251         minor_collection_sections_alloced += num_sections;
252 }
253
254 mword
255 sgen_get_minor_collection_allowance (void)
256 {
257         return minor_collection_allowance;
258 }
259
260 /* Memory pressure API */
261
262 /* Negative value to remove */
263 void
264 mono_gc_add_memory_pressure (gint64 value)
265 {
266         /* FIXME: Use interlocked functions */
267         LOCK_GC;
268         memory_pressure += value;
269         UNLOCK_GC;
270 }
271
272
273 /*
274 Global GC memory tracking.
275 This tracks the total usage of memory by the GC. This includes
276 managed and unmanaged memory.
277 */
278
279 static unsigned long
280 prot_flags_for_activate (int activate)
281 {
282         unsigned long prot_flags = activate? MONO_MMAP_READ|MONO_MMAP_WRITE: MONO_MMAP_NONE;
283         return prot_flags | MONO_MMAP_PRIVATE | MONO_MMAP_ANON;
284 }
285
286 void
287 sgen_assert_memory_alloc (void *ptr, size_t requested_size, const char *assert_description)
288 {
289         if (ptr || !assert_description)
290                 return;
291         fprintf (stderr, "Error: Garbage collector could not allocate %zu bytes of memory for %s.\n", requested_size, assert_description);
292         exit (1);
293 }
294
295 /*
296  * Allocate a big chunk of memory from the OS (usually 64KB to several megabytes).
297  * This must not require any lock.
298  */
299 void*
300 sgen_alloc_os_memory (size_t size, SgenAllocFlags flags, const char *assert_description)
301 {
302         void *ptr;
303
304         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
305
306         ptr = mono_valloc (0, size, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
307         sgen_assert_memory_alloc (ptr, size, assert_description);
308         if (ptr) {
309                 SGEN_ATOMIC_ADD_P (total_alloc, size);
310                 if (flags & SGEN_ALLOC_HEAP)
311                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
312         }
313         return ptr;
314 }
315
316 /* size must be a power of 2 */
317 void*
318 sgen_alloc_os_memory_aligned (size_t size, mword alignment, SgenAllocFlags flags, const char *assert_description)
319 {
320         void *ptr;
321
322         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
323
324         ptr = mono_valloc_aligned (size, alignment, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
325         sgen_assert_memory_alloc (ptr, size, assert_description);
326         if (ptr) {
327                 SGEN_ATOMIC_ADD_P (total_alloc, size);
328                 if (flags & SGEN_ALLOC_HEAP)
329                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
330         }
331         return ptr;
332 }
333
334 /*
335  * Free the memory returned by sgen_alloc_os_memory (), returning it to the OS.
336  */
337 void
338 sgen_free_os_memory (void *addr, size_t size, SgenAllocFlags flags)
339 {
340         g_assert (!(flags & ~SGEN_ALLOC_HEAP));
341
342         mono_vfree (addr, size);
343         SGEN_ATOMIC_ADD_P (total_alloc, -size);
344         if (flags & SGEN_ALLOC_HEAP)
345                 MONO_GC_HEAP_FREE ((mword)addr, size);
346 }
347
348 int64_t
349 mono_gc_get_heap_size (void)
350 {
351         return total_alloc;
352 }
353
354
355 /*
356 Heap Sizing limits.
357 This limit the max size of the heap. It takes into account
358 only memory actively in use to hold heap objects and not
359 for other parts of the GC.
360  */
361 static mword
362 sgen_memgov_available_free_space (void)
363 {
364         return max_heap_size - MIN (allocated_heap, max_heap_size);
365 }
366
367 void
368 sgen_memgov_release_space (mword size, int space)
369 {
370         SGEN_ATOMIC_ADD_P (allocated_heap, -size);
371 }
372
373 gboolean
374 sgen_memgov_try_alloc_space (mword size, int space)
375 {
376         if (sgen_memgov_available_free_space () < size)
377                 return FALSE;
378
379         SGEN_ATOMIC_ADD_P (allocated_heap, size);
380         mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
381         return TRUE;
382 }
383
384 void
385 sgen_memgov_init (glong max_heap, glong soft_limit, gboolean debug_allowance, double allowance_ratio, double save_target)
386 {
387         if (soft_limit)
388                 soft_heap_limit = soft_limit;
389
390         debug_print_allowance = debug_allowance;
391
392         if (max_heap == 0)
393                 return;
394
395         if (max_heap < soft_limit) {
396                 fprintf (stderr, "max-heap-size must be at least as large as soft-heap-limit.\n");
397                 exit (1);
398         }
399
400         if (max_heap < sgen_nursery_size * 4) {
401                 fprintf (stderr, "max-heap-size must be at least 4 times larger than nursery size.\n");
402                 exit (1);
403         }
404         max_heap_size = max_heap - sgen_nursery_size;
405
406         minor_collection_allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
407
408         if (allowance_ratio)
409                 default_allowance_nursery_size_ratio = allowance_ratio;
410
411         if (save_target)
412                 save_target_ratio = save_target;
413 }
414
415 #endif