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