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