1 // Copyright 2014 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.
7 // This was originally based on tcmalloc, but has diverged quite a bit.
8 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html
10 // The main allocator works in runs of pages.
11 // Small allocation sizes (up to and including 32 kB) are
12 // rounded to one of about 70 size classes, each of which
13 // has its own free set of objects of exactly that size.
14 // Any free page of memory can be split into a set of objects
15 // of one size class, which are then managed using a free bitmap.
17 // The allocator's data structures are:
19 // fixalloc: a free-list allocator for fixed-size off-heap objects,
20 // used to manage storage used by the allocator.
21 // mheap: the malloc heap, managed at page (8192-byte) granularity.
22 // mspan: a run of in-use pages managed by the mheap.
23 // mcentral: collects all spans of a given size class.
24 // mcache: a per-P cache of mspans with free space.
25 // mstats: allocation statistics.
27 // Allocating a small object proceeds up a hierarchy of caches:
29 // 1. Round the size up to one of the small size classes
30 // and look in the corresponding mspan in this P's mcache.
31 // Scan the mspan's free bitmap to find a free slot.
32 // If there is a free slot, allocate it.
33 // This can all be done without acquiring a lock.
35 // 2. If the mspan has no free slots, obtain a new mspan
36 // from the mcentral's list of mspans of the required size
37 // class that have free space.
38 // Obtaining a whole span amortizes the cost of locking
41 // 3. If the mcentral's mspan list is empty, obtain a run
42 // of pages from the mheap to use for the mspan.
44 // 4. If the mheap is empty or has no page runs large enough,
45 // allocate a new group of pages (at least 1MB) from the
46 // operating system. Allocating a large run of pages
47 // amortizes the cost of talking to the operating system.
49 // Sweeping an mspan and freeing objects on it proceeds up a similar
52 // 1. If the mspan is being swept in response to allocation, it
53 // is returned to the mcache to satisfy the allocation.
55 // 2. Otherwise, if the mspan still has allocated objects in it,
56 // it is placed on the mcentral free list for the mspan's size
59 // 3. Otherwise, if all objects in the mspan are free, the mspan's
60 // pages are returned to the mheap and the mspan is now dead.
62 // Allocating and freeing a large object uses the mheap
63 // directly, bypassing the mcache and mcentral.
65 // Free object slots in an mspan are zeroed only if mspan.needzero is
66 // false. If needzero is true, objects are zeroed as they are
67 // allocated. There are various benefits to delaying zeroing this way:
69 // 1. Stack frame allocation can avoid zeroing altogether.
71 // 2. It exhibits better temporal locality, since the program is
72 // probably about to write to the memory.
74 // 3. We don't zero pages that never get reused.
76 // Virtual memory layout
78 // The heap consists of a set of arenas, which are 64MB on 64-bit and
79 // 4MB on 32-bit (heapArenaBytes). Each arena's start address is also
80 // aligned to the arena size.
82 // Each arena has an associated heapArena object that stores the
83 // metadata for that arena: the heap bitmap for all words in the arena
84 // and the span map for all pages in the arena. heapArena objects are
85 // themselves allocated off-heap.
87 // Since arenas are aligned, the address space can be viewed as a
88 // series of arena frames. The arena map (mheap_.arenas) maps from
89 // arena frame number to *heapArena, or nil for parts of the address
90 // space not backed by the Go heap. The arena map is structured as a
91 // two-level array consisting of a "L1" arena map and many "L2" arena
92 // maps; however, since arenas are large, on many architectures, the
93 // arena map consists of a single, large L2 map.
95 // The arena map covers the entire possible address space, allowing
96 // the Go heap to use any part of the address space. The allocator
97 // attempts to keep arenas contiguous so that large spans (and hence
98 // large objects) can cross arenas.
103 "runtime/internal/atomic"
104 "runtime/internal/math"
105 "runtime/internal/sys"
109 // C function to get the end of the program's memory.
110 func getEnd() uintptr
112 // For gccgo, use go:linkname to export compiler-called functions.
114 //go:linkname newobject
116 // Functions called by C code.
117 //go:linkname mallocgc
122 maxTinySize = _TinySize
123 tinySizeClass = _TinySizeClass
124 maxSmallSize = _MaxSmallSize
126 pageShift = _PageShift
129 // By construction, single page spans of the smallest object class
130 // have the most objects per span.
131 maxObjsPerSpan = pageSize / 8
133 concurrentSweep = _ConcurrentSweep
135 _PageSize = 1 << _PageShift
136 _PageMask = _PageSize - 1
138 // _64bit = 1 on 64-bit systems, 0 on 32-bit systems
139 _64bit = 1 << (^uintptr(0) >> 63) / 2
141 // Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
143 _TinySizeClass = int8(2)
145 _FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
147 // Per-P, per order stack segment cache size.
148 _StackCacheSize = 32 * 1024
150 // Number of orders that get caching. Order 0 is FixedStack
151 // and each successive order is twice as large.
152 // We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
153 // will be allocated directly.
154 // Since FixedStack is different on different systems, we
155 // must vary NumStackOrders to keep the same maximum cached size.
156 // OS | FixedStack | NumStackOrders
157 // -----------------+------------+---------------
158 // linux/darwin/bsd | 2KB | 4
159 // windows/32 | 4KB | 3
160 // windows/64 | 8KB | 2
162 _NumStackOrders = 4 - sys.PtrSize/4*sys.GoosWindows - 1*sys.GoosPlan9
164 // heapAddrBits is the number of bits in a heap address. On
165 // amd64, addresses are sign-extended beyond heapAddrBits. On
166 // other arches, they are zero-extended.
168 // On most 64-bit platforms, we limit this to 48 bits based on a
169 // combination of hardware and OS limitations.
171 // amd64 hardware limits addresses to 48 bits, sign-extended
172 // to 64 bits. Addresses where the top 16 bits are not either
173 // all 0 or all 1 are "non-canonical" and invalid. Because of
174 // these "negative" addresses, we offset addresses by 1<<47
175 // (arenaBaseOffset) on amd64 before computing indexes into
176 // the heap arenas index. In 2017, amd64 hardware added
177 // support for 57 bit addresses; however, currently only Linux
178 // supports this extension and the kernel will never choose an
179 // address above 1<<47 unless mmap is called with a hint
180 // address above 1<<47 (which we never do).
182 // arm64 hardware (as of ARMv8) limits user addresses to 48
183 // bits, in the range [0, 1<<48).
185 // ppc64, mips64, and s390x support arbitrary 64 bit addresses
186 // in hardware. On Linux, Go leans on stricter OS limits. Based
187 // on Linux's processor.h, the user address space is limited as
188 // follows on 64-bit architectures:
190 // Architecture Name Maximum Value (exclusive)
191 // ---------------------------------------------------------------------
192 // amd64 TASK_SIZE_MAX 0x007ffffffff000 (47 bit addresses)
193 // arm64 TASK_SIZE_64 0x01000000000000 (48 bit addresses)
194 // ppc64{,le} TASK_SIZE_USER64 0x00400000000000 (46 bit addresses)
195 // mips64{,le} TASK_SIZE64 0x00010000000000 (40 bit addresses)
196 // s390x TASK_SIZE 1<<64 (64 bit addresses)
198 // These limits may increase over time, but are currently at
199 // most 48 bits except on s390x. On all architectures, Linux
200 // starts placing mmap'd regions at addresses that are
201 // significantly below 48 bits, so even if it's possible to
202 // exceed Go's 48 bit limit, it's extremely unlikely in
205 // On 32-bit platforms, we accept the full 32-bit address
206 // space because doing so is cheap.
207 // mips32 only has access to the low 2GB of virtual memory, so
208 // we further limit it to 31 bits.
210 // On darwin/arm64, although 64-bit pointers are presumably
211 // available, pointers are truncated to 33 bits. Furthermore,
212 // only the top 4 GiB of the address space are actually available
213 // to the application, but we allow the whole 33 bits anyway for
215 // TODO(mknyszek): Consider limiting it to 32 bits and using
216 // arenaBaseOffset to offset into the top 4 GiB.
218 // WebAssembly currently has a limit of 4GB linear memory.
219 heapAddrBits = (_64bit*(1-sys.GoarchWasm)*(1-sys.GoosDarwin*sys.GoarchArm64))*48 + (1-_64bit+sys.GoarchWasm)*(32-(sys.GoarchMips+sys.GoarchMipsle)) + 33*sys.GoosDarwin*sys.GoarchArm64
221 // maxAlloc is the maximum size of an allocation. On 64-bit,
222 // it's theoretically possible to allocate 1<<heapAddrBits bytes. On
223 // 32-bit, however, this is one less than 1<<32 because the
224 // number of bytes in the address space doesn't actually fit
226 maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1
228 // The number of bits in a heap address, the size of heap
229 // arenas, and the L1 and L2 arena map sizes are related by
231 // (1 << addr bits) = arena size * L1 entries * L2 entries
233 // Currently, we balance these as follows:
235 // Platform Addr bits Arena size L1 entries L2 entries
236 // -------------- --------- ---------- ---------- -----------
237 // */64-bit 48 64MB 1 4M (32MB)
238 // windows/64-bit 48 4MB 64 1M (8MB)
239 // */32-bit 32 4MB 1 1024 (4KB)
240 // */mips(le) 31 4MB 1 512 (2KB)
242 // heapArenaBytes is the size of a heap arena. The heap
243 // consists of mappings of size heapArenaBytes, aligned to
244 // heapArenaBytes. The initial heap mapping is one arena.
246 // This is currently 64MB on 64-bit non-Windows and 4MB on
247 // 32-bit and on Windows. We use smaller arenas on Windows
248 // because all committed memory is charged to the process,
249 // even if it's not touched. Hence, for processes with small
250 // heaps, the mapped arena space needs to be commensurate.
251 // This is particularly important with the race detector,
252 // since it significantly amplifies the cost of committed
254 heapArenaBytes = 1 << logHeapArenaBytes
256 // logHeapArenaBytes is log_2 of heapArenaBytes. For clarity,
257 // prefer using heapArenaBytes where possible (we need the
258 // constant to compute some other constants).
259 logHeapArenaBytes = (6+20)*(_64bit*(1-sys.GoosWindows)*(1-sys.GoarchWasm)) + (2+20)*(_64bit*sys.GoosWindows) + (2+20)*(1-_64bit) + (2+20)*sys.GoarchWasm
261 // heapArenaBitmapBytes is the size of each heap arena's bitmap.
262 heapArenaBitmapBytes = heapArenaBytes / (sys.PtrSize * 8 / 2)
264 pagesPerArena = heapArenaBytes / pageSize
266 // arenaL1Bits is the number of bits of the arena number
267 // covered by the first level arena map.
269 // This number should be small, since the first level arena
270 // map requires PtrSize*(1<<arenaL1Bits) of space in the
271 // binary's BSS. It can be zero, in which case the first level
272 // index is effectively unused. There is a performance benefit
273 // to this, since the generated code can be more efficient,
274 // but comes at the cost of having a large L2 mapping.
276 // We use the L1 map on 64-bit Windows because the arena size
277 // is small, but the address space is still 48 bits, and
278 // there's a high cost to having a large L2.
279 arenaL1Bits = 6 * (_64bit * sys.GoosWindows)
281 // arenaL2Bits is the number of bits of the arena number
282 // covered by the second level arena index.
284 // The size of each arena map allocation is proportional to
285 // 1<<arenaL2Bits, so it's important that this not be too
286 // large. 48 bits leads to 32MB arena index allocations, which
287 // is about the practical threshold.
288 arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits
290 // arenaL1Shift is the number of bits to shift an arena frame
291 // number by to compute an index into the first level arena map.
292 arenaL1Shift = arenaL2Bits
294 // arenaBits is the total bits in a combined arena map index.
295 // This is split between the index into the L1 arena map and
297 arenaBits = arenaL1Bits + arenaL2Bits
299 // arenaBaseOffset is the pointer value that corresponds to
300 // index 0 in the heap arena map.
302 // On amd64, the address space is 48 bits, sign extended to 64
303 // bits. This offset lets us handle "negative" addresses (or
304 // high addresses if viewed as unsigned).
306 // On aix/ppc64, this offset allows to keep the heapAddrBits to
307 // 48. Otherwize, it would be 60 in order to handle mmap addresses
308 // (in range 0x0a00000000000000 - 0x0afffffffffffff). But in this
309 // case, the memory reserved in (s *pageAlloc).init for chunks
310 // is causing important slowdowns.
312 // On other platforms, the user address space is contiguous
313 // and starts at 0, so no offset is necessary.
314 arenaBaseOffset = sys.GoarchAmd64*(1<<47) + (^0x0a00000000000000+1)&uintptrMask*sys.GoosAix
316 // Max number of threads to run garbage collection.
317 // 2, 3, and 4 are all plausible maximums depending
318 // on the hardware details of the machine. The garbage
319 // collector scales well to 32 cpus.
322 // minLegalPointer is the smallest possible legal pointer.
323 // This is the smallest possible architectural page size,
324 // since we assume that the first page is never mapped.
326 // This should agree with minZeroPage in the compiler.
327 minLegalPointer uintptr = 4096
330 // physPageSize is the size in bytes of the OS's physical pages.
331 // Mapping and unmapping operations must be done at multiples of
334 // This must be set by the OS init code (typically in osinit) before
336 var physPageSize uintptr
338 // physHugePageSize is the size in bytes of the OS's default physical huge
339 // page size whose allocation is opaque to the application. It is assumed
340 // and verified to be a power of two.
342 // If set, this must be set by the OS init code (typically in osinit) before
343 // mallocinit. However, setting it at all is optional, and leaving the default
344 // value is always safe (though potentially less efficient).
346 // Since physHugePageSize is always assumed to be a power of two,
347 // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
348 // The purpose of physHugePageShift is to avoid doing divisions in
349 // performance critical functions.
351 physHugePageSize uintptr
352 physHugePageShift uint
355 // OS memory management abstraction layer
357 // Regions of the address space managed by the runtime may be in one of four
358 // states at any given time:
359 // 1) None - Unreserved and unmapped, the default state of any region.
360 // 2) Reserved - Owned by the runtime, but accessing it would cause a fault.
361 // Does not count against the process' memory footprint.
362 // 3) Prepared - Reserved, intended not to be backed by physical memory (though
363 // an OS may implement this lazily). Can transition efficiently to
364 // Ready. Accessing memory in such a region is undefined (may
365 // fault, may give back unexpected zeroes, etc.).
366 // 4) Ready - may be accessed safely.
368 // This set of states is more than is strictly necessary to support all the
369 // currently supported platforms. One could get by with just None, Reserved, and
370 // Ready. However, the Prepared state gives us flexibility for performance
371 // purposes. For example, on POSIX-y operating systems, Reserved is usually a
372 // private anonymous mmap'd region with PROT_NONE set, and to transition
373 // to Ready would require setting PROT_READ|PROT_WRITE. However the
374 // underspecification of Prepared lets us use just MADV_FREE to transition from
375 // Ready to Prepared. Thus with the Prepared state we can set the permission
376 // bits just once early on, we can efficiently tell the OS that it's free to
377 // take pages away from us when we don't strictly need them.
379 // For each OS there is a common set of helpers defined that transition
380 // memory regions between these states. The helpers are as follows:
382 // sysAlloc transitions an OS-chosen region of memory from None to Ready.
383 // More specifically, it obtains a large chunk of zeroed memory from the
384 // operating system, typically on the order of a hundred kilobytes
385 // or a megabyte. This memory is always immediately available for use.
387 // sysFree transitions a memory region from any state to None. Therefore, it
388 // returns memory unconditionally. It is used if an out-of-memory error has been
389 // detected midway through an allocation or to carve out an aligned section of
390 // the address space. It is okay if sysFree is a no-op only if sysReserve always
391 // returns a memory region aligned to the heap allocator's alignment
394 // sysReserve transitions a memory region from None to Reserved. It reserves
395 // address space in such a way that it would cause a fatal fault upon access
396 // (either via permissions or not committing the memory). Such a reservation is
397 // thus never backed by physical memory.
398 // If the pointer passed to it is non-nil, the caller wants the
399 // reservation there, but sysReserve can still choose another
400 // location if that one is unavailable.
401 // NOTE: sysReserve returns OS-aligned memory, but the heap allocator
402 // may use larger alignment, so the caller must be careful to realign the
403 // memory obtained by sysReserve.
405 // sysMap transitions a memory region from Reserved to Prepared. It ensures the
406 // memory region can be efficiently transitioned to Ready.
408 // sysUsed transitions a memory region from Prepared to Ready. It notifies the
409 // operating system that the memory region is needed and ensures that the region
410 // may be safely accessed. This is typically a no-op on systems that don't have
411 // an explicit commit step and hard over-commit limits, but is critical on
412 // Windows, for example.
414 // sysUnused transitions a memory region from Ready to Prepared. It notifies the
415 // operating system that the physical pages backing this memory region are no
416 // longer needed and can be reused for other purposes. The contents of a
417 // sysUnused memory region are considered forfeit and the region must not be
418 // accessed again until sysUsed is called.
420 // sysFault transitions a memory region from Ready or Prepared to Reserved. It
421 // marks a region such that it will always fault if accessed. Used only for
422 // debugging the runtime.
425 if class_to_size[_TinySizeClass] != _TinySize {
426 throw("bad TinySizeClass")
429 // Not used for gccgo.
432 if heapArenaBitmapBytes&(heapArenaBitmapBytes-1) != 0 {
433 // heapBits expects modular arithmetic on bitmap
434 // addresses to work.
435 throw("heapArenaBitmapBytes not a power of 2")
438 // Copy class sizes out for statistics table.
439 for i := range class_to_size {
440 memstats.by_size[i].size = uint32(class_to_size[i])
443 // Check physPageSize.
444 if physPageSize == 0 {
445 // The OS init code failed to fetch the physical page size.
446 throw("failed to get system page size")
448 if physPageSize > maxPhysPageSize {
449 print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n")
450 throw("bad system page size")
452 if physPageSize < minPhysPageSize {
453 print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
454 throw("bad system page size")
456 if physPageSize&(physPageSize-1) != 0 {
457 print("system page size (", physPageSize, ") must be a power of 2\n")
458 throw("bad system page size")
460 if physHugePageSize&(physHugePageSize-1) != 0 {
461 print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
462 throw("bad system huge page size")
464 if physHugePageSize > maxPhysHugePageSize {
465 // physHugePageSize is greater than the maximum supported huge page size.
466 // Don't throw here, like in the other cases, since a system configured
467 // in this way isn't wrong, we just don't have the code to support them.
468 // Instead, silently set the huge page size to zero.
471 if physHugePageSize != 0 {
472 // Since physHugePageSize is a power of 2, it suffices to increase
473 // physHugePageShift until 1<<physHugePageShift == physHugePageSize.
474 for 1<<physHugePageShift != physHugePageSize {
479 // Initialize the heap.
482 _g_.m.mcache = allocmcache()
484 // Create initial arena growth hints.
485 if sys.PtrSize == 8 {
486 // On a 64-bit machine, we pick the following hints
489 // 1. Starting from the middle of the address space
490 // makes it easier to grow out a contiguous range
491 // without running in to some other mapping.
493 // 2. This makes Go heap addresses more easily
494 // recognizable when debugging.
496 // 3. Stack scanning in gccgo is still conservative,
497 // so it's important that addresses be distinguishable
500 // Starting at 0x00c0 means that the valid memory addresses
501 // will begin 0x00c0, 0x00c1, ...
502 // In little-endian, that's c0 00, c1 00, ... None of those are valid
503 // UTF-8 sequences, and they are otherwise as far away from
504 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
505 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
506 // on OS X during thread allocations. 0x00c0 causes conflicts with
507 // AddressSanitizer which reserves all memory up to 0x0100.
508 // These choices reduce the odds of a conservative garbage collector
509 // not collecting memory because some non-pointer block of memory
510 // had a bit pattern that matched a memory address.
512 // However, on arm64, we ignore all this advice above and slam the
513 // allocation at 0x40 << 32 because when using 4k pages with 3-level
514 // translation buffers, the user address space is limited to 39 bits
515 // On darwin/arm64, the address space is even smaller.
516 // On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
518 for i := 0x7f; i >= 0; i-- {
521 case GOARCH == "arm64" && GOOS == "darwin":
522 p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
523 case GOARCH == "arm64":
524 p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
527 // We don't use addresses directly after 0x0A00000000000000
528 // to avoid collisions with others mmaps done by non-go programs.
531 p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
533 // The TSAN runtime requires the heap
534 // to be in the range [0x00c000000000,
536 p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
537 if p >= uintptrMask&0x00e000000000 {
541 p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
543 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
545 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
548 // On a 32-bit machine, we're much more concerned
549 // about keeping the usable heap contiguous.
552 // 1. We reserve space for all heapArenas up front so
553 // they don't get interleaved with the heap. They're
554 // ~258MB, so this isn't too bad. (We could reserve a
555 // smaller amount of space up front if this is a
558 // 2. We hint the heap to start right above the end of
559 // the binary so we have the best chance of keeping it
562 // 3. We try to stake out a reasonably large initial
565 const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
566 meta := uintptr(sysReserve(nil, arenaMetaSize))
568 mheap_.heapArenaAlloc.init(meta, arenaMetaSize)
571 // We want to start the arena low, but if we're linked
572 // against C code, it's possible global constructors
573 // have called malloc and adjusted the process' brk.
574 // Query the brk so we can avoid trying to map the
575 // region over it (which will cause the kernel to put
576 // the region somewhere else, likely at a high
580 // If we ask for the end of the data segment but the
581 // operating system requires a little more space
582 // before we can start allocating, it will give out a
583 // slightly higher pointer. Except QEMU, which is
584 // buggy, as usual: it won't adjust the pointer
585 // upward. So adjust it upward a little bit ourselves:
586 // 1/4 MB to get away from the running binary image.
591 if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
592 p = mheap_.heapArenaAlloc.end
594 p = alignUp(p+(256<<10), heapArenaBytes)
595 // Because we're worried about fragmentation on
596 // 32-bit, we try to make a large initial reservation.
597 arenaSizes := [...]uintptr{
602 for _, arenaSize := range &arenaSizes {
603 a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes)
605 mheap_.arena.init(uintptr(a), size)
606 p = uintptr(a) + size // For hint below
610 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
612 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
616 // sysAlloc allocates heap arena space for at least n bytes. The
617 // returned pointer is always heapArenaBytes-aligned and backed by
618 // h.arenas metadata. The returned size is always a multiple of
619 // heapArenaBytes. sysAlloc returns nil on failure.
620 // There is no corresponding free function.
622 // sysAlloc returns a memory region in the Prepared state. This region must
623 // be transitioned to Ready before use.
626 func (h *mheap) sysAlloc(n uintptr) (v unsafe.Pointer, size uintptr) {
627 n = alignUp(n, heapArenaBytes)
629 // First, try the arena pre-reservation.
630 v = h.arena.alloc(n, heapArenaBytes, &memstats.heap_sys)
636 // Try to grow the heap at a hint address.
637 for h.arenaHints != nil {
644 // We can't use this, so don't ask.
646 } else if arenaIndex(p+n-1) >= 1<<arenaBits {
647 // Outside addressable heap. Can't use.
650 v = sysReserve(unsafe.Pointer(p), n)
653 // Success. Update the hint.
661 // Failed. Discard this hint and try the next.
663 // TODO: This would be cleaner if sysReserve could be
664 // told to only return the requested address. In
665 // particular, this is already how Windows behaves, so
666 // it would simplify things there.
670 h.arenaHints = hint.next
671 h.arenaHintAlloc.free(unsafe.Pointer(hint))
676 // The race detector assumes the heap lives in
677 // [0x00c000000000, 0x00e000000000), but we
678 // just ran out of hints in this region. Give
680 throw("too many address space collisions for -race mode")
683 // All of the hints failed, so we'll take any
684 // (sufficiently aligned) address the kernel will give
686 v, size = sysReserveAligned(nil, n, heapArenaBytes)
691 // Create new hints for extending this region.
692 hint := (*arenaHint)(h.arenaHintAlloc.alloc())
693 hint.addr, hint.down = uintptr(v), true
694 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
695 hint = (*arenaHint)(h.arenaHintAlloc.alloc())
696 hint.addr = uintptr(v) + size
697 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
700 // Check for bad pointers or pointers we can't use.
705 bad = "region exceeds uintptr range"
706 } else if arenaIndex(p) >= 1<<arenaBits {
707 bad = "base outside usable address space"
708 } else if arenaIndex(p+size-1) >= 1<<arenaBits {
709 bad = "end outside usable address space"
712 // This should be impossible on most architectures,
713 // but it would be really confusing to debug.
714 print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
715 throw("memory reservation exceeds address space limit")
719 if uintptr(v)&(heapArenaBytes-1) != 0 {
720 throw("misrounded allocation in sysAlloc")
723 // Transition from Reserved to Prepared.
724 sysMap(v, size, &memstats.heap_sys)
727 // Create arena metadata.
728 for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
729 l2 := h.arenas[ri.l1()]
731 // Allocate an L2 arena map.
732 l2 = (*[1 << arenaL2Bits]*heapArena)(persistentalloc(unsafe.Sizeof(*l2), sys.PtrSize, nil))
734 throw("out of memory allocating heap arena map")
736 atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
739 if l2[ri.l2()] != nil {
740 throw("arena already initialized")
743 r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), sys.PtrSize, &memstats.gc_sys))
745 r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), sys.PtrSize, &memstats.gc_sys))
747 throw("out of memory allocating heap arena metadata")
751 // Add the arena to the arenas list.
752 if len(h.allArenas) == cap(h.allArenas) {
753 size := 2 * uintptr(cap(h.allArenas)) * sys.PtrSize
757 newArray := (*notInHeap)(persistentalloc(size, sys.PtrSize, &memstats.gc_sys))
759 throw("out of memory allocating allArenas")
761 oldSlice := h.allArenas
762 *(*notInHeapSlice)(unsafe.Pointer(&h.allArenas)) = notInHeapSlice{newArray, len(h.allArenas), int(size / sys.PtrSize)}
763 copy(h.allArenas, oldSlice)
764 // Do not free the old backing array because
765 // there may be concurrent readers. Since we
766 // double the array each time, this can lead
767 // to at most 2x waste.
769 h.allArenas = h.allArenas[:len(h.allArenas)+1]
770 h.allArenas[len(h.allArenas)-1] = ri
772 // Store atomically just in case an object from the
773 // new heap arena becomes visible before the heap lock
774 // is released (which shouldn't happen, but there's
775 // little downside to this).
776 atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
779 // Tell the race detector about the new heap memory.
781 racemapshadow(v, size)
787 // sysReserveAligned is like sysReserve, but the returned pointer is
788 // aligned to align bytes. It may reserve either n or n+align bytes,
789 // so it returns the size that was reserved.
790 func sysReserveAligned(v unsafe.Pointer, size, align uintptr) (unsafe.Pointer, uintptr) {
791 // Since the alignment is rather large in uses of this
792 // function, we're not likely to get it by chance, so we ask
793 // for a larger region and remove the parts we don't need.
796 p := uintptr(sysReserve(v, size+align))
800 case p&(align-1) == 0:
801 // We got lucky and got an aligned region, so we can
802 // use the whole thing.
803 return unsafe.Pointer(p), size + align
804 case GOOS == "windows":
805 // On Windows we can't release pieces of a
806 // reservation, so we release the whole thing and
807 // re-reserve the aligned sub-region. This may race,
808 // so we may have to try again.
809 sysFree(unsafe.Pointer(p), size+align, nil)
810 p = alignUp(p, align)
811 p2 := sysReserve(unsafe.Pointer(p), size)
812 if p != uintptr(p2) {
813 // Must have raced. Try again.
814 sysFree(p2, size, nil)
815 if retries++; retries == 100 {
816 throw("failed to allocate aligned heap memory; too many retries")
823 // Trim off the unaligned parts.
824 pAligned := alignUp(p, align)
825 sysFree(unsafe.Pointer(p), pAligned-p, nil)
826 end := pAligned + size
827 endLen := (p + size + align) - end
829 sysFree(unsafe.Pointer(end), endLen, nil)
831 return unsafe.Pointer(pAligned), size
835 // base address for all 0-byte allocations
838 // nextFreeFast returns the next free object if one is quickly available.
839 // Otherwise it returns 0.
840 func nextFreeFast(s *mspan) gclinkptr {
841 theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
843 result := s.freeindex + uintptr(theBit)
844 if result < s.nelems {
845 freeidx := result + 1
846 if freeidx%64 == 0 && freeidx != s.nelems {
849 s.allocCache >>= uint(theBit + 1)
850 s.freeindex = freeidx
852 return gclinkptr(result*s.elemsize + s.base())
858 // nextFree returns the next free object from the cached span if one is available.
859 // Otherwise it refills the cache with a span with an available object and
860 // returns that object along with a flag indicating that this was a heavy
861 // weight allocation. If it is a heavy weight allocation the caller must
862 // determine whether a new GC cycle needs to be started or if the GC is active
863 // whether this goroutine needs to assist the GC.
865 // Must run in a non-preemptible context since otherwise the owner of
867 func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
870 freeIndex := s.nextFreeIndex()
871 if freeIndex == s.nelems {
873 if uintptr(s.allocCount) != s.nelems {
874 println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
875 throw("s.allocCount != s.nelems && freeIndex == s.nelems")
881 freeIndex = s.nextFreeIndex()
884 if freeIndex >= s.nelems {
885 throw("freeIndex is not valid")
888 v = gclinkptr(freeIndex*s.elemsize + s.base())
890 if uintptr(s.allocCount) > s.nelems {
891 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
892 throw("s.allocCount > s.nelems")
897 // Allocate an object of size bytes.
898 // Small objects are allocated from the per-P cache's free lists.
899 // Large objects (> 32 kB) are allocated straight from the heap.
900 func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
901 if gcphase == _GCmarktermination {
902 throw("mallocgc called with gcphase == _GCmarktermination")
906 return unsafe.Pointer(&zerobase)
912 // TODO(austin): This should be just
913 // align = uintptr(typ.align)
914 // but that's only 4 on 32-bit platforms,
915 // even if there's a uint64 field in typ (see #599).
916 // This causes 64-bit atomic accesses to panic.
917 // Hence, we use stricter alignment that matches
918 // the normal allocator better.
921 } else if size&3 == 0 {
923 } else if size&1 == 0 {
929 return persistentalloc(size, align, &memstats.other_sys)
932 // When using gccgo, when a cgo or SWIG function has an
933 // interface return type and the function returns a
934 // non-pointer, memory allocation occurs after syscall.Cgocall
935 // but before syscall.CgocallDone. Treat this allocation as a
938 if gomcache() == nil && getg().m.ncgo > 0 {
943 // assistG is the G to charge for this allocation, or nil if
944 // GC is not currently active.
946 if gcBlackenEnabled != 0 {
947 // Charge the current user G for this allocation.
949 if assistG.m.curg != nil {
950 assistG = assistG.m.curg
952 // Charge the allocation against the G. We'll account
953 // for internal fragmentation at the end of mallocgc.
954 assistG.gcAssistBytes -= int64(size)
956 if assistG.gcAssistBytes < 0 {
957 // This G is in debt. Assist the GC to correct
958 // this before allocating. This must happen
959 // before disabling preemption.
960 gcAssistAlloc(assistG)
964 // Set mp.mallocing to keep from being preempted by GC.
966 if mp.mallocing != 0 {
967 throw("malloc deadlock")
969 if mp.gsignal == getg() {
970 throw("malloc during signal")
974 shouldhelpgc := false
978 noscan := typ == nil || typ.ptrdata == 0
979 if size <= maxSmallSize {
980 if noscan && size < maxTinySize {
983 // Tiny allocator combines several tiny allocation requests
984 // into a single memory block. The resulting memory block
985 // is freed when all subobjects are unreachable. The subobjects
986 // must be noscan (don't have pointers), this ensures that
987 // the amount of potentially wasted memory is bounded.
989 // Size of the memory block used for combining (maxTinySize) is tunable.
990 // Current setting is 16 bytes, which relates to 2x worst case memory
991 // wastage (when all but one subobjects are unreachable).
992 // 8 bytes would result in no wastage at all, but provides less
993 // opportunities for combining.
994 // 32 bytes provides more opportunities for combining,
995 // but can lead to 4x worst case wastage.
996 // The best case winning is 8x regardless of block size.
998 // Objects obtained from tiny allocator must not be freed explicitly.
999 // So when an object will be freed explicitly, we ensure that
1000 // its size >= maxTinySize.
1002 // SetFinalizer has a special case for objects potentially coming
1003 // from tiny allocator, it such case it allows to set finalizers
1004 // for an inner byte of a memory block.
1006 // The main targets of tiny allocator are small strings and
1007 // standalone escaping variables. On a json benchmark
1008 // the allocator reduces number of allocations by ~12% and
1009 // reduces heap size by ~20%.
1011 // Align tiny pointer for required (conservative) alignment.
1013 off = alignUp(off, 8)
1014 } else if size&3 == 0 {
1015 off = alignUp(off, 4)
1016 } else if size&1 == 0 {
1017 off = alignUp(off, 2)
1019 if off+size <= maxTinySize && c.tiny != 0 {
1020 // The object fits into existing tiny block.
1021 x = unsafe.Pointer(c.tiny + off)
1022 c.tinyoffset = off + size
1023 c.local_tinyallocs++
1031 // Allocate a new maxTinySize block.
1032 span := c.alloc[tinySpanClass]
1033 v := nextFreeFast(span)
1035 v, _, shouldhelpgc = c.nextFree(tinySpanClass)
1037 x = unsafe.Pointer(v)
1038 (*[2]uint64)(x)[0] = 0
1039 (*[2]uint64)(x)[1] = 0
1040 // See if we need to replace the existing tiny block with the new one
1041 // based on amount of remaining free space.
1042 if size < c.tinyoffset || c.tiny == 0 {
1049 if size <= smallSizeMax-8 {
1050 sizeclass = size_to_class8[(size+smallSizeDiv-1)/smallSizeDiv]
1052 sizeclass = size_to_class128[(size-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
1054 size = uintptr(class_to_size[sizeclass])
1055 spc := makeSpanClass(sizeclass, noscan)
1056 span := c.alloc[spc]
1057 v := nextFreeFast(span)
1059 v, span, shouldhelpgc = c.nextFree(spc)
1061 x = unsafe.Pointer(v)
1062 if needzero && span.needzero != 0 {
1063 memclrNoHeapPointers(unsafe.Pointer(v), size)
1069 systemstack(func() {
1070 s = largeAlloc(size, needzero, noscan)
1074 x = unsafe.Pointer(s.base())
1078 var scanSize uintptr
1080 heapBitsSetType(uintptr(x), size, dataSize, typ)
1081 if dataSize > typ.size {
1082 // Array allocation. If there are any
1083 // pointers, GC has to scan to the last
1085 if typ.ptrdata != 0 {
1086 scanSize = dataSize - typ.size + typ.ptrdata
1089 scanSize = typ.ptrdata
1091 c.local_scan += scanSize
1094 // Ensure that the stores above that initialize x to
1095 // type-safe memory and set the heap bits occur before
1096 // the caller can make x observable to the garbage
1097 // collector. Otherwise, on weakly ordered machines,
1098 // the garbage collector could follow a pointer to x,
1099 // but see uninitialized memory or stale heap bits.
1100 publicationBarrier()
1102 // Allocate black during GC.
1103 // All slots hold nil so no scanning is needed.
1104 // This may be racing with GC so do it atomically if there can be
1105 // a race marking the bit.
1106 if gcphase != _GCoff {
1107 gcmarknewobject(uintptr(x), size, scanSize)
1121 if debug.allocfreetrace != 0 {
1122 tracealloc(x, size, typ)
1125 if rate := MemProfileRate; rate > 0 {
1126 if rate != 1 && size < c.next_sample {
1127 c.next_sample -= size
1130 profilealloc(mp, x, size)
1136 // Account for internal fragmentation in the assist
1137 // debt now that we know it.
1138 assistG.gcAssistBytes -= int64(size - dataSize)
1142 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
1147 // Check preemption, since unlike gc we don't check on every call.
1159 func largeAlloc(size uintptr, needzero bool, noscan bool) *mspan {
1160 // print("largeAlloc size=", size, "\n")
1162 if size+_PageSize < size {
1163 throw("out of memory")
1165 npages := size >> _PageShift
1166 if size&_PageMask != 0 {
1170 // Deduct credit for this span allocation and sweep if
1171 // necessary. mHeap_Alloc will also sweep npages, so this only
1172 // pays the debt down to npage pages.
1173 deductSweepCredit(npages*_PageSize, npages)
1175 s := mheap_.alloc(npages, makeSpanClass(0, noscan), needzero)
1177 throw("out of memory")
1179 s.limit = s.base() + size
1180 heapBitsForAddr(s.base()).initSpan(s)
1184 // implementation of new builtin
1185 // compiler (both frontend and SSA backend) knows the signature
1187 func newobject(typ *_type) unsafe.Pointer {
1188 return mallocgc(typ.size, typ, true)
1191 //go:linkname reflect_unsafe_New reflect.unsafe_New
1192 func reflect_unsafe_New(typ *_type) unsafe.Pointer {
1193 return mallocgc(typ.size, typ, true)
1196 //go:linkname reflectlite_unsafe_New internal..z2freflectlite.unsafe_New
1197 func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
1198 return mallocgc(typ.size, typ, true)
1201 // newarray allocates an array of n elements of type typ.
1202 func newarray(typ *_type, n int) unsafe.Pointer {
1204 return mallocgc(typ.size, typ, true)
1206 mem, overflow := math.MulUintptr(typ.size, uintptr(n))
1207 if overflow || mem > maxAlloc || n < 0 {
1208 panic(plainError("runtime: allocation size out of range"))
1210 return mallocgc(mem, typ, true)
1213 //go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray
1214 func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
1215 return newarray(typ, n)
1218 func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
1219 mp.mcache.next_sample = nextSample()
1220 mProf_Malloc(x, size)
1223 // nextSample returns the next sampling point for heap profiling. The goal is
1224 // to sample allocations on average every MemProfileRate bytes, but with a
1225 // completely random distribution over the allocation timeline; this
1226 // corresponds to a Poisson process with parameter MemProfileRate. In Poisson
1227 // processes, the distance between two samples follows the exponential
1228 // distribution (exp(MemProfileRate)), so the best return value is a random
1229 // number taken from an exponential distribution whose mean is MemProfileRate.
1230 func nextSample() uintptr {
1231 if GOOS == "plan9" {
1232 // Plan 9 doesn't support floating point in note handler.
1233 if g := getg(); g == g.m.gsignal {
1234 return nextSampleNoFP()
1238 return uintptr(fastexprand(MemProfileRate))
1241 // fastexprand returns a random number from an exponential distribution with
1242 // the specified mean.
1243 func fastexprand(mean int) int32 {
1244 // Avoid overflow. Maximum possible step is
1245 // -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
1247 case mean > 0x7000000:
1253 // Take a random sample of the exponential distribution exp(-mean*x).
1254 // The probability distribution function is mean*exp(-mean*x), so the CDF is
1255 // p = 1 - exp(-mean*x), so
1256 // q = 1 - p == exp(-mean*x)
1257 // log_e(q) = -mean*x
1258 // -log_e(q)/mean = x
1259 // x = -log_e(q) * mean
1260 // x = log_2(q) * (-log_e(2)) * mean ; Using log_2 for efficiency
1261 const randomBitCount = 26
1262 q := fastrand()%(1<<randomBitCount) + 1
1263 qlog := fastlog2(float64(q)) - randomBitCount
1267 const minusLog2 = -0.6931471805599453 // -ln(2)
1268 return int32(qlog*(minusLog2*float64(mean))) + 1
1271 // nextSampleNoFP is similar to nextSample, but uses older,
1272 // simpler code to avoid floating point.
1273 func nextSampleNoFP() uintptr {
1274 // Set first allocation sample size.
1275 rate := MemProfileRate
1276 if rate > 0x3fffffff { // make 2*rate not overflow
1280 return uintptr(fastrand() % uint32(2*rate))
1285 type persistentAlloc struct {
1290 var globalAlloc struct {
1295 // persistentChunkSize is the number of bytes we allocate when we grow
1296 // a persistentAlloc.
1297 const persistentChunkSize = 256 << 10
1299 // persistentChunks is a list of all the persistent chunks we have
1300 // allocated. The list is maintained through the first word in the
1301 // persistent chunk. This is updated atomically.
1302 var persistentChunks *notInHeap
1304 // Wrapper around sysAlloc that can allocate small chunks.
1305 // There is no associated free operation.
1306 // Intended for things like function/type/debug-related persistent data.
1307 // If align is 0, uses default align (currently 8).
1308 // The returned memory will be zeroed.
1310 // Consider marking persistentalloc'd types go:notinheap.
1311 func persistentalloc(size, align uintptr, sysStat *uint64) unsafe.Pointer {
1313 systemstack(func() {
1314 p = persistentalloc1(size, align, sysStat)
1316 return unsafe.Pointer(p)
1319 // Must run on system stack because stack growth can (re)invoke it.
1322 func persistentalloc1(size, align uintptr, sysStat *uint64) *notInHeap {
1324 maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
1328 throw("persistentalloc: size == 0")
1331 if align&(align-1) != 0 {
1332 throw("persistentalloc: align is not a power of 2")
1334 if align > _PageSize {
1335 throw("persistentalloc: align is too large")
1341 if size >= maxBlock {
1342 return (*notInHeap)(sysAlloc(size, sysStat))
1346 var persistent *persistentAlloc
1347 if mp != nil && mp.p != 0 {
1348 persistent = &mp.p.ptr().palloc
1350 lock(&globalAlloc.mutex)
1351 persistent = &globalAlloc.persistentAlloc
1353 persistent.off = alignUp(persistent.off, align)
1354 if persistent.off+size > persistentChunkSize || persistent.base == nil {
1355 persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys))
1356 if persistent.base == nil {
1357 if persistent == &globalAlloc.persistentAlloc {
1358 unlock(&globalAlloc.mutex)
1360 throw("runtime: cannot allocate memory")
1363 // Add the new chunk to the persistentChunks list.
1365 chunks := uintptr(unsafe.Pointer(persistentChunks))
1366 *(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
1367 if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
1371 persistent.off = alignUp(sys.PtrSize, align)
1373 p := persistent.base.add(persistent.off)
1374 persistent.off += size
1376 if persistent == &globalAlloc.persistentAlloc {
1377 unlock(&globalAlloc.mutex)
1380 if sysStat != &memstats.other_sys {
1381 mSysStatInc(sysStat, size)
1382 mSysStatDec(&memstats.other_sys, size)
1387 // inPersistentAlloc reports whether p points to memory allocated by
1388 // persistentalloc. This must be nosplit because it is called by the
1389 // cgo checker code, which is called by the write barrier code.
1391 func inPersistentAlloc(p uintptr) bool {
1392 chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
1394 if p >= chunk && p < chunk+persistentChunkSize {
1397 chunk = *(*uintptr)(unsafe.Pointer(chunk))
1402 // linearAlloc is a simple linear allocator that pre-reserves a region
1403 // of memory and then maps that region into the Ready state as needed. The
1404 // caller is responsible for locking.
1405 type linearAlloc struct {
1406 next uintptr // next free byte
1407 mapped uintptr // one byte past end of mapped space
1408 end uintptr // end of reserved space
1411 func (l *linearAlloc) init(base, size uintptr) {
1412 l.next, l.mapped = base, base
1416 func (l *linearAlloc) alloc(size, align uintptr, sysStat *uint64) unsafe.Pointer {
1417 p := alignUp(l.next, align)
1422 if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
1423 // Transition from Reserved to Prepared to Ready.
1424 sysMap(unsafe.Pointer(l.mapped), pEnd-l.mapped, sysStat)
1425 sysUsed(unsafe.Pointer(l.mapped), pEnd-l.mapped)
1428 return unsafe.Pointer(p)
1431 // notInHeap is off-heap memory allocated by a lower-level allocator
1432 // like sysAlloc or persistentAlloc.
1434 // In general, it's better to use real types marked as go:notinheap,
1435 // but this serves as a generic type for situations where that isn't
1436 // possible (like in the allocators).
1438 // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
1441 type notInHeap struct{}
1443 func (p *notInHeap) add(bytes uintptr) *notInHeap {
1444 return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))