Merge pull request #2734 from nealef/master
[mono.git] / mono / sgen / sgen-alloc.c
1 /*
2  * sgen-alloc.c: Object allocation routines + managed allocators
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  * Copyright 2011 Xamarin, Inc.
11  * Copyright (C) 2012 Xamarin Inc
12  *
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 /*
17  * ######################################################################
18  * ########  Object allocation
19  * ######################################################################
20  * This section of code deals with allocating memory for objects.
21  * There are several ways:
22  * *) allocate large objects
23  * *) allocate normal objects
24  * *) fast lock-free allocation
25  * *) allocation of pinned objects
26  */
27
28 #include "config.h"
29 #ifdef HAVE_SGEN_GC
30
31 #include <string.h>
32
33 #include "mono/sgen/sgen-gc.h"
34 #include "mono/sgen/sgen-protocol.h"
35 #include "mono/sgen/sgen-memory-governor.h"
36 #include "mono/sgen/sgen-client.h"
37 #include "mono/utils/mono-memory-model.h"
38
39 #define ALIGN_UP                SGEN_ALIGN_UP
40 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
41 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
42
43 #ifdef HEAVY_STATISTICS
44 static guint64 stat_objects_alloced = 0;
45 static guint64 stat_bytes_alloced = 0;
46 static guint64 stat_bytes_alloced_los = 0;
47
48 #endif
49
50 /*
51  * Allocation is done from a Thread Local Allocation Buffer (TLAB). TLABs are allocated
52  * from nursery fragments.
53  * tlab_next is the pointer to the space inside the TLAB where the next object will 
54  * be allocated.
55  * tlab_temp_end is the pointer to the end of the temporary space reserved for
56  * the allocation: it allows us to set the scan starts at reasonable intervals.
57  * tlab_real_end points to the end of the TLAB.
58  */
59
60 /*
61  * FIXME: What is faster, a TLS variable pointing to a structure, or separate TLS 
62  * variables for next+temp_end ?
63  */
64 #ifdef HAVE_KW_THREAD
65 static __thread char *tlab_start;
66 static __thread char *tlab_next;
67 static __thread char *tlab_temp_end;
68 static __thread char *tlab_real_end;
69 /* Used by the managed allocator/wbarrier */
70 static __thread char **tlab_next_addr MONO_ATTR_USED;
71 #ifndef SGEN_WITHOUT_MONO
72 static __thread volatile int *in_critical_region_addr MONO_ATTR_USED;
73 #endif
74 #endif
75
76 #ifdef HAVE_KW_THREAD
77 #define TLAB_START      tlab_start
78 #define TLAB_NEXT       tlab_next
79 #define TLAB_TEMP_END   tlab_temp_end
80 #define TLAB_REAL_END   tlab_real_end
81 #else
82 #define TLAB_START      (__thread_info__->tlab_start)
83 #define TLAB_NEXT       (__thread_info__->tlab_next)
84 #define TLAB_TEMP_END   (__thread_info__->tlab_temp_end)
85 #define TLAB_REAL_END   (__thread_info__->tlab_real_end)
86 #endif
87
88 static GCObject*
89 alloc_degraded (GCVTable vtable, size_t size, gboolean for_mature)
90 {
91         GCObject *p;
92
93         if (!for_mature) {
94                 sgen_client_degraded_allocation (size);
95                 SGEN_ATOMIC_ADD_P (degraded_mode, size);
96                 sgen_ensure_free_space (size, GENERATION_OLD);
97         } else {
98                 if (sgen_need_major_collection (size))
99                         sgen_perform_collection (size, GENERATION_OLD, "mature allocation failure", !for_mature);
100         }
101
102
103         p = major_collector.alloc_degraded (vtable, size);
104
105         if (!for_mature)
106                 binary_protocol_alloc_degraded (p, vtable, size, sgen_client_get_provenance ());
107
108         return p;
109 }
110
111 static void
112 zero_tlab_if_necessary (void *p, size_t size)
113 {
114         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION || nursery_clear_policy == CLEAR_AT_TLAB_CREATION_DEBUG) {
115                 memset (p, 0, size);
116         } else {
117                 /*
118                  * This function is called for all allocations in
119                  * TLABs.  TLABs originate from fragments, which are
120                  * initialized to be faux arrays.  The remainder of
121                  * the fragments are zeroed out at initialization for
122                  * CLEAR_AT_GC, so here we just need to make sure that
123                  * the array header is zeroed.  Since we don't know
124                  * whether we're called for the start of a fragment or
125                  * for somewhere in between, we zero in any case, just
126                  * to make sure.
127                  */
128                 sgen_client_zero_array_fill_header (p, size);
129         }
130 }
131
132 /*
133  * Provide a variant that takes just the vtable for small fixed-size objects.
134  * The aligned size is already computed and stored in vt->gc_descr.
135  * Note: every SGEN_SCAN_START_SIZE or so we are given the chance to do some special
136  * processing. We can keep track of where objects start, for example,
137  * so when we scan the thread stacks for pinned objects, we can start
138  * a search for the pinned object in SGEN_SCAN_START_SIZE chunks.
139  */
140 GCObject*
141 sgen_alloc_obj_nolock (GCVTable vtable, size_t size)
142 {
143         /* FIXME: handle OOM */
144         void **p;
145         char *new_next;
146         size_t real_size = size;
147         TLAB_ACCESS_INIT;
148         
149         CANARIFY_SIZE(size);
150
151         HEAVY_STAT (++stat_objects_alloced);
152         if (real_size <= SGEN_MAX_SMALL_OBJ_SIZE)
153                 HEAVY_STAT (stat_bytes_alloced += size);
154         else
155                 HEAVY_STAT (stat_bytes_alloced_los += size);
156
157         size = ALIGN_UP (size);
158
159         SGEN_ASSERT (6, sgen_vtable_get_descriptor (vtable), "VTable without descriptor");
160
161         if (G_UNLIKELY (has_per_allocation_action)) {
162                 static int alloc_count;
163                 int current_alloc = InterlockedIncrement (&alloc_count);
164
165                 if (collect_before_allocs) {
166                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
167                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered", TRUE);
168                                 if (!degraded_mode && sgen_can_alloc_size (size) && real_size <= SGEN_MAX_SMALL_OBJ_SIZE) {
169                                         // FIXME:
170                                         g_assert_not_reached ();
171                                 }
172                         }
173                 } else if (verify_before_allocs) {
174                         if ((current_alloc % verify_before_allocs) == 0)
175                                 sgen_check_whole_heap_stw ();
176                 }
177         }
178
179         /*
180          * We must already have the lock here instead of after the
181          * fast path because we might be interrupted in the fast path
182          * (after confirming that new_next < TLAB_TEMP_END) by the GC,
183          * and we'll end up allocating an object in a fragment which
184          * no longer belongs to us.
185          *
186          * The managed allocator does not do this, but it's treated
187          * specially by the world-stopping code.
188          */
189
190         if (real_size > SGEN_MAX_SMALL_OBJ_SIZE) {
191                 p = (void **)sgen_los_alloc_large_inner (vtable, ALIGN_UP (real_size));
192         } else {
193                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
194
195                 p = (void**)TLAB_NEXT;
196                 /* FIXME: handle overflow */
197                 new_next = (char*)p + size;
198                 TLAB_NEXT = new_next;
199
200                 if (G_LIKELY (new_next < TLAB_TEMP_END)) {
201                         /* Fast path */
202
203                         CANARIFY_ALLOC(p,real_size);
204                         SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, sgen_client_vtable_get_name (vtable), size);
205                         binary_protocol_alloc (p , vtable, size, sgen_client_get_provenance ());
206                         g_assert (*p == NULL);
207                         mono_atomic_store_seq (p, vtable);
208
209                         return (GCObject*)p;
210                 }
211
212                 /* Slow path */
213
214                 /* there are two cases: the object is too big or we run out of space in the TLAB */
215                 /* we also reach here when the thread does its first allocation after a minor 
216                  * collection, since the tlab_ variables are initialized to NULL.
217                  * there can be another case (from ORP), if we cooperate with the runtime a bit:
218                  * objects that need finalizers can have the high bit set in their size
219                  * so the above check fails and we can readily add the object to the queue.
220                  * This avoids taking again the GC lock when registering, but this is moot when
221                  * doing thread-local allocation, so it may not be a good idea.
222                  */
223                 if (TLAB_NEXT >= TLAB_REAL_END) {
224                         int available_in_tlab;
225                         /* 
226                          * Run out of space in the TLAB. When this happens, some amount of space
227                          * remains in the TLAB, but not enough to satisfy the current allocation
228                          * request. Currently, we retire the TLAB in all cases, later we could
229                          * keep it if the remaining space is above a treshold, and satisfy the
230                          * allocation directly from the nursery.
231                          */
232                         TLAB_NEXT -= size;
233                         /* when running in degraded mode, we continue allocing that way
234                          * for a while, to decrease the number of useless nursery collections.
235                          */
236                         if (degraded_mode && degraded_mode < DEFAULT_NURSERY_SIZE)
237                                 return alloc_degraded (vtable, size, FALSE);
238
239                         available_in_tlab = (int)(TLAB_REAL_END - TLAB_NEXT);//We'll never have tlabs > 2Gb
240                         if (size > tlab_size || available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
241                                 /* Allocate directly from the nursery */
242                                 p = (void **)sgen_nursery_alloc (size);
243                                 if (!p) {
244                                         /*
245                                          * We couldn't allocate from the nursery, so we try
246                                          * collecting.  Even after the collection, we might
247                                          * still not have enough memory to allocate the
248                                          * object.  The reason will most likely be that we've
249                                          * run out of memory, but there is the theoretical
250                                          * possibility that other threads might have consumed
251                                          * the freed up memory ahead of us.
252                                          *
253                                          * What we do in this case is allocate degraded, i.e.,
254                                          * from the major heap.
255                                          *
256                                          * Ideally we'd like to detect the case of other
257                                          * threads allocating ahead of us and loop (if we
258                                          * always loop we will loop endlessly in the case of
259                                          * OOM).
260                                          */
261                                         sgen_ensure_free_space (real_size, GENERATION_NURSERY);
262                                         if (!degraded_mode)
263                                                 p = (void **)sgen_nursery_alloc (size);
264                                 }
265                                 if (!p)
266                                         return alloc_degraded (vtable, size, FALSE);
267
268                                 zero_tlab_if_necessary (p, size);
269                         } else {
270                                 size_t alloc_size = 0;
271                                 if (TLAB_START)
272                                         SGEN_LOG (3, "Retire TLAB: %p-%p [%ld]", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size));
273                                 sgen_nursery_retire_region (p, available_in_tlab);
274
275                                 p = (void **)sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
276                                 if (!p) {
277                                         /* See comment above in similar case. */
278                                         sgen_ensure_free_space (tlab_size, GENERATION_NURSERY);
279                                         if (!degraded_mode)
280                                                 p = (void **)sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
281                                 }
282                                 if (!p)
283                                         return alloc_degraded (vtable, size, FALSE);
284
285                                 /* Allocate a new TLAB from the current nursery fragment */
286                                 TLAB_START = (char*)p;
287                                 TLAB_NEXT = TLAB_START;
288                                 TLAB_REAL_END = TLAB_START + alloc_size;
289                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
290
291                                 zero_tlab_if_necessary (TLAB_START, alloc_size);
292
293                                 /* Allocate from the TLAB */
294                                 p = (void **)TLAB_NEXT;
295                                 TLAB_NEXT += size;
296                                 sgen_set_nursery_scan_start ((char*)p);
297                         }
298                 } else {
299                         /* Reached tlab_temp_end */
300
301                         /* record the scan start so we can find pinned objects more easily */
302                         sgen_set_nursery_scan_start ((char*)p);
303                         /* we just bump tlab_temp_end as well */
304                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
305                         SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
306                 }
307                 CANARIFY_ALLOC(p,real_size);
308         }
309
310         if (G_LIKELY (p)) {
311                 SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, sgen_client_vtable_get_name (vtable), size);
312                 binary_protocol_alloc (p, vtable, size, sgen_client_get_provenance ());
313                 mono_atomic_store_seq (p, vtable);
314         }
315
316         return (GCObject*)p;
317 }
318
319 GCObject*
320 sgen_try_alloc_obj_nolock (GCVTable vtable, size_t size)
321 {
322         void **p;
323         char *new_next;
324         size_t real_size = size;
325         TLAB_ACCESS_INIT;
326
327         CANARIFY_SIZE(size);
328
329         size = ALIGN_UP (size);
330         SGEN_ASSERT (9, real_size >= SGEN_CLIENT_MINIMUM_OBJECT_SIZE, "Object too small");
331
332         SGEN_ASSERT (6, sgen_vtable_get_descriptor (vtable), "VTable without descriptor");
333
334         if (real_size > SGEN_MAX_SMALL_OBJ_SIZE)
335                 return NULL;
336
337         if (G_UNLIKELY (size > tlab_size)) {
338                 /* Allocate directly from the nursery */
339                 p = (void **)sgen_nursery_alloc (size);
340                 if (!p)
341                         return NULL;
342                 sgen_set_nursery_scan_start ((char*)p);
343
344                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
345                 zero_tlab_if_necessary (p, size);
346         } else {
347                 int available_in_tlab;
348                 char *real_end;
349                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
350
351                 p = (void**)TLAB_NEXT;
352                 /* FIXME: handle overflow */
353                 new_next = (char*)p + size;
354
355                 real_end = TLAB_REAL_END;
356                 available_in_tlab = (int)(real_end - (char*)p);//We'll never have tlabs > 2Gb
357
358                 if (G_LIKELY (new_next < real_end)) {
359                         TLAB_NEXT = new_next;
360
361                         /* Second case, we overflowed temp end */
362                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
363                                 sgen_set_nursery_scan_start (new_next);
364                                 /* we just bump tlab_temp_end as well */
365                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
366                                 SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
367                         }
368                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
369                         /* Allocate directly from the nursery */
370                         p = (void **)sgen_nursery_alloc (size);
371                         if (!p)
372                                 return NULL;
373
374                         zero_tlab_if_necessary (p, size);
375                 } else {
376                         size_t alloc_size = 0;
377
378                         sgen_nursery_retire_region (p, available_in_tlab);
379                         new_next = (char *)sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
380                         p = (void**)new_next;
381                         if (!p)
382                                 return NULL;
383
384                         TLAB_START = (char*)new_next;
385                         TLAB_NEXT = new_next + size;
386                         TLAB_REAL_END = new_next + alloc_size;
387                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
388                         sgen_set_nursery_scan_start ((char*)p);
389
390                         zero_tlab_if_necessary (new_next, alloc_size);
391                 }
392         }
393
394         HEAVY_STAT (++stat_objects_alloced);
395         HEAVY_STAT (stat_bytes_alloced += size);
396
397         CANARIFY_ALLOC(p,real_size);
398         SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, sgen_client_vtable_get_name (vtable), size);
399         binary_protocol_alloc (p, vtable, size, sgen_client_get_provenance ());
400         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
401
402         mono_atomic_store_seq (p, vtable);
403
404         return (GCObject*)p;
405 }
406
407 GCObject*
408 sgen_alloc_obj (GCVTable vtable, size_t size)
409 {
410         GCObject *res;
411         TLAB_ACCESS_INIT;
412
413         if (!SGEN_CAN_ALIGN_UP (size))
414                 return NULL;
415
416         if (G_UNLIKELY (has_per_allocation_action)) {
417                 static int alloc_count;
418                 int current_alloc = InterlockedIncrement (&alloc_count);
419
420                 if (verify_before_allocs) {
421                         if ((current_alloc % verify_before_allocs) == 0)
422                                 sgen_check_whole_heap_stw ();
423                 }
424                 if (collect_before_allocs) {
425                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
426                                 LOCK_GC;
427                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered", TRUE);
428                                 UNLOCK_GC;
429                         }
430                 }
431         }
432
433         ENTER_CRITICAL_REGION;
434         res = sgen_try_alloc_obj_nolock (vtable, size);
435         if (res) {
436                 EXIT_CRITICAL_REGION;
437                 return res;
438         }
439         EXIT_CRITICAL_REGION;
440
441         LOCK_GC;
442         res = sgen_alloc_obj_nolock (vtable, size);
443         UNLOCK_GC;
444         return res;
445 }
446
447 /*
448  * To be used for interned strings and possibly MonoThread, reflection handles.
449  * We may want to explicitly free these objects.
450  */
451 GCObject*
452 sgen_alloc_obj_pinned (GCVTable vtable, size_t size)
453 {
454         GCObject *p;
455
456         if (!SGEN_CAN_ALIGN_UP (size))
457                 return NULL;
458         size = ALIGN_UP (size);
459
460         LOCK_GC;
461
462         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
463                 /* large objects are always pinned anyway */
464                 p = (GCObject *)sgen_los_alloc_large_inner (vtable, size);
465         } else {
466                 SGEN_ASSERT (9, sgen_client_vtable_is_inited (vtable), "class %s:%s is not initialized", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable));
467                 p = major_collector.alloc_small_pinned_obj (vtable, size, SGEN_VTABLE_HAS_REFERENCES (vtable));
468         }
469         if (G_LIKELY (p)) {
470                 SGEN_LOG (6, "Allocated pinned object %p, vtable: %p (%s), size: %zd", p, vtable, sgen_client_vtable_get_name (vtable), size);
471                 binary_protocol_alloc_pinned (p, vtable, size, sgen_client_get_provenance ());
472         }
473         UNLOCK_GC;
474         return p;
475 }
476
477 GCObject*
478 sgen_alloc_obj_mature (GCVTable vtable, size_t size)
479 {
480         GCObject *res;
481
482         if (!SGEN_CAN_ALIGN_UP (size))
483                 return NULL;
484         size = ALIGN_UP (size);
485
486         LOCK_GC;
487         res = alloc_degraded (vtable, size, TRUE);
488         UNLOCK_GC;
489
490         return res;
491 }
492
493 void
494 sgen_init_tlab_info (SgenThreadInfo* info)
495 {
496 #ifndef HAVE_KW_THREAD
497         SgenThreadInfo *__thread_info__ = info;
498 #endif
499
500         info->tlab_start_addr = &TLAB_START;
501         info->tlab_next_addr = &TLAB_NEXT;
502         info->tlab_temp_end_addr = &TLAB_TEMP_END;
503         info->tlab_real_end_addr = &TLAB_REAL_END;
504
505 #ifdef HAVE_KW_THREAD
506         tlab_next_addr = &tlab_next;
507 #ifndef SGEN_WITHOUT_MONO
508         in_critical_region_addr = &info->client_info.in_critical_region;
509 #endif
510 #endif
511 }
512
513 /*
514  * Clear the thread local TLAB variables for all threads.
515  */
516 void
517 sgen_clear_tlabs (void)
518 {
519         FOREACH_THREAD (info) {
520                 /* A new TLAB will be allocated when the thread does its first allocation */
521                 *info->tlab_start_addr = NULL;
522                 *info->tlab_next_addr = NULL;
523                 *info->tlab_temp_end_addr = NULL;
524                 *info->tlab_real_end_addr = NULL;
525         } FOREACH_THREAD_END
526 }
527
528 void
529 sgen_init_allocator (void)
530 {
531 #if defined(HAVE_KW_THREAD) && !defined(SGEN_WITHOUT_MONO)
532         int tlab_next_addr_offset = -1;
533         int tlab_temp_end_offset = -1;
534         int in_critical_region_addr_offset = -1;
535
536         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
537         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
538         MONO_THREAD_VAR_OFFSET (in_critical_region_addr, in_critical_region_addr_offset);
539
540         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_NEXT_ADDR, tlab_next_addr_offset);
541         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_TEMP_END, tlab_temp_end_offset);
542         mono_tls_key_set_offset (TLS_KEY_SGEN_IN_CRITICAL_REGION_ADDR, in_critical_region_addr_offset);
543 #endif
544
545 #ifdef HEAVY_STATISTICS
546         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_objects_alloced);
547         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_bytes_alloced);
548         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_bytes_alloced_los);
549 #endif
550 }
551
552 #endif /*HAVE_SGEN_GC*/