Merge pull request #1685 from esdrubal/touint64
[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/sgen-thread-pool.h"
33 #include "metadata/mono-gc.h"
34
35 #include "utils/mono-counters.h"
36 #include "utils/mono-mmap.h"
37 #include "utils/mono-logger-internal.h"
38 #include "utils/dtrace.h"
39
40 #define MIN_MINOR_COLLECTION_ALLOWANCE  ((mword)(DEFAULT_NURSERY_SIZE * default_allowance_nursery_size_ratio))
41
42 /*Heap limits and allocation knobs*/
43 static mword max_heap_size = ((mword)0)- ((mword)1);
44 static mword soft_heap_limit = ((mword)0) - ((mword)1);
45
46 static double default_allowance_nursery_size_ratio = SGEN_DEFAULT_ALLOWANCE_NURSERY_SIZE_RATIO;
47 static double save_target_ratio = SGEN_DEFAULT_SAVE_TARGET_RATIO;
48
49 /**/
50 static mword allocated_heap;
51 static mword total_alloc = 0;
52 static mword total_alloc_max = 0;
53
54 /* GC triggers. */
55
56 static gboolean debug_print_allowance = FALSE;
57
58
59 /* use this to tune when to do a major/minor collection */
60 static mword memory_pressure = 0;
61 static mword major_collection_trigger_size;
62
63 static mword last_major_num_sections = 0;
64 static mword last_los_memory_usage = 0;
65
66 static gboolean need_calculate_minor_collection_allowance;
67
68 /* The size of the LOS after the last major collection, after sweeping. */
69 static mword last_collection_los_memory_usage = 0;
70
71 static mword sgen_memgov_available_free_space (void);
72
73
74 /* GC trigger heuristics. */
75
76 static void
77 sgen_memgov_calculate_minor_collection_allowance (void)
78 {
79         size_t new_major, new_heap_size, allowance_target, allowance;
80
81         if (!need_calculate_minor_collection_allowance)
82                 return;
83
84         SGEN_ASSERT (0, major_collector.have_swept (), "Can only calculate allowance if heap is swept");
85
86         new_major = major_collector.get_bytes_survived_last_sweep ();
87         new_heap_size = new_major + last_collection_los_memory_usage;
88
89         /*
90          * We allow the heap to grow by one third its current size before we start the next
91          * major collection.
92          */
93         allowance_target = new_heap_size / 3;
94
95         allowance = MAX (allowance_target, MIN_MINOR_COLLECTION_ALLOWANCE);
96
97         if (new_heap_size + allowance > soft_heap_limit) {
98                 if (new_heap_size > soft_heap_limit)
99                         allowance = MIN_MINOR_COLLECTION_ALLOWANCE;
100                 else
101                         allowance = MAX (soft_heap_limit - new_heap_size, MIN_MINOR_COLLECTION_ALLOWANCE);
102         }
103
104         /* FIXME: Why is this here? */
105         if (major_collector.free_swept_blocks)
106                 major_collector.free_swept_blocks (allowance);
107
108         major_collection_trigger_size = new_heap_size + allowance;
109
110         need_calculate_minor_collection_allowance = FALSE;
111
112         if (debug_print_allowance) {
113                 SGEN_LOG (0, "Surviving sweep: %ld bytes (%ld major, %ld LOS)", (long)new_heap_size, (long)new_major, (long)last_collection_los_memory_usage);
114                 SGEN_LOG (0, "Allowance: %ld bytes", (long)allowance);
115                 SGEN_LOG (0, "Trigger size: %ld bytes", (long)major_collection_trigger_size);
116         }
117 }
118
119 gboolean
120 sgen_need_major_collection (mword space_needed)
121 {
122         size_t heap_size;
123
124         if (sgen_concurrent_collection_in_progress ())
125                 return FALSE;
126
127         /* FIXME: This is a cop-out.  We should have some way of figuring this out. */
128         if (!major_collector.have_swept ())
129                 return FALSE;
130
131         if (space_needed > sgen_memgov_available_free_space ())
132                 return TRUE;
133
134         sgen_memgov_calculate_minor_collection_allowance ();
135
136         heap_size = major_collector.get_num_major_sections () * major_collector.section_size + los_memory_usage;
137
138         return heap_size > major_collection_trigger_size;
139 }
140
141 void
142 sgen_memgov_minor_collection_start (void)
143 {
144 }
145
146 void
147 sgen_memgov_minor_collection_end (void)
148 {
149 }
150
151 void
152 sgen_memgov_major_collection_start (void)
153 {
154         need_calculate_minor_collection_allowance = TRUE;
155
156         if (debug_print_allowance) {
157                 SGEN_LOG (0, "Starting collection with heap size %ld bytes", (long)(major_collector.get_num_major_sections () * major_collector.section_size + los_memory_usage));
158         }
159 }
160
161 void
162 sgen_memgov_major_collection_end (gboolean forced)
163 {
164         last_collection_los_memory_usage = los_memory_usage;
165
166         if (forced) {
167                 sgen_get_major_collector ()->finish_sweeping ();
168                 sgen_memgov_calculate_minor_collection_allowance ();
169         }
170 }
171
172 static void
173 log_timming (GGTimingInfo *info)
174 {
175         //unsigned long stw_time, unsigned long bridge_time, gboolean is_overflow
176         mword num_major_sections = major_collector.get_num_major_sections ();
177         char full_timing_buff [1024];
178         full_timing_buff [0] = '\0';
179
180         if (!info->is_overflow)
181                 sprintf (full_timing_buff, "total %.2fms, bridge %.2fms", info->stw_time / 10000.0f, (int)info->bridge_time / 10000.0f);
182         if (info->generation == GENERATION_OLD)
183                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) pause %.2fms, %s major %dK/%dK los %dK/%dK",
184                         info->is_overflow ? "_OVERFLOW" : "",
185                         info->reason ? info->reason : "",
186                         (int)info->total_time / 10000.0f,
187                         full_timing_buff,
188                         major_collector.section_size * num_major_sections / 1024,
189                         major_collector.section_size * last_major_num_sections / 1024,
190                         los_memory_usage / 1024,
191                         last_los_memory_usage / 1024);
192         else
193                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) pause %.2fms, %s promoted %dK major %dK los %dK",
194                                 info->is_overflow ? "_OVERFLOW" : "",
195                         info->reason ? info->reason : "",
196                         (int)info->total_time / 10000.0f,
197                         full_timing_buff,
198                         (num_major_sections - last_major_num_sections) * major_collector.section_size / 1024,
199                         major_collector.section_size * num_major_sections / 1024,
200                         los_memory_usage / 1024);       
201 }
202
203 /* FIXME: Remove either these or the specialized ones above. */
204 void
205 sgen_memgov_collection_start (int generation)
206 {
207 }
208
209 void
210 sgen_memgov_collection_end (int generation, GGTimingInfo* info, int info_count)
211 {
212         int i;
213         for (i = 0; i < info_count; ++i) {
214                 if (info[i].generation != -1)
215                         log_timming (&info [i]);
216         }
217 }
218
219 /* Memory pressure API */
220
221 /* Negative value to remove */
222 void
223 mono_gc_add_memory_pressure (gint64 value)
224 {
225         /* FIXME: Use interlocked functions */
226         LOCK_GC;
227         memory_pressure += value;
228         UNLOCK_GC;
229 }
230
231
232 /*
233 Global GC memory tracking.
234 This tracks the total usage of memory by the GC. This includes
235 managed and unmanaged memory.
236 */
237
238 static unsigned long
239 prot_flags_for_activate (int activate)
240 {
241         unsigned long prot_flags = activate? MONO_MMAP_READ|MONO_MMAP_WRITE: MONO_MMAP_NONE;
242         return prot_flags | MONO_MMAP_PRIVATE | MONO_MMAP_ANON;
243 }
244
245 void
246 sgen_assert_memory_alloc (void *ptr, size_t requested_size, const char *assert_description)
247 {
248         if (ptr || !assert_description)
249                 return;
250         fprintf (stderr, "Error: Garbage collector could not allocate %zu bytes of memory for %s.\n", requested_size, assert_description);
251         exit (1);
252 }
253
254 /*
255  * Allocate a big chunk of memory from the OS (usually 64KB to several megabytes).
256  * This must not require any lock.
257  */
258 void*
259 sgen_alloc_os_memory (size_t size, SgenAllocFlags flags, const char *assert_description)
260 {
261         void *ptr;
262
263         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
264
265         ptr = mono_valloc (0, size, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
266         sgen_assert_memory_alloc (ptr, size, assert_description);
267         if (ptr) {
268                 SGEN_ATOMIC_ADD_P (total_alloc, size);
269                 if (flags & SGEN_ALLOC_HEAP)
270                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
271                 total_alloc_max = MAX (total_alloc_max, total_alloc);
272         }
273         return ptr;
274 }
275
276 /* size must be a power of 2 */
277 void*
278 sgen_alloc_os_memory_aligned (size_t size, mword alignment, SgenAllocFlags flags, const char *assert_description)
279 {
280         void *ptr;
281
282         g_assert (!(flags & ~(SGEN_ALLOC_HEAP | SGEN_ALLOC_ACTIVATE)));
283
284         ptr = mono_valloc_aligned (size, alignment, prot_flags_for_activate (flags & SGEN_ALLOC_ACTIVATE));
285         sgen_assert_memory_alloc (ptr, size, assert_description);
286         if (ptr) {
287                 SGEN_ATOMIC_ADD_P (total_alloc, size);
288                 if (flags & SGEN_ALLOC_HEAP)
289                         MONO_GC_HEAP_ALLOC ((mword)ptr, size);
290                 total_alloc_max = MAX (total_alloc_max, total_alloc);
291         }
292         return ptr;
293 }
294
295 /*
296  * Free the memory returned by sgen_alloc_os_memory (), returning it to the OS.
297  */
298 void
299 sgen_free_os_memory (void *addr, size_t size, SgenAllocFlags flags)
300 {
301         g_assert (!(flags & ~SGEN_ALLOC_HEAP));
302
303         mono_vfree (addr, size);
304         SGEN_ATOMIC_ADD_P (total_alloc, -(gssize)size);
305         if (flags & SGEN_ALLOC_HEAP)
306                 MONO_GC_HEAP_FREE ((mword)addr, size);
307         total_alloc_max = MAX (total_alloc_max, total_alloc);
308 }
309
310 int64_t
311 mono_gc_get_heap_size (void)
312 {
313         return total_alloc;
314 }
315
316
317 /*
318 Heap Sizing limits.
319 This limit the max size of the heap. It takes into account
320 only memory actively in use to hold heap objects and not
321 for other parts of the GC.
322  */
323 static mword
324 sgen_memgov_available_free_space (void)
325 {
326         return max_heap_size - MIN (allocated_heap, max_heap_size);
327 }
328
329 void
330 sgen_memgov_release_space (mword size, int space)
331 {
332         SGEN_ATOMIC_ADD_P (allocated_heap, -(gssize)size);
333 }
334
335 gboolean
336 sgen_memgov_try_alloc_space (mword size, int space)
337 {
338         if (sgen_memgov_available_free_space () < size) {
339                 SGEN_ASSERT (4, !sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Memory shouldn't run out in worker thread");
340                 return FALSE;
341         }
342
343         SGEN_ATOMIC_ADD_P (allocated_heap, size);
344         mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
345         return TRUE;
346 }
347
348 void
349 sgen_memgov_init (size_t max_heap, size_t soft_limit, gboolean debug_allowance, double allowance_ratio, double save_target)
350 {
351         if (soft_limit)
352                 soft_heap_limit = soft_limit;
353
354         debug_print_allowance = debug_allowance;
355         major_collection_trigger_size = MIN_MINOR_COLLECTION_ALLOWANCE;
356
357         mono_counters_register ("Memgov alloc", MONO_COUNTER_GC | MONO_COUNTER_WORD | MONO_COUNTER_BYTES | MONO_COUNTER_VARIABLE, &total_alloc);
358         mono_counters_register ("Memgov max alloc", MONO_COUNTER_GC | MONO_COUNTER_WORD | MONO_COUNTER_BYTES | MONO_COUNTER_MONOTONIC, &total_alloc_max);
359
360         if (max_heap == 0)
361                 return;
362
363         if (max_heap < soft_limit) {
364                 sgen_env_var_error (MONO_GC_PARAMS_NAME, "Setting to minimum.", "`max-heap-size` must be at least as large as `soft-heap-limit`.");
365                 max_heap = soft_limit;
366         }
367
368         if (max_heap < sgen_nursery_size * 4) {
369                 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`.");
370                 max_heap = sgen_nursery_size * 4;
371         }
372         max_heap_size = max_heap - sgen_nursery_size;
373
374         if (allowance_ratio)
375                 default_allowance_nursery_size_ratio = allowance_ratio;
376
377         if (save_target)
378                 save_target_ratio = save_target;
379 }
380
381 #endif