[Patch 2/7 s390] Deprecate *_BY_PIECES_P, move to hookized version
[official-gcc.git] / libgo / runtime / malloc.goc
blobc5e64c893b83e6fff5f7f936227e5bf11a61617f
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // See malloc.h for overview.
6 //
7 // TODO(rsc): double-check stats.
9 package runtime
10 #include <stddef.h>
11 #include <errno.h>
12 #include <stdlib.h>
13 #include "go-alloc.h"
14 #include "runtime.h"
15 #include "arch.h"
16 #include "malloc.h"
17 #include "interface.h"
18 #include "go-type.h"
19 #include "race.h"
21 // Map gccgo field names to gc field names.
22 // Eface aka __go_empty_interface.
23 #define type __type_descriptor
24 // Type aka __go_type_descriptor
25 #define kind __code
26 #define string __reflection
27 #define KindPtr GO_PTR
28 #define KindNoPointers GO_NO_POINTERS
30 // GCCGO SPECIFIC CHANGE
32 // There is a long comment in runtime_mallocinit about where to put the heap
33 // on a 64-bit system.  It makes assumptions that are not valid on linux/arm64
34 // -- it assumes user space can choose the lower 47 bits of a pointer, but on
35 // linux/arm64 we can only choose the lower 39 bits.  This means the heap is
36 // roughly a quarter of the available address space and we cannot choose a bit
37 // pattern that all pointers will have -- luckily the GC is mostly precise
38 // these days so this doesn't matter all that much.  The kernel (as of 3.13)
39 // will allocate address space starting either down from 0x7fffffffff or up
40 // from 0x2000000000, so we put the heap roughly in the middle of these two
41 // addresses to minimize the chance that a non-heap allocation will get in the
42 // way of the heap.
44 // This all means that there isn't much point in trying 256 different
45 // locations for the heap on such systems.
46 #ifdef __aarch64__
47 #define HeapBase(i) ((void*)(uintptr)(0x40ULL<<32))
48 #define HeapBaseOptions 1
49 #else
50 #define HeapBase(i) ((void*)(uintptr)(i<<40|0x00c0ULL<<32))
51 #define HeapBaseOptions 0x80
52 #endif
53 // END GCCGO SPECIFIC CHANGE
55 // Mark mheap as 'no pointers', it does not contain interesting pointers but occupies ~45K.
56 MHeap runtime_mheap;
57 MStats mstats;
59 int32   runtime_checking;
61 extern MStats mstats;   // defined in zruntime_def_$GOOS_$GOARCH.go
63 extern volatile intgo runtime_MemProfileRate
64   __asm__ (GOSYM_PREFIX "runtime.MemProfileRate");
66 static MSpan* largealloc(uint32, uintptr*);
67 static void profilealloc(void *v, uintptr size);
68 static void settype(MSpan *s, void *v, uintptr typ);
70 // Allocate an object of at least size bytes.
71 // Small objects are allocated from the per-thread cache's free lists.
72 // Large objects (> 32 kB) are allocated straight from the heap.
73 // If the block will be freed with runtime_free(), typ must be 0.
74 void*
75 runtime_mallocgc(uintptr size, uintptr typ, uint32 flag)
77         M *m;
78         G *g;
79         int32 sizeclass;
80         uintptr tinysize, size1;
81         intgo rate;
82         MCache *c;
83         MSpan *s;
84         MLink *v, *next;
85         byte *tiny;
86         bool incallback;
87         void *closure;
89         if(size == 0) {
90                 // All 0-length allocations use this pointer.
91                 // The language does not require the allocations to
92                 // have distinct values.
93                 return &runtime_zerobase;
94         }
96         m = runtime_m();
97         g = runtime_g();
99         // We should not be called in between __go_set_closure and the
100         // actual function call, but cope with it if we are.
101         closure = g->closure;
103         incallback = false;
104         if(m->mcache == nil && g->ncgo > 0) {
105                 // For gccgo this case can occur when a cgo or SWIG function
106                 // has an interface return type and the function
107                 // returns a non-pointer, so memory allocation occurs
108                 // after syscall.Cgocall but before syscall.CgocallDone.
109                 // We treat it as a callback.
110                 runtime_exitsyscall();
111                 m = runtime_m();
112                 incallback = true;
113                 flag |= FlagNoInvokeGC;
114         }
116         if(runtime_gcwaiting() && g != m->g0 && m->locks == 0 && !(flag & FlagNoInvokeGC)) {
117                 runtime_gosched();
118                 m = runtime_m();
119         }
120         if(m->mallocing)
121                 runtime_throw("malloc/free - deadlock");
122         // Disable preemption during settype.
123         // We can not use m->mallocing for this, because settype calls mallocgc.
124         m->locks++;
125         m->mallocing = 1;
127         if(DebugTypeAtBlockEnd)
128                 size += sizeof(uintptr);
130         c = m->mcache;
131         if(!runtime_debug.efence && size <= MaxSmallSize) {
132                 if((flag&(FlagNoScan|FlagNoGC)) == FlagNoScan && size < TinySize) {
133                         // Tiny allocator.
134                         //
135                         // Tiny allocator combines several tiny allocation requests
136                         // into a single memory block. The resulting memory block
137                         // is freed when all subobjects are unreachable. The subobjects
138                         // must be FlagNoScan (don't have pointers), this ensures that
139                         // the amount of potentially wasted memory is bounded.
140                         //
141                         // Size of the memory block used for combining (TinySize) is tunable.
142                         // Current setting is 16 bytes, which relates to 2x worst case memory
143                         // wastage (when all but one subobjects are unreachable).
144                         // 8 bytes would result in no wastage at all, but provides less
145                         // opportunities for combining.
146                         // 32 bytes provides more opportunities for combining,
147                         // but can lead to 4x worst case wastage.
148                         // The best case winning is 8x regardless of block size.
149                         //
150                         // Objects obtained from tiny allocator must not be freed explicitly.
151                         // So when an object will be freed explicitly, we ensure that
152                         // its size >= TinySize.
153                         //
154                         // SetFinalizer has a special case for objects potentially coming
155                         // from tiny allocator, it such case it allows to set finalizers
156                         // for an inner byte of a memory block.
157                         //
158                         // The main targets of tiny allocator are small strings and
159                         // standalone escaping variables. On a json benchmark
160                         // the allocator reduces number of allocations by ~12% and
161                         // reduces heap size by ~20%.
163                         tinysize = c->tinysize;
164                         if(size <= tinysize) {
165                                 tiny = c->tiny;
166                                 // Align tiny pointer for required (conservative) alignment.
167                                 if((size&7) == 0)
168                                         tiny = (byte*)ROUND((uintptr)tiny, 8);
169                                 else if((size&3) == 0)
170                                         tiny = (byte*)ROUND((uintptr)tiny, 4);
171                                 else if((size&1) == 0)
172                                         tiny = (byte*)ROUND((uintptr)tiny, 2);
173                                 size1 = size + (tiny - c->tiny);
174                                 if(size1 <= tinysize) {
175                                         // The object fits into existing tiny block.
176                                         v = (MLink*)tiny;
177                                         c->tiny += size1;
178                                         c->tinysize -= size1;
179                                         m->mallocing = 0;
180                                         m->locks--;
181                                         if(incallback)
182                                                 runtime_entersyscall();
183                                         g->closure = closure;
184                                         return v;
185                                 }
186                         }
187                         // Allocate a new TinySize block.
188                         s = c->alloc[TinySizeClass];
189                         if(s->freelist == nil)
190                                 s = runtime_MCache_Refill(c, TinySizeClass);
191                         v = s->freelist;
192                         next = v->next;
193                         s->freelist = next;
194                         s->ref++;
195                         if(next != nil)  // prefetching nil leads to a DTLB miss
196                                 PREFETCH(next);
197                         ((uint64*)v)[0] = 0;
198                         ((uint64*)v)[1] = 0;
199                         // See if we need to replace the existing tiny block with the new one
200                         // based on amount of remaining free space.
201                         if(TinySize-size > tinysize) {
202                                 c->tiny = (byte*)v + size;
203                                 c->tinysize = TinySize - size;
204                         }
205                         size = TinySize;
206                         goto done;
207                 }
208                 // Allocate from mcache free lists.
209                 // Inlined version of SizeToClass().
210                 if(size <= 1024-8)
211                         sizeclass = runtime_size_to_class8[(size+7)>>3];
212                 else
213                         sizeclass = runtime_size_to_class128[(size-1024+127) >> 7];
214                 size = runtime_class_to_size[sizeclass];
215                 s = c->alloc[sizeclass];
216                 if(s->freelist == nil)
217                         s = runtime_MCache_Refill(c, sizeclass);
218                 v = s->freelist;
219                 next = v->next;
220                 s->freelist = next;
221                 s->ref++;
222                 if(next != nil)  // prefetching nil leads to a DTLB miss
223                         PREFETCH(next);
224                 if(!(flag & FlagNoZero)) {
225                         v->next = nil;
226                         // block is zeroed iff second word is zero ...
227                         if(size > 2*sizeof(uintptr) && ((uintptr*)v)[1] != 0)
228                                 runtime_memclr((byte*)v, size);
229                 }
230         done:
231                 c->local_cachealloc += size;
232         } else {
233                 // Allocate directly from heap.
234                 s = largealloc(flag, &size);
235                 v = (void*)(s->start << PageShift);
236         }
238         if(flag & FlagNoGC)
239                 runtime_marknogc(v);
240         else if(!(flag & FlagNoScan))
241                 runtime_markscan(v);
243         if(DebugTypeAtBlockEnd)
244                 *(uintptr*)((uintptr)v+size-sizeof(uintptr)) = typ;
246         m->mallocing = 0;
247         // TODO: save type even if FlagNoScan?  Potentially expensive but might help
248         // heap profiling/tracing.
249         if(UseSpanType && !(flag & FlagNoScan) && typ != 0)
250                 settype(s, v, typ);
252         if(raceenabled)
253                 runtime_racemalloc(v, size);
255         if(runtime_debug.allocfreetrace)
256                 runtime_tracealloc(v, size, typ);
258         if(!(flag & FlagNoProfiling) && (rate = runtime_MemProfileRate) > 0) {
259                 if(size < (uintptr)rate && size < (uintptr)(uint32)c->next_sample)
260                         c->next_sample -= size;
261                 else
262                         profilealloc(v, size);
263         }
265         m->locks--;
267         if(!(flag & FlagNoInvokeGC) && mstats.heap_alloc >= mstats.next_gc)
268                 runtime_gc(0);
270         if(incallback)
271                 runtime_entersyscall();
273         g->closure = closure;
275         return v;
278 static MSpan*
279 largealloc(uint32 flag, uintptr *sizep)
281         uintptr npages, size;
282         MSpan *s;
283         void *v;
285         // Allocate directly from heap.
286         size = *sizep;
287         if(size + PageSize < size)
288                 runtime_throw("out of memory");
289         npages = size >> PageShift;
290         if((size & PageMask) != 0)
291                 npages++;
292         s = runtime_MHeap_Alloc(&runtime_mheap, npages, 0, 1, !(flag & FlagNoZero));
293         if(s == nil)
294                 runtime_throw("out of memory");
295         s->limit = (byte*)(s->start<<PageShift) + size;
296         *sizep = npages<<PageShift;
297         v = (void*)(s->start << PageShift);
298         // setup for mark sweep
299         runtime_markspan(v, 0, 0, true);
300         return s;
303 static void
304 profilealloc(void *v, uintptr size)
306         uintptr rate;
307         int32 next;
308         MCache *c;
310         c = runtime_m()->mcache;
311         rate = runtime_MemProfileRate;
312         if(size < rate) {
313                 // pick next profile time
314                 // If you change this, also change allocmcache.
315                 if(rate > 0x3fffffff)   // make 2*rate not overflow
316                         rate = 0x3fffffff;
317                 next = runtime_fastrand1() % (2*rate);
318                 // Subtract the "remainder" of the current allocation.
319                 // Otherwise objects that are close in size to sampling rate
320                 // will be under-sampled, because we consistently discard this remainder.
321                 next -= (size - c->next_sample);
322                 if(next < 0)
323                         next = 0;
324                 c->next_sample = next;
325         }
326         runtime_MProf_Malloc(v, size);
329 void*
330 __go_alloc(uintptr size)
332         return runtime_mallocgc(size, 0, FlagNoInvokeGC);
335 // Free the object whose base pointer is v.
336 void
337 __go_free(void *v)
339         M *m;
340         int32 sizeclass;
341         MSpan *s;
342         MCache *c;
343         uintptr size;
345         if(v == nil)
346                 return;
347         
348         // If you change this also change mgc0.c:/^sweep,
349         // which has a copy of the guts of free.
351         m = runtime_m();
352         if(m->mallocing)
353                 runtime_throw("malloc/free - deadlock");
354         m->mallocing = 1;
356         if(!runtime_mlookup(v, nil, nil, &s)) {
357                 runtime_printf("free %p: not an allocated block\n", v);
358                 runtime_throw("free runtime_mlookup");
359         }
360         size = s->elemsize;
361         sizeclass = s->sizeclass;
362         // Objects that are smaller than TinySize can be allocated using tiny alloc,
363         // if then such object is combined with an object with finalizer, we will crash.
364         if(size < TinySize)
365                 runtime_throw("freeing too small block");
367         if(runtime_debug.allocfreetrace)
368                 runtime_tracefree(v, size);
370         // Ensure that the span is swept.
371         // If we free into an unswept span, we will corrupt GC bitmaps.
372         runtime_MSpan_EnsureSwept(s);
374         if(s->specials != nil)
375                 runtime_freeallspecials(s, v, size);
377         c = m->mcache;
378         if(sizeclass == 0) {
379                 // Large object.
380                 s->needzero = 1;
381                 // Must mark v freed before calling unmarkspan and MHeap_Free:
382                 // they might coalesce v into other spans and change the bitmap further.
383                 runtime_markfreed(v);
384                 runtime_unmarkspan(v, 1<<PageShift);
385                 // NOTE(rsc,dvyukov): The original implementation of efence
386                 // in CL 22060046 used SysFree instead of SysFault, so that
387                 // the operating system would eventually give the memory
388                 // back to us again, so that an efence program could run
389                 // longer without running out of memory. Unfortunately,
390                 // calling SysFree here without any kind of adjustment of the
391                 // heap data structures means that when the memory does
392                 // come back to us, we have the wrong metadata for it, either in
393                 // the MSpan structures or in the garbage collection bitmap.
394                 // Using SysFault here means that the program will run out of
395                 // memory fairly quickly in efence mode, but at least it won't
396                 // have mysterious crashes due to confused memory reuse.
397                 // It should be possible to switch back to SysFree if we also 
398                 // implement and then call some kind of MHeap_DeleteSpan.
399                 if(runtime_debug.efence)
400                         runtime_SysFault((void*)(s->start<<PageShift), size);
401                 else
402                         runtime_MHeap_Free(&runtime_mheap, s, 1);
403                 c->local_nlargefree++;
404                 c->local_largefree += size;
405         } else {
406                 // Small object.
407                 if(size > 2*sizeof(uintptr))
408                         ((uintptr*)v)[1] = (uintptr)0xfeedfeedfeedfeedll;       // mark as "needs to be zeroed"
409                 else if(size > sizeof(uintptr))
410                         ((uintptr*)v)[1] = 0;
411                 // Must mark v freed before calling MCache_Free:
412                 // it might coalesce v and other blocks into a bigger span
413                 // and change the bitmap further.
414                 c->local_nsmallfree[sizeclass]++;
415                 c->local_cachealloc -= size;
416                 if(c->alloc[sizeclass] == s) {
417                         // We own the span, so we can just add v to the freelist
418                         runtime_markfreed(v);
419                         ((MLink*)v)->next = s->freelist;
420                         s->freelist = v;
421                         s->ref--;
422                 } else {
423                         // Someone else owns this span.  Add to free queue.
424                         runtime_MCache_Free(c, v, sizeclass, size);
425                 }
426         }
427         m->mallocing = 0;
430 int32
431 runtime_mlookup(void *v, byte **base, uintptr *size, MSpan **sp)
433         M *m;
434         uintptr n, i;
435         byte *p;
436         MSpan *s;
438         m = runtime_m();
440         m->mcache->local_nlookup++;
441         if (sizeof(void*) == 4 && m->mcache->local_nlookup >= (1<<30)) {
442                 // purge cache stats to prevent overflow
443                 runtime_lock(&runtime_mheap);
444                 runtime_purgecachedstats(m->mcache);
445                 runtime_unlock(&runtime_mheap);
446         }
448         s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
449         if(sp)
450                 *sp = s;
451         if(s == nil) {
452                 runtime_checkfreed(v, 1);
453                 if(base)
454                         *base = nil;
455                 if(size)
456                         *size = 0;
457                 return 0;
458         }
460         p = (byte*)((uintptr)s->start<<PageShift);
461         if(s->sizeclass == 0) {
462                 // Large object.
463                 if(base)
464                         *base = p;
465                 if(size)
466                         *size = s->npages<<PageShift;
467                 return 1;
468         }
470         n = s->elemsize;
471         if(base) {
472                 i = ((byte*)v - p)/n;
473                 *base = p + i*n;
474         }
475         if(size)
476                 *size = n;
478         return 1;
481 void
482 runtime_purgecachedstats(MCache *c)
484         MHeap *h;
485         int32 i;
487         // Protected by either heap or GC lock.
488         h = &runtime_mheap;
489         mstats.heap_alloc += c->local_cachealloc;
490         c->local_cachealloc = 0;
491         mstats.nlookup += c->local_nlookup;
492         c->local_nlookup = 0;
493         h->largefree += c->local_largefree;
494         c->local_largefree = 0;
495         h->nlargefree += c->local_nlargefree;
496         c->local_nlargefree = 0;
497         for(i=0; i<(int32)nelem(c->local_nsmallfree); i++) {
498                 h->nsmallfree[i] += c->local_nsmallfree[i];
499                 c->local_nsmallfree[i] = 0;
500         }
503 extern uintptr runtime_sizeof_C_MStats
504   __asm__ (GOSYM_PREFIX "runtime.Sizeof_C_MStats");
506 // Size of the trailing by_size array differs between Go and C,
507 // NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
508 // sizeof_C_MStats is what C thinks about size of Go struct.
510 // Initialized in mallocinit because it's defined in go/runtime/mem.go.
512 #define MaxArena32 (2U<<30)
514 void
515 runtime_mallocinit(void)
517         byte *p, *p1;
518         uintptr arena_size, bitmap_size, spans_size, p_size;
519         extern byte _end[];
520         uintptr limit;
521         uint64 i;
522         bool reserved;
524         runtime_sizeof_C_MStats = sizeof(MStats) - (NumSizeClasses - 61) * sizeof(mstats.by_size[0]);
526         p = nil;
527         p_size = 0;
528         arena_size = 0;
529         bitmap_size = 0;
530         spans_size = 0;
531         reserved = false;
533         // for 64-bit build
534         USED(p);
535         USED(p_size);
536         USED(arena_size);
537         USED(bitmap_size);
538         USED(spans_size);
540         runtime_InitSizes();
542         if(runtime_class_to_size[TinySizeClass] != TinySize)
543                 runtime_throw("bad TinySizeClass");
545         // limit = runtime_memlimit();
546         // See https://code.google.com/p/go/issues/detail?id=5049
547         // TODO(rsc): Fix after 1.1.
548         limit = 0;
550         // Set up the allocation arena, a contiguous area of memory where
551         // allocated data will be found.  The arena begins with a bitmap large
552         // enough to hold 4 bits per allocated word.
553         if(sizeof(void*) == 8 && (limit == 0 || limit > (1<<30))) {
554                 // On a 64-bit machine, allocate from a single contiguous reservation.
555                 // 128 GB (MaxMem) should be big enough for now.
556                 //
557                 // The code will work with the reservation at any address, but ask
558                 // SysReserve to use 0x0000XXc000000000 if possible (XX=00...7f).
559                 // Allocating a 128 GB region takes away 37 bits, and the amd64
560                 // doesn't let us choose the top 17 bits, so that leaves the 11 bits
561                 // in the middle of 0x00c0 for us to choose.  Choosing 0x00c0 means
562                 // that the valid memory addresses will begin 0x00c0, 0x00c1, ..., 0x00df.
563                 // In little-endian, that's c0 00, c1 00, ..., df 00. None of those are valid
564                 // UTF-8 sequences, and they are otherwise as far away from 
565                 // ff (likely a common byte) as possible.  If that fails, we try other 0xXXc0
566                 // addresses.  An earlier attempt to use 0x11f8 caused out of memory errors
567                 // on OS X during thread allocations.  0x00c0 causes conflicts with
568                 // AddressSanitizer which reserves all memory up to 0x0100.
569                 // These choices are both for debuggability and to reduce the
570                 // odds of the conservative garbage collector not collecting memory
571                 // because some non-pointer block of memory had a bit pattern
572                 // that matched a memory address.
573                 //
574                 // Actually we reserve 136 GB (because the bitmap ends up being 8 GB)
575                 // but it hardly matters: e0 00 is not valid UTF-8 either.
576                 //
577                 // If this fails we fall back to the 32 bit memory mechanism
578                 arena_size = MaxMem;
579                 bitmap_size = arena_size / (sizeof(void*)*8/4);
580                 spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
581                 spans_size = ROUND(spans_size, PageSize);
582                 for(i = 0; i < HeapBaseOptions; i++) {
583                         p = HeapBase(i);
584                         p_size = bitmap_size + spans_size + arena_size + PageSize;
585                         p = runtime_SysReserve(p, p_size, &reserved);
586                         if(p != nil)
587                                 break;
588                 }
589         }
590         if (p == nil) {
591                 // On a 32-bit machine, we can't typically get away
592                 // with a giant virtual address space reservation.
593                 // Instead we map the memory information bitmap
594                 // immediately after the data segment, large enough
595                 // to handle another 2GB of mappings (256 MB),
596                 // along with a reservation for another 512 MB of memory.
597                 // When that gets used up, we'll start asking the kernel
598                 // for any memory anywhere and hope it's in the 2GB
599                 // following the bitmap (presumably the executable begins
600                 // near the bottom of memory, so we'll have to use up
601                 // most of memory before the kernel resorts to giving out
602                 // memory before the beginning of the text segment).
603                 //
604                 // Alternatively we could reserve 512 MB bitmap, enough
605                 // for 4GB of mappings, and then accept any memory the
606                 // kernel threw at us, but normally that's a waste of 512 MB
607                 // of address space, which is probably too much in a 32-bit world.
608                 bitmap_size = MaxArena32 / (sizeof(void*)*8/4);
609                 arena_size = 512<<20;
610                 spans_size = MaxArena32 / PageSize * sizeof(runtime_mheap.spans[0]);
611                 if(limit > 0 && arena_size+bitmap_size+spans_size > limit) {
612                         bitmap_size = (limit / 9) & ~((1<<PageShift) - 1);
613                         arena_size = bitmap_size * 8;
614                         spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
615                 }
616                 spans_size = ROUND(spans_size, PageSize);
618                 // SysReserve treats the address we ask for, end, as a hint,
619                 // not as an absolute requirement.  If we ask for the end
620                 // of the data segment but the operating system requires
621                 // a little more space before we can start allocating, it will
622                 // give out a slightly higher pointer.  Except QEMU, which
623                 // is buggy, as usual: it won't adjust the pointer upward.
624                 // So adjust it upward a little bit ourselves: 1/4 MB to get
625                 // away from the running binary image and then round up
626                 // to a MB boundary.
627                 p = (byte*)ROUND((uintptr)_end + (1<<18), 1<<20);
628                 p_size = bitmap_size + spans_size + arena_size + PageSize;
629                 p = runtime_SysReserve(p, p_size, &reserved);
630                 if(p == nil)
631                         runtime_throw("runtime: cannot reserve arena virtual address space");
632         }
634         // PageSize can be larger than OS definition of page size,
635         // so SysReserve can give us a PageSize-unaligned pointer.
636         // To overcome this we ask for PageSize more and round up the pointer.
637         p1 = (byte*)ROUND((uintptr)p, PageSize);
639         runtime_mheap.spans = (MSpan**)p1;
640         runtime_mheap.bitmap = p1 + spans_size;
641         runtime_mheap.arena_start = p1 + spans_size + bitmap_size;
642         runtime_mheap.arena_used = runtime_mheap.arena_start;
643         runtime_mheap.arena_end = p + p_size;
644         runtime_mheap.arena_reserved = reserved;
646         if(((uintptr)runtime_mheap.arena_start & (PageSize-1)) != 0)
647                 runtime_throw("misrounded allocation in mallocinit");
649         // Initialize the rest of the allocator.        
650         runtime_MHeap_Init(&runtime_mheap);
651         runtime_m()->mcache = runtime_allocmcache();
653         // See if it works.
654         runtime_free(runtime_malloc(TinySize));
657 void*
658 runtime_MHeap_SysAlloc(MHeap *h, uintptr n)
660         byte *p, *p_end;
661         uintptr p_size;
662         bool reserved;
665         if(n > (uintptr)(h->arena_end - h->arena_used)) {
666                 // We are in 32-bit mode, maybe we didn't use all possible address space yet.
667                 // Reserve some more space.
668                 byte *new_end;
670                 p_size = ROUND(n + PageSize, 256<<20);
671                 new_end = h->arena_end + p_size;
672                 if(new_end <= h->arena_start + MaxArena32) {
673                         // TODO: It would be bad if part of the arena
674                         // is reserved and part is not.
675                         p = runtime_SysReserve(h->arena_end, p_size, &reserved);
676                         if(p == h->arena_end) {
677                                 h->arena_end = new_end;
678                                 h->arena_reserved = reserved;
679                         }
680                         else if(p+p_size <= h->arena_start + MaxArena32) {
681                                 // Keep everything page-aligned.
682                                 // Our pages are bigger than hardware pages.
683                                 h->arena_end = p+p_size;
684                                 h->arena_used = p + (-(uintptr)p&(PageSize-1));
685                                 h->arena_reserved = reserved;
686                         } else {
687                                 uint64 stat;
688                                 stat = 0;
689                                 runtime_SysFree(p, p_size, &stat);
690                         }
691                 }
692         }
693         if(n <= (uintptr)(h->arena_end - h->arena_used)) {
694                 // Keep taking from our reservation.
695                 p = h->arena_used;
696                 runtime_SysMap(p, n, h->arena_reserved, &mstats.heap_sys);
697                 h->arena_used += n;
698                 runtime_MHeap_MapBits(h);
699                 runtime_MHeap_MapSpans(h);
700                 if(raceenabled)
701                         runtime_racemapshadow(p, n);
702                 
703                 if(((uintptr)p & (PageSize-1)) != 0)
704                         runtime_throw("misrounded allocation in MHeap_SysAlloc");
705                 return p;
706         }
707         
708         // If using 64-bit, our reservation is all we have.
709         if((uintptr)(h->arena_end - h->arena_start) >= MaxArena32)
710                 return nil;
712         // On 32-bit, once the reservation is gone we can
713         // try to get memory at a location chosen by the OS
714         // and hope that it is in the range we allocated bitmap for.
715         p_size = ROUND(n, PageSize) + PageSize;
716         p = runtime_SysAlloc(p_size, &mstats.heap_sys);
717         if(p == nil)
718                 return nil;
720         if(p < h->arena_start || (uintptr)(p+p_size - h->arena_start) >= MaxArena32) {
721                 runtime_printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
722                         p, h->arena_start, h->arena_start+MaxArena32);
723                 runtime_SysFree(p, p_size, &mstats.heap_sys);
724                 return nil;
725         }
726         
727         p_end = p + p_size;
728         p += -(uintptr)p & (PageSize-1);
729         if(p+n > h->arena_used) {
730                 h->arena_used = p+n;
731                 if(p_end > h->arena_end)
732                         h->arena_end = p_end;
733                 runtime_MHeap_MapBits(h);
734                 runtime_MHeap_MapSpans(h);
735                 if(raceenabled)
736                         runtime_racemapshadow(p, n);
737         }
738         
739         if(((uintptr)p & (PageSize-1)) != 0)
740                 runtime_throw("misrounded allocation in MHeap_SysAlloc");
741         return p;
744 static struct
746         Lock;
747         byte*   pos;
748         byte*   end;
749 } persistent;
751 enum
753         PersistentAllocChunk    = 256<<10,
754         PersistentAllocMaxBlock = 64<<10,  // VM reservation granularity is 64K on windows
757 // Wrapper around SysAlloc that can allocate small chunks.
758 // There is no associated free operation.
759 // Intended for things like function/type/debug-related persistent data.
760 // If align is 0, uses default align (currently 8).
761 void*
762 runtime_persistentalloc(uintptr size, uintptr align, uint64 *stat)
764         byte *p;
766         if(align != 0) {
767                 if(align&(align-1))
768                         runtime_throw("persistentalloc: align is not a power of 2");
769                 if(align > PageSize)
770                         runtime_throw("persistentalloc: align is too large");
771         } else
772                 align = 8;
773         if(size >= PersistentAllocMaxBlock)
774                 return runtime_SysAlloc(size, stat);
775         runtime_lock(&persistent);
776         persistent.pos = (byte*)ROUND((uintptr)persistent.pos, align);
777         if(persistent.pos + size > persistent.end) {
778                 persistent.pos = runtime_SysAlloc(PersistentAllocChunk, &mstats.other_sys);
779                 if(persistent.pos == nil) {
780                         runtime_unlock(&persistent);
781                         runtime_throw("runtime: cannot allocate memory");
782                 }
783                 persistent.end = persistent.pos + PersistentAllocChunk;
784         }
785         p = persistent.pos;
786         persistent.pos += size;
787         runtime_unlock(&persistent);
788         if(stat != &mstats.other_sys) {
789                 // reaccount the allocation against provided stat
790                 runtime_xadd64(stat, size);
791                 runtime_xadd64(&mstats.other_sys, -(uint64)size);
792         }
793         return p;
796 static void
797 settype(MSpan *s, void *v, uintptr typ)
799         uintptr size, ofs, j, t;
800         uintptr ntypes, nbytes2, nbytes3;
801         uintptr *data2;
802         byte *data3;
804         if(s->sizeclass == 0) {
805                 s->types.compression = MTypes_Single;
806                 s->types.data = typ;
807                 return;
808         }
809         size = s->elemsize;
810         ofs = ((uintptr)v - (s->start<<PageShift)) / size;
812         switch(s->types.compression) {
813         case MTypes_Empty:
814                 ntypes = (s->npages << PageShift) / size;
815                 nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
816                 data3 = runtime_mallocgc(nbytes3, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
817                 s->types.compression = MTypes_Bytes;
818                 s->types.data = (uintptr)data3;
819                 ((uintptr*)data3)[1] = typ;
820                 data3[8*sizeof(uintptr) + ofs] = 1;
821                 break;
822                 
823         case MTypes_Words:
824                 ((uintptr*)s->types.data)[ofs] = typ;
825                 break;
826                 
827         case MTypes_Bytes:
828                 data3 = (byte*)s->types.data;
829                 for(j=1; j<8; j++) {
830                         if(((uintptr*)data3)[j] == typ) {
831                                 break;
832                         }
833                         if(((uintptr*)data3)[j] == 0) {
834                                 ((uintptr*)data3)[j] = typ;
835                                 break;
836                         }
837                 }
838                 if(j < 8) {
839                         data3[8*sizeof(uintptr) + ofs] = j;
840                 } else {
841                         ntypes = (s->npages << PageShift) / size;
842                         nbytes2 = ntypes * sizeof(uintptr);
843                         data2 = runtime_mallocgc(nbytes2, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
844                         s->types.compression = MTypes_Words;
845                         s->types.data = (uintptr)data2;
846                         
847                         // Move the contents of data3 to data2. Then deallocate data3.
848                         for(j=0; j<ntypes; j++) {
849                                 t = data3[8*sizeof(uintptr) + j];
850                                 t = ((uintptr*)data3)[t];
851                                 data2[j] = t;
852                         }
853                         data2[ofs] = typ;
854                 }
855                 break;
856         }
859 uintptr
860 runtime_gettype(void *v)
862         MSpan *s;
863         uintptr t, ofs;
864         byte *data;
866         s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
867         if(s != nil) {
868                 t = 0;
869                 switch(s->types.compression) {
870                 case MTypes_Empty:
871                         break;
872                 case MTypes_Single:
873                         t = s->types.data;
874                         break;
875                 case MTypes_Words:
876                         ofs = (uintptr)v - (s->start<<PageShift);
877                         t = ((uintptr*)s->types.data)[ofs/s->elemsize];
878                         break;
879                 case MTypes_Bytes:
880                         ofs = (uintptr)v - (s->start<<PageShift);
881                         data = (byte*)s->types.data;
882                         t = data[8*sizeof(uintptr) + ofs/s->elemsize];
883                         t = ((uintptr*)data)[t];
884                         break;
885                 default:
886                         runtime_throw("runtime_gettype: invalid compression kind");
887                 }
888                 if(0) {
889                         runtime_printf("%p -> %d,%X\n", v, (int32)s->types.compression, (int64)t);
890                 }
891                 return t;
892         }
893         return 0;
896 // Runtime stubs.
898 void*
899 runtime_mal(uintptr n)
901         return runtime_mallocgc(n, 0, 0);
904 func new(typ *Type) (ret *uint8) {
905         ret = runtime_mallocgc(typ->__size, (uintptr)typ | TypeInfo_SingleObject, typ->kind&KindNoPointers ? FlagNoScan : 0);
908 static void*
909 cnew(const Type *typ, intgo n, int32 objtyp)
911         if((objtyp&(PtrSize-1)) != objtyp)
912                 runtime_throw("runtime: invalid objtyp");
913         if(n < 0 || (typ->__size > 0 && (uintptr)n > (MaxMem/typ->__size)))
914                 runtime_panicstring("runtime: allocation size out of range");
915         return runtime_mallocgc(typ->__size*n, (uintptr)typ | objtyp, typ->kind&KindNoPointers ? FlagNoScan : 0);
918 // same as runtime_new, but callable from C
919 void*
920 runtime_cnew(const Type *typ)
922         return cnew(typ, 1, TypeInfo_SingleObject);
925 void*
926 runtime_cnewarray(const Type *typ, intgo n)
928         return cnew(typ, n, TypeInfo_Array);
931 func GC() {
932         runtime_gc(2);  // force GC and do eager sweep
935 func SetFinalizer(obj Eface, finalizer Eface) {
936         byte *base;
937         uintptr size;
938         const FuncType *ft;
939         const Type *fint;
940         const PtrType *ot;
942         if(obj.__type_descriptor == nil) {
943                 runtime_printf("runtime.SetFinalizer: first argument is nil interface\n");
944                 goto throw;
945         }
946         if(obj.__type_descriptor->__code != GO_PTR) {
947                 runtime_printf("runtime.SetFinalizer: first argument is %S, not pointer\n", *obj.__type_descriptor->__reflection);
948                 goto throw;
949         }
950         ot = (const PtrType*)obj.type;
951         // As an implementation detail we do not run finalizers for zero-sized objects,
952         // because we use &runtime_zerobase for all such allocations.
953         if(ot->__element_type != nil && ot->__element_type->__size == 0)
954                 return;
955         // The following check is required for cases when a user passes a pointer to composite literal,
956         // but compiler makes it a pointer to global. For example:
957         //      var Foo = &Object{}
958         //      func main() {
959         //              runtime.SetFinalizer(Foo, nil)
960         //      }
961         // See issue 7656.
962         if((byte*)obj.__object < runtime_mheap.arena_start || runtime_mheap.arena_used <= (byte*)obj.__object)
963                 return;
964         if(!runtime_mlookup(obj.__object, &base, &size, nil) || obj.__object != base) {
965                 // As an implementation detail we allow to set finalizers for an inner byte
966                 // of an object if it could come from tiny alloc (see mallocgc for details).
967                 if(ot->__element_type == nil || (ot->__element_type->__code&KindNoPointers) == 0 || ot->__element_type->__size >= TinySize) {
968                         runtime_printf("runtime.SetFinalizer: pointer not at beginning of allocated block (%p)\n", obj.__object);
969                         goto throw;
970                 }
971         }
972         if(finalizer.__type_descriptor != nil) {
973                 runtime_createfing();
974                 if(finalizer.__type_descriptor->__code != GO_FUNC)
975                         goto badfunc;
976                 ft = (const FuncType*)finalizer.__type_descriptor;
977                 if(ft->__dotdotdot || ft->__in.__count != 1)
978                         goto badfunc;
979                 fint = *(Type**)ft->__in.__values;
980                 if(__go_type_descriptors_equal(fint, obj.__type_descriptor)) {
981                         // ok - same type
982                 } else if(fint->__code == GO_PTR && (fint->__uncommon == nil || fint->__uncommon->__name == nil || obj.type->__uncommon == nil || obj.type->__uncommon->__name == nil) && __go_type_descriptors_equal(((const PtrType*)fint)->__element_type, ((const PtrType*)obj.type)->__element_type)) {
983                         // ok - not same type, but both pointers,
984                         // one or the other is unnamed, and same element type, so assignable.
985                 } else if(fint->kind == GO_INTERFACE && ((const InterfaceType*)fint)->__methods.__count == 0) {
986                         // ok - satisfies empty interface
987                 } else if(fint->kind == GO_INTERFACE && __go_convert_interface_2(fint, obj.__type_descriptor, 1) != nil) {
988                         // ok - satisfies non-empty interface
989                 } else
990                         goto badfunc;
992                 ot = (const PtrType*)obj.__type_descriptor;
993                 if(!runtime_addfinalizer(obj.__object, *(FuncVal**)finalizer.__object, ft, ot)) {
994                         runtime_printf("runtime.SetFinalizer: finalizer already set\n");
995                         goto throw;
996                 }
997         } else {
998                 // NOTE: asking to remove a finalizer when there currently isn't one set is OK.
999                 runtime_removefinalizer(obj.__object);
1000         }
1001         return;
1003 badfunc:
1004         runtime_printf("runtime.SetFinalizer: cannot pass %S to finalizer %S\n", *obj.__type_descriptor->__reflection, *finalizer.__type_descriptor->__reflection);
1005 throw:
1006         runtime_throw("runtime.SetFinalizer");