[dtrace] Probes for degraded and mature 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                         g_assert (*p == NULL);
224                         mono_atomic_store_seq (p, vtable);
225
226                         return p;
227                 }
228
229                 /* Slow path */
230
231                 /* there are two cases: the object is too big or we run out of space in the TLAB */
232                 /* we also reach here when the thread does its first allocation after a minor 
233                  * collection, since the tlab_ variables are initialized to NULL.
234                  * there can be another case (from ORP), if we cooperate with the runtime a bit:
235                  * objects that need finalizers can have the high bit set in their size
236                  * so the above check fails and we can readily add the object to the queue.
237                  * This avoids taking again the GC lock when registering, but this is moot when
238                  * doing thread-local allocation, so it may not be a good idea.
239                  */
240                 if (TLAB_NEXT >= TLAB_REAL_END) {
241                         int available_in_tlab;
242                         /* 
243                          * Run out of space in the TLAB. When this happens, some amount of space
244                          * remains in the TLAB, but not enough to satisfy the current allocation
245                          * request. Currently, we retire the TLAB in all cases, later we could
246                          * keep it if the remaining space is above a treshold, and satisfy the
247                          * allocation directly from the nursery.
248                          */
249                         TLAB_NEXT -= size;
250                         /* when running in degraded mode, we continue allocing that way
251                          * for a while, to decrease the number of useless nursery collections.
252                          */
253                         if (degraded_mode && degraded_mode < DEFAULT_NURSERY_SIZE)
254                                 return alloc_degraded (vtable, size, FALSE);
255
256                         available_in_tlab = TLAB_REAL_END - TLAB_NEXT;
257                         if (size > tlab_size || available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
258                                 /* Allocate directly from the nursery */
259                                 do {
260                                         p = sgen_nursery_alloc (size);
261                                         if (!p) {
262                                                 sgen_ensure_free_space (size);
263                                                 if (degraded_mode)
264                                                         return alloc_degraded (vtable, size, FALSE);
265                                                 else
266                                                         p = sgen_nursery_alloc (size);
267                                         }
268                                 } while (!p);
269                                 if (!p) {
270                                         // no space left
271                                         g_assert (0);
272                                 }
273                                 if (p)
274                                         MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
275
276                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
277                                         memset (p, 0, size);
278                                 }
279                         } else {
280                                 size_t alloc_size = 0;
281                                 if (TLAB_START)
282                                         DEBUG (3, fprintf (gc_debug_file, "Retire TLAB: %p-%p [%ld]\n", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size)));
283                                 sgen_nursery_retire_region (p, available_in_tlab);
284
285                                 do {
286                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
287                                         if (!p) {
288                                                 sgen_ensure_free_space (tlab_size);
289                                                 if (degraded_mode)
290                                                         return alloc_degraded (vtable, size, FALSE);
291                                                 else
292                                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
293                                         }
294                                 } while (!p);
295                                         
296                                 if (!p) {
297                                         // no space left
298                                         g_assert (0);
299                                 }
300
301                                 /* Allocate a new TLAB from the current nursery fragment */
302                                 TLAB_START = (char*)p;
303                                 TLAB_NEXT = TLAB_START;
304                                 TLAB_REAL_END = TLAB_START + alloc_size;
305                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
306
307                                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
308                                         memset (TLAB_START, 0, alloc_size);
309                                 }
310
311                                 MONO_GC_NURSERY_TLAB_ALLOC (p, alloc_size);
312
313                                 /* Allocate from the TLAB */
314                                 p = (void*)TLAB_NEXT;
315                                 TLAB_NEXT += size;
316                                 sgen_set_nursery_scan_start ((char*)p);
317                         }
318                 } else {
319                         /* Reached tlab_temp_end */
320
321                         /* record the scan start so we can find pinned objects more easily */
322                         sgen_set_nursery_scan_start ((char*)p);
323                         /* we just bump tlab_temp_end as well */
324                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
325                         DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));
326                 }
327         }
328
329         if (G_LIKELY (p)) {
330                 DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
331                 binary_protocol_alloc (p, vtable, size);
332                 mono_atomic_store_seq (p, vtable);
333         }
334
335         return p;
336 }
337
338 static void*
339 mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
340 {
341         void **p;
342         char *new_next;
343         TLAB_ACCESS_INIT;
344
345         size = ALIGN_UP (size);
346
347         g_assert (vtable->gc_descr);
348         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
349                 return NULL;
350
351         if (G_UNLIKELY (size > tlab_size)) {
352                 /* Allocate directly from the nursery */
353                 p = sgen_nursery_alloc (size);
354                 if (!p)
355                         return NULL;
356                 MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
357                 sgen_set_nursery_scan_start ((char*)p);
358
359                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
360                 if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
361                         memset (p, 0, size);
362         } else {
363                 int available_in_tlab;
364                 char *real_end;
365                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
366
367                 p = (void**)TLAB_NEXT;
368                 /* FIXME: handle overflow */
369                 new_next = (char*)p + size;
370
371                 real_end = TLAB_REAL_END;
372                 available_in_tlab = real_end - (char*)p;
373
374                 if (G_LIKELY (new_next < real_end)) {
375                         TLAB_NEXT = new_next;
376
377                         /* Second case, we overflowed temp end */
378                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
379                                 sgen_set_nursery_scan_start (new_next);
380                                 /* we just bump tlab_temp_end as well */
381                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
382                                 DEBUG (5, fprintf (gc_debug_file, "Expanding local alloc: %p-%p\n", TLAB_NEXT, TLAB_TEMP_END));         
383                         }
384                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
385                         /* Allocate directly from the nursery */
386                         p = sgen_nursery_alloc (size);
387                         if (!p)
388                                 return NULL;
389                         MONO_GC_NURSERY_OBJ_ALLOC (p, size, NULL);
390
391                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
392                                 memset (p, 0, size);                    
393                 } else {
394                         size_t alloc_size = 0;
395
396                         sgen_nursery_retire_region (p, available_in_tlab);
397                         new_next = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
398                         p = (void**)new_next;
399                         if (!p)
400                                 return NULL;
401
402                         TLAB_START = (char*)new_next;
403                         TLAB_NEXT = new_next + size;
404                         TLAB_REAL_END = new_next + alloc_size;
405                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
406                         sgen_set_nursery_scan_start ((char*)p);
407
408                         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION)
409                                 memset (new_next, 0, alloc_size);
410
411                         MONO_GC_NURSERY_TLAB_ALLOC (new_next, alloc_size);
412                 }
413         }
414
415         HEAVY_STAT (++stat_objects_alloced);
416         HEAVY_STAT (stat_bytes_alloced += size);
417
418         DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
419         binary_protocol_alloc (p, vtable, size);
420         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
421
422         mono_atomic_store_seq (p, vtable);
423
424         return p;
425 }
426
427 void*
428 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
429 {
430         void *res;
431 #ifndef DISABLE_CRITICAL_REGION
432         TLAB_ACCESS_INIT;
433         ENTER_CRITICAL_REGION;
434         res = mono_gc_try_alloc_obj_nolock (vtable, size);
435         if (res) {
436                 EXIT_CRITICAL_REGION;
437                 return res;
438         }
439         EXIT_CRITICAL_REGION;
440 #endif
441         LOCK_GC;
442         res = mono_gc_alloc_obj_nolock (vtable, size);
443         UNLOCK_GC;
444         if (G_UNLIKELY (!res))
445                 return mono_gc_out_of_memory (size);
446         return res;
447 }
448
449 void*
450 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
451 {
452         MonoArray *arr;
453 #ifndef DISABLE_CRITICAL_REGION
454         TLAB_ACCESS_INIT;
455         ENTER_CRITICAL_REGION;
456         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
457         if (arr) {
458                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
459                 arr->max_length = max_length;
460                 EXIT_CRITICAL_REGION;
461                 return arr;
462         }
463         EXIT_CRITICAL_REGION;
464 #endif
465
466         LOCK_GC;
467
468         arr = mono_gc_alloc_obj_nolock (vtable, size);
469         if (G_UNLIKELY (!arr)) {
470                 UNLOCK_GC;
471                 return mono_gc_out_of_memory (size);
472         }
473
474         arr->max_length = max_length;
475
476         UNLOCK_GC;
477
478         return arr;
479 }
480
481 void*
482 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
483 {
484         MonoArray *arr;
485         MonoArrayBounds *bounds;
486
487 #ifndef DISABLE_CRITICAL_REGION
488         TLAB_ACCESS_INIT;
489         ENTER_CRITICAL_REGION;
490         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
491         if (arr) {
492                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
493                 arr->max_length = max_length;
494
495                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
496                 arr->bounds = bounds;
497                 EXIT_CRITICAL_REGION;
498                 return arr;
499         }
500         EXIT_CRITICAL_REGION;
501 #endif
502
503         LOCK_GC;
504
505         arr = mono_gc_alloc_obj_nolock (vtable, size);
506         if (G_UNLIKELY (!arr)) {
507                 UNLOCK_GC;
508                 return mono_gc_out_of_memory (size);
509         }
510
511         arr->max_length = max_length;
512
513         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
514         arr->bounds = bounds;
515
516         UNLOCK_GC;
517
518         return arr;
519 }
520
521 void*
522 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
523 {
524         MonoString *str;
525 #ifndef DISABLE_CRITICAL_REGION
526         TLAB_ACCESS_INIT;
527         ENTER_CRITICAL_REGION;
528         str = mono_gc_try_alloc_obj_nolock (vtable, size);
529         if (str) {
530                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
531                 str->length = len;
532                 EXIT_CRITICAL_REGION;
533                 return str;
534         }
535         EXIT_CRITICAL_REGION;
536 #endif
537
538         LOCK_GC;
539
540         str = mono_gc_alloc_obj_nolock (vtable, size);
541         if (G_UNLIKELY (!str)) {
542                 UNLOCK_GC;
543                 return mono_gc_out_of_memory (size);
544         }
545
546         str->length = len;
547
548         UNLOCK_GC;
549
550         return str;
551 }
552
553 /*
554  * To be used for interned strings and possibly MonoThread, reflection handles.
555  * We may want to explicitly free these objects.
556  */
557 void*
558 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
559 {
560         void **p;
561         size = ALIGN_UP (size);
562         LOCK_GC;
563
564         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
565                 /* large objects are always pinned anyway */
566                 p = sgen_los_alloc_large_inner (vtable, size);
567         } else {
568                 DEBUG (9, g_assert (vtable->klass->inited));
569                 p = major_collector.alloc_small_pinned_obj (size, SGEN_VTABLE_HAS_REFERENCES (vtable));
570         }
571         if (G_LIKELY (p)) {
572                 DEBUG (6, fprintf (gc_debug_file, "Allocated pinned object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
573                 binary_protocol_alloc_pinned (p, vtable, size);
574                 mono_atomic_store_seq (p, vtable);
575         }
576         UNLOCK_GC;
577         return p;
578 }
579
580 void*
581 mono_gc_alloc_mature (MonoVTable *vtable)
582 {
583         void **res;
584         size_t size = ALIGN_UP (vtable->klass->instance_size);
585         LOCK_GC;
586         res = alloc_degraded (vtable, size, TRUE);
587         mono_atomic_store_seq (res, vtable);
588         UNLOCK_GC;
589         if (G_UNLIKELY (vtable->klass->has_finalize))
590                 mono_object_register_finalizer ((MonoObject*)res);
591
592         return res;
593 }
594
595 void*
596 mono_gc_alloc_fixed (size_t size, void *descr)
597 {
598         /* FIXME: do a single allocation */
599         void *res = calloc (1, size);
600         if (!res)
601                 return NULL;
602         if (!mono_gc_register_root (res, size, descr)) {
603                 free (res);
604                 res = NULL;
605         }
606         return res;
607 }
608
609 void
610 mono_gc_free_fixed (void* addr)
611 {
612         mono_gc_deregister_root (addr);
613         free (addr);
614 }
615
616 void
617 sgen_init_tlab_info (SgenThreadInfo* info)
618 {
619 #ifndef HAVE_KW_THREAD
620         SgenThreadInfo *__thread_info__ = info;
621 #endif
622
623         info->tlab_start_addr = &TLAB_START;
624         info->tlab_next_addr = &TLAB_NEXT;
625         info->tlab_temp_end_addr = &TLAB_TEMP_END;
626         info->tlab_real_end_addr = &TLAB_REAL_END;
627
628 #ifdef HAVE_KW_THREAD
629         tlab_next_addr = &tlab_next;
630 #endif
631 }
632
633 /*
634  * Clear the thread local TLAB variables for all threads.
635  */
636 void
637 sgen_clear_tlabs (void)
638 {
639         SgenThreadInfo *info;
640
641         FOREACH_THREAD (info) {
642                 /* A new TLAB will be allocated when the thread does its first allocation */
643                 *info->tlab_start_addr = NULL;
644                 *info->tlab_next_addr = NULL;
645                 *info->tlab_temp_end_addr = NULL;
646                 *info->tlab_real_end_addr = NULL;
647         } END_FOREACH_THREAD
648 }
649
650 static MonoMethod* alloc_method_cache [ATYPE_NUM];
651
652 #ifdef MANAGED_ALLOCATION
653 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
654  * for each class. This is currently not easy to do, as it is hard to generate basic 
655  * blocks + branches, but it is easy with the linear IL codebase.
656  *
657  * For this to work we'd need to solve the TLAB race, first.  Now we
658  * require the allocator to be in a few known methods to make sure
659  * that they are executed atomically via the restart mechanism.
660  */
661 static MonoMethod*
662 create_allocator (int atype)
663 {
664         int p_var, size_var;
665         guint32 slowpath_branch, max_size_branch;
666         MonoMethodBuilder *mb;
667         MonoMethod *res;
668         MonoMethodSignature *csig;
669         static gboolean registered = FALSE;
670         int tlab_next_addr_var, new_next_var;
671         int num_params, i;
672         const char *name = NULL;
673         AllocatorWrapperInfo *info;
674
675 #ifdef HAVE_KW_THREAD
676         int tlab_next_addr_offset = -1;
677         int tlab_temp_end_offset = -1;
678
679         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
680         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
681
682         g_assert (tlab_next_addr_offset != -1);
683         g_assert (tlab_temp_end_offset != -1);
684 #endif
685
686         if (!registered) {
687                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
688                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
689                 registered = TRUE;
690         }
691
692         if (atype == ATYPE_SMALL) {
693                 num_params = 1;
694                 name = "AllocSmall";
695         } else if (atype == ATYPE_NORMAL) {
696                 num_params = 1;
697                 name = "Alloc";
698         } else if (atype == ATYPE_VECTOR) {
699                 num_params = 2;
700                 name = "AllocVector";
701         } else {
702                 g_assert_not_reached ();
703         }
704
705         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
706         csig->ret = &mono_defaults.object_class->byval_arg;
707         for (i = 0; i < num_params; ++i)
708                 csig->params [i] = &mono_defaults.int_class->byval_arg;
709
710         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
711         size_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
712         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
713                 /* size = vtable->klass->instance_size; */
714                 mono_mb_emit_ldarg (mb, 0);
715                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
716                 mono_mb_emit_byte (mb, CEE_ADD);
717                 mono_mb_emit_byte (mb, CEE_LDIND_I);
718                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
719                 mono_mb_emit_byte (mb, CEE_ADD);
720                 /* FIXME: assert instance_size stays a 4 byte integer */
721                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
722                 mono_mb_emit_stloc (mb, size_var);
723         } else if (atype == ATYPE_VECTOR) {
724                 MonoExceptionClause *clause;
725                 int pos, pos_leave;
726                 MonoClass *oom_exc_class;
727                 MonoMethod *ctor;
728
729                 /* n >  MONO_ARRAY_MAX_INDEX -> OverflowException */
730                 mono_mb_emit_ldarg (mb, 1);
731                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
732                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
733                 mono_mb_emit_exception (mb, "OverflowException", NULL);
734                 mono_mb_patch_short_branch (mb, pos);
735
736                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
737                 clause->try_offset = mono_mb_get_label (mb);
738
739                 /* vtable->klass->sizes.element_size */
740                 mono_mb_emit_ldarg (mb, 0);
741                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
742                 mono_mb_emit_byte (mb, CEE_ADD);
743                 mono_mb_emit_byte (mb, CEE_LDIND_I);
744                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, sizes.element_size));
745                 mono_mb_emit_byte (mb, CEE_ADD);
746                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
747
748                 /* * n */
749                 mono_mb_emit_ldarg (mb, 1);
750                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
751                 /* + sizeof (MonoArray) */
752                 mono_mb_emit_icon (mb, sizeof (MonoArray));
753                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
754                 mono_mb_emit_stloc (mb, size_var);
755
756                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
757
758                 /* catch */
759                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
760                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
761                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
762                                 "System", "OverflowException");
763                 g_assert (clause->data.catch_class);
764                 clause->handler_offset = mono_mb_get_label (mb);
765
766                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
767                                 "System", "OutOfMemoryException");
768                 g_assert (oom_exc_class);
769                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
770                 g_assert (ctor);
771
772                 mono_mb_emit_byte (mb, CEE_POP);
773                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
774                 mono_mb_emit_byte (mb, CEE_THROW);
775
776                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
777                 mono_mb_set_clauses (mb, 1, clause);
778                 mono_mb_patch_branch (mb, pos_leave);
779                 /* end catch */
780         } else {
781                 g_assert_not_reached ();
782         }
783
784         /* size += ALLOC_ALIGN - 1; */
785         mono_mb_emit_ldloc (mb, size_var);
786         mono_mb_emit_icon (mb, ALLOC_ALIGN - 1);
787         mono_mb_emit_byte (mb, CEE_ADD);
788         /* size &= ~(ALLOC_ALIGN - 1); */
789         mono_mb_emit_icon (mb, ~(ALLOC_ALIGN - 1));
790         mono_mb_emit_byte (mb, CEE_AND);
791         mono_mb_emit_stloc (mb, size_var);
792
793         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
794         if (atype != ATYPE_SMALL) {
795                 mono_mb_emit_ldloc (mb, size_var);
796                 mono_mb_emit_icon (mb, MAX_SMALL_OBJ_SIZE);
797                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
798         }
799
800         /*
801          * We need to modify tlab_next, but the JIT only supports reading, so we read
802          * another tls var holding its address instead.
803          */
804
805         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
806         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
807         EMIT_TLS_ACCESS (mb, tlab_next_addr, tlab_next_addr_offset);
808         mono_mb_emit_stloc (mb, tlab_next_addr_var);
809
810         /* p = (void**)tlab_next; */
811         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
812         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
813         mono_mb_emit_byte (mb, CEE_LDIND_I);
814         mono_mb_emit_stloc (mb, p_var);
815         
816         /* new_next = (char*)p + size; */
817         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
818         mono_mb_emit_ldloc (mb, p_var);
819         mono_mb_emit_ldloc (mb, size_var);
820         mono_mb_emit_byte (mb, CEE_CONV_I);
821         mono_mb_emit_byte (mb, CEE_ADD);
822         mono_mb_emit_stloc (mb, new_next_var);
823
824         /* if (G_LIKELY (new_next < tlab_temp_end)) */
825         mono_mb_emit_ldloc (mb, new_next_var);
826         EMIT_TLS_ACCESS (mb, tlab_temp_end, tlab_temp_end_offset);
827         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
828
829         /* Slowpath */
830         if (atype != ATYPE_SMALL)
831                 mono_mb_patch_short_branch (mb, max_size_branch);
832
833         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
834         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
835
836         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
837         mono_mb_emit_ldarg (mb, 0);
838         mono_mb_emit_ldloc (mb, size_var);
839         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
840                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
841         } else if (atype == ATYPE_VECTOR) {
842                 mono_mb_emit_ldarg (mb, 1);
843                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
844         } else {
845                 g_assert_not_reached ();
846         }
847         mono_mb_emit_byte (mb, CEE_RET);
848
849         /* Fastpath */
850         mono_mb_patch_short_branch (mb, slowpath_branch);
851
852         /* FIXME: Memory barrier */
853
854         /* tlab_next = new_next */
855         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
856         mono_mb_emit_ldloc (mb, new_next_var);
857         mono_mb_emit_byte (mb, CEE_STIND_I);
858
859         /*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. */
860         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
861         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
862
863         /* *p = vtable; */
864         mono_mb_emit_ldloc (mb, p_var);
865         mono_mb_emit_ldarg (mb, 0);
866         mono_mb_emit_byte (mb, CEE_STIND_I);
867
868         if (atype == ATYPE_VECTOR) {
869                 /* arr->max_length = max_length; */
870                 mono_mb_emit_ldloc (mb, p_var);
871                 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, max_length));
872                 mono_mb_emit_ldarg (mb, 1);
873 #ifdef MONO_BIG_ARRAYS
874                 mono_mb_emit_byte (mb, CEE_STIND_I);
875 #else
876                 mono_mb_emit_byte (mb, CEE_STIND_I4);
877 #endif
878         }
879
880         /*
881         We must make sure both vtable and max_length are globaly visible before returning to managed land.
882         */
883         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
884         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
885
886         /* return p */
887         mono_mb_emit_ldloc (mb, p_var);
888         mono_mb_emit_byte (mb, CEE_RET);
889
890         res = mono_mb_create_method (mb, csig, 8);
891         mono_mb_free (mb);
892         mono_method_get_header (res)->init_locals = FALSE;
893
894         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
895         info->gc_name = "sgen";
896         info->alloc_type = atype;
897         mono_marshal_set_wrapper_info (res, info);
898
899         return res;
900 }
901 #endif
902
903 /*
904  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
905  * The signature of the called method is:
906  *      object allocate (MonoVTable *vtable)
907  */
908 MonoMethod*
909 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
910 {
911 #ifdef MANAGED_ALLOCATION
912         MonoClass *klass = vtable->klass;
913
914 #ifdef HAVE_KW_THREAD
915         int tlab_next_offset = -1;
916         int tlab_temp_end_offset = -1;
917         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
918         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
919
920         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
921                 return NULL;
922 #endif
923
924         if (!mono_runtime_has_tls_get ())
925                 return NULL;
926         if (klass->instance_size > tlab_size)
927                 return NULL;
928         if (klass->has_finalize || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
929                 return NULL;
930         if (klass->rank)
931                 return NULL;
932         if (klass->byval_arg.type == MONO_TYPE_STRING)
933                 return NULL;
934         if (collect_before_allocs)
935                 return NULL;
936
937         if (ALIGN_TO (klass->instance_size, ALLOC_ALIGN) < MAX_SMALL_OBJ_SIZE)
938                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL);
939         else
940                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL);
941 #else
942         return NULL;
943 #endif
944 }
945
946 MonoMethod*
947 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
948 {
949 #ifdef MANAGED_ALLOCATION
950         MonoClass *klass = vtable->klass;
951
952 #ifdef HAVE_KW_THREAD
953         int tlab_next_offset = -1;
954         int tlab_temp_end_offset = -1;
955         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
956         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
957
958         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
959                 return NULL;
960 #endif
961
962         if (rank != 1)
963                 return NULL;
964         if (!mono_runtime_has_tls_get ())
965                 return NULL;
966         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
967                 return NULL;
968         if (has_per_allocation_action)
969                 return NULL;
970         g_assert (!mono_class_has_finalizer (klass) && !klass->marshalbyref);
971
972         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
973 #else
974         return NULL;
975 #endif
976 }
977
978 MonoMethod*
979 mono_gc_get_managed_allocator_by_type (int atype)
980 {
981 #ifdef MANAGED_ALLOCATION
982         MonoMethod *res;
983
984         if (!mono_runtime_has_tls_get ())
985                 return NULL;
986
987         mono_loader_lock ();
988         res = alloc_method_cache [atype];
989         if (!res)
990                 res = alloc_method_cache [atype] = create_allocator (atype);
991         mono_loader_unlock ();
992         return res;
993 #else
994         return NULL;
995 #endif
996 }
997
998 guint32
999 mono_gc_get_managed_allocator_types (void)
1000 {
1001         return ATYPE_NUM;
1002 }
1003
1004 gboolean
1005 sgen_is_managed_allocator (MonoMethod *method)
1006 {
1007         int i;
1008
1009         for (i = 0; i < ATYPE_NUM; ++i)
1010                 if (method == alloc_method_cache [i])
1011                         return TRUE;
1012         return FALSE;
1013 }
1014
1015 #ifdef HEAVY_STATISTICS
1016 void
1017 sgen_alloc_init_heavy_stats (void)
1018 {
1019         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);     
1020         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
1021         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
1022 }
1023 #endif
1024
1025 #endif /*HAVE_SGEN_GC*/