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