[dtrace] Probes for large and pinned allocation.
[mono.git] / mono / metadata / 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  *
12  * Permission is hereby granted, free of charge, to any person obtaining
13  * a copy of this software and associated documentation files (the
14  * "Software"), to deal in the Software without restriction, including
15  * without limitation the rights to use, copy, modify, merge, publish,
16  * distribute, sublicense, and/or sell copies of the Software, and to
17  * permit persons to whom the Software is furnished to do so, subject to
18  * the following conditions:
19  * 
20  * The above copyright notice and this permission notice shall be
21  * included in all copies or substantial portions of the Software.
22  * 
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30  */
31
32 /*
33  * ######################################################################
34  * ########  Object allocation
35  * ######################################################################
36  * This section of code deals with allocating memory for objects.
37  * There are several ways:
38  * *) allocate large objects
39  * *) allocate normal objects
40  * *) fast lock-free allocation
41  * *) allocation of pinned objects
42  */
43
44 #include "config.h"
45 #ifdef HAVE_SGEN_GC
46
47 #include "metadata/sgen-gc.h"
48 #include "metadata/sgen-protocol.h"
49 #include "metadata/sgen-memory-governor.h"
50 #include "metadata/profiler-private.h"
51 #include "metadata/marshal.h"
52 #include "metadata/method-builder.h"
53 #include "utils/mono-memory-model.h"
54 #include "utils/mono-counters.h"
55
56 #define ALIGN_UP                SGEN_ALIGN_UP
57 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
58 #define ALLOC_ALIGN_BITS        SGEN_ALLOC_ALIGN_BITS
59 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
60 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
61
62 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
63         a = i,
64
65 enum {
66 #include "mono/cil/opcode.def"
67         CEE_LAST
68 };
69
70 #undef OPDEF
71
72 #ifdef HEAVY_STATISTICS
73 static long long stat_objects_alloced = 0;
74 static long long stat_bytes_alloced = 0;
75 static long long stat_bytes_alloced_los = 0;
76
77 #endif
78
79 /*
80  * Allocation is done from a Thread Local Allocation Buffer (TLAB). TLABs are allocated
81  * from nursery fragments.
82  * tlab_next is the pointer to the space inside the TLAB where the next object will 
83  * be allocated.
84  * tlab_temp_end is the pointer to the end of the temporary space reserved for
85  * the allocation: it allows us to set the scan starts at reasonable intervals.
86  * tlab_real_end points to the end of the TLAB.
87  */
88
89 /*
90  * FIXME: What is faster, a TLS variable pointing to a structure, or separate TLS 
91  * variables for next+temp_end ?
92  */
93 #ifdef HAVE_KW_THREAD
94 static __thread char *tlab_start;
95 static __thread char *tlab_next;
96 static __thread char *tlab_temp_end;
97 static __thread char *tlab_real_end;
98 /* Used by the managed allocator/wbarrier */
99 static __thread char **tlab_next_addr;
100 #endif
101
102 #ifdef HAVE_KW_THREAD
103 #define TLAB_START      tlab_start
104 #define TLAB_NEXT       tlab_next
105 #define TLAB_TEMP_END   tlab_temp_end
106 #define TLAB_REAL_END   tlab_real_end
107 #else
108 #define TLAB_START      (__thread_info__->tlab_start)
109 #define TLAB_NEXT       (__thread_info__->tlab_next)
110 #define TLAB_TEMP_END   (__thread_info__->tlab_temp_end)
111 #define TLAB_REAL_END   (__thread_info__->tlab_real_end)
112 #endif
113
114 static void*
115 alloc_degraded (MonoVTable *vtable, size_t size, gboolean for_mature)
116 {
117         static int last_major_gc_warned = -1;
118         static int num_degraded = 0;
119
120         void *p;
121
122         if (!for_mature) {
123                 if (last_major_gc_warned < stat_major_gcs) {
124                         ++num_degraded;
125                         if (num_degraded == 1 || num_degraded == 3)
126                                 fprintf (stderr, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.\n");
127                         else if (num_degraded == 10)
128                                 fprintf (stderr, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.\n");
129                         last_major_gc_warned = stat_major_gcs;
130                 }
131                 InterlockedExchangeAdd (&degraded_mode, size);
132         }
133
134         sgen_ensure_free_space (size);
135
136         p = major_collector.alloc_degraded (vtable, size);
137
138         if (for_mature) {
139                 MONO_GC_MAJOR_OBJ_ALLOC_MATURE (p, size, NULL);
140         } else {
141                 binary_protocol_alloc_degraded (p, vtable, size);
142                 MONO_GC_MAJOR_OBJ_ALLOC_DEGRADED (p, size, NULL);
143         }
144
145         return p;
146 }
147
148 /*
149  * Provide a variant that takes just the vtable for small fixed-size objects.
150  * The aligned size is already computed and stored in vt->gc_descr.
151  * Note: every SGEN_SCAN_START_SIZE or so we are given the chance to do some special
152  * processing. We can keep track of where objects start, for example,
153  * so when we scan the thread stacks for pinned objects, we can start
154  * a search for the pinned object in SGEN_SCAN_START_SIZE chunks.
155  */
156 static void*
157 mono_gc_alloc_obj_nolock (MonoVTable *vtable, size_t size)
158 {
159         /* FIXME: handle OOM */
160         void **p;
161         char *new_next;
162         TLAB_ACCESS_INIT;
163
164         HEAVY_STAT (++stat_objects_alloced);
165         if (size <= SGEN_MAX_SMALL_OBJ_SIZE)
166                 HEAVY_STAT (stat_bytes_alloced += size);
167         else
168                 HEAVY_STAT (stat_bytes_alloced_los += size);
169
170         size = ALIGN_UP (size);
171
172         g_assert (vtable->gc_descr);
173
174         if (G_UNLIKELY (has_per_allocation_action)) {
175                 static int alloc_count;
176                 int current_alloc = InterlockedIncrement (&alloc_count);
177
178                 if (collect_before_allocs) {
179                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
180                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered");
181                                 if (!degraded_mode && sgen_can_alloc_size (size) && size <= SGEN_MAX_SMALL_OBJ_SIZE) {
182                                         // FIXME:
183                                         g_assert_not_reached ();
184                                 }
185                         }
186                 } else if (verify_before_allocs) {
187                         if ((current_alloc % verify_before_allocs) == 0)
188                                 sgen_check_whole_heap_stw ();
189                 }
190         }
191
192         /*
193          * We must already have the lock here instead of after the
194          * fast path because we might be interrupted in the fast path
195          * (after confirming that new_next < TLAB_TEMP_END) by the GC,
196          * and we'll end up allocating an object in a fragment which
197          * no longer belongs to us.
198          *
199          * The managed allocator does not do this, but it's treated
200          * specially by the world-stopping code.
201          */
202
203         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
204                 p = sgen_los_alloc_large_inner (vtable, size);
205         } else {
206                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
207
208                 p = (void**)TLAB_NEXT;
209                 /* FIXME: handle overflow */
210                 new_next = (char*)p + size;
211                 TLAB_NEXT = new_next;
212
213                 if (G_LIKELY (new_next < TLAB_TEMP_END)) {
214                         /* Fast path */
215
216                         /* 
217                          * FIXME: We might need a memory barrier here so the change to tlab_next is 
218                          * visible before the vtable store.
219                          */
220
221                         DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
222                         binary_protocol_alloc (p , vtable, size);
223                         MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
224                         g_assert (*p == NULL);
225                         mono_atomic_store_seq (p, vtable);
226
227                         return p;
228                 }
229
230                 /* Slow path */
231
232                 /* there are two cases: the object is too big or we run out of space in the TLAB */
233                 /* we also reach here when the thread does its first allocation after a minor 
234                  * collection, since the tlab_ variables are initialized to NULL.
235                  * there can be another case (from ORP), if we cooperate with the runtime a bit:
236                  * objects that need finalizers can have the high bit set in their size
237                  * so the above check fails and we can readily add the object to the queue.
238                  * This avoids taking again the GC lock when registering, but this is moot when
239                  * doing thread-local allocation, so it may not be a good idea.
240                  */
241                 if (TLAB_NEXT >= TLAB_REAL_END) {
242                         int available_in_tlab;
243                         /* 
244                          * Run out of space in the TLAB. When this happens, some amount of space
245                          * remains in the TLAB, but not enough to satisfy the current allocation
246                          * request. Currently, we retire the TLAB in all cases, later we could
247                          * keep it if the remaining space is above a treshold, and satisfy the
248                          * allocation directly from the nursery.
249                          */
250                         TLAB_NEXT -= size;
251                         /* when running in degraded mode, we continue allocing that way
252                          * for a while, to decrease the number of useless nursery collections.
253                          */
254                         if (degraded_mode && degraded_mode < DEFAULT_NURSERY_SIZE)
255                                 return alloc_degraded (vtable, size, FALSE);
256
257                         available_in_tlab = TLAB_REAL_END - TLAB_NEXT;
258                         if (size > tlab_size || available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
259                                 /* Allocate directly from the nursery */
260                                 do {
261                                         p = sgen_nursery_alloc (size);
262                                         if (!p) {
263                                                 sgen_ensure_free_space (size);
264                                                 if (degraded_mode)
265                                                         return alloc_degraded (vtable, size, FALSE);
266                                                 else
267                                                         p = sgen_nursery_alloc (size);
268                                         }
269                                 } while (!p);
270                                 if (!p) {
271                                         // no space left
272                                         g_assert (0);
273                                 }
274
275                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
276                                         memset (p, 0, size);
277                                 }
278                         } else {
279                                 size_t alloc_size = 0;
280                                 if (TLAB_START)
281                                         DEBUG (3, fprintf (gc_debug_file, "Retire TLAB: %p-%p [%ld]\n", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size)));
282                                 sgen_nursery_retire_region (p, available_in_tlab);
283
284                                 do {
285                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
286                                         if (!p) {
287                                                 sgen_ensure_free_space (tlab_size);
288                                                 if (degraded_mode)
289                                                         return alloc_degraded (vtable, size, FALSE);
290                                                 else
291                                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
292                                         }
293                                 } while (!p);
294                                         
295                                 if (!p) {
296                                         // no space left
297                                         g_assert (0);
298                                 }
299
300                                 /* Allocate a new TLAB from the current nursery fragment */
301                                 TLAB_START = (char*)p;
302                                 TLAB_NEXT = TLAB_START;
303                                 TLAB_REAL_END = TLAB_START + alloc_size;
304                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
305
306                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
307                                         memset (TLAB_START, 0, alloc_size);
308                                 }
309
310                                 /* Allocate from the TLAB */
311                                 p = (void*)TLAB_NEXT;
312                                 TLAB_NEXT += size;
313                                 sgen_set_nursery_scan_start ((char*)p);
314                         }
315                 } else {
316                         /* Reached tlab_temp_end */
317
318                         /* record the scan start so we can find pinned objects more easily */
319                         sgen_set_nursery_scan_start ((char*)p);
320                         /* we just bump tlab_temp_end as well */
321                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
322                         DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));
323                 }
324         }
325
326         if (G_LIKELY (p)) {
327                 DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
328                 binary_protocol_alloc (p, vtable, size);
329                 if (MONO_GC_MAJOR_OBJ_ALLOC_LARGE_ENABLED () || MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ()) {
330                         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
331                                 MONO_GC_MAJOR_OBJ_ALLOC_LARGE (p, size, NULL);
332                         else
333                                 MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
334                 }
335                 mono_atomic_store_seq (p, vtable);
336         }
337
338         return p;
339 }
340
341 static void*
342 mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
343 {
344         void **p;
345         char *new_next;
346         TLAB_ACCESS_INIT;
347
348         size = ALIGN_UP (size);
349
350         g_assert (vtable->gc_descr);
351         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
352                 return NULL;
353
354         if (G_UNLIKELY (size > tlab_size)) {
355                 /* Allocate directly from the nursery */
356                 p = sgen_nursery_alloc (size);
357                 if (!p)
358                         return NULL;
359                 MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
360                 sgen_set_nursery_scan_start ((char*)p);
361
362                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
363                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
364                         memset (p, 0, size);
365         } else {
366                 int available_in_tlab;
367                 char *real_end;
368                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
369
370                 p = (void**)TLAB_NEXT;
371                 /* FIXME: handle overflow */
372                 new_next = (char*)p + size;
373
374                 real_end = TLAB_REAL_END;
375                 available_in_tlab = real_end - (char*)p;
376
377                 if (G_LIKELY (new_next < real_end)) {
378                         TLAB_NEXT = new_next;
379
380                         /* Second case, we overflowed temp end */
381                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
382                                 sgen_set_nursery_scan_start (new_next);
383                                 /* we just bump tlab_temp_end as well */
384                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
385                                 DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));         
386                         }
387                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
388                         /* Allocate directly from the nursery */
389                         p = sgen_nursery_alloc (size);
390                         if (!p)
391                                 return NULL;
392                         MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
393
394                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
395                                 memset (p, 0, size);                    
396                 } else {
397                         size_t alloc_size = 0;
398
399                         sgen_nursery_retire_region (p, available_in_tlab);
400                         new_next = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
401                         p = (void**)new_next;
402                         if (!p)
403                                 return NULL;
404
405                         TLAB_START = (char*)new_next;
406                         TLAB_NEXT = new_next + size;
407                         TLAB_REAL_END = new_next + alloc_size;
408                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
409                         sgen_set_nursery_scan_start ((char*)p);
410
411                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
412                                 memset (new_next, 0, alloc_size);
413
414                         MONO_GC_NURSERY_TLAB_ALLOC (new_next, alloc_size);
415                 }
416         }
417
418         HEAVY_STAT (++stat_objects_alloced);
419         HEAVY_STAT (stat_bytes_alloced += size);
420
421         DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
422         binary_protocol_alloc (p, vtable, size);
423         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
424
425         mono_atomic_store_seq (p, vtable);
426
427         return p;
428 }
429
430 void*
431 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
432 {
433         void *res;
434 #ifndef DISABLE_CRITICAL_REGION
435         TLAB_ACCESS_INIT;
436         ENTER_CRITICAL_REGION;
437         res = mono_gc_try_alloc_obj_nolock (vtable, size);
438         if (res) {
439                 EXIT_CRITICAL_REGION;
440                 return res;
441         }
442         EXIT_CRITICAL_REGION;
443 #endif
444         LOCK_GC;
445         res = mono_gc_alloc_obj_nolock (vtable, size);
446         UNLOCK_GC;
447         if (G_UNLIKELY (!res))
448                 return mono_gc_out_of_memory (size);
449         return res;
450 }
451
452 void*
453 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
454 {
455         MonoArray *arr;
456 #ifndef DISABLE_CRITICAL_REGION
457         TLAB_ACCESS_INIT;
458         ENTER_CRITICAL_REGION;
459         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
460         if (arr) {
461                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
462                 arr->max_length = max_length;
463                 EXIT_CRITICAL_REGION;
464                 return arr;
465         }
466         EXIT_CRITICAL_REGION;
467 #endif
468
469         LOCK_GC;
470
471         arr = mono_gc_alloc_obj_nolock (vtable, size);
472         if (G_UNLIKELY (!arr)) {
473                 UNLOCK_GC;
474                 return mono_gc_out_of_memory (size);
475         }
476
477         arr->max_length = max_length;
478
479         UNLOCK_GC;
480
481         return arr;
482 }
483
484 void*
485 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
486 {
487         MonoArray *arr;
488         MonoArrayBounds *bounds;
489
490 #ifndef DISABLE_CRITICAL_REGION
491         TLAB_ACCESS_INIT;
492         ENTER_CRITICAL_REGION;
493         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
494         if (arr) {
495                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
496                 arr->max_length = max_length;
497
498                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
499                 arr->bounds = bounds;
500                 EXIT_CRITICAL_REGION;
501                 return arr;
502         }
503         EXIT_CRITICAL_REGION;
504 #endif
505
506         LOCK_GC;
507
508         arr = mono_gc_alloc_obj_nolock (vtable, size);
509         if (G_UNLIKELY (!arr)) {
510                 UNLOCK_GC;
511                 return mono_gc_out_of_memory (size);
512         }
513
514         arr->max_length = max_length;
515
516         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
517         arr->bounds = bounds;
518
519         UNLOCK_GC;
520
521         return arr;
522 }
523
524 void*
525 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
526 {
527         MonoString *str;
528 #ifndef DISABLE_CRITICAL_REGION
529         TLAB_ACCESS_INIT;
530         ENTER_CRITICAL_REGION;
531         str = mono_gc_try_alloc_obj_nolock (vtable, size);
532         if (str) {
533                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
534                 str->length = len;
535                 EXIT_CRITICAL_REGION;
536                 return str;
537         }
538         EXIT_CRITICAL_REGION;
539 #endif
540
541         LOCK_GC;
542
543         str = mono_gc_alloc_obj_nolock (vtable, size);
544         if (G_UNLIKELY (!str)) {
545                 UNLOCK_GC;
546                 return mono_gc_out_of_memory (size);
547         }
548
549         str->length = len;
550
551         UNLOCK_GC;
552
553         return str;
554 }
555
556 /*
557  * To be used for interned strings and possibly MonoThread, reflection handles.
558  * We may want to explicitly free these objects.
559  */
560 void*
561 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
562 {
563         void **p;
564         size = ALIGN_UP (size);
565         LOCK_GC;
566
567         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
568                 /* large objects are always pinned anyway */
569                 p = sgen_los_alloc_large_inner (vtable, size);
570         } else {
571                 DEBUG (9, g_assert (vtable->klass->inited));
572                 p = major_collector.alloc_small_pinned_obj (size, SGEN_VTABLE_HAS_REFERENCES (vtable));
573         }
574         if (G_LIKELY (p)) {
575                 DEBUG (6, fprintf (gc_debug_file, "Allocated pinned object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
576                 if (size > SGEN_MAX_SMALL_OBJ_SIZE)
577                         MONO_GC_MAJOR_OBJ_ALLOC_LARGE (p, size, NULL);
578                 else
579                         MONO_GC_MAJOR_OBJ_ALLOC_PINNED (p, size, NULL);
580                 binary_protocol_alloc_pinned (p, vtable, size);
581                 mono_atomic_store_seq (p, vtable);
582         }
583         UNLOCK_GC;
584         return p;
585 }
586
587 void*
588 mono_gc_alloc_mature (MonoVTable *vtable)
589 {
590         void **res;
591         size_t size = ALIGN_UP (vtable->klass->instance_size);
592         LOCK_GC;
593         res = alloc_degraded (vtable, size, TRUE);
594         mono_atomic_store_seq (res, vtable);
595         UNLOCK_GC;
596         if (G_UNLIKELY (vtable->klass->has_finalize))
597                 mono_object_register_finalizer ((MonoObject*)res);
598
599         return res;
600 }
601
602 void*
603 mono_gc_alloc_fixed (size_t size, void *descr)
604 {
605         /* FIXME: do a single allocation */
606         void *res = calloc (1, size);
607         if (!res)
608                 return NULL;
609         if (!mono_gc_register_root (res, size, descr)) {
610                 free (res);
611                 res = NULL;
612         }
613         return res;
614 }
615
616 void
617 mono_gc_free_fixed (void* addr)
618 {
619         mono_gc_deregister_root (addr);
620         free (addr);
621 }
622
623 void
624 sgen_init_tlab_info (SgenThreadInfo* info)
625 {
626 #ifndef HAVE_KW_THREAD
627         SgenThreadInfo *__thread_info__ = info;
628 #endif
629
630         info->tlab_start_addr = &TLAB_START;
631         info->tlab_next_addr = &TLAB_NEXT;
632         info->tlab_temp_end_addr = &TLAB_TEMP_END;
633         info->tlab_real_end_addr = &TLAB_REAL_END;
634
635 #ifdef HAVE_KW_THREAD
636         tlab_next_addr = &tlab_next;
637 #endif
638 }
639
640 /*
641  * Clear the thread local TLAB variables for all threads.
642  */
643 void
644 sgen_clear_tlabs (void)
645 {
646         SgenThreadInfo *info;
647
648         FOREACH_THREAD (info) {
649                 /* A new TLAB will be allocated when the thread does its first allocation */
650                 *info->tlab_start_addr = NULL;
651                 *info->tlab_next_addr = NULL;
652                 *info->tlab_temp_end_addr = NULL;
653                 *info->tlab_real_end_addr = NULL;
654         } END_FOREACH_THREAD
655 }
656
657 static MonoMethod* alloc_method_cache [ATYPE_NUM];
658
659 #ifdef MANAGED_ALLOCATION
660 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
661  * for each class. This is currently not easy to do, as it is hard to generate basic 
662  * blocks + branches, but it is easy with the linear IL codebase.
663  *
664  * For this to work we'd need to solve the TLAB race, first.  Now we
665  * require the allocator to be in a few known methods to make sure
666  * that they are executed atomically via the restart mechanism.
667  */
668 static MonoMethod*
669 create_allocator (int atype)
670 {
671         int p_var, size_var;
672         guint32 slowpath_branch, max_size_branch;
673         MonoMethodBuilder *mb;
674         MonoMethod *res;
675         MonoMethodSignature *csig;
676         static gboolean registered = FALSE;
677         int tlab_next_addr_var, new_next_var;
678         int num_params, i;
679         const char *name = NULL;
680         AllocatorWrapperInfo *info;
681
682 #ifdef HAVE_KW_THREAD
683         int tlab_next_addr_offset = -1;
684         int tlab_temp_end_offset = -1;
685
686         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
687         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
688
689         g_assert (tlab_next_addr_offset != -1);
690         g_assert (tlab_temp_end_offset != -1);
691 #endif
692
693         if (!registered) {
694                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
695                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
696                 registered = TRUE;
697         }
698
699         if (atype == ATYPE_SMALL) {
700                 num_params = 1;
701                 name = "AllocSmall";
702         } else if (atype == ATYPE_NORMAL) {
703                 num_params = 1;
704                 name = "Alloc";
705         } else if (atype == ATYPE_VECTOR) {
706                 num_params = 2;
707                 name = "AllocVector";
708         } else {
709                 g_assert_not_reached ();
710         }
711
712         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
713         csig->ret = &mono_defaults.object_class->byval_arg;
714         for (i = 0; i < num_params; ++i)
715                 csig->params [i] = &mono_defaults.int_class->byval_arg;
716
717         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
718         size_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
719         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
720                 /* size = vtable->klass->instance_size; */
721                 mono_mb_emit_ldarg (mb, 0);
722                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
723                 mono_mb_emit_byte (mb, CEE_ADD);
724                 mono_mb_emit_byte (mb, CEE_LDIND_I);
725                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
726                 mono_mb_emit_byte (mb, CEE_ADD);
727                 /* FIXME: assert instance_size stays a 4 byte integer */
728                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
729                 mono_mb_emit_stloc (mb, size_var);
730         } else if (atype == ATYPE_VECTOR) {
731                 MonoExceptionClause *clause;
732                 int pos, pos_leave;
733                 MonoClass *oom_exc_class;
734                 MonoMethod *ctor;
735
736                 /* n >  MONO_ARRAY_MAX_INDEX -> OverflowException */
737                 mono_mb_emit_ldarg (mb, 1);
738                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
739                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
740                 mono_mb_emit_exception (mb, "OverflowException", NULL);
741                 mono_mb_patch_short_branch (mb, pos);
742
743                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
744                 clause->try_offset = mono_mb_get_label (mb);
745
746                 /* vtable->klass->sizes.element_size */
747                 mono_mb_emit_ldarg (mb, 0);
748                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
749                 mono_mb_emit_byte (mb, CEE_ADD);
750                 mono_mb_emit_byte (mb, CEE_LDIND_I);
751                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, sizes.element_size));
752                 mono_mb_emit_byte (mb, CEE_ADD);
753                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
754
755                 /* * n */
756                 mono_mb_emit_ldarg (mb, 1);
757                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
758                 /* + sizeof (MonoArray) */
759                 mono_mb_emit_icon (mb, sizeof (MonoArray));
760                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
761                 mono_mb_emit_stloc (mb, size_var);
762
763                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
764
765                 /* catch */
766                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
767                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
768                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
769                                 "System", "OverflowException");
770                 g_assert (clause->data.catch_class);
771                 clause->handler_offset = mono_mb_get_label (mb);
772
773                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
774                                 "System", "OutOfMemoryException");
775                 g_assert (oom_exc_class);
776                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
777                 g_assert (ctor);
778
779                 mono_mb_emit_byte (mb, CEE_POP);
780                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
781                 mono_mb_emit_byte (mb, CEE_THROW);
782
783                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
784                 mono_mb_set_clauses (mb, 1, clause);
785                 mono_mb_patch_branch (mb, pos_leave);
786                 /* end catch */
787         } else {
788                 g_assert_not_reached ();
789         }
790
791         /* size += ALLOC_ALIGN - 1; */
792         mono_mb_emit_ldloc (mb, size_var);
793         mono_mb_emit_icon (mb, ALLOC_ALIGN - 1);
794         mono_mb_emit_byte (mb, CEE_ADD);
795         /* size &= ~(ALLOC_ALIGN - 1); */
796         mono_mb_emit_icon (mb, ~(ALLOC_ALIGN - 1));
797         mono_mb_emit_byte (mb, CEE_AND);
798         mono_mb_emit_stloc (mb, size_var);
799
800         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
801         if (atype != ATYPE_SMALL) {
802                 mono_mb_emit_ldloc (mb, size_var);
803                 mono_mb_emit_icon (mb, MAX_SMALL_OBJ_SIZE);
804                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
805         }
806
807         /*
808          * We need to modify tlab_next, but the JIT only supports reading, so we read
809          * another tls var holding its address instead.
810          */
811
812         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
813         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
814         EMIT_TLS_ACCESS (mb, tlab_next_addr, tlab_next_addr_offset);
815         mono_mb_emit_stloc (mb, tlab_next_addr_var);
816
817         /* p = (void**)tlab_next; */
818         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
819         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
820         mono_mb_emit_byte (mb, CEE_LDIND_I);
821         mono_mb_emit_stloc (mb, p_var);
822         
823         /* new_next = (char*)p + size; */
824         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
825         mono_mb_emit_ldloc (mb, p_var);
826         mono_mb_emit_ldloc (mb, size_var);
827         mono_mb_emit_byte (mb, CEE_CONV_I);
828         mono_mb_emit_byte (mb, CEE_ADD);
829         mono_mb_emit_stloc (mb, new_next_var);
830
831         /* if (G_LIKELY (new_next < tlab_temp_end)) */
832         mono_mb_emit_ldloc (mb, new_next_var);
833         EMIT_TLS_ACCESS (mb, tlab_temp_end, tlab_temp_end_offset);
834         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
835
836         /* Slowpath */
837         if (atype != ATYPE_SMALL)
838                 mono_mb_patch_short_branch (mb, max_size_branch);
839
840         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
841         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
842
843         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
844         mono_mb_emit_ldarg (mb, 0);
845         mono_mb_emit_ldloc (mb, size_var);
846         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
847                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
848         } else if (atype == ATYPE_VECTOR) {
849                 mono_mb_emit_ldarg (mb, 1);
850                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
851         } else {
852                 g_assert_not_reached ();
853         }
854         mono_mb_emit_byte (mb, CEE_RET);
855
856         /* Fastpath */
857         mono_mb_patch_short_branch (mb, slowpath_branch);
858
859         /* FIXME: Memory barrier */
860
861         /* tlab_next = new_next */
862         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
863         mono_mb_emit_ldloc (mb, new_next_var);
864         mono_mb_emit_byte (mb, CEE_STIND_I);
865
866         /*The tlab store must be visible before the the vtable store. This could be replaced with a DDS but doing it with IL would be tricky. */
867         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
868         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
869
870         /* *p = vtable; */
871         mono_mb_emit_ldloc (mb, p_var);
872         mono_mb_emit_ldarg (mb, 0);
873         mono_mb_emit_byte (mb, CEE_STIND_I);
874
875         if (atype == ATYPE_VECTOR) {
876                 /* arr->max_length = max_length; */
877                 mono_mb_emit_ldloc (mb, p_var);
878                 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, max_length));
879                 mono_mb_emit_ldarg (mb, 1);
880 #ifdef MONO_BIG_ARRAYS
881                 mono_mb_emit_byte (mb, CEE_STIND_I);
882 #else
883                 mono_mb_emit_byte (mb, CEE_STIND_I4);
884 #endif
885         }
886
887         /*
888         We must make sure both vtable and max_length are globaly visible before returning to managed land.
889         */
890         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
891         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
892
893         /* return p */
894         mono_mb_emit_ldloc (mb, p_var);
895         mono_mb_emit_byte (mb, CEE_RET);
896
897         res = mono_mb_create_method (mb, csig, 8);
898         mono_mb_free (mb);
899         mono_method_get_header (res)->init_locals = FALSE;
900
901         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
902         info->gc_name = "sgen";
903         info->alloc_type = atype;
904         mono_marshal_set_wrapper_info (res, info);
905
906         return res;
907 }
908 #endif
909
910 /*
911  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
912  * The signature of the called method is:
913  *      object allocate (MonoVTable *vtable)
914  */
915 MonoMethod*
916 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
917 {
918 #ifdef MANAGED_ALLOCATION
919         MonoClass *klass = vtable->klass;
920
921 #ifdef HAVE_KW_THREAD
922         int tlab_next_offset = -1;
923         int tlab_temp_end_offset = -1;
924         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
925         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
926
927         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
928                 return NULL;
929 #endif
930
931         if (!mono_runtime_has_tls_get ())
932                 return NULL;
933         if (klass->instance_size > tlab_size)
934                 return NULL;
935         if (klass->has_finalize || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
936                 return NULL;
937         if (klass->rank)
938                 return NULL;
939         if (klass->byval_arg.type == MONO_TYPE_STRING)
940                 return NULL;
941         if (collect_before_allocs)
942                 return NULL;
943
944         if (ALIGN_TO (klass->instance_size, ALLOC_ALIGN) < MAX_SMALL_OBJ_SIZE)
945                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL);
946         else
947                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL);
948 #else
949         return NULL;
950 #endif
951 }
952
953 MonoMethod*
954 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
955 {
956 #ifdef MANAGED_ALLOCATION
957         MonoClass *klass = vtable->klass;
958
959 #ifdef HAVE_KW_THREAD
960         int tlab_next_offset = -1;
961         int tlab_temp_end_offset = -1;
962         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
963         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
964
965         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
966                 return NULL;
967 #endif
968
969         if (rank != 1)
970                 return NULL;
971         if (!mono_runtime_has_tls_get ())
972                 return NULL;
973         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
974                 return NULL;
975         if (has_per_allocation_action)
976                 return NULL;
977         g_assert (!mono_class_has_finalizer (klass) && !klass->marshalbyref);
978
979         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
980 #else
981         return NULL;
982 #endif
983 }
984
985 MonoMethod*
986 mono_gc_get_managed_allocator_by_type (int atype)
987 {
988 #ifdef MANAGED_ALLOCATION
989         MonoMethod *res;
990
991         if (!mono_runtime_has_tls_get ())
992                 return NULL;
993
994         mono_loader_lock ();
995         res = alloc_method_cache [atype];
996         if (!res)
997                 res = alloc_method_cache [atype] = create_allocator (atype);
998         mono_loader_unlock ();
999         return res;
1000 #else
1001         return NULL;
1002 #endif
1003 }
1004
1005 guint32
1006 mono_gc_get_managed_allocator_types (void)
1007 {
1008         return ATYPE_NUM;
1009 }
1010
1011 gboolean
1012 sgen_is_managed_allocator (MonoMethod *method)
1013 {
1014         int i;
1015
1016         for (i = 0; i < ATYPE_NUM; ++i)
1017                 if (method == alloc_method_cache [i])
1018                         return TRUE;
1019         return FALSE;
1020 }
1021
1022 #ifdef HEAVY_STATISTICS
1023 void
1024 sgen_alloc_init_heavy_stats (void)
1025 {
1026         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);     
1027         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
1028         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
1029 }
1030 #endif
1031
1032 #endif /*HAVE_SGEN_GC*/