Merge pull request #1066 from esdrubal/bug19313
[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 mword minor_collection_sections_alloced = 0;
61
62 static mword last_major_num_sections = 0;
63 static mword last_los_memory_usage = 0;
64
65 static gboolean need_calculate_minor_collection_allowance;
66
67 static mword 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         size_t 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: %ld bytes (%ld major, %ld LOS)",
143                                   (long)(old_major + last_collection_old_los_memory_usage), (long)old_major, (long)last_collection_old_los_memory_usage);
144                 SGEN_LOG (1, "After collection: %ld bytes (%ld major, %ld LOS)",
145                                   (long)new_heap_size, (long)new_major, (long)last_collection_los_memory_usage);
146                 SGEN_LOG (1, "Allowance: %ld bytes", (long)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         if (sgen_concurrent_collection_in_progress ())
161                 return FALSE;
162         los_alloced = los_memory_usage - MIN (last_collection_los_memory_usage, los_memory_usage);
163         return (space_needed > sgen_memgov_available_free_space ()) ||
164                 minor_collection_sections_alloced * major_collector.section_size + los_alloced > minor_collection_allowance;
165 }
166
167 void
168 sgen_memgov_minor_collection_start (void)
169 {
170         sgen_memgov_try_calculate_minor_collection_allowance (FALSE);
171 }
172
173 void
174 sgen_memgov_minor_collection_end (void)
175 {
176 }
177
178 void
179 sgen_memgov_major_collection_start (void)
180 {
181         last_collection_old_num_major_sections = sgen_get_major_collector ()->get_num_major_sections ();
182
183         /*
184          * A domain could have been freed, resulting in
185          * los_memory_usage being less than last_collection_los_memory_usage.
186          */
187         last_collection_los_memory_alloced = los_memory_usage - MIN (last_collection_los_memory_usage, los_memory_usage);
188         last_collection_old_los_memory_usage = los_memory_usage;
189
190         need_calculate_minor_collection_allowance = TRUE;
191 }
192
193 void
194 sgen_memgov_major_collection_end (void)
195 {
196         sgen_memgov_try_calculate_minor_collection_allowance (TRUE);
197
198         minor_collection_sections_alloced = 0;
199         last_collection_los_memory_usage = los_memory_usage;
200 }
201
202 void
203 sgen_memgov_collection_start (int generation)
204 {
205         last_major_num_sections = major_collector.get_num_major_sections ();
206         last_los_memory_usage = los_memory_usage;
207 }
208
209 static void
210 log_timming (GGTimingInfo *info)
211 {
212         //unsigned long stw_time, unsigned long bridge_time, gboolean is_overflow
213         mword num_major_sections = major_collector.get_num_major_sections ();
214         char full_timing_buff [1024];
215         full_timing_buff [0] = '\0';
216
217         if (!info->is_overflow)
218                 sprintf (full_timing_buff, "total %.2fms, bridge %.2fms", info->stw_time / 10000.0f, (int)info->bridge_time / 10000.0f);
219         if (info->generation == GENERATION_OLD)
220                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) pause %.2fms, %s major %dK/%dK los %dK/%dK",
221                         info->is_overflow ? "_OVERFLOW" : "",
222                         info->reason ? info->reason : "",
223                         (int)info->total_time / 10000.0f,
224                         full_timing_buff,
225                         major_collector.section_size * num_major_sections / 1024,
226                         major_collector.section_size * last_major_num_sections / 1024,
227                         los_memory_usage / 1024,
228                         last_los_memory_usage / 1024);
229         else
230                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) pause %.2fms, %s promoted %dK major %dK los %dK",
231                                 info->is_overflow ? "_OVERFLOW" : "",
232                         info->reason ? info->reason : "",
233                         (int)info->total_time / 10000.0f,
234                         full_timing_buff,
235                         (num_major_sections - last_major_num_sections) * major_collector.section_size / 1024,
236                         major_collector.section_size * num_major_sections / 1024,
237                         los_memory_usage / 1024);       
238 }
239
240 void
241 sgen_memgov_collection_end (int generation, GGTimingInfo* info, int info_count)
242 {
243         int i;
244         for (i = 0; i < info_count; ++i) {
245                 if (info[i].generation != -1)
246                         log_timming (&info [i]);
247         }
248 }
249
250 void
251 sgen_register_major_sections_alloced (size_t num_sections)
252 {
253         minor_collection_sections_alloced += num_sections;
254 }
255
256 mword
257 sgen_get_minor_collection_allowance (void)
258 {
259         return minor_collection_allowance;
260 }
261
262 /* Memory pressure API */
263
264 /* Negative value to remove */
265 void
266 mono_gc_add_memory_pressure (gint64 value)
267 {
268         /* FIXME: Use interlocked functions */
269         LOCK_GC;
270         memory_pressure += value;
271         UNLOCK_GC;
272 }
273
274
275 /*
276 Global GC memory tracking.
277 This tracks the total usage of memory by the GC. This includes
278 managed and unmanaged memory.
279 */
280
281 static unsigned long
282 prot_flags_for_activate (int activate)
283 {
284         unsigned long prot_flags = activate? MONO_MMAP_READ|MONO_MMAP_WRITE: MONO_MMAP_NONE;
285         return prot_flags | MONO_MMAP_PRIVATE | MONO_MMAP_ANON;
286 }
287
288 void
289 sgen_assert_memory_alloc (void *ptr, size_t requested_size, const char *assert_description)
290 {
291         if (ptr || !assert_description)
292                 return;
293         fprintf (stderr, "Error: Garbage collector could not allocate %zu bytes of memory for %s.\n", requested_size, assert_description);
294         exit (1);
295 }
296
297 /*
298  * Allocate a big chunk of memory from the OS (usually 64KB to several megabytes).
299  * This must not require any lock.
300  */
301 void*
302 sgen_alloc_os_memory (size_t size, SgenAllocFlags flags, const char *assert_description)
303 {
304         void *ptr;
305
306         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
307
308         ptr = mono_valloc (0, size, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
309         sgen_assert_memory_alloc (ptr, size, assert_description);
310         if (ptr) {
311                 SGEN_ATOMIC_ADD_P (total_alloc, size);
312                 if (flags & SGEN_ALLOC_HEAP)
313                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
314         }
315         return ptr;
316 }
317
318 /* size must be a power of 2 */
319 void*
320 sgen_alloc_os_memory_aligned (size_t size, mword alignment, SgenAllocFlags flags, const char *assert_description)
321 {
322         void *ptr;
323
324         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
325
326         ptr = mono_valloc_aligned (size, alignment, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
327         sgen_assert_memory_alloc (ptr, size, assert_description);
328         if (ptr) {
329                 SGEN_ATOMIC_ADD_P (total_alloc, size);
330                 if (flags & SGEN_ALLOC_HEAP)
331                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
332         }
333         return ptr;
334 }
335
336 /*
337  * Free the memory returned by sgen_alloc_os_memory (), returning it to the OS.
338  */
339 void
340 sgen_free_os_memory (void *addr, size_t size, SgenAllocFlags flags)
341 {
342         g_assert (!(flags & ~SGEN_ALLOC_HEAP));
343
344         mono_vfree (addr, size);
345         SGEN_ATOMIC_ADD_P (total_alloc, -(gssize)size);
346         if (flags & SGEN_ALLOC_HEAP)
347                 MONO_GC_HEAP_FREE ((mword)addr, size);
348 }
349
350 int64_t
351 mono_gc_get_heap_size (void)
352 {
353         return total_alloc;
354 }
355
356
357 /*
358 Heap Sizing limits.
359 This limit the max size of the heap. It takes into account
360 only memory actively in use to hold heap objects and not
361 for other parts of the GC.
362  */
363 static mword
364 sgen_memgov_available_free_space (void)
365 {
366         return max_heap_size - MIN (allocated_heap, max_heap_size);
367 }
368
369 void
370 sgen_memgov_release_space (mword size, int space)
371 {
372         SGEN_ATOMIC_ADD_P (allocated_heap, -(gssize)size);
373 }
374
375 gboolean
376 sgen_memgov_try_alloc_space (mword size, int space)
377 {
378         if (sgen_memgov_available_free_space () < size)
379                 return FALSE;
380
381         SGEN_ATOMIC_ADD_P (allocated_heap, size);
382         mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
383         return TRUE;
384 }
385
386 void
387 sgen_memgov_init (size_t max_heap, size_t soft_limit, gboolean debug_allowance, double allowance_ratio, double save_target)
388 {
389         if (soft_limit)
390                 soft_heap_limit = soft_limit;
391
392         debug_print_allowance = debug_allowance;
393         minor_collection_allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
394
395         if (max_heap == 0)
396                 return;
397
398         if (max_heap < soft_limit) {
399                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Setting to minimum.", "`max-heap-size` must be at least as large as `soft-heap-limit`.");
400                 max_heap = soft_limit;
401         }
402
403         if (max_heap < sgen_nursery_size * 4) {
404                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Setting to minimum.", "`max-heap-size` must be at least 4 times as large as `nursery size`.");
405                 max_heap = sgen_nursery_size * 4;
406         }
407         max_heap_size = max_heap - sgen_nursery_size;
408
409         if (allowance_ratio)
410                 default_allowance_nursery_size_ratio = allowance_ratio;
411
412         if (save_target)
413                 save_target_ratio = save_target;
414         minor_collection_allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
415 }
416
417 #endif