]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/malloc2.go
[dev.garbage] all: merge dev.cc into dev.garbage
[gostls13.git] / src / runtime / malloc2.go
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.
4
5 package runtime
6
7 import "unsafe"
8
9 // Memory allocator, based on tcmalloc.
10 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html
11
12 // The main allocator works in runs of pages.
13 // Small allocation sizes (up to and including 32 kB) are
14 // rounded to one of about 100 size classes, each of which
15 // has its own free list of objects of exactly that size.
16 // Any free page of memory can be split into a set of objects
17 // of one size class, which are then managed using free list
18 // allocators.
19 //
20 // The allocator's data structures are:
21 //
22 //      FixAlloc: a free-list allocator for fixed-size objects,
23 //              used to manage storage used by the allocator.
24 //      MHeap: the malloc heap, managed at page (4096-byte) granularity.
25 //      MSpan: a run of pages managed by the MHeap.
26 //      MCentral: a shared free list for a given size class.
27 //      MCache: a per-thread (in Go, per-P) cache for small objects.
28 //      MStats: allocation statistics.
29 //
30 // Allocating a small object proceeds up a hierarchy of caches:
31 //
32 //      1. Round the size up to one of the small size classes
33 //         and look in the corresponding MCache free list.
34 //         If the list is not empty, allocate an object from it.
35 //         This can all be done without acquiring a lock.
36 //
37 //      2. If the MCache free list is empty, replenish it by
38 //         taking a bunch of objects from the MCentral free list.
39 //         Moving a bunch amortizes the cost of acquiring the MCentral lock.
40 //
41 //      3. If the MCentral free list is empty, replenish it by
42 //         allocating a run of pages from the MHeap and then
43 //         chopping that memory into a objects of the given size.
44 //         Allocating many objects amortizes the cost of locking
45 //         the heap.
46 //
47 //      4. If the MHeap is empty or has no page runs large enough,
48 //         allocate a new group of pages (at least 1MB) from the
49 //         operating system.  Allocating a large run of pages
50 //         amortizes the cost of talking to the operating system.
51 //
52 // Freeing a small object proceeds up the same hierarchy:
53 //
54 //      1. Look up the size class for the object and add it to
55 //         the MCache free list.
56 //
57 //      2. If the MCache free list is too long or the MCache has
58 //         too much memory, return some to the MCentral free lists.
59 //
60 //      3. If all the objects in a given span have returned to
61 //         the MCentral list, return that span to the page heap.
62 //
63 //      4. If the heap has too much memory, return some to the
64 //         operating system.
65 //
66 //      TODO(rsc): Step 4 is not implemented.
67 //
68 // Allocating and freeing a large object uses the page heap
69 // directly, bypassing the MCache and MCentral free lists.
70 //
71 // The small objects on the MCache and MCentral free lists
72 // may or may not be zeroed.  They are zeroed if and only if
73 // the second word of the object is zero.  A span in the
74 // page heap is zeroed unless s->needzero is set. When a span
75 // is allocated to break into small objects, it is zeroed if needed
76 // and s->needzero is set. There are two main benefits to delaying the
77 // zeroing this way:
78 //
79 //      1. stack frames allocated from the small object lists
80 //         or the page heap can avoid zeroing altogether.
81 //      2. the cost of zeroing when reusing a small object is
82 //         charged to the mutator, not the garbage collector.
83 //
84 // This C code was written with an eye toward translating to Go
85 // in the future.  Methods have the form Type_Method(Type *t, ...).
86
87 const (
88         _PageShift = 13
89         _PageSize  = 1 << _PageShift
90         _PageMask  = _PageSize - 1
91 )
92
93 const (
94         // _64bit = 1 on 64-bit systems, 0 on 32-bit systems
95         _64bit = 1 << (^uintptr(0) >> 63) / 2
96
97         // Computed constant.  The definition of MaxSmallSize and the
98         // algorithm in msize.c produce some number of different allocation
99         // size classes.  NumSizeClasses is that number.  It's needed here
100         // because there are static arrays of this length; when msize runs its
101         // size choosing algorithm it double-checks that NumSizeClasses agrees.
102         _NumSizeClasses = 67
103
104         // Tunable constants.
105         _MaxSmallSize = 32 << 10
106
107         // Tiny allocator parameters, see "Tiny allocator" comment in malloc.goc.
108         _TinySize      = 16
109         _TinySizeClass = 2
110
111         _FixAllocChunk  = 16 << 10               // Chunk size for FixAlloc
112         _MaxMHeapList   = 1 << (20 - _PageShift) // Maximum page length for fixed-size list in MHeap.
113         _HeapAllocChunk = 1 << 20                // Chunk size for heap growth
114
115         // Per-P, per order stack segment cache size.
116         _StackCacheSize = 32 * 1024
117
118         // Number of orders that get caching.  Order 0 is FixedStack
119         // and each successive order is twice as large.
120         _NumStackOrders = 3
121
122         // Number of bits in page to span calculations (4k pages).
123         // On Windows 64-bit we limit the arena to 32GB or 35 bits.
124         // Windows counts memory used by page table into committed memory
125         // of the process, so we can't reserve too much memory.
126         // See http://golang.org/issue/5402 and http://golang.org/issue/5236.
127         // On other 64-bit platforms, we limit the arena to 128GB, or 37 bits.
128         // On 32-bit, we don't bother limiting anything, so we use the full 32-bit address.
129         _MHeapMap_TotalBits = (_64bit*_Windows)*35 + (_64bit*(1-_Windows))*37 + (1-_64bit)*32
130         _MHeapMap_Bits      = _MHeapMap_TotalBits - _PageShift
131
132         _MaxMem = uintptr(1<<_MHeapMap_TotalBits - 1)
133
134         // Max number of threads to run garbage collection.
135         // 2, 3, and 4 are all plausible maximums depending
136         // on the hardware details of the machine.  The garbage
137         // collector scales well to 32 cpus.
138         _MaxGcproc = 32
139 )
140
141 // A generic linked list of blocks.  (Typically the block is bigger than sizeof(MLink).)
142 type mlink struct {
143         next *mlink
144 }
145
146 // sysAlloc obtains a large chunk of zeroed memory from the
147 // operating system, typically on the order of a hundred kilobytes
148 // or a megabyte.
149 // NOTE: sysAlloc returns OS-aligned memory, but the heap allocator
150 // may use larger alignment, so the caller must be careful to realign the
151 // memory obtained by sysAlloc.
152 //
153 // SysUnused notifies the operating system that the contents
154 // of the memory region are no longer needed and can be reused
155 // for other purposes.
156 // SysUsed notifies the operating system that the contents
157 // of the memory region are needed again.
158 //
159 // SysFree returns it unconditionally; this is only used if
160 // an out-of-memory error has been detected midway through
161 // an allocation.  It is okay if SysFree is a no-op.
162 //
163 // SysReserve reserves address space without allocating memory.
164 // If the pointer passed to it is non-nil, the caller wants the
165 // reservation there, but SysReserve can still choose another
166 // location if that one is unavailable.  On some systems and in some
167 // cases SysReserve will simply check that the address space is
168 // available and not actually reserve it.  If SysReserve returns
169 // non-nil, it sets *reserved to true if the address space is
170 // reserved, false if it has merely been checked.
171 // NOTE: SysReserve returns OS-aligned memory, but the heap allocator
172 // may use larger alignment, so the caller must be careful to realign the
173 // memory obtained by sysAlloc.
174 //
175 // SysMap maps previously reserved address space for use.
176 // The reserved argument is true if the address space was really
177 // reserved, not merely checked.
178 //
179 // SysFault marks a (already sysAlloc'd) region to fault
180 // if accessed.  Used only for debugging the runtime.
181
182 // FixAlloc is a simple free-list allocator for fixed size objects.
183 // Malloc uses a FixAlloc wrapped around sysAlloc to manages its
184 // MCache and MSpan objects.
185 //
186 // Memory returned by FixAlloc_Alloc is not zeroed.
187 // The caller is responsible for locking around FixAlloc calls.
188 // Callers can keep state in the object but the first word is
189 // smashed by freeing and reallocating.
190 type fixalloc struct {
191         size   uintptr
192         first  unsafe.Pointer // go func(unsafe.pointer, unsafe.pointer); f(arg, p) called first time p is returned
193         arg    unsafe.Pointer
194         list   *mlink
195         chunk  *byte
196         nchunk uint32
197         inuse  uintptr // in-use bytes now
198         stat   *uint64
199 }
200
201 // Statistics.
202 // Shared with Go: if you edit this structure, also edit type MemStats in mem.go.
203 type mstats struct {
204         // General statistics.
205         alloc       uint64 // bytes allocated and still in use
206         total_alloc uint64 // bytes allocated (even if freed)
207         sys         uint64 // bytes obtained from system (should be sum of xxx_sys below, no locking, approximate)
208         nlookup     uint64 // number of pointer lookups
209         nmalloc     uint64 // number of mallocs
210         nfree       uint64 // number of frees
211
212         // Statistics about malloc heap.
213         // protected by mheap.lock
214         heap_alloc    uint64 // bytes allocated and still in use
215         heap_sys      uint64 // bytes obtained from system
216         heap_idle     uint64 // bytes in idle spans
217         heap_inuse    uint64 // bytes in non-idle spans
218         heap_released uint64 // bytes released to the os
219         heap_objects  uint64 // total number of allocated objects
220
221         // Statistics about allocation of low-level fixed-size structures.
222         // Protected by FixAlloc locks.
223         stacks_inuse uint64 // this number is included in heap_inuse above
224         stacks_sys   uint64 // always 0 in mstats
225         mspan_inuse  uint64 // mspan structures
226         mspan_sys    uint64
227         mcache_inuse uint64 // mcache structures
228         mcache_sys   uint64
229         buckhash_sys uint64 // profiling bucket hash table
230         gc_sys       uint64
231         other_sys    uint64
232
233         // Statistics about garbage collector.
234         // Protected by mheap or stopping the world during GC.
235         next_gc        uint64 // next gc (in heap_alloc time)
236         last_gc        uint64 // last gc (in absolute time)
237         pause_total_ns uint64
238         pause_ns       [256]uint64 // circular buffer of recent gc pause lengths
239         pause_end      [256]uint64 // circular buffer of recent gc end times (nanoseconds since 1970)
240         numgc          uint32
241         enablegc       bool
242         debuggc        bool
243
244         // Statistics about allocation size classes.
245
246         by_size [_NumSizeClasses]struct {
247                 size    uint32
248                 nmalloc uint64
249                 nfree   uint64
250         }
251
252         tinyallocs uint64 // number of tiny allocations that didn't cause actual allocation; not exported to go directly
253 }
254
255 var memstats mstats
256
257 // Size classes.  Computed and initialized by InitSizes.
258 //
259 // SizeToClass(0 <= n <= MaxSmallSize) returns the size class,
260 //      1 <= sizeclass < NumSizeClasses, for n.
261 //      Size class 0 is reserved to mean "not small".
262 //
263 // class_to_size[i] = largest size in class i
264 // class_to_allocnpages[i] = number of pages to allocate when
265 //      making new objects in class i
266
267 var class_to_size [_NumSizeClasses]int32
268 var class_to_allocnpages [_NumSizeClasses]int32
269 var size_to_class8 [1024/8 + 1]int8
270 var size_to_class128 [(_MaxSmallSize-1024)/128 + 1]int8
271
272 type mcachelist struct {
273         list  *mlink
274         nlist uint32
275 }
276
277 type stackfreelist struct {
278         list *mlink  // linked list of free stacks
279         size uintptr // total size of stacks in list
280 }
281
282 // Per-thread (in Go, per-P) cache for small objects.
283 // No locking needed because it is per-thread (per-P).
284 type mcache struct {
285         // The following members are accessed on every malloc,
286         // so they are grouped here for better caching.
287         next_sample      int32  // trigger heap sample after allocating this many bytes
288         local_cachealloc intptr // bytes allocated (or freed) from cache since last lock of heap
289         // Allocator cache for tiny objects w/o pointers.
290         // See "Tiny allocator" comment in malloc.goc.
291         tiny             *byte
292         tinysize         uintptr
293         local_tinyallocs uintptr // number of tiny allocs not counted in other stats
294
295         // The rest is not accessed on every malloc.
296         alloc [_NumSizeClasses]*mspan // spans to allocate from
297
298         stackcache [_NumStackOrders]stackfreelist
299
300         sudogcache *sudog
301
302         // Local allocator stats, flushed during GC.
303         local_nlookup    uintptr                  // number of pointer lookups
304         local_largefree  uintptr                  // bytes freed for large objects (>maxsmallsize)
305         local_nlargefree uintptr                  // number of frees for large objects (>maxsmallsize)
306         local_nsmallfree [_NumSizeClasses]uintptr // number of frees for small objects (<=maxsmallsize)
307 }
308
309 const (
310         _KindSpecialFinalizer = 1
311         _KindSpecialProfile   = 2
312         // Note: The finalizer special must be first because if we're freeing
313         // an object, a finalizer special will cause the freeing operation
314         // to abort, and we want to keep the other special records around
315         // if that happens.
316 )
317
318 type special struct {
319         next   *special // linked list in span
320         offset uint16   // span offset of object
321         kind   byte     // kind of special
322 }
323
324 // The described object has a finalizer set for it.
325 type specialfinalizer struct {
326         special special
327         fn      *funcval
328         nret    uintptr
329         fint    *_type
330         ot      *ptrtype
331 }
332
333 // The described object is being heap profiled.
334 type specialprofile struct {
335         special special
336         b       *bucket
337 }
338
339 // An MSpan is a run of pages.
340 const (
341         _MSpanInUse = iota // allocated for garbage collected heap
342         _MSpanStack        // allocated for use by stack allocator
343         _MSpanFree
344         _MSpanListHead
345         _MSpanDead
346 )
347
348 type mspan struct {
349         next     *mspan  // in a span linked list
350         prev     *mspan  // in a span linked list
351         start    pageID  // starting page number
352         npages   uintptr // number of pages in span
353         freelist *mlink  // list of free objects
354         // sweep generation:
355         // if sweepgen == h->sweepgen - 2, the span needs sweeping
356         // if sweepgen == h->sweepgen - 1, the span is currently being swept
357         // if sweepgen == h->sweepgen, the span is swept and ready to use
358         // h->sweepgen is incremented by 2 after every GC
359         sweepgen    uint32
360         ref         uint16   // capacity - number of objects in freelist
361         sizeclass   uint8    // size class
362         incache     bool     // being used by an mcache
363         state       uint8    // mspaninuse etc
364         needzero    uint8    // needs to be zeroed before allocation
365         elemsize    uintptr  // computed from sizeclass or from npages
366         unusedsince int64    // first time spotted by gc in mspanfree state
367         npreleased  uintptr  // number of pages released to the os
368         limit       uintptr  // end of data in span
369         speciallock mutex    // guards specials list
370         specials    *special // linked list of special records sorted by offset.
371 }
372
373 // Every MSpan is in one doubly-linked list,
374 // either one of the MHeap's free lists or one of the
375 // MCentral's span lists.  We use empty MSpan structures as list heads.
376
377 // Central list of free objects of a given size.
378 type mcentral struct {
379         lock      mutex
380         sizeclass int32
381         nonempty  mspan // list of spans with a free object
382         empty     mspan // list of spans with no free objects (or cached in an mcache)
383 }
384
385 // Main malloc heap.
386 // The heap itself is the "free[]" and "large" arrays,
387 // but all the other global data is here too.
388 type mheap struct {
389         lock      mutex
390         free      [_MaxMHeapList]mspan // free lists of given length
391         freelarge mspan                // free lists length >= _MaxMHeapList
392         busy      [_MaxMHeapList]mspan // busy lists of large objects of given length
393         busylarge mspan                // busy lists of large objects length >= _MaxMHeapList
394         allspans  **mspan              // all spans out there
395         gcspans   **mspan              // copy of allspans referenced by gc marker or sweeper
396         nspan     uint32
397         sweepgen  uint32 // sweep generation, see comment in mspan
398         sweepdone uint32 // all spans are swept
399
400         // span lookup
401         spans        **mspan
402         spans_mapped uintptr
403
404         // range of addresses we might see in the heap
405         bitmap         uintptr
406         bitmap_mapped  uintptr
407         arena_start    uintptr
408         arena_used     uintptr
409         arena_end      uintptr
410         arena_reserved bool
411
412         // central free lists for small size classes.
413         // the padding makes sure that the MCentrals are
414         // spaced CacheLineSize bytes apart, so that each MCentral.lock
415         // gets its own cache line.
416         central [_NumSizeClasses]struct {
417                 mcentral mcentral
418                 pad      [_CacheLineSize]byte
419         }
420
421         spanalloc             fixalloc // allocator for span*
422         cachealloc            fixalloc // allocator for mcache*
423         specialfinalizeralloc fixalloc // allocator for specialfinalizer*
424         specialprofilealloc   fixalloc // allocator for specialprofile*
425         speciallock           mutex    // lock for sepcial record allocators.
426
427         // Malloc stats.
428         largefree  uint64                  // bytes freed for large objects (>maxsmallsize)
429         nlargefree uint64                  // number of frees for large objects (>maxsmallsize)
430         nsmallfree [_NumSizeClasses]uint64 // number of frees for small objects (<=maxsmallsize)
431 }
432
433 var mheap_ mheap
434
435 const (
436         // flags to malloc
437         _FlagNoScan = 1 << 0 // GC doesn't have to scan object
438         _FlagNoZero = 1 << 1 // don't zero memory
439 )
440
441 // NOTE: Layout known to queuefinalizer.
442 type finalizer struct {
443         fn   *funcval       // function to call
444         arg  unsafe.Pointer // ptr to object
445         nret uintptr        // bytes of return values from fn
446         fint *_type         // type of first argument of fn
447         ot   *ptrtype       // type of ptr to object
448 }
449
450 type finblock struct {
451         alllink *finblock
452         next    *finblock
453         cnt     int32
454         cap     int32
455         fin     [1]finalizer
456 }
457
458 // Information from the compiler about the layout of stack frames.
459 type bitvector struct {
460         n        int32 // # of bits
461         bytedata *uint8
462 }
463
464 type stackmap struct {
465         n        int32   // number of bitmaps
466         nbit     int32   // number of bits in each bitmap
467         bytedata [0]byte // bitmaps, each starting on a 32-bit boundary
468 }
469
470 // Returns pointer map data for the given stackmap index
471 // (the index is encoded in PCDATA_StackMapIndex).
472
473 // defined in mgc0.go