]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/malloc.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / runtime / malloc.go
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.
4
5 // Memory allocator.
6 //
7 // This was originally based on tcmalloc, but has diverged quite a bit.
8 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html
9
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.
16 //
17 // The allocator's data structures are:
18 //
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.
26 //
27 // Allocating a small object proceeds up a hierarchy of caches:
28 //
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.
34 //
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
39 //         the mcentral.
40 //
41 //      3. If the mcentral's mspan list is empty, obtain a run
42 //         of pages from the mheap to use for the mspan.
43 //
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.
48 //
49 // Sweeping an mspan and freeing objects on it proceeds up a similar
50 // hierarchy:
51 //
52 //      1. If the mspan is being swept in response to allocation, it
53 //         is returned to the mcache to satisfy the allocation.
54 //
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
57 //         class.
58 //
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.
61 //
62 // Allocating and freeing a large object uses the mheap
63 // directly, bypassing the mcache and mcentral.
64 //
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
68 // this way:
69 //
70 //      1. Stack frame allocation can avoid zeroing altogether.
71 //
72 //      2. It exhibits better temporal locality, since the program is
73 //         probably about to write to the memory.
74 //
75 //      3. We don't zero pages that never get reused.
76
77 // Virtual memory layout
78 //
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.
82 //
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.
87 //
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.
95 //
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.
100
101 package runtime
102
103 import (
104         "internal/goarch"
105         "internal/goos"
106         "runtime/internal/atomic"
107         "runtime/internal/math"
108         "runtime/internal/sys"
109         "unsafe"
110 )
111
112 const (
113         debugMalloc = false
114
115         maxTinySize   = _TinySize
116         tinySizeClass = _TinySizeClass
117         maxSmallSize  = _MaxSmallSize
118
119         pageShift = _PageShift
120         pageSize  = _PageSize
121         pageMask  = _PageMask
122         // By construction, single page spans of the smallest object class
123         // have the most objects per span.
124         maxObjsPerSpan = pageSize / 8
125
126         concurrentSweep = _ConcurrentSweep
127
128         _PageSize = 1 << _PageShift
129         _PageMask = _PageSize - 1
130
131         // _64bit = 1 on 64-bit systems, 0 on 32-bit systems
132         _64bit = 1 << (^uintptr(0) >> 63) / 2
133
134         // Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
135         _TinySize      = 16
136         _TinySizeClass = int8(2)
137
138         _FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
139
140         // Per-P, per order stack segment cache size.
141         _StackCacheSize = 32 * 1024
142
143         // Number of orders that get caching. Order 0 is FixedStack
144         // and each successive order is twice as large.
145         // We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
146         // will be allocated directly.
147         // Since FixedStack is different on different systems, we
148         // must vary NumStackOrders to keep the same maximum cached size.
149         //   OS               | FixedStack | NumStackOrders
150         //   -----------------+------------+---------------
151         //   linux/darwin/bsd | 2KB        | 4
152         //   windows/32       | 4KB        | 3
153         //   windows/64       | 8KB        | 2
154         //   plan9            | 4KB        | 3
155         _NumStackOrders = 4 - goarch.PtrSize/4*goos.IsWindows - 1*goos.IsPlan9
156
157         // heapAddrBits is the number of bits in a heap address. On
158         // amd64, addresses are sign-extended beyond heapAddrBits. On
159         // other arches, they are zero-extended.
160         //
161         // On most 64-bit platforms, we limit this to 48 bits based on a
162         // combination of hardware and OS limitations.
163         //
164         // amd64 hardware limits addresses to 48 bits, sign-extended
165         // to 64 bits. Addresses where the top 16 bits are not either
166         // all 0 or all 1 are "non-canonical" and invalid. Because of
167         // these "negative" addresses, we offset addresses by 1<<47
168         // (arenaBaseOffset) on amd64 before computing indexes into
169         // the heap arenas index. In 2017, amd64 hardware added
170         // support for 57 bit addresses; however, currently only Linux
171         // supports this extension and the kernel will never choose an
172         // address above 1<<47 unless mmap is called with a hint
173         // address above 1<<47 (which we never do).
174         //
175         // arm64 hardware (as of ARMv8) limits user addresses to 48
176         // bits, in the range [0, 1<<48).
177         //
178         // ppc64, mips64, and s390x support arbitrary 64 bit addresses
179         // in hardware. On Linux, Go leans on stricter OS limits. Based
180         // on Linux's processor.h, the user address space is limited as
181         // follows on 64-bit architectures:
182         //
183         // Architecture  Name              Maximum Value (exclusive)
184         // ---------------------------------------------------------------------
185         // amd64         TASK_SIZE_MAX     0x007ffffffff000 (47 bit addresses)
186         // arm64         TASK_SIZE_64      0x01000000000000 (48 bit addresses)
187         // ppc64{,le}    TASK_SIZE_USER64  0x00400000000000 (46 bit addresses)
188         // mips64{,le}   TASK_SIZE64       0x00010000000000 (40 bit addresses)
189         // s390x         TASK_SIZE         1<<64 (64 bit addresses)
190         //
191         // These limits may increase over time, but are currently at
192         // most 48 bits except on s390x. On all architectures, Linux
193         // starts placing mmap'd regions at addresses that are
194         // significantly below 48 bits, so even if it's possible to
195         // exceed Go's 48 bit limit, it's extremely unlikely in
196         // practice.
197         //
198         // On 32-bit platforms, we accept the full 32-bit address
199         // space because doing so is cheap.
200         // mips32 only has access to the low 2GB of virtual memory, so
201         // we further limit it to 31 bits.
202         //
203         // On ios/arm64, although 64-bit pointers are presumably
204         // available, pointers are truncated to 33 bits in iOS <14.
205         // Furthermore, only the top 4 GiB of the address space are
206         // actually available to the application. In iOS >=14, more
207         // of the address space is available, and the OS can now
208         // provide addresses outside of those 33 bits. Pick 40 bits
209         // as a reasonable balance between address space usage by the
210         // page allocator, and flexibility for what mmap'd regions
211         // we'll accept for the heap. We can't just move to the full
212         // 48 bits because this uses too much address space for older
213         // iOS versions.
214         // TODO(mknyszek): Once iOS <14 is deprecated, promote ios/arm64
215         // to a 48-bit address space like every other arm64 platform.
216         //
217         // WebAssembly currently has a limit of 4GB linear memory.
218         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
219
220         // maxAlloc is the maximum size of an allocation. On 64-bit,
221         // it's theoretically possible to allocate 1<<heapAddrBits bytes. On
222         // 32-bit, however, this is one less than 1<<32 because the
223         // number of bytes in the address space doesn't actually fit
224         // in a uintptr.
225         maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1
226
227         // The number of bits in a heap address, the size of heap
228         // arenas, and the L1 and L2 arena map sizes are related by
229         //
230         //   (1 << addr bits) = arena size * L1 entries * L2 entries
231         //
232         // Currently, we balance these as follows:
233         //
234         //       Platform  Addr bits  Arena size  L1 entries   L2 entries
235         // --------------  ---------  ----------  ----------  -----------
236         //       */64-bit         48        64MB           1    4M (32MB)
237         // windows/64-bit         48         4MB          64    1M  (8MB)
238         //      ios/arm64         33         4MB           1  2048  (8KB)
239         //       */32-bit         32         4MB           1  1024  (4KB)
240         //     */mips(le)         31         4MB           1   512  (2KB)
241
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.
245         //
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
253         // memory.
254         heapArenaBytes = 1 << logHeapArenaBytes
255
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-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
260
261         // heapArenaBitmapBytes is the size of each heap arena's bitmap.
262         heapArenaBitmapBytes = heapArenaBytes / (goarch.PtrSize * 8 / 2)
263
264         pagesPerArena = heapArenaBytes / pageSize
265
266         // arenaL1Bits is the number of bits of the arena number
267         // covered by the first level arena map.
268         //
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.
275         //
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 * goos.IsWindows)
280
281         // arenaL2Bits is the number of bits of the arena number
282         // covered by the second level arena index.
283         //
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
289
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
293
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
296         // the L2 arena map.
297         arenaBits = arenaL1Bits + arenaL2Bits
298
299         // arenaBaseOffset is the pointer value that corresponds to
300         // index 0 in the heap arena map.
301         //
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).
305         //
306         // On aix/ppc64, this offset allows to keep the heapAddrBits to
307         // 48. Otherwise, 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.
311         //
312         // On other platforms, the user address space is contiguous
313         // and starts at 0, so no offset is necessary.
314         arenaBaseOffset = 0xffff800000000000*goarch.IsAmd64 + 0x0a00000000000000*goos.IsAix
315         // A typed version of this constant that will make it into DWARF (for viewcore).
316         arenaBaseOffsetUintptr = uintptr(arenaBaseOffset)
317
318         // Max number of threads to run garbage collection.
319         // 2, 3, and 4 are all plausible maximums depending
320         // on the hardware details of the machine. The garbage
321         // collector scales well to 32 cpus.
322         _MaxGcproc = 32
323
324         // minLegalPointer is the smallest possible legal pointer.
325         // This is the smallest possible architectural page size,
326         // since we assume that the first page is never mapped.
327         //
328         // This should agree with minZeroPage in the compiler.
329         minLegalPointer uintptr = 4096
330 )
331
332 // physPageSize is the size in bytes of the OS's physical pages.
333 // Mapping and unmapping operations must be done at multiples of
334 // physPageSize.
335 //
336 // This must be set by the OS init code (typically in osinit) before
337 // mallocinit.
338 var physPageSize uintptr
339
340 // physHugePageSize is the size in bytes of the OS's default physical huge
341 // page size whose allocation is opaque to the application. It is assumed
342 // and verified to be a power of two.
343 //
344 // If set, this must be set by the OS init code (typically in osinit) before
345 // mallocinit. However, setting it at all is optional, and leaving the default
346 // value is always safe (though potentially less efficient).
347 //
348 // Since physHugePageSize is always assumed to be a power of two,
349 // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
350 // The purpose of physHugePageShift is to avoid doing divisions in
351 // performance critical functions.
352 var (
353         physHugePageSize  uintptr
354         physHugePageShift uint
355 )
356
357 func mallocinit() {
358         if class_to_size[_TinySizeClass] != _TinySize {
359                 throw("bad TinySizeClass")
360         }
361
362         if heapArenaBitmapBytes&(heapArenaBitmapBytes-1) != 0 {
363                 // heapBits expects modular arithmetic on bitmap
364                 // addresses to work.
365                 throw("heapArenaBitmapBytes not a power of 2")
366         }
367
368         // Check physPageSize.
369         if physPageSize == 0 {
370                 // The OS init code failed to fetch the physical page size.
371                 throw("failed to get system page size")
372         }
373         if physPageSize > maxPhysPageSize {
374                 print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n")
375                 throw("bad system page size")
376         }
377         if physPageSize < minPhysPageSize {
378                 print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
379                 throw("bad system page size")
380         }
381         if physPageSize&(physPageSize-1) != 0 {
382                 print("system page size (", physPageSize, ") must be a power of 2\n")
383                 throw("bad system page size")
384         }
385         if physHugePageSize&(physHugePageSize-1) != 0 {
386                 print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
387                 throw("bad system huge page size")
388         }
389         if physHugePageSize > maxPhysHugePageSize {
390                 // physHugePageSize is greater than the maximum supported huge page size.
391                 // Don't throw here, like in the other cases, since a system configured
392                 // in this way isn't wrong, we just don't have the code to support them.
393                 // Instead, silently set the huge page size to zero.
394                 physHugePageSize = 0
395         }
396         if physHugePageSize != 0 {
397                 // Since physHugePageSize is a power of 2, it suffices to increase
398                 // physHugePageShift until 1<<physHugePageShift == physHugePageSize.
399                 for 1<<physHugePageShift != physHugePageSize {
400                         physHugePageShift++
401                 }
402         }
403         if pagesPerArena%pagesPerSpanRoot != 0 {
404                 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerSpanRoot (", pagesPerSpanRoot, ")\n")
405                 throw("bad pagesPerSpanRoot")
406         }
407         if pagesPerArena%pagesPerReclaimerChunk != 0 {
408                 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerReclaimerChunk (", pagesPerReclaimerChunk, ")\n")
409                 throw("bad pagesPerReclaimerChunk")
410         }
411
412         // Initialize the heap.
413         mheap_.init()
414         mcache0 = allocmcache()
415         lockInit(&gcBitsArenas.lock, lockRankGcBitsArenas)
416         lockInit(&proflock, lockRankProf)
417         lockInit(&globalAlloc.mutex, lockRankGlobalAlloc)
418
419         // Create initial arena growth hints.
420         if goarch.PtrSize == 8 {
421                 // On a 64-bit machine, we pick the following hints
422                 // because:
423                 //
424                 // 1. Starting from the middle of the address space
425                 // makes it easier to grow out a contiguous range
426                 // without running in to some other mapping.
427                 //
428                 // 2. This makes Go heap addresses more easily
429                 // recognizable when debugging.
430                 //
431                 // 3. Stack scanning in gccgo is still conservative,
432                 // so it's important that addresses be distinguishable
433                 // from other data.
434                 //
435                 // Starting at 0x00c0 means that the valid memory addresses
436                 // will begin 0x00c0, 0x00c1, ...
437                 // In little-endian, that's c0 00, c1 00, ... None of those are valid
438                 // UTF-8 sequences, and they are otherwise as far away from
439                 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
440                 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
441                 // on OS X during thread allocations.  0x00c0 causes conflicts with
442                 // AddressSanitizer which reserves all memory up to 0x0100.
443                 // These choices reduce the odds of a conservative garbage collector
444                 // not collecting memory because some non-pointer block of memory
445                 // had a bit pattern that matched a memory address.
446                 //
447                 // However, on arm64, we ignore all this advice above and slam the
448                 // allocation at 0x40 << 32 because when using 4k pages with 3-level
449                 // translation buffers, the user address space is limited to 39 bits
450                 // On ios/arm64, the address space is even smaller.
451                 //
452                 // On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
453                 // processes.
454                 for i := 0x7f; i >= 0; i-- {
455                         var p uintptr
456                         switch {
457                         case raceenabled:
458                                 // The TSAN runtime requires the heap
459                                 // to be in the range [0x00c000000000,
460                                 // 0x00e000000000).
461                                 p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
462                                 if p >= uintptrMask&0x00e000000000 {
463                                         continue
464                                 }
465                         case GOARCH == "arm64" && GOOS == "ios":
466                                 p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
467                         case GOARCH == "arm64":
468                                 p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
469                         case GOOS == "aix":
470                                 if i == 0 {
471                                         // We don't use addresses directly after 0x0A00000000000000
472                                         // to avoid collisions with others mmaps done by non-go programs.
473                                         continue
474                                 }
475                                 p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
476                         default:
477                                 p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
478                         }
479                         hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
480                         hint.addr = p
481                         hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
482                 }
483         } else {
484                 // On a 32-bit machine, we're much more concerned
485                 // about keeping the usable heap contiguous.
486                 // Hence:
487                 //
488                 // 1. We reserve space for all heapArenas up front so
489                 // they don't get interleaved with the heap. They're
490                 // ~258MB, so this isn't too bad. (We could reserve a
491                 // smaller amount of space up front if this is a
492                 // problem.)
493                 //
494                 // 2. We hint the heap to start right above the end of
495                 // the binary so we have the best chance of keeping it
496                 // contiguous.
497                 //
498                 // 3. We try to stake out a reasonably large initial
499                 // heap reservation.
500
501                 const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
502                 meta := uintptr(sysReserve(nil, arenaMetaSize))
503                 if meta != 0 {
504                         mheap_.heapArenaAlloc.init(meta, arenaMetaSize, true)
505                 }
506
507                 // We want to start the arena low, but if we're linked
508                 // against C code, it's possible global constructors
509                 // have called malloc and adjusted the process' brk.
510                 // Query the brk so we can avoid trying to map the
511                 // region over it (which will cause the kernel to put
512                 // the region somewhere else, likely at a high
513                 // address).
514                 procBrk := sbrk0()
515
516                 // If we ask for the end of the data segment but the
517                 // operating system requires a little more space
518                 // before we can start allocating, it will give out a
519                 // slightly higher pointer. Except QEMU, which is
520                 // buggy, as usual: it won't adjust the pointer
521                 // upward. So adjust it upward a little bit ourselves:
522                 // 1/4 MB to get away from the running binary image.
523                 p := firstmoduledata.end
524                 if p < procBrk {
525                         p = procBrk
526                 }
527                 if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
528                         p = mheap_.heapArenaAlloc.end
529                 }
530                 p = alignUp(p+(256<<10), heapArenaBytes)
531                 // Because we're worried about fragmentation on
532                 // 32-bit, we try to make a large initial reservation.
533                 arenaSizes := []uintptr{
534                         512 << 20,
535                         256 << 20,
536                         128 << 20,
537                 }
538                 for _, arenaSize := range arenaSizes {
539                         a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes)
540                         if a != nil {
541                                 mheap_.arena.init(uintptr(a), size, false)
542                                 p = mheap_.arena.end // For hint below
543                                 break
544                         }
545                 }
546                 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
547                 hint.addr = p
548                 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
549         }
550 }
551
552 // sysAlloc allocates heap arena space for at least n bytes. The
553 // returned pointer is always heapArenaBytes-aligned and backed by
554 // h.arenas metadata. The returned size is always a multiple of
555 // heapArenaBytes. sysAlloc returns nil on failure.
556 // There is no corresponding free function.
557 //
558 // sysAlloc returns a memory region in the Reserved state. This region must
559 // be transitioned to Prepared and then Ready before use.
560 //
561 // h must be locked.
562 func (h *mheap) sysAlloc(n uintptr) (v unsafe.Pointer, size uintptr) {
563         assertLockHeld(&h.lock)
564
565         n = alignUp(n, heapArenaBytes)
566
567         // First, try the arena pre-reservation.
568         v = h.arena.alloc(n, heapArenaBytes, &memstats.heap_sys)
569         if v != nil {
570                 size = n
571                 goto mapped
572         }
573
574         // Try to grow the heap at a hint address.
575         for h.arenaHints != nil {
576                 hint := h.arenaHints
577                 p := hint.addr
578                 if hint.down {
579                         p -= n
580                 }
581                 if p+n < p {
582                         // We can't use this, so don't ask.
583                         v = nil
584                 } else if arenaIndex(p+n-1) >= 1<<arenaBits {
585                         // Outside addressable heap. Can't use.
586                         v = nil
587                 } else {
588                         v = sysReserve(unsafe.Pointer(p), n)
589                 }
590                 if p == uintptr(v) {
591                         // Success. Update the hint.
592                         if !hint.down {
593                                 p += n
594                         }
595                         hint.addr = p
596                         size = n
597                         break
598                 }
599                 // Failed. Discard this hint and try the next.
600                 //
601                 // TODO: This would be cleaner if sysReserve could be
602                 // told to only return the requested address. In
603                 // particular, this is already how Windows behaves, so
604                 // it would simplify things there.
605                 if v != nil {
606                         sysFree(v, n, nil)
607                 }
608                 h.arenaHints = hint.next
609                 h.arenaHintAlloc.free(unsafe.Pointer(hint))
610         }
611
612         if size == 0 {
613                 if raceenabled {
614                         // The race detector assumes the heap lives in
615                         // [0x00c000000000, 0x00e000000000), but we
616                         // just ran out of hints in this region. Give
617                         // a nice failure.
618                         throw("too many address space collisions for -race mode")
619                 }
620
621                 // All of the hints failed, so we'll take any
622                 // (sufficiently aligned) address the kernel will give
623                 // us.
624                 v, size = sysReserveAligned(nil, n, heapArenaBytes)
625                 if v == nil {
626                         return nil, 0
627                 }
628
629                 // Create new hints for extending this region.
630                 hint := (*arenaHint)(h.arenaHintAlloc.alloc())
631                 hint.addr, hint.down = uintptr(v), true
632                 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
633                 hint = (*arenaHint)(h.arenaHintAlloc.alloc())
634                 hint.addr = uintptr(v) + size
635                 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
636         }
637
638         // Check for bad pointers or pointers we can't use.
639         {
640                 var bad string
641                 p := uintptr(v)
642                 if p+size < p {
643                         bad = "region exceeds uintptr range"
644                 } else if arenaIndex(p) >= 1<<arenaBits {
645                         bad = "base outside usable address space"
646                 } else if arenaIndex(p+size-1) >= 1<<arenaBits {
647                         bad = "end outside usable address space"
648                 }
649                 if bad != "" {
650                         // This should be impossible on most architectures,
651                         // but it would be really confusing to debug.
652                         print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
653                         throw("memory reservation exceeds address space limit")
654                 }
655         }
656
657         if uintptr(v)&(heapArenaBytes-1) != 0 {
658                 throw("misrounded allocation in sysAlloc")
659         }
660
661 mapped:
662         // Create arena metadata.
663         for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
664                 l2 := h.arenas[ri.l1()]
665                 if l2 == nil {
666                         // Allocate an L2 arena map.
667                         l2 = (*[1 << arenaL2Bits]*heapArena)(persistentalloc(unsafe.Sizeof(*l2), goarch.PtrSize, nil))
668                         if l2 == nil {
669                                 throw("out of memory allocating heap arena map")
670                         }
671                         atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
672                 }
673
674                 if l2[ri.l2()] != nil {
675                         throw("arena already initialized")
676                 }
677                 var r *heapArena
678                 r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
679                 if r == nil {
680                         r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
681                         if r == nil {
682                                 throw("out of memory allocating heap arena metadata")
683                         }
684                 }
685
686                 // Add the arena to the arenas list.
687                 if len(h.allArenas) == cap(h.allArenas) {
688                         size := 2 * uintptr(cap(h.allArenas)) * goarch.PtrSize
689                         if size == 0 {
690                                 size = physPageSize
691                         }
692                         newArray := (*notInHeap)(persistentalloc(size, goarch.PtrSize, &memstats.gcMiscSys))
693                         if newArray == nil {
694                                 throw("out of memory allocating allArenas")
695                         }
696                         oldSlice := h.allArenas
697                         *(*notInHeapSlice)(unsafe.Pointer(&h.allArenas)) = notInHeapSlice{newArray, len(h.allArenas), int(size / goarch.PtrSize)}
698                         copy(h.allArenas, oldSlice)
699                         // Do not free the old backing array because
700                         // there may be concurrent readers. Since we
701                         // double the array each time, this can lead
702                         // to at most 2x waste.
703                 }
704                 h.allArenas = h.allArenas[:len(h.allArenas)+1]
705                 h.allArenas[len(h.allArenas)-1] = ri
706
707                 // Store atomically just in case an object from the
708                 // new heap arena becomes visible before the heap lock
709                 // is released (which shouldn't happen, but there's
710                 // little downside to this).
711                 atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
712         }
713
714         // Tell the race detector about the new heap memory.
715         if raceenabled {
716                 racemapshadow(v, size)
717         }
718
719         return
720 }
721
722 // sysReserveAligned is like sysReserve, but the returned pointer is
723 // aligned to align bytes. It may reserve either n or n+align bytes,
724 // so it returns the size that was reserved.
725 func sysReserveAligned(v unsafe.Pointer, size, align uintptr) (unsafe.Pointer, uintptr) {
726         // Since the alignment is rather large in uses of this
727         // function, we're not likely to get it by chance, so we ask
728         // for a larger region and remove the parts we don't need.
729         retries := 0
730 retry:
731         p := uintptr(sysReserve(v, size+align))
732         switch {
733         case p == 0:
734                 return nil, 0
735         case p&(align-1) == 0:
736                 // We got lucky and got an aligned region, so we can
737                 // use the whole thing.
738                 return unsafe.Pointer(p), size + align
739         case GOOS == "windows":
740                 // On Windows we can't release pieces of a
741                 // reservation, so we release the whole thing and
742                 // re-reserve the aligned sub-region. This may race,
743                 // so we may have to try again.
744                 sysFree(unsafe.Pointer(p), size+align, nil)
745                 p = alignUp(p, align)
746                 p2 := sysReserve(unsafe.Pointer(p), size)
747                 if p != uintptr(p2) {
748                         // Must have raced. Try again.
749                         sysFree(p2, size, nil)
750                         if retries++; retries == 100 {
751                                 throw("failed to allocate aligned heap memory; too many retries")
752                         }
753                         goto retry
754                 }
755                 // Success.
756                 return p2, size
757         default:
758                 // Trim off the unaligned parts.
759                 pAligned := alignUp(p, align)
760                 sysFree(unsafe.Pointer(p), pAligned-p, nil)
761                 end := pAligned + size
762                 endLen := (p + size + align) - end
763                 if endLen > 0 {
764                         sysFree(unsafe.Pointer(end), endLen, nil)
765                 }
766                 return unsafe.Pointer(pAligned), size
767         }
768 }
769
770 // base address for all 0-byte allocations
771 var zerobase uintptr
772
773 // nextFreeFast returns the next free object if one is quickly available.
774 // Otherwise it returns 0.
775 func nextFreeFast(s *mspan) gclinkptr {
776         theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
777         if theBit < 64 {
778                 result := s.freeindex + uintptr(theBit)
779                 if result < s.nelems {
780                         freeidx := result + 1
781                         if freeidx%64 == 0 && freeidx != s.nelems {
782                                 return 0
783                         }
784                         s.allocCache >>= uint(theBit + 1)
785                         s.freeindex = freeidx
786                         s.allocCount++
787                         return gclinkptr(result*s.elemsize + s.base())
788                 }
789         }
790         return 0
791 }
792
793 // nextFree returns the next free object from the cached span if one is available.
794 // Otherwise it refills the cache with a span with an available object and
795 // returns that object along with a flag indicating that this was a heavy
796 // weight allocation. If it is a heavy weight allocation the caller must
797 // determine whether a new GC cycle needs to be started or if the GC is active
798 // whether this goroutine needs to assist the GC.
799 //
800 // Must run in a non-preemptible context since otherwise the owner of
801 // c could change.
802 func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
803         s = c.alloc[spc]
804         shouldhelpgc = false
805         freeIndex := s.nextFreeIndex()
806         if freeIndex == s.nelems {
807                 // The span is full.
808                 if uintptr(s.allocCount) != s.nelems {
809                         println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
810                         throw("s.allocCount != s.nelems && freeIndex == s.nelems")
811                 }
812                 c.refill(spc)
813                 shouldhelpgc = true
814                 s = c.alloc[spc]
815
816                 freeIndex = s.nextFreeIndex()
817         }
818
819         if freeIndex >= s.nelems {
820                 throw("freeIndex is not valid")
821         }
822
823         v = gclinkptr(freeIndex*s.elemsize + s.base())
824         s.allocCount++
825         if uintptr(s.allocCount) > s.nelems {
826                 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
827                 throw("s.allocCount > s.nelems")
828         }
829         return
830 }
831
832 // Allocate an object of size bytes.
833 // Small objects are allocated from the per-P cache's free lists.
834 // Large objects (> 32 kB) are allocated straight from the heap.
835 func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
836         if gcphase == _GCmarktermination {
837                 throw("mallocgc called with gcphase == _GCmarktermination")
838         }
839
840         if size == 0 {
841                 return unsafe.Pointer(&zerobase)
842         }
843         userSize := size
844         if asanenabled {
845                 // Refer to ASAN runtime library, the malloc() function allocates extra memory,
846                 // the redzone, around the user requested memory region. And the redzones are marked
847                 // as unaddressable. We perform the same operations in Go to detect the overflows or
848                 // underflows.
849                 size += computeRZlog(size)
850         }
851
852         if debug.malloc {
853                 if debug.sbrk != 0 {
854                         align := uintptr(16)
855                         if typ != nil {
856                                 // TODO(austin): This should be just
857                                 //   align = uintptr(typ.align)
858                                 // but that's only 4 on 32-bit platforms,
859                                 // even if there's a uint64 field in typ (see #599).
860                                 // This causes 64-bit atomic accesses to panic.
861                                 // Hence, we use stricter alignment that matches
862                                 // the normal allocator better.
863                                 if size&7 == 0 {
864                                         align = 8
865                                 } else if size&3 == 0 {
866                                         align = 4
867                                 } else if size&1 == 0 {
868                                         align = 2
869                                 } else {
870                                         align = 1
871                                 }
872                         }
873                         return persistentalloc(size, align, &memstats.other_sys)
874                 }
875
876                 if inittrace.active && inittrace.id == getg().goid {
877                         // Init functions are executed sequentially in a single goroutine.
878                         inittrace.allocs += 1
879                 }
880         }
881
882         // assistG is the G to charge for this allocation, or nil if
883         // GC is not currently active.
884         var assistG *g
885         if gcBlackenEnabled != 0 {
886                 // Charge the current user G for this allocation.
887                 assistG = getg()
888                 if assistG.m.curg != nil {
889                         assistG = assistG.m.curg
890                 }
891                 // Charge the allocation against the G. We'll account
892                 // for internal fragmentation at the end of mallocgc.
893                 assistG.gcAssistBytes -= int64(size)
894
895                 if assistG.gcAssistBytes < 0 {
896                         // This G is in debt. Assist the GC to correct
897                         // this before allocating. This must happen
898                         // before disabling preemption.
899                         gcAssistAlloc(assistG)
900                 }
901         }
902
903         // Set mp.mallocing to keep from being preempted by GC.
904         mp := acquirem()
905         if mp.mallocing != 0 {
906                 throw("malloc deadlock")
907         }
908         if mp.gsignal == getg() {
909                 throw("malloc during signal")
910         }
911         mp.mallocing = 1
912
913         shouldhelpgc := false
914         dataSize := userSize
915         c := getMCache(mp)
916         if c == nil {
917                 throw("mallocgc called without a P or outside bootstrapping")
918         }
919         var span *mspan
920         var x unsafe.Pointer
921         noscan := typ == nil || typ.ptrdata == 0
922         // In some cases block zeroing can profitably (for latency reduction purposes)
923         // be delayed till preemption is possible; delayedZeroing tracks that state.
924         delayedZeroing := false
925         if size <= maxSmallSize {
926                 if noscan && size < maxTinySize {
927                         // Tiny allocator.
928                         //
929                         // Tiny allocator combines several tiny allocation requests
930                         // into a single memory block. The resulting memory block
931                         // is freed when all subobjects are unreachable. The subobjects
932                         // must be noscan (don't have pointers), this ensures that
933                         // the amount of potentially wasted memory is bounded.
934                         //
935                         // Size of the memory block used for combining (maxTinySize) is tunable.
936                         // Current setting is 16 bytes, which relates to 2x worst case memory
937                         // wastage (when all but one subobjects are unreachable).
938                         // 8 bytes would result in no wastage at all, but provides less
939                         // opportunities for combining.
940                         // 32 bytes provides more opportunities for combining,
941                         // but can lead to 4x worst case wastage.
942                         // The best case winning is 8x regardless of block size.
943                         //
944                         // Objects obtained from tiny allocator must not be freed explicitly.
945                         // So when an object will be freed explicitly, we ensure that
946                         // its size >= maxTinySize.
947                         //
948                         // SetFinalizer has a special case for objects potentially coming
949                         // from tiny allocator, it such case it allows to set finalizers
950                         // for an inner byte of a memory block.
951                         //
952                         // The main targets of tiny allocator are small strings and
953                         // standalone escaping variables. On a json benchmark
954                         // the allocator reduces number of allocations by ~12% and
955                         // reduces heap size by ~20%.
956                         off := c.tinyoffset
957                         // Align tiny pointer for required (conservative) alignment.
958                         if size&7 == 0 {
959                                 off = alignUp(off, 8)
960                         } else if goarch.PtrSize == 4 && size == 12 {
961                                 // Conservatively align 12-byte objects to 8 bytes on 32-bit
962                                 // systems so that objects whose first field is a 64-bit
963                                 // value is aligned to 8 bytes and does not cause a fault on
964                                 // atomic access. See issue 37262.
965                                 // TODO(mknyszek): Remove this workaround if/when issue 36606
966                                 // is resolved.
967                                 off = alignUp(off, 8)
968                         } else if size&3 == 0 {
969                                 off = alignUp(off, 4)
970                         } else if size&1 == 0 {
971                                 off = alignUp(off, 2)
972                         }
973                         if off+size <= maxTinySize && c.tiny != 0 {
974                                 // The object fits into existing tiny block.
975                                 x = unsafe.Pointer(c.tiny + off)
976                                 c.tinyoffset = off + size
977                                 c.tinyAllocs++
978                                 mp.mallocing = 0
979                                 releasem(mp)
980                                 return x
981                         }
982                         // Allocate a new maxTinySize block.
983                         span = c.alloc[tinySpanClass]
984                         v := nextFreeFast(span)
985                         if v == 0 {
986                                 v, span, shouldhelpgc = c.nextFree(tinySpanClass)
987                         }
988                         x = unsafe.Pointer(v)
989                         (*[2]uint64)(x)[0] = 0
990                         (*[2]uint64)(x)[1] = 0
991                         // See if we need to replace the existing tiny block with the new one
992                         // based on amount of remaining free space.
993                         if !raceenabled && (size < c.tinyoffset || c.tiny == 0) {
994                                 // Note: disabled when race detector is on, see comment near end of this function.
995                                 c.tiny = uintptr(x)
996                                 c.tinyoffset = size
997                         }
998                         size = maxTinySize
999                 } else {
1000                         var sizeclass uint8
1001                         if size <= smallSizeMax-8 {
1002                                 sizeclass = size_to_class8[divRoundUp(size, smallSizeDiv)]
1003                         } else {
1004                                 sizeclass = size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)]
1005                         }
1006                         size = uintptr(class_to_size[sizeclass])
1007                         spc := makeSpanClass(sizeclass, noscan)
1008                         span = c.alloc[spc]
1009                         v := nextFreeFast(span)
1010                         if v == 0 {
1011                                 v, span, shouldhelpgc = c.nextFree(spc)
1012                         }
1013                         x = unsafe.Pointer(v)
1014                         if needzero && span.needzero != 0 {
1015                                 memclrNoHeapPointers(unsafe.Pointer(v), size)
1016                         }
1017                 }
1018         } else {
1019                 shouldhelpgc = true
1020                 // For large allocations, keep track of zeroed state so that
1021                 // bulk zeroing can be happen later in a preemptible context.
1022                 span = c.allocLarge(size, noscan)
1023                 span.freeindex = 1
1024                 span.allocCount = 1
1025                 size = span.elemsize
1026                 x = unsafe.Pointer(span.base())
1027                 if needzero && span.needzero != 0 {
1028                         if noscan {
1029                                 delayedZeroing = true
1030                         } else {
1031                                 memclrNoHeapPointers(x, size)
1032                                 // We've in theory cleared almost the whole span here,
1033                                 // and could take the extra step of actually clearing
1034                                 // the whole thing. However, don't. Any GC bits for the
1035                                 // uncleared parts will be zero, and it's just going to
1036                                 // be needzero = 1 once freed anyway.
1037                         }
1038                 }
1039         }
1040
1041         var scanSize uintptr
1042         if !noscan {
1043                 heapBitsSetType(uintptr(x), size, dataSize, typ)
1044                 if dataSize > typ.size {
1045                         // Array allocation. If there are any
1046                         // pointers, GC has to scan to the last
1047                         // element.
1048                         if typ.ptrdata != 0 {
1049                                 scanSize = dataSize - typ.size + typ.ptrdata
1050                         }
1051                 } else {
1052                         scanSize = typ.ptrdata
1053                 }
1054                 c.scanAlloc += scanSize
1055         }
1056
1057         // Ensure that the stores above that initialize x to
1058         // type-safe memory and set the heap bits occur before
1059         // the caller can make x observable to the garbage
1060         // collector. Otherwise, on weakly ordered machines,
1061         // the garbage collector could follow a pointer to x,
1062         // but see uninitialized memory or stale heap bits.
1063         publicationBarrier()
1064
1065         // Allocate black during GC.
1066         // All slots hold nil so no scanning is needed.
1067         // This may be racing with GC so do it atomically if there can be
1068         // a race marking the bit.
1069         if gcphase != _GCoff {
1070                 gcmarknewobject(span, uintptr(x), size, scanSize)
1071         }
1072
1073         if raceenabled {
1074                 racemalloc(x, size)
1075         }
1076
1077         if msanenabled {
1078                 msanmalloc(x, size)
1079         }
1080
1081         if asanenabled {
1082                 // We should only read/write the memory with the size asked by the user.
1083                 // The rest of the allocated memory should be poisoned, so that we can report
1084                 // errors when accessing poisoned memory.
1085                 // The allocated memory is larger than required userSize, it will also include
1086                 // redzone and some other padding bytes.
1087                 rzBeg := unsafe.Add(x, userSize)
1088                 asanpoison(rzBeg, size-userSize)
1089                 asanunpoison(x, userSize)
1090         }
1091
1092         if rate := MemProfileRate; rate > 0 {
1093                 // Note cache c only valid while m acquired; see #47302
1094                 if rate != 1 && size < c.nextSample {
1095                         c.nextSample -= size
1096                 } else {
1097                         profilealloc(mp, x, size)
1098                 }
1099         }
1100         mp.mallocing = 0
1101         releasem(mp)
1102
1103         // Pointerfree data can be zeroed late in a context where preemption can occur.
1104         // x will keep the memory alive.
1105         if delayedZeroing {
1106                 if !noscan {
1107                         throw("delayed zeroing on data that may contain pointers")
1108                 }
1109                 memclrNoHeapPointersChunked(size, x) // This is a possible preemption point: see #47302
1110         }
1111
1112         if debug.malloc {
1113                 if debug.allocfreetrace != 0 {
1114                         tracealloc(x, size, typ)
1115                 }
1116
1117                 if inittrace.active && inittrace.id == getg().goid {
1118                         // Init functions are executed sequentially in a single goroutine.
1119                         inittrace.bytes += uint64(size)
1120                 }
1121         }
1122
1123         if assistG != nil {
1124                 // Account for internal fragmentation in the assist
1125                 // debt now that we know it.
1126                 assistG.gcAssistBytes -= int64(size - dataSize)
1127         }
1128
1129         if shouldhelpgc {
1130                 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
1131                         gcStart(t)
1132                 }
1133         }
1134
1135         if raceenabled && noscan && dataSize < maxTinySize {
1136                 // Pad tinysize allocations so they are aligned with the end
1137                 // of the tinyalloc region. This ensures that any arithmetic
1138                 // that goes off the top end of the object will be detectable
1139                 // by checkptr (issue 38872).
1140                 // Note that we disable tinyalloc when raceenabled for this to work.
1141                 // TODO: This padding is only performed when the race detector
1142                 // is enabled. It would be nice to enable it if any package
1143                 // was compiled with checkptr, but there's no easy way to
1144                 // detect that (especially at compile time).
1145                 // TODO: enable this padding for all allocations, not just
1146                 // tinyalloc ones. It's tricky because of pointer maps.
1147                 // Maybe just all noscan objects?
1148                 x = add(x, size-dataSize)
1149         }
1150
1151         return x
1152 }
1153
1154 // memclrNoHeapPointersChunked repeatedly calls memclrNoHeapPointers
1155 // on chunks of the buffer to be zeroed, with opportunities for preemption
1156 // along the way.  memclrNoHeapPointers contains no safepoints and also
1157 // cannot be preemptively scheduled, so this provides a still-efficient
1158 // block copy that can also be preempted on a reasonable granularity.
1159 //
1160 // Use this with care; if the data being cleared is tagged to contain
1161 // pointers, this allows the GC to run before it is all cleared.
1162 func memclrNoHeapPointersChunked(size uintptr, x unsafe.Pointer) {
1163         v := uintptr(x)
1164         // got this from benchmarking. 128k is too small, 512k is too large.
1165         const chunkBytes = 256 * 1024
1166         vsize := v + size
1167         for voff := v; voff < vsize; voff = voff + chunkBytes {
1168                 if getg().preempt {
1169                         // may hold locks, e.g., profiling
1170                         goschedguarded()
1171                 }
1172                 // clear min(avail, lump) bytes
1173                 n := vsize - voff
1174                 if n > chunkBytes {
1175                         n = chunkBytes
1176                 }
1177                 memclrNoHeapPointers(unsafe.Pointer(voff), n)
1178         }
1179 }
1180
1181 // implementation of new builtin
1182 // compiler (both frontend and SSA backend) knows the signature
1183 // of this function
1184 func newobject(typ *_type) unsafe.Pointer {
1185         return mallocgc(typ.size, typ, true)
1186 }
1187
1188 //go:linkname reflect_unsafe_New reflect.unsafe_New
1189 func reflect_unsafe_New(typ *_type) unsafe.Pointer {
1190         return mallocgc(typ.size, typ, true)
1191 }
1192
1193 //go:linkname reflectlite_unsafe_New internal/reflectlite.unsafe_New
1194 func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
1195         return mallocgc(typ.size, typ, true)
1196 }
1197
1198 // newarray allocates an array of n elements of type typ.
1199 func newarray(typ *_type, n int) unsafe.Pointer {
1200         if n == 1 {
1201                 return mallocgc(typ.size, typ, true)
1202         }
1203         mem, overflow := math.MulUintptr(typ.size, uintptr(n))
1204         if overflow || mem > maxAlloc || n < 0 {
1205                 panic(plainError("runtime: allocation size out of range"))
1206         }
1207         return mallocgc(mem, typ, true)
1208 }
1209
1210 //go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray
1211 func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
1212         return newarray(typ, n)
1213 }
1214
1215 func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
1216         c := getMCache(mp)
1217         if c == nil {
1218                 throw("profilealloc called without a P or outside bootstrapping")
1219         }
1220         c.nextSample = nextSample()
1221         mProf_Malloc(x, size)
1222 }
1223
1224 // nextSample returns the next sampling point for heap profiling. The goal is
1225 // to sample allocations on average every MemProfileRate bytes, but with a
1226 // completely random distribution over the allocation timeline; this
1227 // corresponds to a Poisson process with parameter MemProfileRate. In Poisson
1228 // processes, the distance between two samples follows the exponential
1229 // distribution (exp(MemProfileRate)), so the best return value is a random
1230 // number taken from an exponential distribution whose mean is MemProfileRate.
1231 func nextSample() uintptr {
1232         if MemProfileRate == 1 {
1233                 // Callers assign our return value to
1234                 // mcache.next_sample, but next_sample is not used
1235                 // when the rate is 1. So avoid the math below and
1236                 // just return something.
1237                 return 0
1238         }
1239         if GOOS == "plan9" {
1240                 // Plan 9 doesn't support floating point in note handler.
1241                 if g := getg(); g == g.m.gsignal {
1242                         return nextSampleNoFP()
1243                 }
1244         }
1245
1246         return uintptr(fastexprand(MemProfileRate))
1247 }
1248
1249 // fastexprand returns a random number from an exponential distribution with
1250 // the specified mean.
1251 func fastexprand(mean int) int32 {
1252         // Avoid overflow. Maximum possible step is
1253         // -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
1254         switch {
1255         case mean > 0x7000000:
1256                 mean = 0x7000000
1257         case mean == 0:
1258                 return 0
1259         }
1260
1261         // Take a random sample of the exponential distribution exp(-mean*x).
1262         // The probability distribution function is mean*exp(-mean*x), so the CDF is
1263         // p = 1 - exp(-mean*x), so
1264         // q = 1 - p == exp(-mean*x)
1265         // log_e(q) = -mean*x
1266         // -log_e(q)/mean = x
1267         // x = -log_e(q) * mean
1268         // x = log_2(q) * (-log_e(2)) * mean    ; Using log_2 for efficiency
1269         const randomBitCount = 26
1270         q := fastrandn(1<<randomBitCount) + 1
1271         qlog := fastlog2(float64(q)) - randomBitCount
1272         if qlog > 0 {
1273                 qlog = 0
1274         }
1275         const minusLog2 = -0.6931471805599453 // -ln(2)
1276         return int32(qlog*(minusLog2*float64(mean))) + 1
1277 }
1278
1279 // nextSampleNoFP is similar to nextSample, but uses older,
1280 // simpler code to avoid floating point.
1281 func nextSampleNoFP() uintptr {
1282         // Set first allocation sample size.
1283         rate := MemProfileRate
1284         if rate > 0x3fffffff { // make 2*rate not overflow
1285                 rate = 0x3fffffff
1286         }
1287         if rate != 0 {
1288                 return uintptr(fastrandn(uint32(2 * rate)))
1289         }
1290         return 0
1291 }
1292
1293 type persistentAlloc struct {
1294         base *notInHeap
1295         off  uintptr
1296 }
1297
1298 var globalAlloc struct {
1299         mutex
1300         persistentAlloc
1301 }
1302
1303 // persistentChunkSize is the number of bytes we allocate when we grow
1304 // a persistentAlloc.
1305 const persistentChunkSize = 256 << 10
1306
1307 // persistentChunks is a list of all the persistent chunks we have
1308 // allocated. The list is maintained through the first word in the
1309 // persistent chunk. This is updated atomically.
1310 var persistentChunks *notInHeap
1311
1312 // Wrapper around sysAlloc that can allocate small chunks.
1313 // There is no associated free operation.
1314 // Intended for things like function/type/debug-related persistent data.
1315 // If align is 0, uses default align (currently 8).
1316 // The returned memory will be zeroed.
1317 //
1318 // Consider marking persistentalloc'd types go:notinheap.
1319 func persistentalloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1320         var p *notInHeap
1321         systemstack(func() {
1322                 p = persistentalloc1(size, align, sysStat)
1323         })
1324         return unsafe.Pointer(p)
1325 }
1326
1327 // Must run on system stack because stack growth can (re)invoke it.
1328 // See issue 9174.
1329 //go:systemstack
1330 func persistentalloc1(size, align uintptr, sysStat *sysMemStat) *notInHeap {
1331         const (
1332                 maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
1333         )
1334
1335         if size == 0 {
1336                 throw("persistentalloc: size == 0")
1337         }
1338         if align != 0 {
1339                 if align&(align-1) != 0 {
1340                         throw("persistentalloc: align is not a power of 2")
1341                 }
1342                 if align > _PageSize {
1343                         throw("persistentalloc: align is too large")
1344                 }
1345         } else {
1346                 align = 8
1347         }
1348
1349         if size >= maxBlock {
1350                 return (*notInHeap)(sysAlloc(size, sysStat))
1351         }
1352
1353         mp := acquirem()
1354         var persistent *persistentAlloc
1355         if mp != nil && mp.p != 0 {
1356                 persistent = &mp.p.ptr().palloc
1357         } else {
1358                 lock(&globalAlloc.mutex)
1359                 persistent = &globalAlloc.persistentAlloc
1360         }
1361         persistent.off = alignUp(persistent.off, align)
1362         if persistent.off+size > persistentChunkSize || persistent.base == nil {
1363                 persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys))
1364                 if persistent.base == nil {
1365                         if persistent == &globalAlloc.persistentAlloc {
1366                                 unlock(&globalAlloc.mutex)
1367                         }
1368                         throw("runtime: cannot allocate memory")
1369                 }
1370
1371                 // Add the new chunk to the persistentChunks list.
1372                 for {
1373                         chunks := uintptr(unsafe.Pointer(persistentChunks))
1374                         *(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
1375                         if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
1376                                 break
1377                         }
1378                 }
1379                 persistent.off = alignUp(goarch.PtrSize, align)
1380         }
1381         p := persistent.base.add(persistent.off)
1382         persistent.off += size
1383         releasem(mp)
1384         if persistent == &globalAlloc.persistentAlloc {
1385                 unlock(&globalAlloc.mutex)
1386         }
1387
1388         if sysStat != &memstats.other_sys {
1389                 sysStat.add(int64(size))
1390                 memstats.other_sys.add(-int64(size))
1391         }
1392         return p
1393 }
1394
1395 // inPersistentAlloc reports whether p points to memory allocated by
1396 // persistentalloc. This must be nosplit because it is called by the
1397 // cgo checker code, which is called by the write barrier code.
1398 //go:nosplit
1399 func inPersistentAlloc(p uintptr) bool {
1400         chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
1401         for chunk != 0 {
1402                 if p >= chunk && p < chunk+persistentChunkSize {
1403                         return true
1404                 }
1405                 chunk = *(*uintptr)(unsafe.Pointer(chunk))
1406         }
1407         return false
1408 }
1409
1410 // linearAlloc is a simple linear allocator that pre-reserves a region
1411 // of memory and then optionally maps that region into the Ready state
1412 // as needed.
1413 //
1414 // The caller is responsible for locking.
1415 type linearAlloc struct {
1416         next   uintptr // next free byte
1417         mapped uintptr // one byte past end of mapped space
1418         end    uintptr // end of reserved space
1419
1420         mapMemory bool // transition memory from Reserved to Ready if true
1421 }
1422
1423 func (l *linearAlloc) init(base, size uintptr, mapMemory bool) {
1424         if base+size < base {
1425                 // Chop off the last byte. The runtime isn't prepared
1426                 // to deal with situations where the bounds could overflow.
1427                 // Leave that memory reserved, though, so we don't map it
1428                 // later.
1429                 size -= 1
1430         }
1431         l.next, l.mapped = base, base
1432         l.end = base + size
1433         l.mapMemory = mapMemory
1434 }
1435
1436 func (l *linearAlloc) alloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1437         p := alignUp(l.next, align)
1438         if p+size > l.end {
1439                 return nil
1440         }
1441         l.next = p + size
1442         if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
1443                 if l.mapMemory {
1444                         // Transition from Reserved to Prepared to Ready.
1445                         sysMap(unsafe.Pointer(l.mapped), pEnd-l.mapped, sysStat)
1446                         sysUsed(unsafe.Pointer(l.mapped), pEnd-l.mapped)
1447                 }
1448                 l.mapped = pEnd
1449         }
1450         return unsafe.Pointer(p)
1451 }
1452
1453 // notInHeap is off-heap memory allocated by a lower-level allocator
1454 // like sysAlloc or persistentAlloc.
1455 //
1456 // In general, it's better to use real types marked as go:notinheap,
1457 // but this serves as a generic type for situations where that isn't
1458 // possible (like in the allocators).
1459 //
1460 // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
1461 //
1462 //go:notinheap
1463 type notInHeap struct{}
1464
1465 func (p *notInHeap) add(bytes uintptr) *notInHeap {
1466         return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))
1467 }
1468
1469 // computeRZlog computes the size of the redzone.
1470 // Refer to the implementation of the compiler-rt.
1471 func computeRZlog(userSize uintptr) uintptr {
1472         switch {
1473         case userSize <= (64 - 16):
1474                 return 16 << 0
1475         case userSize <= (128 - 32):
1476                 return 16 << 1
1477         case userSize <= (512 - 64):
1478                 return 16 << 2
1479         case userSize <= (4096 - 128):
1480                 return 16 << 3
1481         case userSize <= (1<<14)-256:
1482                 return 16 << 4
1483         case userSize <= (1<<15)-512:
1484                 return 16 << 5
1485         case userSize <= (1<<16)-1024:
1486                 return 16 << 6
1487         default:
1488                 return 16 << 7
1489         }
1490 }