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 // If mspan.needzero is false, then free object slots in the mspan are
66 // already zeroed. Otherwise if needzero is true, objects are zeroed as
67 // they are allocated. There are various benefits to delaying zeroing
70 // 1. Stack frame allocation can avoid zeroing altogether.
72 // 2. It exhibits better temporal locality, since the program is
73 // probably about to write to the memory.
75 // 3. We don't zero pages that never get reused.
77 // Virtual memory layout
79 // The heap consists of a set of arenas, which are 64MB on 64-bit and
80 // 4MB on 32-bit (heapArenaBytes). Each arena's start address is also
81 // aligned to the arena size.
83 // Each arena has an associated heapArena object that stores the
84 // metadata for that arena: the heap bitmap for all words in the arena
85 // and the span map for all pages in the arena. heapArena objects are
86 // themselves allocated off-heap.
88 // Since arenas are aligned, the address space can be viewed as a
89 // series of arena frames. The arena map (mheap_.arenas) maps from
90 // arena frame number to *heapArena, or nil for parts of the address
91 // space not backed by the Go heap. The arena map is structured as a
92 // two-level array consisting of a "L1" arena map and many "L2" arena
93 // maps; however, since arenas are large, on many architectures, the
94 // arena map consists of a single, large L2 map.
96 // The arena map covers the entire possible address space, allowing
97 // the Go heap to use any part of the address space. The allocator
98 // attempts to keep arenas contiguous so that large spans (and hence
99 // large objects) can cross arenas.
106 "runtime/internal/atomic"
107 "runtime/internal/math"
108 "runtime/internal/sys"
113 maxTinySize = _TinySize
114 tinySizeClass = _TinySizeClass
115 maxSmallSize = _MaxSmallSize
117 pageShift = _PageShift
120 concurrentSweep = _ConcurrentSweep
122 _PageSize = 1 << _PageShift
123 _PageMask = _PageSize - 1
125 // _64bit = 1 on 64-bit systems, 0 on 32-bit systems
126 _64bit = 1 << (^uintptr(0) >> 63) / 2
128 // Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
130 _TinySizeClass = int8(2)
132 _FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
134 // Per-P, per order stack segment cache size.
135 _StackCacheSize = 32 * 1024
137 // Number of orders that get caching. Order 0 is FixedStack
138 // and each successive order is twice as large.
139 // We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
140 // will be allocated directly.
141 // Since FixedStack is different on different systems, we
142 // must vary NumStackOrders to keep the same maximum cached size.
143 // OS | FixedStack | NumStackOrders
144 // -----------------+------------+---------------
145 // linux/darwin/bsd | 2KB | 4
146 // windows/32 | 4KB | 3
147 // windows/64 | 8KB | 2
149 _NumStackOrders = 4 - goarch.PtrSize/4*goos.IsWindows - 1*goos.IsPlan9
151 // heapAddrBits is the number of bits in a heap address. On
152 // amd64, addresses are sign-extended beyond heapAddrBits. On
153 // other arches, they are zero-extended.
155 // On most 64-bit platforms, we limit this to 48 bits based on a
156 // combination of hardware and OS limitations.
158 // amd64 hardware limits addresses to 48 bits, sign-extended
159 // to 64 bits. Addresses where the top 16 bits are not either
160 // all 0 or all 1 are "non-canonical" and invalid. Because of
161 // these "negative" addresses, we offset addresses by 1<<47
162 // (arenaBaseOffset) on amd64 before computing indexes into
163 // the heap arenas index. In 2017, amd64 hardware added
164 // support for 57 bit addresses; however, currently only Linux
165 // supports this extension and the kernel will never choose an
166 // address above 1<<47 unless mmap is called with a hint
167 // address above 1<<47 (which we never do).
169 // arm64 hardware (as of ARMv8) limits user addresses to 48
170 // bits, in the range [0, 1<<48).
172 // ppc64, mips64, and s390x support arbitrary 64 bit addresses
173 // in hardware. On Linux, Go leans on stricter OS limits. Based
174 // on Linux's processor.h, the user address space is limited as
175 // follows on 64-bit architectures:
177 // Architecture Name Maximum Value (exclusive)
178 // ---------------------------------------------------------------------
179 // amd64 TASK_SIZE_MAX 0x007ffffffff000 (47 bit addresses)
180 // arm64 TASK_SIZE_64 0x01000000000000 (48 bit addresses)
181 // ppc64{,le} TASK_SIZE_USER64 0x00400000000000 (46 bit addresses)
182 // mips64{,le} TASK_SIZE64 0x00010000000000 (40 bit addresses)
183 // s390x TASK_SIZE 1<<64 (64 bit addresses)
185 // These limits may increase over time, but are currently at
186 // most 48 bits except on s390x. On all architectures, Linux
187 // starts placing mmap'd regions at addresses that are
188 // significantly below 48 bits, so even if it's possible to
189 // exceed Go's 48 bit limit, it's extremely unlikely in
192 // On 32-bit platforms, we accept the full 32-bit address
193 // space because doing so is cheap.
194 // mips32 only has access to the low 2GB of virtual memory, so
195 // we further limit it to 31 bits.
197 // On ios/arm64, although 64-bit pointers are presumably
198 // available, pointers are truncated to 33 bits in iOS <14.
199 // Furthermore, only the top 4 GiB of the address space are
200 // actually available to the application. In iOS >=14, more
201 // of the address space is available, and the OS can now
202 // provide addresses outside of those 33 bits. Pick 40 bits
203 // as a reasonable balance between address space usage by the
204 // page allocator, and flexibility for what mmap'd regions
205 // we'll accept for the heap. We can't just move to the full
206 // 48 bits because this uses too much address space for older
208 // TODO(mknyszek): Once iOS <14 is deprecated, promote ios/arm64
209 // to a 48-bit address space like every other arm64 platform.
211 // WebAssembly currently has a limit of 4GB linear memory.
212 heapAddrBits = (_64bit*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64))*48 + (1-_64bit+goarch.IsWasm)*(32-(goarch.IsMips+goarch.IsMipsle)) + 40*goos.IsIos*goarch.IsArm64
214 // maxAlloc is the maximum size of an allocation. On 64-bit,
215 // it's theoretically possible to allocate 1<<heapAddrBits bytes. On
216 // 32-bit, however, this is one less than 1<<32 because the
217 // number of bytes in the address space doesn't actually fit
219 maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1
221 // The number of bits in a heap address, the size of heap
222 // arenas, and the L1 and L2 arena map sizes are related by
224 // (1 << addr bits) = arena size * L1 entries * L2 entries
226 // Currently, we balance these as follows:
228 // Platform Addr bits Arena size L1 entries L2 entries
229 // -------------- --------- ---------- ---------- -----------
230 // */64-bit 48 64MB 1 4M (32MB)
231 // windows/64-bit 48 4MB 64 1M (8MB)
232 // ios/arm64 33 4MB 1 2048 (8KB)
233 // */32-bit 32 4MB 1 1024 (4KB)
234 // */mips(le) 31 4MB 1 512 (2KB)
236 // heapArenaBytes is the size of a heap arena. The heap
237 // consists of mappings of size heapArenaBytes, aligned to
238 // heapArenaBytes. The initial heap mapping is one arena.
240 // This is currently 64MB on 64-bit non-Windows and 4MB on
241 // 32-bit and on Windows. We use smaller arenas on Windows
242 // because all committed memory is charged to the process,
243 // even if it's not touched. Hence, for processes with small
244 // heaps, the mapped arena space needs to be commensurate.
245 // This is particularly important with the race detector,
246 // since it significantly amplifies the cost of committed
248 heapArenaBytes = 1 << logHeapArenaBytes
250 heapArenaWords = heapArenaBytes / goarch.PtrSize
252 // logHeapArenaBytes is log_2 of heapArenaBytes. For clarity,
253 // prefer using heapArenaBytes where possible (we need the
254 // constant to compute some other constants).
255 logHeapArenaBytes = (6+20)*(_64bit*(1-goos.IsWindows)*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64)) + (2+20)*(_64bit*goos.IsWindows) + (2+20)*(1-_64bit) + (2+20)*goarch.IsWasm + (2+20)*goos.IsIos*goarch.IsArm64
257 // heapArenaBitmapWords is the size of each heap arena's bitmap in uintptrs.
258 heapArenaBitmapWords = heapArenaWords / (8 * goarch.PtrSize)
260 pagesPerArena = heapArenaBytes / pageSize
262 // arenaL1Bits is the number of bits of the arena number
263 // covered by the first level arena map.
265 // This number should be small, since the first level arena
266 // map requires PtrSize*(1<<arenaL1Bits) of space in the
267 // binary's BSS. It can be zero, in which case the first level
268 // index is effectively unused. There is a performance benefit
269 // to this, since the generated code can be more efficient,
270 // but comes at the cost of having a large L2 mapping.
272 // We use the L1 map on 64-bit Windows because the arena size
273 // is small, but the address space is still 48 bits, and
274 // there's a high cost to having a large L2.
275 arenaL1Bits = 6 * (_64bit * goos.IsWindows)
277 // arenaL2Bits is the number of bits of the arena number
278 // covered by the second level arena index.
280 // The size of each arena map allocation is proportional to
281 // 1<<arenaL2Bits, so it's important that this not be too
282 // large. 48 bits leads to 32MB arena index allocations, which
283 // is about the practical threshold.
284 arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits
286 // arenaL1Shift is the number of bits to shift an arena frame
287 // number by to compute an index into the first level arena map.
288 arenaL1Shift = arenaL2Bits
290 // arenaBits is the total bits in a combined arena map index.
291 // This is split between the index into the L1 arena map and
293 arenaBits = arenaL1Bits + arenaL2Bits
295 // arenaBaseOffset is the pointer value that corresponds to
296 // index 0 in the heap arena map.
298 // On amd64, the address space is 48 bits, sign extended to 64
299 // bits. This offset lets us handle "negative" addresses (or
300 // high addresses if viewed as unsigned).
302 // On aix/ppc64, this offset allows to keep the heapAddrBits to
303 // 48. Otherwise, it would be 60 in order to handle mmap addresses
304 // (in range 0x0a00000000000000 - 0x0afffffffffffff). But in this
305 // case, the memory reserved in (s *pageAlloc).init for chunks
306 // is causing important slowdowns.
308 // On other platforms, the user address space is contiguous
309 // and starts at 0, so no offset is necessary.
310 arenaBaseOffset = 0xffff800000000000*goarch.IsAmd64 + 0x0a00000000000000*goos.IsAix
311 // A typed version of this constant that will make it into DWARF (for viewcore).
312 arenaBaseOffsetUintptr = uintptr(arenaBaseOffset)
314 // Max number of threads to run garbage collection.
315 // 2, 3, and 4 are all plausible maximums depending
316 // on the hardware details of the machine. The garbage
317 // collector scales well to 32 cpus.
320 // minLegalPointer is the smallest possible legal pointer.
321 // This is the smallest possible architectural page size,
322 // since we assume that the first page is never mapped.
324 // This should agree with minZeroPage in the compiler.
325 minLegalPointer uintptr = 4096
328 // physPageSize is the size in bytes of the OS's physical pages.
329 // Mapping and unmapping operations must be done at multiples of
332 // This must be set by the OS init code (typically in osinit) before
334 var physPageSize uintptr
336 // physHugePageSize is the size in bytes of the OS's default physical huge
337 // page size whose allocation is opaque to the application. It is assumed
338 // and verified to be a power of two.
340 // If set, this must be set by the OS init code (typically in osinit) before
341 // mallocinit. However, setting it at all is optional, and leaving the default
342 // value is always safe (though potentially less efficient).
344 // Since physHugePageSize is always assumed to be a power of two,
345 // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
346 // The purpose of physHugePageShift is to avoid doing divisions in
347 // performance critical functions.
349 physHugePageSize uintptr
350 physHugePageShift uint
354 if class_to_size[_TinySizeClass] != _TinySize {
355 throw("bad TinySizeClass")
358 if heapArenaBitmapWords&(heapArenaBitmapWords-1) != 0 {
359 // heapBits expects modular arithmetic on bitmap
360 // addresses to work.
361 throw("heapArenaBitmapWords not a power of 2")
364 // Check physPageSize.
365 if physPageSize == 0 {
366 // The OS init code failed to fetch the physical page size.
367 throw("failed to get system page size")
369 if physPageSize > maxPhysPageSize {
370 print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n")
371 throw("bad system page size")
373 if physPageSize < minPhysPageSize {
374 print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
375 throw("bad system page size")
377 if physPageSize&(physPageSize-1) != 0 {
378 print("system page size (", physPageSize, ") must be a power of 2\n")
379 throw("bad system page size")
381 if physHugePageSize&(physHugePageSize-1) != 0 {
382 print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
383 throw("bad system huge page size")
385 if physHugePageSize > maxPhysHugePageSize {
386 // physHugePageSize is greater than the maximum supported huge page size.
387 // Don't throw here, like in the other cases, since a system configured
388 // in this way isn't wrong, we just don't have the code to support them.
389 // Instead, silently set the huge page size to zero.
392 if physHugePageSize != 0 {
393 // Since physHugePageSize is a power of 2, it suffices to increase
394 // physHugePageShift until 1<<physHugePageShift == physHugePageSize.
395 for 1<<physHugePageShift != physHugePageSize {
399 if pagesPerArena%pagesPerSpanRoot != 0 {
400 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerSpanRoot (", pagesPerSpanRoot, ")\n")
401 throw("bad pagesPerSpanRoot")
403 if pagesPerArena%pagesPerReclaimerChunk != 0 {
404 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerReclaimerChunk (", pagesPerReclaimerChunk, ")\n")
405 throw("bad pagesPerReclaimerChunk")
408 // Initialize the heap.
410 mcache0 = allocmcache()
411 lockInit(&gcBitsArenas.lock, lockRankGcBitsArenas)
412 lockInit(&profInsertLock, lockRankProfInsert)
413 lockInit(&profBlockLock, lockRankProfBlock)
414 lockInit(&profMemActiveLock, lockRankProfMemActive)
415 for i := range profMemFutureLock {
416 lockInit(&profMemFutureLock[i], lockRankProfMemFuture)
418 lockInit(&globalAlloc.mutex, lockRankGlobalAlloc)
420 // Create initial arena growth hints.
421 if goarch.PtrSize == 8 {
422 // On a 64-bit machine, we pick the following hints
425 // 1. Starting from the middle of the address space
426 // makes it easier to grow out a contiguous range
427 // without running in to some other mapping.
429 // 2. This makes Go heap addresses more easily
430 // recognizable when debugging.
432 // 3. Stack scanning in gccgo is still conservative,
433 // so it's important that addresses be distinguishable
436 // Starting at 0x00c0 means that the valid memory addresses
437 // will begin 0x00c0, 0x00c1, ...
438 // In little-endian, that's c0 00, c1 00, ... None of those are valid
439 // UTF-8 sequences, and they are otherwise as far away from
440 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
441 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
442 // on OS X during thread allocations. 0x00c0 causes conflicts with
443 // AddressSanitizer which reserves all memory up to 0x0100.
444 // These choices reduce the odds of a conservative garbage collector
445 // not collecting memory because some non-pointer block of memory
446 // had a bit pattern that matched a memory address.
448 // However, on arm64, we ignore all this advice above and slam the
449 // allocation at 0x40 << 32 because when using 4k pages with 3-level
450 // translation buffers, the user address space is limited to 39 bits
451 // On ios/arm64, the address space is even smaller.
453 // On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
455 for i := 0x7f; i >= 0; i-- {
459 // The TSAN runtime requires the heap
460 // to be in the range [0x00c000000000,
462 p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
463 if p >= uintptrMask&0x00e000000000 {
466 case GOARCH == "arm64" && GOOS == "ios":
467 p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
468 case GOARCH == "arm64":
469 p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
472 // We don't use addresses directly after 0x0A00000000000000
473 // to avoid collisions with others mmaps done by non-go programs.
476 p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
478 p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
480 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
482 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
485 // On a 32-bit machine, we're much more concerned
486 // about keeping the usable heap contiguous.
489 // 1. We reserve space for all heapArenas up front so
490 // they don't get interleaved with the heap. They're
491 // ~258MB, so this isn't too bad. (We could reserve a
492 // smaller amount of space up front if this is a
495 // 2. We hint the heap to start right above the end of
496 // the binary so we have the best chance of keeping it
499 // 3. We try to stake out a reasonably large initial
502 const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
503 meta := uintptr(sysReserve(nil, arenaMetaSize))
505 mheap_.heapArenaAlloc.init(meta, arenaMetaSize, true)
508 // We want to start the arena low, but if we're linked
509 // against C code, it's possible global constructors
510 // have called malloc and adjusted the process' brk.
511 // Query the brk so we can avoid trying to map the
512 // region over it (which will cause the kernel to put
513 // the region somewhere else, likely at a high
517 // If we ask for the end of the data segment but the
518 // operating system requires a little more space
519 // before we can start allocating, it will give out a
520 // slightly higher pointer. Except QEMU, which is
521 // buggy, as usual: it won't adjust the pointer
522 // upward. So adjust it upward a little bit ourselves:
523 // 1/4 MB to get away from the running binary image.
524 p := firstmoduledata.end
528 if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
529 p = mheap_.heapArenaAlloc.end
531 p = alignUp(p+(256<<10), heapArenaBytes)
532 // Because we're worried about fragmentation on
533 // 32-bit, we try to make a large initial reservation.
534 arenaSizes := []uintptr{
539 for _, arenaSize := range arenaSizes {
540 a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes)
542 mheap_.arena.init(uintptr(a), size, false)
543 p = mheap_.arena.end // For hint below
547 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
549 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
553 // sysAlloc allocates heap arena space for at least n bytes. The
554 // returned pointer is always heapArenaBytes-aligned and backed by
555 // h.arenas metadata. The returned size is always a multiple of
556 // heapArenaBytes. sysAlloc returns nil on failure.
557 // There is no corresponding free function.
559 // sysAlloc returns a memory region in the Reserved state. This region must
560 // be transitioned to Prepared and then Ready before use.
563 func (h *mheap) sysAlloc(n uintptr) (v unsafe.Pointer, size uintptr) {
564 assertLockHeld(&h.lock)
566 n = alignUp(n, heapArenaBytes)
568 // First, try the arena pre-reservation.
569 // Newly-used mappings are considered released.
570 v = h.arena.alloc(n, heapArenaBytes, &gcController.heapReleased)
576 // Try to grow the heap at a hint address.
577 for h.arenaHints != nil {
584 // We can't use this, so don't ask.
586 } else if arenaIndex(p+n-1) >= 1<<arenaBits {
587 // Outside addressable heap. Can't use.
590 v = sysReserve(unsafe.Pointer(p), n)
593 // Success. Update the hint.
601 // Failed. Discard this hint and try the next.
603 // TODO: This would be cleaner if sysReserve could be
604 // told to only return the requested address. In
605 // particular, this is already how Windows behaves, so
606 // it would simplify things there.
610 h.arenaHints = hint.next
611 h.arenaHintAlloc.free(unsafe.Pointer(hint))
616 // The race detector assumes the heap lives in
617 // [0x00c000000000, 0x00e000000000), but we
618 // just ran out of hints in this region. Give
620 throw("too many address space collisions for -race mode")
623 // All of the hints failed, so we'll take any
624 // (sufficiently aligned) address the kernel will give
626 v, size = sysReserveAligned(nil, n, heapArenaBytes)
631 // Create new hints for extending this region.
632 hint := (*arenaHint)(h.arenaHintAlloc.alloc())
633 hint.addr, hint.down = uintptr(v), true
634 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
635 hint = (*arenaHint)(h.arenaHintAlloc.alloc())
636 hint.addr = uintptr(v) + size
637 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
640 // Check for bad pointers or pointers we can't use.
645 bad = "region exceeds uintptr range"
646 } else if arenaIndex(p) >= 1<<arenaBits {
647 bad = "base outside usable address space"
648 } else if arenaIndex(p+size-1) >= 1<<arenaBits {
649 bad = "end outside usable address space"
652 // This should be impossible on most architectures,
653 // but it would be really confusing to debug.
654 print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
655 throw("memory reservation exceeds address space limit")
659 if uintptr(v)&(heapArenaBytes-1) != 0 {
660 throw("misrounded allocation in sysAlloc")
664 // Create arena metadata.
665 for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
666 l2 := h.arenas[ri.l1()]
668 // Allocate an L2 arena map.
670 // Use sysAllocOS instead of sysAlloc or persistentalloc because there's no
671 // statistic we can comfortably account for this space in. With this structure,
672 // we rely on demand paging to avoid large overheads, but tracking which memory
673 // is paged in is too expensive. Trying to account for the whole region means
674 // that it will appear like an enormous memory overhead in statistics, even though
676 l2 = (*[1 << arenaL2Bits]*heapArena)(sysAllocOS(unsafe.Sizeof(*l2)))
678 throw("out of memory allocating heap arena map")
680 atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
683 if l2[ri.l2()] != nil {
684 throw("arena already initialized")
687 r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
689 r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
691 throw("out of memory allocating heap arena metadata")
695 // Add the arena to the arenas list.
696 if len(h.allArenas) == cap(h.allArenas) {
697 size := 2 * uintptr(cap(h.allArenas)) * goarch.PtrSize
701 newArray := (*notInHeap)(persistentalloc(size, goarch.PtrSize, &memstats.gcMiscSys))
703 throw("out of memory allocating allArenas")
705 oldSlice := h.allArenas
706 *(*notInHeapSlice)(unsafe.Pointer(&h.allArenas)) = notInHeapSlice{newArray, len(h.allArenas), int(size / goarch.PtrSize)}
707 copy(h.allArenas, oldSlice)
708 // Do not free the old backing array because
709 // there may be concurrent readers. Since we
710 // double the array each time, this can lead
711 // to at most 2x waste.
713 h.allArenas = h.allArenas[:len(h.allArenas)+1]
714 h.allArenas[len(h.allArenas)-1] = ri
716 // Store atomically just in case an object from the
717 // new heap arena becomes visible before the heap lock
718 // is released (which shouldn't happen, but there's
719 // little downside to this).
720 atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
723 // Tell the race detector about the new heap memory.
725 racemapshadow(v, size)
731 // sysReserveAligned is like sysReserve, but the returned pointer is
732 // aligned to align bytes. It may reserve either n or n+align bytes,
733 // so it returns the size that was reserved.
734 func sysReserveAligned(v unsafe.Pointer, size, align uintptr) (unsafe.Pointer, uintptr) {
735 // Since the alignment is rather large in uses of this
736 // function, we're not likely to get it by chance, so we ask
737 // for a larger region and remove the parts we don't need.
740 p := uintptr(sysReserve(v, size+align))
744 case p&(align-1) == 0:
745 // We got lucky and got an aligned region, so we can
746 // use the whole thing.
747 return unsafe.Pointer(p), size + align
748 case GOOS == "windows":
749 // On Windows we can't release pieces of a
750 // reservation, so we release the whole thing and
751 // re-reserve the aligned sub-region. This may race,
752 // so we may have to try again.
753 sysFreeOS(unsafe.Pointer(p), size+align)
754 p = alignUp(p, align)
755 p2 := sysReserve(unsafe.Pointer(p), size)
756 if p != uintptr(p2) {
757 // Must have raced. Try again.
759 if retries++; retries == 100 {
760 throw("failed to allocate aligned heap memory; too many retries")
767 // Trim off the unaligned parts.
768 pAligned := alignUp(p, align)
769 sysFreeOS(unsafe.Pointer(p), pAligned-p)
770 end := pAligned + size
771 endLen := (p + size + align) - end
773 sysFreeOS(unsafe.Pointer(end), endLen)
775 return unsafe.Pointer(pAligned), size
779 // base address for all 0-byte allocations
782 // nextFreeFast returns the next free object if one is quickly available.
783 // Otherwise it returns 0.
784 func nextFreeFast(s *mspan) gclinkptr {
785 theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
787 result := s.freeindex + uintptr(theBit)
788 if result < s.nelems {
789 freeidx := result + 1
790 if freeidx%64 == 0 && freeidx != s.nelems {
793 s.allocCache >>= uint(theBit + 1)
794 s.freeindex = freeidx
796 return gclinkptr(result*s.elemsize + s.base())
802 // nextFree returns the next free object from the cached span if one is available.
803 // Otherwise it refills the cache with a span with an available object and
804 // returns that object along with a flag indicating that this was a heavy
805 // weight allocation. If it is a heavy weight allocation the caller must
806 // determine whether a new GC cycle needs to be started or if the GC is active
807 // whether this goroutine needs to assist the GC.
809 // Must run in a non-preemptible context since otherwise the owner of
811 func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
814 freeIndex := s.nextFreeIndex()
815 if freeIndex == s.nelems {
817 if uintptr(s.allocCount) != s.nelems {
818 println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
819 throw("s.allocCount != s.nelems && freeIndex == s.nelems")
825 freeIndex = s.nextFreeIndex()
828 if freeIndex >= s.nelems {
829 throw("freeIndex is not valid")
832 v = gclinkptr(freeIndex*s.elemsize + s.base())
834 if uintptr(s.allocCount) > s.nelems {
835 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
836 throw("s.allocCount > s.nelems")
841 // Allocate an object of size bytes.
842 // Small objects are allocated from the per-P cache's free lists.
843 // Large objects (> 32 kB) are allocated straight from the heap.
844 func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
845 if gcphase == _GCmarktermination {
846 throw("mallocgc called with gcphase == _GCmarktermination")
850 return unsafe.Pointer(&zerobase)
853 // It's possible for any malloc to trigger sweeping, which may in
854 // turn queue finalizers. Record this dynamic lock edge.
855 lockRankMayQueueFinalizer()
859 // Refer to ASAN runtime library, the malloc() function allocates extra memory,
860 // the redzone, around the user requested memory region. And the redzones are marked
861 // as unaddressable. We perform the same operations in Go to detect the overflows or
863 size += computeRZlog(size)
870 // TODO(austin): This should be just
871 // align = uintptr(typ.align)
872 // but that's only 4 on 32-bit platforms,
873 // even if there's a uint64 field in typ (see #599).
874 // This causes 64-bit atomic accesses to panic.
875 // Hence, we use stricter alignment that matches
876 // the normal allocator better.
879 } else if size&3 == 0 {
881 } else if size&1 == 0 {
887 return persistentalloc(size, align, &memstats.other_sys)
890 if inittrace.active && inittrace.id == getg().goid {
891 // Init functions are executed sequentially in a single goroutine.
892 inittrace.allocs += 1
896 // assistG is the G to charge for this allocation, or nil if
897 // GC is not currently active.
899 if gcBlackenEnabled != 0 {
900 // Charge the current user G for this allocation.
902 if assistG.m.curg != nil {
903 assistG = assistG.m.curg
905 // Charge the allocation against the G. We'll account
906 // for internal fragmentation at the end of mallocgc.
907 assistG.gcAssistBytes -= int64(size)
909 if assistG.gcAssistBytes < 0 {
910 // This G is in debt. Assist the GC to correct
911 // this before allocating. This must happen
912 // before disabling preemption.
913 gcAssistAlloc(assistG)
917 // Set mp.mallocing to keep from being preempted by GC.
919 if mp.mallocing != 0 {
920 throw("malloc deadlock")
922 if mp.gsignal == getg() {
923 throw("malloc during signal")
927 shouldhelpgc := false
931 throw("mallocgc called without a P or outside bootstrapping")
935 noscan := typ == nil || typ.ptrdata == 0
936 // In some cases block zeroing can profitably (for latency reduction purposes)
937 // be delayed till preemption is possible; delayedZeroing tracks that state.
938 delayedZeroing := false
939 if size <= maxSmallSize {
940 if noscan && size < maxTinySize {
943 // Tiny allocator combines several tiny allocation requests
944 // into a single memory block. The resulting memory block
945 // is freed when all subobjects are unreachable. The subobjects
946 // must be noscan (don't have pointers), this ensures that
947 // the amount of potentially wasted memory is bounded.
949 // Size of the memory block used for combining (maxTinySize) is tunable.
950 // Current setting is 16 bytes, which relates to 2x worst case memory
951 // wastage (when all but one subobjects are unreachable).
952 // 8 bytes would result in no wastage at all, but provides less
953 // opportunities for combining.
954 // 32 bytes provides more opportunities for combining,
955 // but can lead to 4x worst case wastage.
956 // The best case winning is 8x regardless of block size.
958 // Objects obtained from tiny allocator must not be freed explicitly.
959 // So when an object will be freed explicitly, we ensure that
960 // its size >= maxTinySize.
962 // SetFinalizer has a special case for objects potentially coming
963 // from tiny allocator, it such case it allows to set finalizers
964 // for an inner byte of a memory block.
966 // The main targets of tiny allocator are small strings and
967 // standalone escaping variables. On a json benchmark
968 // the allocator reduces number of allocations by ~12% and
969 // reduces heap size by ~20%.
971 // Align tiny pointer for required (conservative) alignment.
973 off = alignUp(off, 8)
974 } else if goarch.PtrSize == 4 && size == 12 {
975 // Conservatively align 12-byte objects to 8 bytes on 32-bit
976 // systems so that objects whose first field is a 64-bit
977 // value is aligned to 8 bytes and does not cause a fault on
978 // atomic access. See issue 37262.
979 // TODO(mknyszek): Remove this workaround if/when issue 36606
981 off = alignUp(off, 8)
982 } else if size&3 == 0 {
983 off = alignUp(off, 4)
984 } else if size&1 == 0 {
985 off = alignUp(off, 2)
987 if off+size <= maxTinySize && c.tiny != 0 {
988 // The object fits into existing tiny block.
989 x = unsafe.Pointer(c.tiny + off)
990 c.tinyoffset = off + size
996 // Allocate a new maxTinySize block.
997 span = c.alloc[tinySpanClass]
998 v := nextFreeFast(span)
1000 v, span, shouldhelpgc = c.nextFree(tinySpanClass)
1002 x = unsafe.Pointer(v)
1003 (*[2]uint64)(x)[0] = 0
1004 (*[2]uint64)(x)[1] = 0
1005 // See if we need to replace the existing tiny block with the new one
1006 // based on amount of remaining free space.
1007 if !raceenabled && (size < c.tinyoffset || c.tiny == 0) {
1008 // Note: disabled when race detector is on, see comment near end of this function.
1015 if size <= smallSizeMax-8 {
1016 sizeclass = size_to_class8[divRoundUp(size, smallSizeDiv)]
1018 sizeclass = size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)]
1020 size = uintptr(class_to_size[sizeclass])
1021 spc := makeSpanClass(sizeclass, noscan)
1023 v := nextFreeFast(span)
1025 v, span, shouldhelpgc = c.nextFree(spc)
1027 x = unsafe.Pointer(v)
1028 if needzero && span.needzero != 0 {
1029 memclrNoHeapPointers(unsafe.Pointer(v), size)
1034 // For large allocations, keep track of zeroed state so that
1035 // bulk zeroing can be happen later in a preemptible context.
1036 span = c.allocLarge(size, noscan)
1039 size = span.elemsize
1040 x = unsafe.Pointer(span.base())
1041 if needzero && span.needzero != 0 {
1043 delayedZeroing = true
1045 memclrNoHeapPointers(x, size)
1046 // We've in theory cleared almost the whole span here,
1047 // and could take the extra step of actually clearing
1048 // the whole thing. However, don't. Any GC bits for the
1049 // uncleared parts will be zero, and it's just going to
1050 // be needzero = 1 once freed anyway.
1055 var scanSize uintptr
1057 heapBitsSetType(uintptr(x), size, dataSize, typ)
1058 if dataSize > typ.size {
1059 // Array allocation. If there are any
1060 // pointers, GC has to scan to the last
1062 if typ.ptrdata != 0 {
1063 scanSize = dataSize - typ.size + typ.ptrdata
1066 scanSize = typ.ptrdata
1068 c.scanAlloc += scanSize
1071 // Ensure that the stores above that initialize x to
1072 // type-safe memory and set the heap bits occur before
1073 // the caller can make x observable to the garbage
1074 // collector. Otherwise, on weakly ordered machines,
1075 // the garbage collector could follow a pointer to x,
1076 // but see uninitialized memory or stale heap bits.
1077 publicationBarrier()
1079 // Allocate black during GC.
1080 // All slots hold nil so no scanning is needed.
1081 // This may be racing with GC so do it atomically if there can be
1082 // a race marking the bit.
1083 if gcphase != _GCoff {
1084 gcmarknewobject(span, uintptr(x), size, scanSize)
1096 // We should only read/write the memory with the size asked by the user.
1097 // The rest of the allocated memory should be poisoned, so that we can report
1098 // errors when accessing poisoned memory.
1099 // The allocated memory is larger than required userSize, it will also include
1100 // redzone and some other padding bytes.
1101 rzBeg := unsafe.Add(x, userSize)
1102 asanpoison(rzBeg, size-userSize)
1103 asanunpoison(x, userSize)
1106 if rate := MemProfileRate; rate > 0 {
1107 // Note cache c only valid while m acquired; see #47302
1108 if rate != 1 && size < c.nextSample {
1109 c.nextSample -= size
1111 profilealloc(mp, x, size)
1117 // Pointerfree data can be zeroed late in a context where preemption can occur.
1118 // x will keep the memory alive.
1121 throw("delayed zeroing on data that may contain pointers")
1123 memclrNoHeapPointersChunked(size, x) // This is a possible preemption point: see #47302
1127 if debug.allocfreetrace != 0 {
1128 tracealloc(x, size, typ)
1131 if inittrace.active && inittrace.id == getg().goid {
1132 // Init functions are executed sequentially in a single goroutine.
1133 inittrace.bytes += uint64(size)
1138 // Account for internal fragmentation in the assist
1139 // debt now that we know it.
1140 assistG.gcAssistBytes -= int64(size - dataSize)
1144 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
1149 if raceenabled && noscan && dataSize < maxTinySize {
1150 // Pad tinysize allocations so they are aligned with the end
1151 // of the tinyalloc region. This ensures that any arithmetic
1152 // that goes off the top end of the object will be detectable
1153 // by checkptr (issue 38872).
1154 // Note that we disable tinyalloc when raceenabled for this to work.
1155 // TODO: This padding is only performed when the race detector
1156 // is enabled. It would be nice to enable it if any package
1157 // was compiled with checkptr, but there's no easy way to
1158 // detect that (especially at compile time).
1159 // TODO: enable this padding for all allocations, not just
1160 // tinyalloc ones. It's tricky because of pointer maps.
1161 // Maybe just all noscan objects?
1162 x = add(x, size-dataSize)
1168 // memclrNoHeapPointersChunked repeatedly calls memclrNoHeapPointers
1169 // on chunks of the buffer to be zeroed, with opportunities for preemption
1170 // along the way. memclrNoHeapPointers contains no safepoints and also
1171 // cannot be preemptively scheduled, so this provides a still-efficient
1172 // block copy that can also be preempted on a reasonable granularity.
1174 // Use this with care; if the data being cleared is tagged to contain
1175 // pointers, this allows the GC to run before it is all cleared.
1176 func memclrNoHeapPointersChunked(size uintptr, x unsafe.Pointer) {
1178 // got this from benchmarking. 128k is too small, 512k is too large.
1179 const chunkBytes = 256 * 1024
1181 for voff := v; voff < vsize; voff = voff + chunkBytes {
1183 // may hold locks, e.g., profiling
1186 // clear min(avail, lump) bytes
1191 memclrNoHeapPointers(unsafe.Pointer(voff), n)
1195 // implementation of new builtin
1196 // compiler (both frontend and SSA backend) knows the signature
1198 func newobject(typ *_type) unsafe.Pointer {
1199 return mallocgc(typ.size, typ, true)
1202 //go:linkname reflect_unsafe_New reflect.unsafe_New
1203 func reflect_unsafe_New(typ *_type) unsafe.Pointer {
1204 return mallocgc(typ.size, typ, true)
1207 //go:linkname reflectlite_unsafe_New internal/reflectlite.unsafe_New
1208 func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
1209 return mallocgc(typ.size, typ, true)
1212 // newarray allocates an array of n elements of type typ.
1213 func newarray(typ *_type, n int) unsafe.Pointer {
1215 return mallocgc(typ.size, typ, true)
1217 mem, overflow := math.MulUintptr(typ.size, uintptr(n))
1218 if overflow || mem > maxAlloc || n < 0 {
1219 panic(plainError("runtime: allocation size out of range"))
1221 return mallocgc(mem, typ, true)
1224 //go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray
1225 func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
1226 return newarray(typ, n)
1229 func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
1232 throw("profilealloc called without a P or outside bootstrapping")
1234 c.nextSample = nextSample()
1235 mProf_Malloc(x, size)
1238 // nextSample returns the next sampling point for heap profiling. The goal is
1239 // to sample allocations on average every MemProfileRate bytes, but with a
1240 // completely random distribution over the allocation timeline; this
1241 // corresponds to a Poisson process with parameter MemProfileRate. In Poisson
1242 // processes, the distance between two samples follows the exponential
1243 // distribution (exp(MemProfileRate)), so the best return value is a random
1244 // number taken from an exponential distribution whose mean is MemProfileRate.
1245 func nextSample() uintptr {
1246 if MemProfileRate == 1 {
1247 // Callers assign our return value to
1248 // mcache.next_sample, but next_sample is not used
1249 // when the rate is 1. So avoid the math below and
1250 // just return something.
1253 if GOOS == "plan9" {
1254 // Plan 9 doesn't support floating point in note handler.
1255 if gp := getg(); gp == gp.m.gsignal {
1256 return nextSampleNoFP()
1260 return uintptr(fastexprand(MemProfileRate))
1263 // fastexprand returns a random number from an exponential distribution with
1264 // the specified mean.
1265 func fastexprand(mean int) int32 {
1266 // Avoid overflow. Maximum possible step is
1267 // -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
1269 case mean > 0x7000000:
1275 // Take a random sample of the exponential distribution exp(-mean*x).
1276 // The probability distribution function is mean*exp(-mean*x), so the CDF is
1277 // p = 1 - exp(-mean*x), so
1278 // q = 1 - p == exp(-mean*x)
1279 // log_e(q) = -mean*x
1280 // -log_e(q)/mean = x
1281 // x = -log_e(q) * mean
1282 // x = log_2(q) * (-log_e(2)) * mean ; Using log_2 for efficiency
1283 const randomBitCount = 26
1284 q := fastrandn(1<<randomBitCount) + 1
1285 qlog := fastlog2(float64(q)) - randomBitCount
1289 const minusLog2 = -0.6931471805599453 // -ln(2)
1290 return int32(qlog*(minusLog2*float64(mean))) + 1
1293 // nextSampleNoFP is similar to nextSample, but uses older,
1294 // simpler code to avoid floating point.
1295 func nextSampleNoFP() uintptr {
1296 // Set first allocation sample size.
1297 rate := MemProfileRate
1298 if rate > 0x3fffffff { // make 2*rate not overflow
1302 return uintptr(fastrandn(uint32(2 * rate)))
1307 type persistentAlloc struct {
1312 var globalAlloc struct {
1317 // persistentChunkSize is the number of bytes we allocate when we grow
1318 // a persistentAlloc.
1319 const persistentChunkSize = 256 << 10
1321 // persistentChunks is a list of all the persistent chunks we have
1322 // allocated. The list is maintained through the first word in the
1323 // persistent chunk. This is updated atomically.
1324 var persistentChunks *notInHeap
1326 // Wrapper around sysAlloc that can allocate small chunks.
1327 // There is no associated free operation.
1328 // Intended for things like function/type/debug-related persistent data.
1329 // If align is 0, uses default align (currently 8).
1330 // The returned memory will be zeroed.
1331 // sysStat must be non-nil.
1333 // Consider marking persistentalloc'd types not in heap by embedding
1334 // runtime/internal/sys.NotInHeap.
1335 func persistentalloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1337 systemstack(func() {
1338 p = persistentalloc1(size, align, sysStat)
1340 return unsafe.Pointer(p)
1343 // Must run on system stack because stack growth can (re)invoke it.
1347 func persistentalloc1(size, align uintptr, sysStat *sysMemStat) *notInHeap {
1349 maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
1353 throw("persistentalloc: size == 0")
1356 if align&(align-1) != 0 {
1357 throw("persistentalloc: align is not a power of 2")
1359 if align > _PageSize {
1360 throw("persistentalloc: align is too large")
1366 if size >= maxBlock {
1367 return (*notInHeap)(sysAlloc(size, sysStat))
1371 var persistent *persistentAlloc
1372 if mp != nil && mp.p != 0 {
1373 persistent = &mp.p.ptr().palloc
1375 lock(&globalAlloc.mutex)
1376 persistent = &globalAlloc.persistentAlloc
1378 persistent.off = alignUp(persistent.off, align)
1379 if persistent.off+size > persistentChunkSize || persistent.base == nil {
1380 persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys))
1381 if persistent.base == nil {
1382 if persistent == &globalAlloc.persistentAlloc {
1383 unlock(&globalAlloc.mutex)
1385 throw("runtime: cannot allocate memory")
1388 // Add the new chunk to the persistentChunks list.
1390 chunks := uintptr(unsafe.Pointer(persistentChunks))
1391 *(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
1392 if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
1396 persistent.off = alignUp(goarch.PtrSize, align)
1398 p := persistent.base.add(persistent.off)
1399 persistent.off += size
1401 if persistent == &globalAlloc.persistentAlloc {
1402 unlock(&globalAlloc.mutex)
1405 if sysStat != &memstats.other_sys {
1406 sysStat.add(int64(size))
1407 memstats.other_sys.add(-int64(size))
1412 // inPersistentAlloc reports whether p points to memory allocated by
1413 // persistentalloc. This must be nosplit because it is called by the
1414 // cgo checker code, which is called by the write barrier code.
1417 func inPersistentAlloc(p uintptr) bool {
1418 chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
1420 if p >= chunk && p < chunk+persistentChunkSize {
1423 chunk = *(*uintptr)(unsafe.Pointer(chunk))
1428 // linearAlloc is a simple linear allocator that pre-reserves a region
1429 // of memory and then optionally maps that region into the Ready state
1432 // The caller is responsible for locking.
1433 type linearAlloc struct {
1434 next uintptr // next free byte
1435 mapped uintptr // one byte past end of mapped space
1436 end uintptr // end of reserved space
1438 mapMemory bool // transition memory from Reserved to Ready if true
1441 func (l *linearAlloc) init(base, size uintptr, mapMemory bool) {
1442 if base+size < base {
1443 // Chop off the last byte. The runtime isn't prepared
1444 // to deal with situations where the bounds could overflow.
1445 // Leave that memory reserved, though, so we don't map it
1449 l.next, l.mapped = base, base
1451 l.mapMemory = mapMemory
1454 func (l *linearAlloc) alloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1455 p := alignUp(l.next, align)
1460 if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
1462 // Transition from Reserved to Prepared to Ready.
1463 n := pEnd - l.mapped
1464 sysMap(unsafe.Pointer(l.mapped), n, sysStat)
1465 sysUsed(unsafe.Pointer(l.mapped), n, n)
1469 return unsafe.Pointer(p)
1472 // notInHeap is off-heap memory allocated by a lower-level allocator
1473 // like sysAlloc or persistentAlloc.
1475 // In general, it's better to use real types which embed
1476 // runtime/internal/sys.NotInHeap, but this serves as a generic type
1477 // for situations where that isn't possible (like in the allocators).
1479 // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
1480 type notInHeap struct{ _ sys.NotInHeap }
1482 func (p *notInHeap) add(bytes uintptr) *notInHeap {
1483 return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))
1486 // computeRZlog computes the size of the redzone.
1487 // Refer to the implementation of the compiler-rt.
1488 func computeRZlog(userSize uintptr) uintptr {
1490 case userSize <= (64 - 16):
1492 case userSize <= (128 - 32):
1494 case userSize <= (512 - 64):
1496 case userSize <= (4096 - 128):
1498 case userSize <= (1<<14)-256:
1500 case userSize <= (1<<15)-512:
1502 case userSize <= (1<<16)-1024: