libgo: Update to weekly.2011-12-22.
[gcc.git] / libgo / runtime / malloc.h
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 // Memory allocator, based on tcmalloc.
6 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html
7
8 // The main allocator works in runs of pages.
9 // Small allocation sizes (up to and including 32 kB) are
10 // rounded to one of about 100 size classes, each of which
11 // has its own free list of objects of exactly that size.
12 // Any free page of memory can be split into a set of objects
13 // of one size class, which are then managed using free list
14 // allocators.
15 //
16 // The allocator's data structures are:
17 //
18 // FixAlloc: a free-list allocator for fixed-size objects,
19 // used to manage storage used by the allocator.
20 // MHeap: the malloc heap, managed at page (4096-byte) granularity.
21 // MSpan: a run of pages managed by the MHeap.
22 // MCentral: a shared free list for a given size class.
23 // MCache: a per-thread (in Go, per-M) cache for small objects.
24 // MStats: allocation statistics.
25 //
26 // Allocating a small object proceeds up a hierarchy of caches:
27 //
28 // 1. Round the size up to one of the small size classes
29 // and look in the corresponding MCache free list.
30 // If the list is not empty, allocate an object from it.
31 // This can all be done without acquiring a lock.
32 //
33 // 2. If the MCache free list is empty, replenish it by
34 // taking a bunch of objects from the MCentral free list.
35 // Moving a bunch amortizes the cost of acquiring the MCentral lock.
36 //
37 // 3. If the MCentral free list is empty, replenish it by
38 // allocating a run of pages from the MHeap and then
39 // chopping that memory into a objects of the given size.
40 // Allocating many objects amortizes the cost of locking
41 // the heap.
42 //
43 // 4. If the MHeap is empty or has no page runs large enough,
44 // allocate a new group of pages (at least 1MB) from the
45 // operating system. Allocating a large run of pages
46 // amortizes the cost of talking to the operating system.
47 //
48 // Freeing a small object proceeds up the same hierarchy:
49 //
50 // 1. Look up the size class for the object and add it to
51 // the MCache free list.
52 //
53 // 2. If the MCache free list is too long or the MCache has
54 // too much memory, return some to the MCentral free lists.
55 //
56 // 3. If all the objects in a given span have returned to
57 // the MCentral list, return that span to the page heap.
58 //
59 // 4. If the heap has too much memory, return some to the
60 // operating system.
61 //
62 // TODO(rsc): Step 4 is not implemented.
63 //
64 // Allocating and freeing a large object uses the page heap
65 // directly, bypassing the MCache and MCentral free lists.
66 //
67 // The small objects on the MCache and MCentral free lists
68 // may or may not be zeroed. They are zeroed if and only if
69 // the second word of the object is zero. The spans in the
70 // page heap are always zeroed. When a span full of objects
71 // is returned to the page heap, the objects that need to be
72 // are zeroed first. There are two main benefits to delaying the
73 // zeroing this way:
74 //
75 // 1. stack frames allocated from the small object lists
76 // can avoid zeroing altogether.
77 // 2. the cost of zeroing when reusing a small object is
78 // charged to the mutator, not the garbage collector.
79 //
80 // This C code was written with an eye toward translating to Go
81 // in the future. Methods have the form Type_Method(Type *t, ...).
82
83 typedef struct MCentral MCentral;
84 typedef struct MHeap MHeap;
85 typedef struct MSpan MSpan;
86 typedef struct MStats MStats;
87 typedef struct MLink MLink;
88
89 enum
90 {
91 PageShift = 12,
92 PageSize = 1<<PageShift,
93 PageMask = PageSize - 1,
94 };
95 typedef uintptr PageID; // address >> PageShift
96
97 enum
98 {
99 // Computed constant. The definition of MaxSmallSize and the
100 // algorithm in msize.c produce some number of different allocation
101 // size classes. NumSizeClasses is that number. It's needed here
102 // because there are static arrays of this length; when msize runs its
103 // size choosing algorithm it double-checks that NumSizeClasses agrees.
104 NumSizeClasses = 61,
105
106 // Tunable constants.
107 MaxSmallSize = 32<<10,
108
109 FixAllocChunk = 128<<10, // Chunk size for FixAlloc
110 MaxMCacheListLen = 256, // Maximum objects on MCacheList
111 MaxMCacheSize = 2<<20, // Maximum bytes in one MCache
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 // Number of bits in page to span calculations (4k pages).
116 // On 64-bit, we limit the arena to 16G, so 22 bits suffices.
117 // On 32-bit, we don't bother limiting anything: 20 bits for 4G.
118 #if __SIZEOF_POINTER__ == 8
119 MHeapMap_Bits = 22,
120 #else
121 MHeapMap_Bits = 20,
122 #endif
123
124 // Max number of threads to run garbage collection.
125 // 2, 3, and 4 are all plausible maximums depending
126 // on the hardware details of the machine. The second
127 // proc is the one that helps the most (after the first),
128 // so start with just 2 for now.
129 MaxGcproc = 2,
130 };
131
132 // A generic linked list of blocks. (Typically the block is bigger than sizeof(MLink).)
133 struct MLink
134 {
135 MLink *next;
136 };
137
138 // SysAlloc obtains a large chunk of zeroed memory from the
139 // operating system, typically on the order of a hundred kilobytes
140 // or a megabyte. If the pointer argument is non-nil, the caller
141 // wants a mapping there or nowhere.
142 //
143 // SysUnused notifies the operating system that the contents
144 // of the memory region are no longer needed and can be reused
145 // for other purposes. The program reserves the right to start
146 // accessing those pages in the future.
147 //
148 // SysFree returns it unconditionally; this is only used if
149 // an out-of-memory error has been detected midway through
150 // an allocation. It is okay if SysFree is a no-op.
151 //
152 // SysReserve reserves address space without allocating memory.
153 // If the pointer passed to it is non-nil, the caller wants the
154 // reservation there, but SysReserve can still choose another
155 // location if that one is unavailable.
156 //
157 // SysMap maps previously reserved address space for use.
158
159 void* runtime_SysAlloc(uintptr nbytes);
160 void runtime_SysFree(void *v, uintptr nbytes);
161 void runtime_SysUnused(void *v, uintptr nbytes);
162 void runtime_SysMap(void *v, uintptr nbytes);
163 void* runtime_SysReserve(void *v, uintptr nbytes);
164
165 // FixAlloc is a simple free-list allocator for fixed size objects.
166 // Malloc uses a FixAlloc wrapped around SysAlloc to manages its
167 // MCache and MSpan objects.
168 //
169 // Memory returned by FixAlloc_Alloc is not zeroed.
170 // The caller is responsible for locking around FixAlloc calls.
171 // Callers can keep state in the object but the first word is
172 // smashed by freeing and reallocating.
173 struct FixAlloc
174 {
175 uintptr size;
176 void *(*alloc)(uintptr);
177 void (*first)(void *arg, byte *p); // called first time p is returned
178 void *arg;
179 MLink *list;
180 byte *chunk;
181 uint32 nchunk;
182 uintptr inuse; // in-use bytes now
183 uintptr sys; // bytes obtained from system
184 };
185
186 void runtime_FixAlloc_Init(FixAlloc *f, uintptr size, void *(*alloc)(uintptr), void (*first)(void*, byte*), void *arg);
187 void* runtime_FixAlloc_Alloc(FixAlloc *f);
188 void runtime_FixAlloc_Free(FixAlloc *f, void *p);
189
190
191 // Statistics.
192 // Shared with Go: if you edit this structure, also edit extern.go.
193 struct MStats
194 {
195 // General statistics.
196 uint64 alloc; // bytes allocated and still in use
197 uint64 total_alloc; // bytes allocated (even if freed)
198 uint64 sys; // bytes obtained from system (should be sum of xxx_sys below, no locking, approximate)
199 uint64 nlookup; // number of pointer lookups
200 uint64 nmalloc; // number of mallocs
201 uint64 nfree; // number of frees
202
203 // Statistics about malloc heap.
204 // protected by mheap.Lock
205 uint64 heap_alloc; // bytes allocated and still in use
206 uint64 heap_sys; // bytes obtained from system
207 uint64 heap_idle; // bytes in idle spans
208 uint64 heap_inuse; // bytes in non-idle spans
209 uint64 heap_objects; // total number of allocated objects
210
211 // Statistics about allocation of low-level fixed-size structures.
212 // Protected by FixAlloc locks.
213 uint64 stacks_inuse; // bootstrap stacks
214 uint64 stacks_sys;
215 uint64 mspan_inuse; // MSpan structures
216 uint64 mspan_sys;
217 uint64 mcache_inuse; // MCache structures
218 uint64 mcache_sys;
219 uint64 buckhash_sys; // profiling bucket hash table
220
221 // Statistics about garbage collector.
222 // Protected by stopping the world during GC.
223 uint64 next_gc; // next GC (in heap_alloc time)
224 uint64 pause_total_ns;
225 uint64 pause_ns[256];
226 uint32 numgc;
227 bool enablegc;
228 bool debuggc;
229
230 // Statistics about allocation size classes.
231 struct {
232 uint32 size;
233 uint64 nmalloc;
234 uint64 nfree;
235 } by_size[NumSizeClasses];
236 };
237
238 extern MStats mstats
239 __asm__ ("libgo_runtime.runtime.MemStats");
240
241
242 // Size classes. Computed and initialized by InitSizes.
243 //
244 // SizeToClass(0 <= n <= MaxSmallSize) returns the size class,
245 // 1 <= sizeclass < NumSizeClasses, for n.
246 // Size class 0 is reserved to mean "not small".
247 //
248 // class_to_size[i] = largest size in class i
249 // class_to_allocnpages[i] = number of pages to allocate when
250 // making new objects in class i
251 // class_to_transfercount[i] = number of objects to move when
252 // taking a bunch of objects out of the central lists
253 // and putting them in the thread free list.
254
255 int32 runtime_SizeToClass(int32);
256 extern int32 runtime_class_to_size[NumSizeClasses];
257 extern int32 runtime_class_to_allocnpages[NumSizeClasses];
258 extern int32 runtime_class_to_transfercount[NumSizeClasses];
259 extern void runtime_InitSizes(void);
260
261
262 // Per-thread (in Go, per-M) cache for small objects.
263 // No locking needed because it is per-thread (per-M).
264 typedef struct MCacheList MCacheList;
265 struct MCacheList
266 {
267 MLink *list;
268 uint32 nlist;
269 uint32 nlistmin;
270 };
271
272 struct MCache
273 {
274 MCacheList list[NumSizeClasses];
275 uint64 size;
276 int64 local_cachealloc; // bytes allocated (or freed) from cache since last lock of heap
277 int64 local_objects; // objects allocated (or freed) from cache since last lock of heap
278 int64 local_alloc; // bytes allocated (or freed) since last lock of heap
279 int64 local_total_alloc; // bytes allocated (even if freed) since last lock of heap
280 int64 local_nmalloc; // number of mallocs since last lock of heap
281 int64 local_nfree; // number of frees since last lock of heap
282 int64 local_nlookup; // number of pointer lookups since last lock of heap
283 int32 next_sample; // trigger heap sample after allocating this many bytes
284 // Statistics about allocation size classes since last lock of heap
285 struct {
286 int64 nmalloc;
287 int64 nfree;
288 } local_by_size[NumSizeClasses];
289
290 };
291
292 void* runtime_MCache_Alloc(MCache *c, int32 sizeclass, uintptr size, int32 zeroed);
293 void runtime_MCache_Free(MCache *c, void *p, int32 sizeclass, uintptr size);
294 void runtime_MCache_ReleaseAll(MCache *c);
295
296 // An MSpan is a run of pages.
297 enum
298 {
299 MSpanInUse = 0,
300 MSpanFree,
301 MSpanListHead,
302 MSpanDead,
303 };
304 struct MSpan
305 {
306 MSpan *next; // in a span linked list
307 MSpan *prev; // in a span linked list
308 MSpan *allnext; // in the list of all spans
309 PageID start; // starting page number
310 uintptr npages; // number of pages in span
311 MLink *freelist; // list of free objects
312 uint32 ref; // number of allocated objects in this span
313 uint32 sizeclass; // size class
314 uint32 state; // MSpanInUse etc
315 byte *limit; // end of data in span
316 };
317
318 void runtime_MSpan_Init(MSpan *span, PageID start, uintptr npages);
319
320 // Every MSpan is in one doubly-linked list,
321 // either one of the MHeap's free lists or one of the
322 // MCentral's span lists. We use empty MSpan structures as list heads.
323 void runtime_MSpanList_Init(MSpan *list);
324 bool runtime_MSpanList_IsEmpty(MSpan *list);
325 void runtime_MSpanList_Insert(MSpan *list, MSpan *span);
326 void runtime_MSpanList_Remove(MSpan *span); // from whatever list it is in
327
328
329 // Central list of free objects of a given size.
330 struct MCentral
331 {
332 Lock;
333 int32 sizeclass;
334 MSpan nonempty;
335 MSpan empty;
336 int32 nfree;
337 };
338
339 void runtime_MCentral_Init(MCentral *c, int32 sizeclass);
340 int32 runtime_MCentral_AllocList(MCentral *c, int32 n, MLink **first);
341 void runtime_MCentral_FreeList(MCentral *c, int32 n, MLink *first);
342
343 // Main malloc heap.
344 // The heap itself is the "free[]" and "large" arrays,
345 // but all the other global data is here too.
346 struct MHeap
347 {
348 Lock;
349 MSpan free[MaxMHeapList]; // free lists of given length
350 MSpan large; // free lists length >= MaxMHeapList
351 MSpan *allspans;
352
353 // span lookup
354 MSpan *map[1<<MHeapMap_Bits];
355
356 // range of addresses we might see in the heap
357 byte *bitmap;
358 uintptr bitmap_mapped;
359 byte *arena_start;
360 byte *arena_used;
361 byte *arena_end;
362
363 // central free lists for small size classes.
364 // the union makes sure that the MCentrals are
365 // spaced CacheLineSize bytes apart, so that each MCentral.Lock
366 // gets its own cache line.
367 union {
368 MCentral;
369 byte pad[CacheLineSize];
370 } central[NumSizeClasses];
371
372 FixAlloc spanalloc; // allocator for Span*
373 FixAlloc cachealloc; // allocator for MCache*
374 };
375 extern MHeap runtime_mheap;
376
377 void runtime_MHeap_Init(MHeap *h, void *(*allocator)(uintptr));
378 MSpan* runtime_MHeap_Alloc(MHeap *h, uintptr npage, int32 sizeclass, int32 acct);
379 void runtime_MHeap_Free(MHeap *h, MSpan *s, int32 acct);
380 MSpan* runtime_MHeap_Lookup(MHeap *h, void *v);
381 MSpan* runtime_MHeap_LookupMaybe(MHeap *h, void *v);
382 void runtime_MGetSizeClassInfo(int32 sizeclass, uintptr *size, int32 *npages, int32 *nobj);
383 void* runtime_MHeap_SysAlloc(MHeap *h, uintptr n);
384 void runtime_MHeap_MapBits(MHeap *h);
385
386 void* runtime_mallocgc(uintptr size, uint32 flag, int32 dogc, int32 zeroed);
387 int32 runtime_mlookup(void *v, byte **base, uintptr *size, MSpan **s);
388 void runtime_gc(int32 force);
389 void runtime_markallocated(void *v, uintptr n, bool noptr);
390 void runtime_checkallocated(void *v, uintptr n);
391 void runtime_markfreed(void *v, uintptr n);
392 void runtime_checkfreed(void *v, uintptr n);
393 int32 runtime_checking;
394 void runtime_markspan(void *v, uintptr size, uintptr n, bool leftover);
395 void runtime_unmarkspan(void *v, uintptr size);
396 bool runtime_blockspecial(void*);
397 void runtime_setblockspecial(void*, bool);
398 void runtime_purgecachedstats(M*);
399
400 enum
401 {
402 // flags to malloc
403 FlagNoPointers = 1<<0, // no pointers here
404 FlagNoProfiling = 1<<1, // must not profile
405 FlagNoGC = 1<<2, // must not free or scan for pointers
406 };
407
408 void runtime_MProf_Malloc(void*, uintptr);
409 void runtime_MProf_Free(void*, uintptr);
410 void runtime_MProf_Mark(void (*scan)(byte *, int64));
411 int32 runtime_helpgc(bool*);
412 void runtime_gchelper(void);
413
414 // Malloc profiling settings.
415 // Must match definition in extern.go.
416 enum {
417 MProf_None = 0,
418 MProf_Sample = 1,
419 MProf_All = 2,
420 };
421 extern int32 runtime_malloc_profile;
422
423 struct __go_func_type;
424 bool runtime_getfinalizer(void *p, bool del, void (**fn)(void*), const struct __go_func_type **ft);
425 void runtime_walkfintab(void (*fn)(void*), void (*scan)(byte *, int64));