Source file 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/goexperiment"
   106  	"internal/goos"
   107  	"internal/runtime/atomic"
   108  	"internal/runtime/gc"
   109  	"internal/runtime/math"
   110  	"internal/runtime/sys"
   111  	"unsafe"
   112  )
   113  
   114  const (
   115  	maxTinySize   = _TinySize
   116  	tinySizeClass = _TinySizeClass
   117  	maxSmallSize  = gc.MaxSmallSize
   118  	pageSize      = 1 << gc.PageShift
   119  	pageMask      = pageSize - 1
   120  
   121  	// Unused. Left for viewcore.
   122  	_PageSize              = pageSize
   123  	minSizeForMallocHeader = gc.MinSizeForMallocHeader
   124  	mallocHeaderSize       = gc.MallocHeaderSize
   125  
   126  	// _64bit = 1 on 64-bit systems, 0 on 32-bit systems
   127  	_64bit = 1 << (^uintptr(0) >> 63) / 2
   128  
   129  	// Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
   130  	_TinySize      = gc.TinySize
   131  	_TinySizeClass = int8(gc.TinySizeClass)
   132  
   133  	_FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
   134  
   135  	// Per-P, per order stack segment cache size.
   136  	_StackCacheSize = 32 * 1024
   137  
   138  	// Number of orders that get caching. Order 0 is FixedStack
   139  	// and each successive order is twice as large.
   140  	// We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
   141  	// will be allocated directly.
   142  	// Since FixedStack is different on different systems, we
   143  	// must vary NumStackOrders to keep the same maximum cached size.
   144  	//   OS               | FixedStack | NumStackOrders
   145  	//   -----------------+------------+---------------
   146  	//   linux/darwin/bsd | 2KB        | 4
   147  	//   windows/32       | 4KB        | 3
   148  	//   windows/64       | 8KB        | 2
   149  	//   plan9            | 4KB        | 3
   150  	_NumStackOrders = 4 - goarch.PtrSize/4*goos.IsWindows - 1*goos.IsPlan9
   151  
   152  	// heapAddrBits is the number of bits in a heap address, and
   153  	// maxAlloc the maximum size of an allocation.
   154  	// See internal/runtime/sys.
   155  	heapAddrBits = sys.HeapAddrBits
   156  	maxAlloc     = sys.MaxAlloc
   157  
   158  	// The number of bits in a heap address, the size of heap
   159  	// arenas, and the L1 and L2 arena map sizes are related by
   160  	//
   161  	//   (1 << addr bits) = arena size * L1 entries * L2 entries
   162  	//
   163  	// Currently, we balance these as follows:
   164  	//
   165  	//       Platform  Addr bits  Arena size  L1 entries   L2 entries
   166  	// --------------  ---------  ----------  ----------  -----------
   167  	//       */64-bit         48        64MB           1    4M (32MB)
   168  	// windows/64-bit         48         4MB          64    1M  (8MB)
   169  	//      ios/arm64         40         4MB           1  256K  (2MB)
   170  	//       */32-bit         32         4MB           1  1024  (4KB)
   171  	//     */mips(le)         31         4MB           1   512  (2KB)
   172  	//           wasm         32       512KB           1  8192 (64KB)
   173  	//         wasm32         32       512KB           1  8192 (32KB)
   174  	//  openbsd/arm64         39         4MB           1  128K  (1MB)
   175  
   176  	// heapArenaBytes is the size of a heap arena. The heap
   177  	// consists of mappings of size heapArenaBytes, aligned to
   178  	// heapArenaBytes. The initial heap mapping is one arena.
   179  	//
   180  	// This is currently 64MB on 64-bit non-Windows, 4MB on
   181  	// 32-bit and on Windows, and 512KB on Wasm. We use smaller
   182  	// arenas on Windows because all committed memory is charged
   183  	// to the process, even if it's not touched. Hence, for
   184  	// processes with small heaps, the mapped arena space needs
   185  	// to be commensurate. This is particularly important with
   186  	// the race detector, since it significantly amplifies the
   187  	// cost of committed memory. We use smaller arenas on Wasm
   188  	// because some Wasm programs have very small heap, and
   189  	// everything in the Wasm linear memory is charged.
   190  	heapArenaBytes = 1 << logHeapArenaBytes
   191  
   192  	heapArenaWords = heapArenaBytes / goarch.PtrSize
   193  
   194  	// logHeapArenaBytes is log_2 of heapArenaBytes. For clarity,
   195  	// prefer using heapArenaBytes where possible (we need the
   196  	// constant to compute some other constants).
   197  	logHeapArenaBytes = (6+20)*(_64bit*(1-goos.IsWindows)*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64)*(1-goos.IsOpenbsd*goarch.IsArm64)) +
   198  		(2+20)*(_64bit*goos.IsWindows+goarch.IsArm64*goos.IsOpenbsd) +
   199  		(2+20)*((1-_64bit)*(1-goarch.IsWasm32)) +
   200  		(9+10)*(goarch.IsWasm|goarch.IsWasm32) +
   201  		(2+20)*goos.IsIos*goarch.IsArm64
   202  
   203  	// heapArenaBitmapWords is the size of each heap arena's bitmap in uintptrs.
   204  	heapArenaBitmapWords = heapArenaWords / (8 * goarch.PtrSize)
   205  
   206  	pagesPerArena = heapArenaBytes / pageSize
   207  
   208  	// arenaL1Bits is the number of bits of the arena number
   209  	// covered by the first level arena map.
   210  	//
   211  	// This number should be small, since the first level arena
   212  	// map requires PtrSize*(1<<arenaL1Bits) of space in the
   213  	// binary's BSS. It can be zero, in which case the first level
   214  	// index is effectively unused. There is a performance benefit
   215  	// to this, since the generated code can be more efficient,
   216  	// but comes at the cost of having a large L2 mapping.
   217  	//
   218  	// We use the L1 map on 64-bit Windows because the arena size
   219  	// is small, but the address space is still 48 bits, and
   220  	// there's a high cost to having a large L2.
   221  	arenaL1Bits = 6 * (_64bit * goos.IsWindows)
   222  
   223  	// arenaL2Bits is the number of bits of the arena number
   224  	// covered by the second level arena index.
   225  	//
   226  	// The size of each arena map allocation is proportional to
   227  	// 1<<arenaL2Bits, so it's important that this not be too
   228  	// large. 48 bits leads to 32MB arena index allocations, which
   229  	// is about the practical threshold.
   230  	arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits
   231  
   232  	// arenaL1Shift is the number of bits to shift an arena frame
   233  	// number by to compute an index into the first level arena map.
   234  	arenaL1Shift = arenaL2Bits
   235  
   236  	// arenaBits is the total bits in a combined arena map index.
   237  	// This is split between the index into the L1 arena map and
   238  	// the L2 arena map.
   239  	arenaBits = arenaL1Bits + arenaL2Bits
   240  
   241  	// arenaBaseOffset is the pointer value that corresponds to
   242  	// index 0 in the heap arena map.
   243  	//
   244  	// On amd64, the address space is 48 bits, sign extended to 64
   245  	// bits. This offset lets us handle "negative" addresses (or
   246  	// high addresses if viewed as unsigned).
   247  	//
   248  	// On aix/ppc64, this offset allows to keep the heapAddrBits to
   249  	// 48. Otherwise, it would be 60 in order to handle mmap addresses
   250  	// (in range 0x0a00000000000000 - 0x0afffffffffffff). But in this
   251  	// case, the memory reserved in (s *pageAlloc).init for chunks
   252  	// is causing important slowdowns.
   253  	//
   254  	// On other platforms, the user address space is contiguous
   255  	// and starts at 0, so no offset is necessary.
   256  	arenaBaseOffset = 0xffff800000000000*goarch.IsAmd64 + 0x0a00000000000000*goos.IsAix
   257  	// A typed version of this constant that will make it into DWARF (for viewcore).
   258  	arenaBaseOffsetUintptr = uintptr(arenaBaseOffset)
   259  
   260  	// Max number of threads to run garbage collection.
   261  	// 2, 3, and 4 are all plausible maximums depending
   262  	// on the hardware details of the machine. The garbage
   263  	// collector scales well to 32 cpus.
   264  	_MaxGcproc = 32
   265  
   266  	// minLegalPointer is the smallest possible legal pointer.
   267  	// This is the smallest possible architectural page size,
   268  	// since we assume that the first page is never mapped.
   269  	//
   270  	// This should agree with minZeroPage in the compiler.
   271  	minLegalPointer uintptr = 4096
   272  
   273  	// minHeapForMetadataHugePages sets a threshold on when certain kinds of
   274  	// heap metadata, currently the arenas map L2 entries and page alloc bitmap
   275  	// mappings, are allowed to be backed by huge pages. If the heap goal ever
   276  	// exceeds this threshold, then huge pages are enabled.
   277  	//
   278  	// These numbers are chosen with the assumption that huge pages are on the
   279  	// order of a few MiB in size.
   280  	//
   281  	// The kind of metadata this applies to has a very low overhead when compared
   282  	// to address space used, but their constant overheads for small heaps would
   283  	// be very high if they were to be backed by huge pages (e.g. a few MiB makes
   284  	// a huge difference for an 8 MiB heap, but barely any difference for a 1 GiB
   285  	// heap). The benefit of huge pages is also not worth it for small heaps,
   286  	// because only a very, very small part of the metadata is used for small heaps.
   287  	//
   288  	// N.B. If the heap goal exceeds the threshold then shrinks to a very small size
   289  	// again, then huge pages will still be enabled for this mapping. The reason is that
   290  	// there's no point unless we're also returning the physical memory for these
   291  	// metadata mappings back to the OS. That would be quite complex to do in general
   292  	// as the heap is likely fragmented after a reduction in heap size.
   293  	minHeapForMetadataHugePages = 1 << 30
   294  
   295  	// randomizeHeapBase indicates if the heap base address should be randomized.
   296  	// See comment in mallocinit for how the randomization is performed.
   297  	randomizeHeapBase = goexperiment.RandomizedHeapBase64 && goarch.PtrSize == 8 && !isSbrkPlatform && !raceenabled && !msanenabled && !asanenabled
   298  
   299  	// randHeapAddrBits is the number of address bits usable by the randomized
   300  	// heap base. heapAddrBits is 48 on most platforms, but we only use 47 of
   301  	// those bits in order to provide a good amount of room for the heap to
   302  	// grow contiguously. On amd64, there are 48 bits, but the top bit is sign
   303  	// extended, so we throw away another bit, just to be safe.
   304  	randHeapAddrBits = heapAddrBits - 1 - goarch.IsAmd64
   305  
   306  	// randHeapBasePrefixMask clears the top byte of the randomized heap base
   307  	// address -- the byte hint generation replaces with randHeapBasePrefix+i.
   308  	// The prefix occupies bits [randHeapAddrBits-8, randHeapAddrBits), so the
   309  	// mask must be defined from randHeapAddrBits, not heapAddrBits: a wider
   310  	// mask would let stray randHeapBase bits overlap the prefix byte in the
   311  	// OR that hint generation performs, and wherever such a stray bit is 1,
   312  	// the corresponding bit of every generated prefix is forced to 1,
   313  	// collapsing distinct prefixes into duplicate hint addresses.
   314  	randHeapBasePrefixMask = ^uintptr(0xff << (randHeapAddrBits - 8))
   315  )
   316  
   317  // physPageSize is the size in bytes of the OS's physical pages.
   318  // Mapping and unmapping operations must be done at multiples of
   319  // physPageSize.
   320  //
   321  // This must be set by the OS init code (typically in osinit) before
   322  // mallocinit.
   323  var physPageSize uintptr
   324  
   325  // physHugePageSize is the size in bytes of the OS's default physical huge
   326  // page size whose allocation is opaque to the application. It is assumed
   327  // and verified to be a power of two.
   328  //
   329  // If set, this must be set by the OS init code (typically in osinit) before
   330  // mallocinit. However, setting it at all is optional, and leaving the default
   331  // value is always safe (though potentially less efficient).
   332  //
   333  // Since physHugePageSize is always assumed to be a power of two,
   334  // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
   335  // The purpose of physHugePageShift is to avoid doing divisions in
   336  // performance critical functions.
   337  var (
   338  	physHugePageSize  uintptr
   339  	physHugePageShift uint
   340  )
   341  
   342  var (
   343  	// heapRandSeed is a random value that is populated in mallocinit if
   344  	// randomizeHeapBase is set. It is used in mallocinit, and mheap.grow, to
   345  	// randomize the base heap address.
   346  	heapRandSeed              uintptr
   347  	heapRandSeedBitsRemaining int
   348  )
   349  
   350  func nextHeapRandBits(bits int) uintptr {
   351  	if bits > heapRandSeedBitsRemaining {
   352  		throw("not enough heapRandSeed bits remaining")
   353  	}
   354  	r := heapRandSeed >> (64 - bits)
   355  	heapRandSeed <<= bits
   356  	heapRandSeedBitsRemaining -= bits
   357  	return r
   358  }
   359  
   360  func mallocinit() {
   361  	if gc.SizeClassToSize[tinySizeClass] != maxTinySize {
   362  		throw("bad TinySizeClass")
   363  	}
   364  
   365  	if heapArenaBitmapWords&(heapArenaBitmapWords-1) != 0 {
   366  		// heapBits expects modular arithmetic on bitmap
   367  		// addresses to work.
   368  		throw("heapArenaBitmapWords not a power of 2")
   369  	}
   370  
   371  	// Check physPageSize.
   372  	if physPageSize == 0 {
   373  		// The OS init code failed to fetch the physical page size.
   374  		throw("failed to get system page size")
   375  	}
   376  	if physPageSize > maxPhysPageSize {
   377  		print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n")
   378  		throw("bad system page size")
   379  	}
   380  	if physPageSize < minPhysPageSize {
   381  		print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
   382  		throw("bad system page size")
   383  	}
   384  	if physPageSize&(physPageSize-1) != 0 {
   385  		print("system page size (", physPageSize, ") must be a power of 2\n")
   386  		throw("bad system page size")
   387  	}
   388  	if physHugePageSize&(physHugePageSize-1) != 0 {
   389  		print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
   390  		throw("bad system huge page size")
   391  	}
   392  	if physHugePageSize > maxPhysHugePageSize {
   393  		// physHugePageSize is greater than the maximum supported huge page size.
   394  		// Don't throw here, like in the other cases, since a system configured
   395  		// in this way isn't wrong, we just don't have the code to support them.
   396  		// Instead, silently set the huge page size to zero.
   397  		physHugePageSize = 0
   398  	}
   399  	if physHugePageSize != 0 {
   400  		// Since physHugePageSize is a power of 2, it suffices to increase
   401  		// physHugePageShift until 1<<physHugePageShift == physHugePageSize.
   402  		for 1<<physHugePageShift != physHugePageSize {
   403  			physHugePageShift++
   404  		}
   405  	}
   406  	if pagesPerArena%pagesPerSpanRoot != 0 {
   407  		print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerSpanRoot (", pagesPerSpanRoot, ")\n")
   408  		throw("bad pagesPerSpanRoot")
   409  	}
   410  	if pagesPerArena%pagesPerReclaimerChunk != 0 {
   411  		print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerReclaimerChunk (", pagesPerReclaimerChunk, ")\n")
   412  		throw("bad pagesPerReclaimerChunk")
   413  	}
   414  	// Check that the minimum size (exclusive) for a malloc header is also
   415  	// a size class boundary. This is important to making sure checks align
   416  	// across different parts of the runtime.
   417  	//
   418  	// While we're here, also check to make sure all these size classes'
   419  	// span sizes are one page. Some code relies on this.
   420  	minSizeForMallocHeaderIsSizeClass := false
   421  	sizeClassesUpToMinSizeForMallocHeaderAreOnePage := true
   422  	for i := 0; i < len(gc.SizeClassToSize); i++ {
   423  		if gc.SizeClassToNPages[i] > 1 {
   424  			sizeClassesUpToMinSizeForMallocHeaderAreOnePage = false
   425  		}
   426  		if gc.MinSizeForMallocHeader == uintptr(gc.SizeClassToSize[i]) {
   427  			minSizeForMallocHeaderIsSizeClass = true
   428  			break
   429  		}
   430  	}
   431  	if !minSizeForMallocHeaderIsSizeClass {
   432  		throw("min size of malloc header is not a size class boundary")
   433  	}
   434  	if !sizeClassesUpToMinSizeForMallocHeaderAreOnePage {
   435  		throw("expected all size classes up to min size for malloc header to fit in one-page spans")
   436  	}
   437  	// Check that the pointer bitmap for all small sizes without a malloc header
   438  	// fits in a word.
   439  	if gc.MinSizeForMallocHeader/goarch.PtrSize > 8*goarch.PtrSize {
   440  		throw("max pointer/scan bitmap size for headerless objects is too large")
   441  	}
   442  
   443  	if minTagBits > tagBits {
   444  		throw("tagBits too small")
   445  	}
   446  
   447  	// Initialize the heap.
   448  	mheap_.init()
   449  	mcache0 = allocmcache()
   450  	lockInit(&gcBitsArenas.lock, lockRankGcBitsArenas)
   451  	lockInit(&profInsertLock, lockRankProfInsert)
   452  	lockInit(&profBlockLock, lockRankProfBlock)
   453  	lockInit(&profMemActiveLock, lockRankProfMemActive)
   454  	for i := range profMemFutureLock {
   455  		lockInit(&profMemFutureLock[i], lockRankProfMemFuture)
   456  	}
   457  	lockInit(&globalAlloc.mutex, lockRankGlobalAlloc)
   458  
   459  	// Create initial arena growth hints.
   460  	if isSbrkPlatform {
   461  		// Don't generate hints on sbrk platforms. We can
   462  		// only grow the break sequentially.
   463  	} else if goarch.PtrSize == 8 {
   464  		// On a 64-bit machine, we pick the following hints
   465  		// because:
   466  		//
   467  		// 1. Starting from the middle of the address space
   468  		// makes it easier to grow out a contiguous range
   469  		// without running in to some other mapping.
   470  		//
   471  		// 2. This makes Go heap addresses more easily
   472  		// recognizable when debugging.
   473  		//
   474  		// 3. Stack scanning in gccgo is still conservative,
   475  		// so it's important that addresses be distinguishable
   476  		// from other data.
   477  		//
   478  		// Starting at 0x00c0 means that the valid memory addresses
   479  		// will begin 0x00c0, 0x00c1, ...
   480  		// In little-endian, that's c0 00, c1 00, ... None of those are valid
   481  		// UTF-8 sequences, and they are otherwise as far away from
   482  		// ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
   483  		// addresses. An earlier attempt to use 0x11f8 caused out of memory errors
   484  		// on OS X during thread allocations.  0x00c0 causes conflicts with
   485  		// AddressSanitizer which reserves all memory up to 0x0100.
   486  		// These choices reduce the odds of a conservative garbage collector
   487  		// not collecting memory because some non-pointer block of memory
   488  		// had a bit pattern that matched a memory address.
   489  		//
   490  		// However, on arm64, we ignore all this advice above and slam the
   491  		// allocation at 0x40 << 32 because when using 4k pages with 3-level
   492  		// translation buffers, the user address space is limited to 39 bits
   493  		// On ios/arm64, the address space is even smaller.
   494  		//
   495  		// On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
   496  		// processes.
   497  		//
   498  		// Space mapped for user arenas comes immediately after the range
   499  		// originally reserved for the regular heap when race mode is not
   500  		// enabled because user arena chunks can never be used for regular heap
   501  		// allocations and we want to avoid fragmenting the address space.
   502  		//
   503  		// In race mode we have no choice but to just use the same hints because
   504  		// the race detector requires that the heap be mapped contiguously.
   505  		//
   506  		// If randomizeHeapBase is set, we attempt to randomize the base address
   507  		// as much as possible. We do this by generating a random uint64 via
   508  		// bootstrapRand and using it's bits to randomize portions of the base
   509  		// address as follows:
   510  		//   * We first generate a random heapArenaBytes aligned address that we use for
   511  		//     generating the hints.
   512  		//   * On the first call to mheap.grow, we then generate a random PallocChunkBytes
   513  		//     aligned offset into the mmap'd heap region, which we use as the base for
   514  		//     the heap region.
   515  		//   * We then select a page offset in that PallocChunkBytes region to start the
   516  		//     heap at, and mark all the pages up to that offset as allocated.
   517  		//
   518  		// Our final randomized "heap base address" becomes the first byte of
   519  		// the first available page returned by the page allocator. This results
   520  		// in an address with at least heapAddrBits-gc.PageShift-2-(1*goarch.IsAmd64)
   521  		// bits of entropy.
   522  
   523  		var randHeapBase uintptr
   524  		var randHeapBasePrefix byte
   525  		if randomizeHeapBase {
   526  			// Generate a random value, and take the bottom heapAddrBits-logHeapArenaBytes
   527  			// bits, using them as the top bits for randHeapBase.
   528  			heapRandSeed, heapRandSeedBitsRemaining = uintptr(bootstrapRand()), 64
   529  
   530  			topBits := (randHeapAddrBits - logHeapArenaBytes)
   531  			randHeapBase = nextHeapRandBits(topBits) << (randHeapAddrBits - topBits)
   532  			randHeapBase = alignUp(randHeapBase, heapArenaBytes)
   533  			if GOOS == "aix" {
   534  				randHeapBase += arenaBaseOffset
   535  			}
   536  			randHeapBasePrefix = byte(randHeapBase >> (randHeapAddrBits - 8))
   537  		}
   538  
   539  		var vmaSize int
   540  		if GOARCH == "riscv64" {
   541  			// Identify which memory layout is in use based on the system
   542  			// stack address, knowing that the bottom half of virtual memory
   543  			// is user space. This should result in 39, 48 or 57. It may be
   544  			// possible to use RISCV_HWPROBE_KEY_HIGHEST_VIRT_ADDRESS at some
   545  			// point in the future - for now use the system stack address.
   546  			vmaSize = sys.Len64(uint64(getg().m.g0.stack.hi)) + 1
   547  			if raceenabled && vmaSize != 39 && vmaSize != 48 {
   548  				println("vma size = ", vmaSize)
   549  				throw("riscv64 vma size is unknown and race mode is enabled")
   550  			}
   551  		}
   552  
   553  		for i := 0x7f; i >= 0; i-- {
   554  			var p uintptr
   555  			switch {
   556  			case raceenabled && GOARCH == "riscv64" && vmaSize == 39:
   557  				p = uintptr(i)<<28 | uintptrMask&(0x0013<<28)
   558  				if p >= uintptrMask&0x000f00000000 {
   559  					continue
   560  				}
   561  			case raceenabled:
   562  				// The TSAN runtime requires the heap
   563  				// to be in the range [0x00c000000000,
   564  				// 0x00e000000000).
   565  				p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
   566  				if p >= uintptrMask&0x00e000000000 {
   567  					continue
   568  				}
   569  			case randomizeHeapBase:
   570  				prefix := uintptr(randHeapBasePrefix+byte(i)) << (randHeapAddrBits - 8)
   571  				if GOOS == "aix" {
   572  					p = arenaBaseOffset + (prefix | ((randHeapBase - arenaBaseOffset) & randHeapBasePrefixMask))
   573  				} else {
   574  					p = prefix | (randHeapBase & randHeapBasePrefixMask)
   575  				}
   576  			case GOARCH == "arm64" && GOOS == "ios":
   577  				p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
   578  			case GOARCH == "arm64":
   579  				p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
   580  			case GOARCH == "riscv64" && vmaSize == 39:
   581  				p = uintptr(i)<<32 | uintptrMask&(0x0013<<28)
   582  			case GOOS == "aix":
   583  				if i == 0 {
   584  					// We don't use addresses directly after 0x0A00000000000000
   585  					// to avoid collisions with others mmaps done by non-go programs.
   586  					continue
   587  				}
   588  				p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
   589  			default:
   590  				p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
   591  			}
   592  			// Switch to generating hints for user arenas if we've gone
   593  			// through about half the hints. In race mode, take only about
   594  			// a quarter; we don't have very much space to work with.
   595  			hintList := &mheap_.arenaHints
   596  			if (!raceenabled && i > 0x3f) || (raceenabled && i > 0x5f) {
   597  				hintList = &mheap_.userArena.arenaHints
   598  			}
   599  			hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
   600  			hint.addr = p
   601  			hint.next, *hintList = *hintList, hint
   602  		}
   603  	} else {
   604  		// On a 32-bit machine, we're much more concerned
   605  		// about keeping the usable heap contiguous.
   606  		// Hence:
   607  		//
   608  		// 1. We reserve space for all heapArenas up front so
   609  		// they don't get interleaved with the heap. They're
   610  		// ~258MB, so this isn't too bad. (We could reserve a
   611  		// smaller amount of space up front if this is a
   612  		// problem.)
   613  		//
   614  		// 2. We hint the heap to start right above the end of
   615  		// the binary so we have the best chance of keeping it
   616  		// contiguous.
   617  		//
   618  		// 3. We try to stake out a reasonably large initial
   619  		// heap reservation.
   620  
   621  		const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
   622  		meta := uintptr(sysReserve(nil, arenaMetaSize, "heap reservation"))
   623  		if meta != 0 {
   624  			mheap_.heapArenaAlloc.init(meta, arenaMetaSize, true)
   625  		}
   626  
   627  		// We want to start the arena low, but if we're linked
   628  		// against C code, it's possible global constructors
   629  		// have called malloc and adjusted the process' brk.
   630  		// Query the brk so we can avoid trying to map the
   631  		// region over it (which will cause the kernel to put
   632  		// the region somewhere else, likely at a high
   633  		// address).
   634  		procBrk := sbrk0()
   635  
   636  		// If we ask for the end of the data segment but the
   637  		// operating system requires a little more space
   638  		// before we can start allocating, it will give out a
   639  		// slightly higher pointer. Except QEMU, which is
   640  		// buggy, as usual: it won't adjust the pointer
   641  		// upward. So adjust it upward a little bit ourselves:
   642  		// 1/4 MB to get away from the running binary image.
   643  		p := firstmoduledata.end
   644  		if p < procBrk {
   645  			p = procBrk
   646  		}
   647  		if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
   648  			p = mheap_.heapArenaAlloc.end
   649  		}
   650  		p = alignUp(p+(256<<10), heapArenaBytes)
   651  		// Because we're worried about fragmentation on
   652  		// 32-bit, we try to make a large initial reservation.
   653  		arenaSizes := []uintptr{
   654  			512 << 20,
   655  			256 << 20,
   656  			128 << 20,
   657  		}
   658  		for _, arenaSize := range arenaSizes {
   659  			a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes, "heap reservation")
   660  			if a != nil {
   661  				mheap_.arena.init(uintptr(a), size, false)
   662  				p = mheap_.arena.end // For hint below
   663  				break
   664  			}
   665  		}
   666  		hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
   667  		hint.addr = p
   668  		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
   669  
   670  		// Place the hint for user arenas just after the large reservation.
   671  		//
   672  		// While this potentially competes with the hint above, in practice we probably
   673  		// aren't going to be getting this far anyway on 32-bit platforms.
   674  		userArenaHint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
   675  		userArenaHint.addr = p
   676  		userArenaHint.next, mheap_.userArena.arenaHints = mheap_.userArena.arenaHints, userArenaHint
   677  	}
   678  	// Initialize the memory limit here because the allocator is going to look at it
   679  	// but we haven't called gcinit yet and we're definitely going to allocate memory before then.
   680  	gcController.memoryLimit.Store(math.MaxInt64)
   681  }
   682  
   683  // sysAlloc allocates heap arena space for at least n bytes. The
   684  // returned pointer is always heapArenaBytes-aligned and backed by
   685  // h.arenas metadata. The returned size is always a multiple of
   686  // heapArenaBytes. sysAlloc returns nil on failure.
   687  // There is no corresponding free function.
   688  //
   689  // hintList is a list of hint addresses for where to allocate new
   690  // heap arenas. It must be non-nil.
   691  //
   692  // sysAlloc returns a memory region in the Reserved state. This region must
   693  // be transitioned to Prepared and then Ready before use.
   694  //
   695  // arenaList is the list the arena should be added to.
   696  //
   697  // h must be locked.
   698  func (h *mheap) sysAlloc(n uintptr, hintList **arenaHint, arenaList *[]arenaIdx) (v unsafe.Pointer, size uintptr) {
   699  	assertLockHeld(&h.lock)
   700  
   701  	n = alignUp(n, heapArenaBytes)
   702  
   703  	if hintList == &h.arenaHints {
   704  		// First, try the arena pre-reservation.
   705  		// Newly-used mappings are considered released.
   706  		//
   707  		// Only do this if we're using the regular heap arena hints.
   708  		// This behavior is only for the heap.
   709  		v = h.arena.alloc(n, heapArenaBytes, &gcController.heapReleased, "heap")
   710  		if v != nil {
   711  			size = n
   712  			goto mapped
   713  		}
   714  	}
   715  
   716  	// Try to grow the heap at a hint address.
   717  	for *hintList != nil {
   718  		hint := *hintList
   719  		p := hint.addr
   720  		if hint.down {
   721  			p -= n
   722  		}
   723  		if p+n < p {
   724  			// We can't use this, so don't ask.
   725  			v = nil
   726  		} else if arenaIndex(p+n-1) >= 1<<arenaBits {
   727  			// Outside addressable heap. Can't use.
   728  			v = nil
   729  		} else {
   730  			v = sysReserve(unsafe.Pointer(p), n, "heap reservation")
   731  		}
   732  		if p == uintptr(v) && v != nil {
   733  			// Success. Update the hint.
   734  			if !hint.down {
   735  				p += n
   736  			}
   737  			hint.addr = p
   738  			size = n
   739  			break
   740  		}
   741  		// Failed. Discard this hint and try the next.
   742  		//
   743  		// TODO: This would be cleaner if sysReserve could be
   744  		// told to only return the requested address. In
   745  		// particular, this is already how Windows behaves, so
   746  		// it would simplify things there.
   747  		if v != nil {
   748  			sysUnreserve(v, n)
   749  		}
   750  		*hintList = hint.next
   751  		h.arenaHintAlloc.free(unsafe.Pointer(hint))
   752  	}
   753  
   754  	if size == 0 {
   755  		if raceenabled {
   756  			// The race detector assumes the heap lives in
   757  			// [0x00c000000000, 0x00e000000000), but we
   758  			// just ran out of hints in this region. Give
   759  			// a nice failure.
   760  			throw("too many address space collisions for -race mode")
   761  		}
   762  
   763  		// All of the hints failed, so we'll take any
   764  		// (sufficiently aligned) address the kernel will give
   765  		// us.
   766  		v, size = sysReserveAligned(nil, n, heapArenaBytes, "heap")
   767  		if v == nil {
   768  			return nil, 0
   769  		}
   770  
   771  		// Create new hints for extending this region.
   772  		hint := (*arenaHint)(h.arenaHintAlloc.alloc())
   773  		hint.addr, hint.down = uintptr(v), true
   774  		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
   775  		hint = (*arenaHint)(h.arenaHintAlloc.alloc())
   776  		hint.addr = uintptr(v) + size
   777  		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
   778  	}
   779  
   780  	// Check for bad pointers or pointers we can't use.
   781  	{
   782  		var bad string
   783  		p := uintptr(v)
   784  		if p+size < p {
   785  			bad = "region exceeds uintptr range"
   786  		} else if arenaIndex(p) >= 1<<arenaBits {
   787  			bad = "base outside usable address space"
   788  		} else if arenaIndex(p+size-1) >= 1<<arenaBits {
   789  			bad = "end outside usable address space"
   790  		}
   791  		if bad != "" {
   792  			// This should be impossible on most architectures,
   793  			// but it would be really confusing to debug.
   794  			print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
   795  			throw("memory reservation exceeds address space limit")
   796  		}
   797  	}
   798  
   799  	if uintptr(v)&(heapArenaBytes-1) != 0 {
   800  		throw("misrounded allocation in sysAlloc")
   801  	}
   802  
   803  mapped:
   804  	if valgrindenabled {
   805  		valgrindCreateMempool(v)
   806  		valgrindMakeMemNoAccess(v, size)
   807  	}
   808  
   809  	// Create arena metadata.
   810  	for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
   811  		l2 := h.arenas[ri.l1()]
   812  		if l2 == nil {
   813  			// Allocate an L2 arena map.
   814  			//
   815  			// Use sysAllocOS instead of sysAlloc or persistentalloc because there's no
   816  			// statistic we can comfortably account for this space in. With this structure,
   817  			// we rely on demand paging to avoid large overheads, but tracking which memory
   818  			// is paged in is too expensive. Trying to account for the whole region means
   819  			// that it will appear like an enormous memory overhead in statistics, even though
   820  			// it is not.
   821  			l2 = (*[1 << arenaL2Bits]*heapArena)(sysAllocOS(unsafe.Sizeof(*l2), "heap index"))
   822  			if l2 == nil {
   823  				throw("out of memory allocating heap arena map")
   824  			}
   825  			if h.arenasHugePages {
   826  				sysHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2))
   827  			} else {
   828  				sysNoHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2))
   829  			}
   830  			atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
   831  		}
   832  
   833  		if l2[ri.l2()] != nil {
   834  			throw("arena already initialized")
   835  		}
   836  		var r *heapArena
   837  		r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys, "heap metadata"))
   838  		if r == nil {
   839  			r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
   840  			if r == nil {
   841  				throw("out of memory allocating heap arena metadata")
   842  			}
   843  		}
   844  
   845  		// Register the arena in allArenas if requested.
   846  		if len((*arenaList)) == cap((*arenaList)) {
   847  			size := 2 * uintptr(cap((*arenaList))) * goarch.PtrSize
   848  			if size == 0 {
   849  				size = physPageSize
   850  			}
   851  			newArray := (*notInHeap)(persistentalloc(size, goarch.PtrSize, &memstats.gcMiscSys))
   852  			if newArray == nil {
   853  				throw("out of memory allocating allArenas")
   854  			}
   855  			oldSlice := (*arenaList)
   856  			*(*notInHeapSlice)(unsafe.Pointer(&(*arenaList))) = notInHeapSlice{newArray, len((*arenaList)), int(size / goarch.PtrSize)}
   857  			copy((*arenaList), oldSlice)
   858  			// Do not free the old backing array because
   859  			// there may be concurrent readers. Since we
   860  			// double the array each time, this can lead
   861  			// to at most 2x waste.
   862  		}
   863  		(*arenaList) = (*arenaList)[:len((*arenaList))+1]
   864  		(*arenaList)[len((*arenaList))-1] = ri
   865  
   866  		// Store atomically just in case an object from the
   867  		// new heap arena becomes visible before the heap lock
   868  		// is released (which shouldn't happen, but there's
   869  		// little downside to this).
   870  		atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
   871  	}
   872  
   873  	// Tell the race detector about the new heap memory.
   874  	if raceenabled {
   875  		racemapshadow(v, size)
   876  	}
   877  
   878  	return
   879  }
   880  
   881  // enableMetadataHugePages enables huge pages for various sources of heap metadata.
   882  //
   883  // A note on latency: for sufficiently small heaps (<10s of GiB) this function will take constant
   884  // time, but may take time proportional to the size of the mapped heap beyond that.
   885  //
   886  // This function is idempotent.
   887  //
   888  // The heap lock must not be held over this operation, since it will briefly acquire
   889  // the heap lock.
   890  //
   891  // Must be called on the system stack because it acquires the heap lock.
   892  //
   893  //go:systemstack
   894  func (h *mheap) enableMetadataHugePages() {
   895  	// Enable huge pages for page structure.
   896  	h.pages.enableChunkHugePages()
   897  
   898  	// Grab the lock and set arenasHugePages if it's not.
   899  	//
   900  	// Once arenasHugePages is set, all new L2 entries will be eligible for
   901  	// huge pages. We'll set all the old entries after we release the lock.
   902  	lock(&h.lock)
   903  	if h.arenasHugePages {
   904  		unlock(&h.lock)
   905  		return
   906  	}
   907  	h.arenasHugePages = true
   908  	unlock(&h.lock)
   909  
   910  	// N.B. The arenas L1 map is quite small on all platforms, so it's fine to
   911  	// just iterate over the whole thing.
   912  	for i := range h.arenas {
   913  		l2 := (*[1 << arenaL2Bits]*heapArena)(atomic.Loadp(unsafe.Pointer(&h.arenas[i])))
   914  		if l2 == nil {
   915  			continue
   916  		}
   917  		sysHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2))
   918  	}
   919  }
   920  
   921  // base address for all 0-byte allocations
   922  var zerobase uintptr
   923  
   924  // nextFreeFast returns the next free object if one is quickly available.
   925  // Otherwise it returns 0.
   926  func nextFreeFast(s *mspan) gclinkptr {
   927  	theBit := sys.TrailingZeros64(s.allocCache) // Is there a free object in the allocCache?
   928  	if theBit < 64 {
   929  		result := s.freeindex + uint16(theBit)
   930  		if result < s.nelems {
   931  			freeidx := result + 1
   932  			if freeidx%64 == 0 && freeidx != s.nelems {
   933  				return 0
   934  			}
   935  			s.allocCache >>= uint(theBit + 1)
   936  			s.freeindex = freeidx
   937  			s.allocCount++
   938  			return gclinkptr(uintptr(result)*s.elemsize + s.base())
   939  		}
   940  	}
   941  	return 0
   942  }
   943  
   944  // nextFree returns the next free object from the cached span if one is available.
   945  // Otherwise it refills the cache with a span with an available object and
   946  // returns that object along with a flag indicating that this was a heavy
   947  // weight allocation. If it is a heavy weight allocation the caller must
   948  // determine whether a new GC cycle needs to be started or if the GC is active
   949  // whether this goroutine needs to assist the GC.
   950  //
   951  // Must run in a non-preemptible context since otherwise the owner of
   952  // c could change.
   953  func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, checkGCTrigger bool) {
   954  	s = c.alloc[spc]
   955  	checkGCTrigger = false
   956  	freeIndex := s.nextFreeIndex()
   957  	if freeIndex == s.nelems {
   958  		// The span is full.
   959  		if s.allocCount != s.nelems {
   960  			println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
   961  			throw("s.allocCount != s.nelems && freeIndex == s.nelems")
   962  		}
   963  		c.refill(spc)
   964  		checkGCTrigger = true
   965  		s = c.alloc[spc]
   966  
   967  		freeIndex = s.nextFreeIndex()
   968  	}
   969  
   970  	if freeIndex >= s.nelems {
   971  		throw("freeIndex is not valid")
   972  	}
   973  
   974  	v = gclinkptr(uintptr(freeIndex)*s.elemsize + s.base())
   975  	s.allocCount++
   976  	if s.allocCount > s.nelems {
   977  		println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
   978  		throw("s.allocCount > s.nelems")
   979  	}
   980  	return
   981  }
   982  
   983  // doubleCheckMalloc enables a bunch of extra checks to malloc to double-check
   984  // that various invariants are upheld.
   985  //
   986  // We might consider turning these on by default; many of them previously were.
   987  // They account for a few % of mallocgc's cost though, which does matter somewhat
   988  // at scale. (When testing changes to malloc, consider enabling this, and also
   989  // some function-local 'doubleCheck' consts such as in mbitmap.go currently.)
   990  const doubleCheckMalloc = false
   991  
   992  // sizeSpecializedMallocEnabled is the set of conditions where we enable the size-specialized
   993  // mallocgc implementation: none of the sanitizers should be enabled. The tables used to select
   994  // the size-specialized malloc function do not compile properly on plan9, so
   995  // size-specialized malloc is also disabled on plan9.
   996  const sizeSpecializedMallocEnabled = GOOS != "plan9" && !asanenabled && !raceenabled && !msanenabled && !valgrindenabled
   997  
   998  // runtimeFreegcEnabled is the set of conditions where we enable the runtime.freegc
   999  // implementation and the corresponding allocation-related changes: the experiment must be
  1000  // enabled, and none of the memory sanitizers should be enabled. We allow the race detector,
  1001  // in contrast to sizeSpecializedMallocEnabled.
  1002  // TODO(thepudds): it would be nice to check Valgrind integration, though there are some hints
  1003  // there might not be any canned tests in tree for Go's integration with Valgrind.
  1004  const runtimeFreegcEnabled = goexperiment.RuntimeFreegc && !asanenabled && !msanenabled && !valgrindenabled
  1005  
  1006  // Allocate an object of size bytes.
  1007  // Small objects are allocated from the per-P cache's free lists.
  1008  // Large objects (> 32 kB) are allocated straight from the heap.
  1009  //
  1010  // mallocgc should be an internal detail,
  1011  // but widely used packages access it using linkname.
  1012  // Notable members of the hall of shame include:
  1013  //   - github.com/bytedance/gopkg
  1014  //   - github.com/bytedance/sonic
  1015  //   - github.com/cloudwego/frugal
  1016  //   - github.com/cockroachdb/cockroach
  1017  //   - github.com/cockroachdb/pebble
  1018  //   - github.com/ugorji/go/codec
  1019  //
  1020  // Do not remove or change the type signature.
  1021  // See go.dev/issue/67401.
  1022  //
  1023  //go:linkname mallocgc
  1024  func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
  1025  	if doubleCheckMalloc {
  1026  		if gcphase == _GCmarktermination {
  1027  			throw("mallocgc called with gcphase == _GCmarktermination")
  1028  		}
  1029  	}
  1030  
  1031  	// Short-circuit zero-sized allocation requests.
  1032  	if size == 0 {
  1033  		return unsafe.Pointer(&zerobase)
  1034  	}
  1035  
  1036  	if sizeSpecializedMallocEnabled && size < uintptr(len(mallocNoScanTable)) {
  1037  		if typ == nil || !typ.Pointers() {
  1038  			if size >= maxTinySize {
  1039  				return mallocNoScanTable[size](size, typ, needzero)
  1040  			}
  1041  			return mallocgcTinySC2(size, typ, needzero)
  1042  		} else {
  1043  			if !needzero {
  1044  				throw("objects with pointers must be zeroed")
  1045  			}
  1046  			return mallocScanTable[size](size, typ, needzero)
  1047  		}
  1048  	}
  1049  
  1050  	// It's possible for any malloc to trigger sweeping, which may in
  1051  	// turn queue finalizers. Record this dynamic lock edge.
  1052  	// N.B. Compiled away if lockrank experiment is not enabled.
  1053  	lockRankMayQueueFinalizer()
  1054  
  1055  	// Pre-malloc debug hooks.
  1056  	if debug.malloc {
  1057  		if x := preMallocgcDebug(size, typ); x != nil {
  1058  			return x
  1059  		}
  1060  	}
  1061  
  1062  	// For ASAN, we allocate extra memory around each allocation called the "redzone."
  1063  	// These "redzones" are marked as unaddressable.
  1064  	var asanRZ uintptr
  1065  	if asanenabled {
  1066  		asanRZ = redZoneSize(size)
  1067  		size += asanRZ
  1068  	}
  1069  
  1070  	// Assist the GC if needed. (On the reuse path, we currently compensate for this;
  1071  	// changes here might require changes there.)
  1072  	if gcBlackenEnabled != 0 {
  1073  		deductAssistCredit(size)
  1074  	}
  1075  
  1076  	// Actually do the allocation.
  1077  	var x unsafe.Pointer
  1078  	var elemsize uintptr
  1079  	if sizeSpecializedMallocEnabled {
  1080  		if size <= maxSmallSize-gc.MallocHeaderSize {
  1081  			if typ == nil || !typ.Pointers() {
  1082  				x, elemsize = mallocgcSmallNoscan(size, typ, needzero)
  1083  			} else {
  1084  				if !needzero {
  1085  					throw("objects with pointers must be zeroed")
  1086  				}
  1087  				if heapBitsInSpan(size) {
  1088  					x, elemsize = mallocgcSmallScanNoHeader(size, typ)
  1089  				} else {
  1090  					x, elemsize = mallocgcSmallScanHeader(size, typ)
  1091  				}
  1092  			}
  1093  		} else {
  1094  			x, elemsize = mallocgcLarge(size, typ, needzero)
  1095  		}
  1096  	} else {
  1097  		if size <= maxSmallSize-gc.MallocHeaderSize {
  1098  			if typ == nil || !typ.Pointers() {
  1099  				// tiny allocations might be kept alive by other co-located values.
  1100  				// Make sure secret allocations get zeroed by avoiding the tiny allocator
  1101  				// See go.dev/issue/76356
  1102  				gp := getg()
  1103  				if size < maxTinySize && gp.secret == 0 {
  1104  					x, elemsize = mallocgcTiny(size, typ)
  1105  				} else {
  1106  					x, elemsize = mallocgcSmallNoscan(size, typ, needzero)
  1107  				}
  1108  			} else {
  1109  				if !needzero {
  1110  					throw("objects with pointers must be zeroed")
  1111  				}
  1112  				if heapBitsInSpan(size) {
  1113  					x, elemsize = mallocgcSmallScanNoHeader(size, typ)
  1114  				} else {
  1115  					x, elemsize = mallocgcSmallScanHeader(size, typ)
  1116  				}
  1117  			}
  1118  		} else {
  1119  			x, elemsize = mallocgcLarge(size, typ, needzero)
  1120  		}
  1121  	}
  1122  
  1123  	gp := getg()
  1124  	if goexperiment.RuntimeSecret && gp.secret > 0 {
  1125  		// Mark any object allocated while in secret mode as secret.
  1126  		// This ensures we zero it immediately when freeing it.
  1127  		addSecret(x, size)
  1128  	}
  1129  
  1130  	// Notify sanitizers, if enabled.
  1131  	if raceenabled {
  1132  		racemalloc(x, size-asanRZ)
  1133  	}
  1134  	if msanenabled {
  1135  		msanmalloc(x, size-asanRZ)
  1136  	}
  1137  	if asanenabled {
  1138  		// Poison the space between the end of the requested size of x
  1139  		// and the end of the slot. Unpoison the requested allocation.
  1140  		asanpoison(unsafe.Add(x, size-asanRZ), asanRZ)
  1141  		asanunpoison(x, size-asanRZ)
  1142  	}
  1143  	if valgrindenabled {
  1144  		valgrindMalloc(x, size-asanRZ)
  1145  	}
  1146  
  1147  	// Adjust our GC assist debt to account for internal fragmentation.
  1148  	if gcBlackenEnabled != 0 && elemsize != 0 {
  1149  		if assistG := getg().m.curg; assistG != nil {
  1150  			assistG.gcAssistBytes -= int64(elemsize - size)
  1151  		}
  1152  	}
  1153  
  1154  	// Post-malloc debug hooks.
  1155  	if debug.malloc {
  1156  		postMallocgcDebug(x, elemsize, typ)
  1157  	}
  1158  	return x
  1159  }
  1160  
  1161  func mallocgcTiny(size uintptr, typ *_type) (unsafe.Pointer, uintptr) {
  1162  	// Set mp.mallocing to keep from being preempted by GC.
  1163  	mp := acquirem()
  1164  	if doubleCheckMalloc {
  1165  		if mp.mallocing != 0 {
  1166  			throw("malloc deadlock")
  1167  		}
  1168  		if mp.gsignal == getg() {
  1169  			throw("malloc during signal")
  1170  		}
  1171  		if typ != nil && typ.Pointers() {
  1172  			throw("expected noscan for tiny alloc")
  1173  		}
  1174  	}
  1175  	mp.mallocing = 1
  1176  
  1177  	// Tiny allocator.
  1178  	//
  1179  	// Tiny allocator combines several tiny allocation requests
  1180  	// into a single memory block. The resulting memory block
  1181  	// is freed when all subobjects are unreachable. The subobjects
  1182  	// must be noscan (don't have pointers), this ensures that
  1183  	// the amount of potentially wasted memory is bounded.
  1184  	//
  1185  	// Size of the memory block used for combining (maxTinySize) is tunable.
  1186  	// Current setting is 16 bytes, which relates to 2x worst case memory
  1187  	// wastage (when all but one subobjects are unreachable).
  1188  	// 8 bytes would result in no wastage at all, but provides less
  1189  	// opportunities for combining.
  1190  	// 32 bytes provides more opportunities for combining,
  1191  	// but can lead to 4x worst case wastage.
  1192  	// The best case winning is 8x regardless of block size.
  1193  	//
  1194  	// Objects obtained from tiny allocator must not be freed explicitly.
  1195  	// So when an object will be freed explicitly, we ensure that
  1196  	// its size >= maxTinySize.
  1197  	//
  1198  	// SetFinalizer has a special case for objects potentially coming
  1199  	// from tiny allocator, it such case it allows to set finalizers
  1200  	// for an inner byte of a memory block.
  1201  	//
  1202  	// The main targets of tiny allocator are small strings and
  1203  	// standalone escaping variables. On a json benchmark
  1204  	// the allocator reduces number of allocations by ~12% and
  1205  	// reduces heap size by ~20%.
  1206  	c := getMCache(mp)
  1207  	off := c.tinyoffset
  1208  	// Align tiny pointer for required (conservative) alignment.
  1209  	if size&7 == 0 {
  1210  		off = alignUp(off, 8)
  1211  	} else if goarch.PtrSize == 4 && size == 12 {
  1212  		// Conservatively align 12-byte objects to 8 bytes on 32-bit
  1213  		// systems so that objects whose first field is a 64-bit
  1214  		// value is aligned to 8 bytes and does not cause a fault on
  1215  		// atomic access. See issue 37262.
  1216  		// TODO(mknyszek): Remove this workaround if/when issue 36606
  1217  		// is resolved.
  1218  		off = alignUp(off, 8)
  1219  	} else if size&3 == 0 {
  1220  		off = alignUp(off, 4)
  1221  	} else if size&1 == 0 {
  1222  		off = alignUp(off, 2)
  1223  	}
  1224  	if off+size <= maxTinySize && c.tiny != 0 {
  1225  		// The object fits into existing tiny block.
  1226  		x := unsafe.Pointer(c.tiny + off)
  1227  		c.tinyoffset = off + size
  1228  		c.tinyAllocs++
  1229  		mp.mallocing = 0
  1230  		releasem(mp)
  1231  		return x, 0
  1232  	}
  1233  	// Allocate a new maxTinySize block.
  1234  	checkGCTrigger := false
  1235  	span := c.alloc[tinySpanClass]
  1236  	v := nextFreeFast(span)
  1237  	if v == 0 {
  1238  		v, span, checkGCTrigger = c.nextFree(tinySpanClass)
  1239  	}
  1240  	x := unsafe.Pointer(v)
  1241  	(*[2]uint64)(x)[0] = 0 // Always zero
  1242  	(*[2]uint64)(x)[1] = 0
  1243  	// See if we need to replace the existing tiny block with the new one
  1244  	// based on amount of remaining free space.
  1245  	if !raceenabled && (size < c.tinyoffset || c.tiny == 0) {
  1246  		// Note: disabled when race detector is on, see comment near end of this function.
  1247  		c.tiny = uintptr(x)
  1248  		c.tinyoffset = size
  1249  	}
  1250  
  1251  	// Ensure that the stores above that initialize x to
  1252  	// type-safe memory and set the heap bits occur before
  1253  	// the caller can make x observable to the garbage
  1254  	// collector. Otherwise, on weakly ordered machines,
  1255  	// the garbage collector could follow a pointer to x,
  1256  	// but see uninitialized memory or stale heap bits.
  1257  	publicationBarrier()
  1258  
  1259  	if writeBarrier.enabled {
  1260  		// Allocate black during GC.
  1261  		// All slots hold nil so no scanning is needed.
  1262  		// This may be racing with GC so do it atomically if there can be
  1263  		// a race marking the bit.
  1264  		gcmarknewobject(span, uintptr(x))
  1265  	} else {
  1266  		// Track the last free index before the mark phase. This field
  1267  		// is only used by the garbage collector. During the mark phase
  1268  		// this is used by the conservative scanner to filter out objects
  1269  		// that are both free and recently-allocated. It's safe to do that
  1270  		// because we allocate-black if the GC is enabled. The conservative
  1271  		// scanner produces pointers out of thin air, so without additional
  1272  		// synchronization it might otherwise observe a partially-initialized
  1273  		// object, which could crash the program.
  1274  		span.freeIndexForScan = span.freeindex
  1275  	}
  1276  
  1277  	// Note cache c only valid while m acquired; see #47302
  1278  	//
  1279  	// N.B. Use the full size because that matches how the GC
  1280  	// will update the mem profile on the "free" side.
  1281  	//
  1282  	// TODO(mknyszek): We should really count the header as part
  1283  	// of gc_sys or something. The code below just pretends it is
  1284  	// internal fragmentation and matches the GC's accounting by
  1285  	// using the whole allocation slot.
  1286  	c.nextSample -= int64(span.elemsize)
  1287  	if c.nextSample < 0 || MemProfileRate != c.memProfRate {
  1288  		profilealloc(mp, x, span.elemsize)
  1289  	}
  1290  	mp.mallocing = 0
  1291  	releasem(mp)
  1292  
  1293  	if checkGCTrigger {
  1294  		if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  1295  			gcStart(t)
  1296  		}
  1297  	}
  1298  
  1299  	if raceenabled {
  1300  		// Pad tinysize allocations so they are aligned with the end
  1301  		// of the tinyalloc region. This ensures that any arithmetic
  1302  		// that goes off the top end of the object will be detectable
  1303  		// by checkptr (issue 38872).
  1304  		// Note that we disable tinyalloc when raceenabled for this to work.
  1305  		// TODO: This padding is only performed when the race detector
  1306  		// is enabled. It would be nice to enable it if any package
  1307  		// was compiled with checkptr, but there's no easy way to
  1308  		// detect that (especially at compile time).
  1309  		// TODO: enable this padding for all allocations, not just
  1310  		// tinyalloc ones. It's tricky because of pointer maps.
  1311  		// Maybe just all noscan objects?
  1312  		x = add(x, span.elemsize-size)
  1313  	}
  1314  	return x, span.elemsize
  1315  }
  1316  
  1317  func mallocgcSmallNoscan(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) {
  1318  	// Set mp.mallocing to keep from being preempted by GC.
  1319  	mp := acquirem()
  1320  	if doubleCheckMalloc {
  1321  		if mp.mallocing != 0 {
  1322  			throw("malloc deadlock")
  1323  		}
  1324  		if mp.gsignal == getg() {
  1325  			throw("malloc during signal")
  1326  		}
  1327  		if typ != nil && typ.Pointers() {
  1328  			throw("expected noscan type for noscan alloc")
  1329  		}
  1330  	}
  1331  	mp.mallocing = 1
  1332  
  1333  	checkGCTrigger := false
  1334  	c := getMCache(mp)
  1335  	var sizeclass uint8
  1336  	if size <= gc.SmallSizeMax-8 {
  1337  		sizeclass = gc.SizeToSizeClass8[divRoundUp(size, gc.SmallSizeDiv)]
  1338  	} else {
  1339  		sizeclass = gc.SizeToSizeClass128[divRoundUp(size-gc.SmallSizeMax, gc.LargeSizeDiv)]
  1340  	}
  1341  	size = uintptr(gc.SizeClassToSize[sizeclass])
  1342  	spc := makeSpanClass(sizeclass, true)
  1343  	span := c.alloc[spc]
  1344  
  1345  	// First, check for a reusable object.
  1346  	if runtimeFreegcEnabled && c.hasReusableNoscan(spc) {
  1347  		// We have a reusable object, use it.
  1348  		x := mallocgcSmallNoscanReuse(c, span, spc, size, needzero)
  1349  		mp.mallocing = 0
  1350  		releasem(mp)
  1351  		return x, size
  1352  	}
  1353  
  1354  	v := nextFreeFast(span)
  1355  	if v == 0 {
  1356  		v, span, checkGCTrigger = c.nextFree(spc)
  1357  	}
  1358  	x := unsafe.Pointer(v)
  1359  	if needzero && span.needzero != 0 {
  1360  		memclrNoHeapPointers(x, size)
  1361  	}
  1362  
  1363  	// Ensure that the stores above that initialize x to
  1364  	// type-safe memory and set the heap bits occur before
  1365  	// the caller can make x observable to the garbage
  1366  	// collector. Otherwise, on weakly ordered machines,
  1367  	// the garbage collector could follow a pointer to x,
  1368  	// but see uninitialized memory or stale heap bits.
  1369  	publicationBarrier()
  1370  
  1371  	if writeBarrier.enabled {
  1372  		// Allocate black during GC.
  1373  		// All slots hold nil so no scanning is needed.
  1374  		// This may be racing with GC so do it atomically if there can be
  1375  		// a race marking the bit.
  1376  		gcmarknewobject(span, uintptr(x))
  1377  	} else {
  1378  		// Track the last free index before the mark phase. This field
  1379  		// is only used by the garbage collector. During the mark phase
  1380  		// this is used by the conservative scanner to filter out objects
  1381  		// that are both free and recently-allocated. It's safe to do that
  1382  		// because we allocate-black if the GC is enabled. The conservative
  1383  		// scanner produces pointers out of thin air, so without additional
  1384  		// synchronization it might otherwise observe a partially-initialized
  1385  		// object, which could crash the program.
  1386  		span.freeIndexForScan = span.freeindex
  1387  	}
  1388  
  1389  	// Note cache c only valid while m acquired; see #47302
  1390  	//
  1391  	// N.B. Use the full size because that matches how the GC
  1392  	// will update the mem profile on the "free" side.
  1393  	//
  1394  	// TODO(mknyszek): We should really count the header as part
  1395  	// of gc_sys or something. The code below just pretends it is
  1396  	// internal fragmentation and matches the GC's accounting by
  1397  	// using the whole allocation slot.
  1398  	c.nextSample -= int64(size)
  1399  	if c.nextSample < 0 || MemProfileRate != c.memProfRate {
  1400  		profilealloc(mp, x, size)
  1401  	}
  1402  	mp.mallocing = 0
  1403  	releasem(mp)
  1404  
  1405  	if checkGCTrigger {
  1406  		if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  1407  			gcStart(t)
  1408  		}
  1409  	}
  1410  	return x, size
  1411  }
  1412  
  1413  // mallocgcSmallNoscanReuse returns a previously freed noscan object after preparing it for reuse.
  1414  // It must only be called if hasReusableNoscan returned true.
  1415  func mallocgcSmallNoscanReuse(c *mcache, span *mspan, spc spanClass, size uintptr, needzero bool) unsafe.Pointer {
  1416  	// TODO(thepudds): could nextFreeFast, nextFree and nextReusable return unsafe.Pointer?
  1417  	// Maybe doesn't matter. gclinkptr might be for historical reasons.
  1418  	v, span := c.nextReusableNoScan(span, spc)
  1419  	x := unsafe.Pointer(v)
  1420  
  1421  	// Compensate for the GC assist credit deducted in mallocgc (before calling us and
  1422  	// after we return) because this is not a newly allocated object. We use the full slot
  1423  	// size (elemsize) here because that's what mallocgc deducts overall. Note we only
  1424  	// adjust this when gcBlackenEnabled is true, which follows mallocgc behavior.
  1425  	// TODO(thepudds): a follow-up CL adds a more specific test of our assist credit
  1426  	// handling, including for validating internal fragmentation handling.
  1427  	if gcBlackenEnabled != 0 {
  1428  		addAssistCredit(size)
  1429  	}
  1430  
  1431  	// This is a previously used object, so only check needzero (and not span.needzero)
  1432  	// for clearing.
  1433  	if needzero {
  1434  		memclrNoHeapPointers(x, size)
  1435  	}
  1436  
  1437  	// See publicationBarrier comment in mallocgcSmallNoscan.
  1438  	publicationBarrier()
  1439  
  1440  	// Finish and return. Note that we do not update span.freeIndexForScan, profiling info,
  1441  	// nor do we check gcTrigger.
  1442  	// TODO(thepudds): the current approach is viable for a GOEXPERIMENT, but
  1443  	// means we do not profile reused heap objects. Ultimately, we will need a better
  1444  	// approach for profiling, or at least ensure we are not introducing bias in the
  1445  	// profiled allocations.
  1446  	// TODO(thepudds): related, we probably want to adjust how allocs and frees are counted
  1447  	// in the existing stats. Currently, reused objects are not counted as allocs nor
  1448  	// frees, but instead roughly appear as if the original heap object lived on. We
  1449  	// probably will also want some additional runtime/metrics, and generally think about
  1450  	// user-facing observability & diagnostics, though all this likely can wait for an
  1451  	// official proposal.
  1452  	if writeBarrier.enabled {
  1453  		// Allocate black during GC.
  1454  		// All slots hold nil so no scanning is needed.
  1455  		// This may be racing with GC so do it atomically if there can be
  1456  		// a race marking the bit.
  1457  		gcmarknewobject(span, uintptr(x))
  1458  	}
  1459  	return x
  1460  }
  1461  
  1462  func mallocgcSmallScanNoHeader(size uintptr, typ *_type) (unsafe.Pointer, uintptr) {
  1463  	// Set mp.mallocing to keep from being preempted by GC.
  1464  	mp := acquirem()
  1465  	if doubleCheckMalloc {
  1466  		if mp.mallocing != 0 {
  1467  			throw("malloc deadlock")
  1468  		}
  1469  		if mp.gsignal == getg() {
  1470  			throw("malloc during signal")
  1471  		}
  1472  		if typ == nil || !typ.Pointers() {
  1473  			throw("noscan allocated in scan-only path")
  1474  		}
  1475  		if !heapBitsInSpan(size) {
  1476  			throw("heap bits in not in span for non-header-only path")
  1477  		}
  1478  	}
  1479  	mp.mallocing = 1
  1480  
  1481  	checkGCTrigger := false
  1482  	c := getMCache(mp)
  1483  	sizeclass := gc.SizeToSizeClass8[divRoundUp(size, gc.SmallSizeDiv)]
  1484  	spc := makeSpanClass(sizeclass, false)
  1485  	span := c.alloc[spc]
  1486  	v := nextFreeFast(span)
  1487  	if v == 0 {
  1488  		v, span, checkGCTrigger = c.nextFree(spc)
  1489  	}
  1490  	x := unsafe.Pointer(v)
  1491  	if span.needzero != 0 {
  1492  		memclrNoHeapPointers(x, size)
  1493  	}
  1494  	if goarch.PtrSize == 8 && sizeclass == 1 {
  1495  		// initHeapBits already set the pointer bits for the 8-byte sizeclass
  1496  		// on 64-bit platforms.
  1497  		c.scanAlloc += 8
  1498  	} else {
  1499  		c.scanAlloc += heapSetTypeNoHeader(uintptr(x), size, typ, span)
  1500  	}
  1501  	size = uintptr(gc.SizeClassToSize[sizeclass])
  1502  
  1503  	// Ensure that the stores above that initialize x to
  1504  	// type-safe memory and set the heap bits occur before
  1505  	// the caller can make x observable to the garbage
  1506  	// collector. Otherwise, on weakly ordered machines,
  1507  	// the garbage collector could follow a pointer to x,
  1508  	// but see uninitialized memory or stale heap bits.
  1509  	publicationBarrier()
  1510  
  1511  	if writeBarrier.enabled {
  1512  		// Allocate black during GC.
  1513  		// All slots hold nil so no scanning is needed.
  1514  		// This may be racing with GC so do it atomically if there can be
  1515  		// a race marking the bit.
  1516  		gcmarknewobject(span, uintptr(x))
  1517  	} else {
  1518  		// Track the last free index before the mark phase. This field
  1519  		// is only used by the garbage collector. During the mark phase
  1520  		// this is used by the conservative scanner to filter out objects
  1521  		// that are both free and recently-allocated. It's safe to do that
  1522  		// because we allocate-black if the GC is enabled. The conservative
  1523  		// scanner produces pointers out of thin air, so without additional
  1524  		// synchronization it might otherwise observe a partially-initialized
  1525  		// object, which could crash the program.
  1526  		span.freeIndexForScan = span.freeindex
  1527  	}
  1528  
  1529  	// Note cache c only valid while m acquired; see #47302
  1530  	//
  1531  	// N.B. Use the full size because that matches how the GC
  1532  	// will update the mem profile on the "free" side.
  1533  	//
  1534  	// TODO(mknyszek): We should really count the header as part
  1535  	// of gc_sys or something. The code below just pretends it is
  1536  	// internal fragmentation and matches the GC's accounting by
  1537  	// using the whole allocation slot.
  1538  	c.nextSample -= int64(size)
  1539  	if c.nextSample < 0 || MemProfileRate != c.memProfRate {
  1540  		profilealloc(mp, x, size)
  1541  	}
  1542  	mp.mallocing = 0
  1543  	releasem(mp)
  1544  
  1545  	if checkGCTrigger {
  1546  		if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  1547  			gcStart(t)
  1548  		}
  1549  	}
  1550  	return x, size
  1551  }
  1552  
  1553  func mallocgcSmallScanHeader(size uintptr, typ *_type) (unsafe.Pointer, uintptr) {
  1554  	// Set mp.mallocing to keep from being preempted by GC.
  1555  	mp := acquirem()
  1556  	if doubleCheckMalloc {
  1557  		if mp.mallocing != 0 {
  1558  			throw("malloc deadlock")
  1559  		}
  1560  		if mp.gsignal == getg() {
  1561  			throw("malloc during signal")
  1562  		}
  1563  		if typ == nil || !typ.Pointers() {
  1564  			throw("noscan allocated in scan-only path")
  1565  		}
  1566  		if heapBitsInSpan(size) {
  1567  			throw("heap bits in span for header-only path")
  1568  		}
  1569  	}
  1570  	mp.mallocing = 1
  1571  
  1572  	checkGCTrigger := false
  1573  	c := getMCache(mp)
  1574  	size += gc.MallocHeaderSize
  1575  	var sizeclass uint8
  1576  	if size <= gc.SmallSizeMax-8 {
  1577  		sizeclass = gc.SizeToSizeClass8[divRoundUp(size, gc.SmallSizeDiv)]
  1578  	} else {
  1579  		sizeclass = gc.SizeToSizeClass128[divRoundUp(size-gc.SmallSizeMax, gc.LargeSizeDiv)]
  1580  	}
  1581  	size = uintptr(gc.SizeClassToSize[sizeclass])
  1582  	spc := makeSpanClass(sizeclass, false)
  1583  	span := c.alloc[spc]
  1584  	v := nextFreeFast(span)
  1585  	if v == 0 {
  1586  		v, span, checkGCTrigger = c.nextFree(spc)
  1587  	}
  1588  	x := unsafe.Pointer(v)
  1589  	if span.needzero != 0 {
  1590  		memclrNoHeapPointers(x, size)
  1591  	}
  1592  	header := (**_type)(x)
  1593  	x = add(x, gc.MallocHeaderSize)
  1594  	c.scanAlloc += heapSetTypeSmallHeader(uintptr(x), size-gc.MallocHeaderSize, typ, header, span)
  1595  
  1596  	// Ensure that the stores above that initialize x to
  1597  	// type-safe memory and set the heap bits occur before
  1598  	// the caller can make x observable to the garbage
  1599  	// collector. Otherwise, on weakly ordered machines,
  1600  	// the garbage collector could follow a pointer to x,
  1601  	// but see uninitialized memory or stale heap bits.
  1602  	publicationBarrier()
  1603  
  1604  	if writeBarrier.enabled {
  1605  		// Allocate black during GC.
  1606  		// All slots hold nil so no scanning is needed.
  1607  		// This may be racing with GC so do it atomically if there can be
  1608  		// a race marking the bit.
  1609  		gcmarknewobject(span, uintptr(x))
  1610  	} else {
  1611  		// Track the last free index before the mark phase. This field
  1612  		// is only used by the garbage collector. During the mark phase
  1613  		// this is used by the conservative scanner to filter out objects
  1614  		// that are both free and recently-allocated. It's safe to do that
  1615  		// because we allocate-black if the GC is enabled. The conservative
  1616  		// scanner produces pointers out of thin air, so without additional
  1617  		// synchronization it might otherwise observe a partially-initialized
  1618  		// object, which could crash the program.
  1619  		span.freeIndexForScan = span.freeindex
  1620  	}
  1621  
  1622  	// Note cache c only valid while m acquired; see #47302
  1623  	//
  1624  	// N.B. Use the full size because that matches how the GC
  1625  	// will update the mem profile on the "free" side.
  1626  	//
  1627  	// TODO(mknyszek): We should really count the header as part
  1628  	// of gc_sys or something. The code below just pretends it is
  1629  	// internal fragmentation and matches the GC's accounting by
  1630  	// using the whole allocation slot.
  1631  	c.nextSample -= int64(size)
  1632  	if c.nextSample < 0 || MemProfileRate != c.memProfRate {
  1633  		profilealloc(mp, x, size)
  1634  	}
  1635  	mp.mallocing = 0
  1636  	releasem(mp)
  1637  
  1638  	if checkGCTrigger {
  1639  		if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  1640  			gcStart(t)
  1641  		}
  1642  	}
  1643  	return x, size
  1644  }
  1645  
  1646  func mallocgcLarge(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) {
  1647  	// Set mp.mallocing to keep from being preempted by GC.
  1648  	mp := acquirem()
  1649  	if doubleCheckMalloc {
  1650  		if mp.mallocing != 0 {
  1651  			throw("malloc deadlock")
  1652  		}
  1653  		if mp.gsignal == getg() {
  1654  			throw("malloc during signal")
  1655  		}
  1656  	}
  1657  	mp.mallocing = 1
  1658  
  1659  	c := getMCache(mp)
  1660  	// For large allocations, keep track of zeroed state so that
  1661  	// bulk zeroing can be happen later in a preemptible context.
  1662  	span := c.allocLarge(size, typ == nil || !typ.Pointers())
  1663  	span.freeindex = 1
  1664  	span.allocCount = 1
  1665  	span.largeType = nil // Tell the GC not to look at this yet.
  1666  	size = span.elemsize
  1667  	x := unsafe.Pointer(span.base())
  1668  
  1669  	// Ensure that the store above that sets largeType to
  1670  	// nil happens before the caller can make x observable
  1671  	// to the garbage collector.
  1672  	//
  1673  	// Otherwise, on weakly ordered machines, the garbage
  1674  	// collector could follow a pointer to x, but see a stale
  1675  	// largeType value.
  1676  	publicationBarrier()
  1677  
  1678  	if writeBarrier.enabled {
  1679  		// Allocate black during GC.
  1680  		// All slots hold nil so no scanning is needed.
  1681  		// This may be racing with GC so do it atomically if there can be
  1682  		// a race marking the bit.
  1683  		gcmarknewobject(span, uintptr(x))
  1684  	} else {
  1685  		// Track the last free index before the mark phase. This field
  1686  		// is only used by the garbage collector. During the mark phase
  1687  		// this is used by the conservative scanner to filter out objects
  1688  		// that are both free and recently-allocated. It's safe to do that
  1689  		// because we allocate-black if the GC is enabled. The conservative
  1690  		// scanner produces pointers out of thin air, so without additional
  1691  		// synchronization it might otherwise observe a partially-initialized
  1692  		// object, which could crash the program.
  1693  		span.freeIndexForScan = span.freeindex
  1694  	}
  1695  
  1696  	// Note cache c only valid while m acquired; see #47302
  1697  	//
  1698  	// N.B. Use the full size because that matches how the GC
  1699  	// will update the mem profile on the "free" side.
  1700  	//
  1701  	// TODO(mknyszek): We should really count the header as part
  1702  	// of gc_sys or something. The code below just pretends it is
  1703  	// internal fragmentation and matches the GC's accounting by
  1704  	// using the whole allocation slot.
  1705  	c.nextSample -= int64(size)
  1706  	if c.nextSample < 0 || MemProfileRate != c.memProfRate {
  1707  		profilealloc(mp, x, size)
  1708  	}
  1709  	mp.mallocing = 0
  1710  	releasem(mp)
  1711  
  1712  	// Check to see if we need to trigger the GC.
  1713  	if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  1714  		gcStart(t)
  1715  	}
  1716  
  1717  	// Objects can be zeroed late in a context where preemption can occur.
  1718  	//
  1719  	// x will keep the memory alive.
  1720  	if needzero && span.needzero != 0 {
  1721  		// N.B. size == fullSize always in this case.
  1722  		memclrNoHeapPointersChunked(size, x) // This is a possible preemption point: see #47302
  1723  	}
  1724  
  1725  	// Set the type and run the publication barrier while non-preemptible. We need to make
  1726  	// sure that between heapSetTypeLarge and publicationBarrier we cannot get preempted,
  1727  	// otherwise the GC could potentially observe non-zeroed memory but largeType set on weak
  1728  	// memory architectures.
  1729  	//
  1730  	// The GC can also potentially observe non-zeroed memory if conservative scanning spuriously
  1731  	// observes a partially-allocated object, see the freeIndexForScan update above. This case is
  1732  	// handled by synchronization inside heapSetTypeLarge.
  1733  	mp = acquirem()
  1734  	if typ != nil && typ.Pointers() {
  1735  		// Finish storing the type information, now that we're certain the memory is zeroed.
  1736  		getMCache(mp).scanAlloc += heapSetTypeLarge(uintptr(x), size, typ, span)
  1737  	}
  1738  	// Publish the object again, now with zeroed memory and initialized type information.
  1739  	//
  1740  	// Even if we didn't update any type information, this is necessary to ensure that, for example,
  1741  	// x written to a global without any synchronization still results in other goroutines observing
  1742  	// zeroed memory.
  1743  	publicationBarrier()
  1744  	releasem(mp)
  1745  	return x, size
  1746  }
  1747  
  1748  func preMallocgcDebug(size uintptr, typ *_type) unsafe.Pointer {
  1749  	if debug.sbrk != 0 {
  1750  		align := uintptr(16)
  1751  		if typ != nil {
  1752  			// TODO(austin): This should be just
  1753  			//   align = uintptr(typ.align)
  1754  			// but that's only 4 on 32-bit platforms,
  1755  			// even if there's a uint64 field in typ (see #599).
  1756  			// This causes 64-bit atomic accesses to panic.
  1757  			// Hence, we use stricter alignment that matches
  1758  			// the normal allocator better.
  1759  			if size&7 == 0 {
  1760  				align = 8
  1761  			} else if size&3 == 0 {
  1762  				align = 4
  1763  			} else if size&1 == 0 {
  1764  				align = 2
  1765  			} else {
  1766  				align = 1
  1767  			}
  1768  		}
  1769  		return persistentalloc(size, align, &memstats.other_sys)
  1770  	}
  1771  	if inittrace.active && inittrace.id == getg().goid {
  1772  		// Init functions are executed sequentially in a single goroutine.
  1773  		inittrace.allocs += 1
  1774  	}
  1775  	return nil
  1776  }
  1777  
  1778  func postMallocgcDebug(x unsafe.Pointer, elemsize uintptr, typ *_type) {
  1779  	if inittrace.active && inittrace.id == getg().goid {
  1780  		// Init functions are executed sequentially in a single goroutine.
  1781  		inittrace.bytes += uint64(elemsize)
  1782  	}
  1783  
  1784  	if traceAllocFreeEnabled() {
  1785  		trace := traceAcquire()
  1786  		if trace.ok() {
  1787  			trace.HeapObjectAlloc(uintptr(x), typ)
  1788  			traceRelease(trace)
  1789  		}
  1790  	}
  1791  
  1792  	// N.B. elemsize == 0 indicates a tiny allocation, since no new slot was
  1793  	// allocated to fulfill this call to mallocgc. This means checkfinalizer
  1794  	// will only flag an error if there is actually any risk. If an allocation
  1795  	// has the tiny block to itself, it will not get flagged, because we won't
  1796  	// mark the block as a tiny block.
  1797  	if debug.checkfinalizers != 0 && elemsize == 0 {
  1798  		setTinyBlockContext(unsafe.Pointer(alignDown(uintptr(x), maxTinySize)))
  1799  	}
  1800  }
  1801  
  1802  // addAssistCredit is like deductAssistCredit,
  1803  // but adds credit rather than removes,
  1804  // and never calls gcAssistAlloc.
  1805  func addAssistCredit(size uintptr) {
  1806  	// Credit the current user G.
  1807  	assistG := getg()
  1808  	if assistG.m.curg != nil { // TODO(thepudds): do we need to do this?
  1809  		assistG = assistG.m.curg
  1810  	}
  1811  	// Credit the size against the G.
  1812  	assistG.gcAssistBytes += int64(size)
  1813  }
  1814  
  1815  const (
  1816  	// doubleCheckReusable enables some additional invariant checks for the
  1817  	// runtime.freegc and reusable objects. Note that some of these checks alter timing,
  1818  	// and it is good to test changes with and without this enabled.
  1819  	doubleCheckReusable = false
  1820  
  1821  	// debugReusableLog enables some printlns for runtime.freegc and reusable objects.
  1822  	debugReusableLog = false
  1823  )
  1824  
  1825  // freegc records that a heap object is reusable and available for
  1826  // immediate reuse in a subsequent mallocgc allocation, without
  1827  // needing to wait for the GC cycle to progress.
  1828  //
  1829  // The information is recorded in a free list stored in the
  1830  // current P's mcache. The caller must pass in the user size
  1831  // and whether the object has pointers, which allows a faster free
  1832  // operation.
  1833  //
  1834  // freegc must be called by the effective owner of ptr who knows
  1835  // the pointer is logically dead, with no possible aliases that might
  1836  // be used past that moment. In other words, ptr must be the
  1837  // last and only pointer to its referent.
  1838  //
  1839  // The intended caller is the compiler.
  1840  //
  1841  // Note: please do not send changes that attempt to add freegc calls
  1842  // to the standard library.
  1843  //
  1844  // ptr must point to a heap object or into the current g's stack,
  1845  // in which case freegc is a no-op. In particular, ptr must not point
  1846  // to memory in the data or bss sections, which is partially enforced.
  1847  // For objects with a malloc header, ptr should point mallocHeaderSize bytes
  1848  // past the base; otherwise, ptr should point to the base of the heap object.
  1849  // In other words, ptr should be the same pointer that was returned by mallocgc.
  1850  //
  1851  // In addition, the caller must know that ptr's object has no specials, such
  1852  // as might have been created by a call to SetFinalizer or AddCleanup.
  1853  // (Internally, the runtime deals appropriately with internally-created
  1854  // specials, such as specials for memory profiling).
  1855  //
  1856  // If the size of ptr's object is less than 16 bytes or greater than
  1857  // 32KiB - gc.MallocHeaderSize bytes, freegc is currently a no-op. It must only
  1858  // be called in alloc-safe places. It currently throws if noscan is false
  1859  // (support for which is implemented in a later CL in our stack).
  1860  //
  1861  // Note that freegc accepts an unsafe.Pointer and hence keeps the pointer
  1862  // alive. It therefore could be a pessimization in some cases (such
  1863  // as a long-lived function) if the caller does not call freegc before
  1864  // or roughly when the liveness analysis of the compiler
  1865  // would otherwise have determined ptr's object is reclaimable by the GC.
  1866  func freegc(ptr unsafe.Pointer, size uintptr, noscan bool) bool {
  1867  	if !runtimeFreegcEnabled || !reusableSize(size) {
  1868  		return false
  1869  	}
  1870  	if sizeSpecializedMallocEnabled && !noscan {
  1871  		// TODO(thepudds): temporarily disable freegc with SizeSpecializedMalloc for pointer types
  1872  		// until we finish integrating.
  1873  		return false
  1874  	}
  1875  
  1876  	if ptr == nil {
  1877  		throw("freegc nil")
  1878  	}
  1879  
  1880  	// Set mp.mallocing to keep from being preempted by GC.
  1881  	// Otherwise, the GC could flush our mcache or otherwise cause problems.
  1882  	mp := acquirem()
  1883  	if mp.mallocing != 0 {
  1884  		throw("freegc deadlock")
  1885  	}
  1886  	if mp.gsignal == getg() {
  1887  		throw("freegc during signal")
  1888  	}
  1889  	mp.mallocing = 1
  1890  
  1891  	if mp.curg.stack.lo <= uintptr(ptr) && uintptr(ptr) < mp.curg.stack.hi {
  1892  		// This points into our stack, so free is a no-op.
  1893  		mp.mallocing = 0
  1894  		releasem(mp)
  1895  		return false
  1896  	}
  1897  
  1898  	if doubleCheckReusable {
  1899  		// TODO(thepudds): we could enforce no free on globals in bss or data. Maybe by
  1900  		// checking span via spanOf or spanOfHeap, or maybe walk from firstmoduledata
  1901  		// like isGoPointerWithoutSpan, or activeModules, or something. If so, we might
  1902  		// be able to delay checking until reuse (e.g., check span just before reusing,
  1903  		// though currently we don't always need to lookup a span on reuse). If we think
  1904  		// no usage patterns could result in globals, maybe enforcement for globals could
  1905  		// be behind -d=checkptr=1 or similar. The compiler can have knowledge of where
  1906  		// a variable is allocated, but stdlib does not, although there are certain
  1907  		// usage patterns that cannot result in a global.
  1908  		// TODO(thepudds): separately, consider a local debugReusableMcacheOnly here
  1909  		// to ignore freed objects if not in mspan in mcache,  maybe when freeing and reading,
  1910  		// by checking something like s.base() <= uintptr(v) && uintptr(v) < s.limit. Or
  1911  		// maybe a GODEBUG or compiler debug flag.
  1912  		span := spanOf(uintptr(ptr))
  1913  		if span == nil {
  1914  			throw("nextReusable: nil span for pointer in free list")
  1915  		}
  1916  		if state := span.state.get(); state != mSpanInUse {
  1917  			throw("nextReusable: span is not in use")
  1918  		}
  1919  	}
  1920  
  1921  	if debug.clobberfree != 0 {
  1922  		clobberfree(ptr, size)
  1923  	}
  1924  
  1925  	// We first check if p is still in our per-P cache.
  1926  	// Get our per-P cache for small objects.
  1927  	c := getMCache(mp)
  1928  	if c == nil {
  1929  		throw("freegc called without a P or outside bootstrapping")
  1930  	}
  1931  
  1932  	v := uintptr(ptr)
  1933  	if !noscan && !heapBitsInSpan(size) {
  1934  		// mallocgcSmallScanHeader expects to get the base address of the object back
  1935  		// from the findReusable funcs (as well as from nextFreeFast and nextFree), and
  1936  		// not mallocHeaderSize bytes into a object, so adjust that here.
  1937  		v -= mallocHeaderSize
  1938  
  1939  		// The size class lookup wants size to be adjusted by mallocHeaderSize.
  1940  		size += mallocHeaderSize
  1941  	}
  1942  
  1943  	// TODO(thepudds): should verify (behind doubleCheckReusable constant) that our calculated
  1944  	// sizeclass here matches what's in span found via spanOf(ptr) or findObject(ptr).
  1945  	var sizeclass uint8
  1946  	if size <= gc.SmallSizeMax-8 {
  1947  		sizeclass = gc.SizeToSizeClass8[divRoundUp(size, gc.SmallSizeDiv)]
  1948  	} else {
  1949  		sizeclass = gc.SizeToSizeClass128[divRoundUp(size-gc.SmallSizeMax, gc.LargeSizeDiv)]
  1950  	}
  1951  
  1952  	spc := makeSpanClass(sizeclass, noscan)
  1953  	s := c.alloc[spc]
  1954  
  1955  	if debugReusableLog {
  1956  		if s.base() <= uintptr(v) && uintptr(v) < s.limit {
  1957  			println("freegc [in mcache]:", hex(uintptr(v)), "sweepgen:", mheap_.sweepgen, "writeBarrier.enabled:", writeBarrier.enabled)
  1958  		} else {
  1959  			println("freegc [NOT in mcache]:", hex(uintptr(v)), "sweepgen:", mheap_.sweepgen, "writeBarrier.enabled:", writeBarrier.enabled)
  1960  		}
  1961  	}
  1962  
  1963  	if noscan {
  1964  		c.addReusableNoscan(spc, uintptr(v))
  1965  	} else {
  1966  		// TODO(thepudds): implemented in later CL in our stack.
  1967  		throw("freegc called for object with pointers, not yet implemented")
  1968  	}
  1969  
  1970  	// For stats, for now we leave allocCount alone, roughly pretending to the rest
  1971  	// of the system that this potential reuse never happened.
  1972  
  1973  	mp.mallocing = 0
  1974  	releasem(mp)
  1975  
  1976  	return true
  1977  }
  1978  
  1979  // nextReusableNoScan returns the next reusable object for a noscan span,
  1980  // or 0 if no reusable object is found.
  1981  func (c *mcache) nextReusableNoScan(s *mspan, spc spanClass) (gclinkptr, *mspan) {
  1982  	if !runtimeFreegcEnabled {
  1983  		return 0, s
  1984  	}
  1985  
  1986  	// Pop a reusable pointer from the free list for this span class.
  1987  	v := c.reusableNoscan[spc]
  1988  	if v == 0 {
  1989  		return 0, s
  1990  	}
  1991  	c.reusableNoscan[spc] = v.ptr().next
  1992  
  1993  	if debugReusableLog {
  1994  		println("reusing from ptr free list:", hex(v), "sweepgen:", mheap_.sweepgen, "writeBarrier.enabled:", writeBarrier.enabled)
  1995  	}
  1996  	if doubleCheckReusable {
  1997  		doubleCheckNextReusable(v) // debug only sanity check
  1998  	}
  1999  
  2000  	// For noscan spans, we only need the span if the write barrier is enabled (so that our caller
  2001  	// can call gcmarknewobject to allocate black). If the write barrier is enabled, we can skip
  2002  	// looking up the span when the pointer is in a span in the mcache.
  2003  	if !writeBarrier.enabled {
  2004  		return v, nil
  2005  	}
  2006  	if s.base() <= uintptr(v) && uintptr(v) < s.limit {
  2007  		// Return the original span.
  2008  		return v, s
  2009  	}
  2010  
  2011  	// We must find and return the span.
  2012  	span := spanOf(uintptr(v))
  2013  	if span == nil {
  2014  		// TODO(thepudds): construct a test that triggers this throw.
  2015  		throw("nextReusableNoScan: nil span for pointer in reusable object free list")
  2016  	}
  2017  
  2018  	return v, span
  2019  }
  2020  
  2021  // doubleCheckNextReusable checks some invariants.
  2022  // TODO(thepudds): will probably delete some of this. Can mostly be ignored for review.
  2023  func doubleCheckNextReusable(v gclinkptr) {
  2024  	// TODO(thepudds): should probably take the spanClass as well to confirm expected
  2025  	// sizeclass match.
  2026  	_, span, objIndex := findObject(uintptr(v), 0, 0)
  2027  	if span == nil {
  2028  		throw("nextReusable: nil span for pointer in free list")
  2029  	}
  2030  	if state := span.state.get(); state != mSpanInUse {
  2031  		throw("nextReusable: span is not in use")
  2032  	}
  2033  	if uintptr(v) < span.base() || uintptr(v) >= span.limit {
  2034  		throw("nextReusable: span is not in range")
  2035  	}
  2036  	if span.objBase(uintptr(v)) != uintptr(v) {
  2037  		print("nextReusable: v=", hex(v), " base=", hex(span.objBase(uintptr(v))), "\n")
  2038  		throw("nextReusable: v is non-base-address for object found on pointer free list")
  2039  	}
  2040  	if span.isFree(objIndex) {
  2041  		throw("nextReusable: pointer on free list is free")
  2042  	}
  2043  
  2044  	const debugReusableEnsureSwept = false
  2045  	if debugReusableEnsureSwept {
  2046  		// Currently disabled.
  2047  		// Note: ensureSwept here alters behavior (not just an invariant check).
  2048  		span.ensureSwept()
  2049  		if span.isFree(objIndex) {
  2050  			throw("nextReusable: pointer on free list is free after ensureSwept")
  2051  		}
  2052  	}
  2053  }
  2054  
  2055  // reusableSize reports if size is a currently supported size for a reusable object.
  2056  func reusableSize(size uintptr) bool {
  2057  	if size < maxTinySize || size > maxSmallSize-mallocHeaderSize {
  2058  		return false
  2059  	}
  2060  	return true
  2061  }
  2062  
  2063  // memclrNoHeapPointersChunked repeatedly calls memclrNoHeapPointers
  2064  // on chunks of the buffer to be zeroed, with opportunities for preemption
  2065  // along the way.  memclrNoHeapPointers contains no safepoints and also
  2066  // cannot be preemptively scheduled, so this provides a still-efficient
  2067  // block copy that can also be preempted on a reasonable granularity.
  2068  //
  2069  // Use this with care; if the data being cleared is tagged to contain
  2070  // pointers, this allows the GC to run before it is all cleared.
  2071  func memclrNoHeapPointersChunked(size uintptr, x unsafe.Pointer) {
  2072  	v := uintptr(x)
  2073  	// got this from benchmarking. 128k is too small, 512k is too large.
  2074  	const chunkBytes = 256 * 1024
  2075  	vsize := v + size
  2076  	for voff := v; voff < vsize; voff = voff + chunkBytes {
  2077  		if getg().preempt {
  2078  			// may hold locks, e.g., profiling
  2079  			goschedguarded()
  2080  		}
  2081  		// clear min(avail, lump) bytes
  2082  		n := vsize - voff
  2083  		if n > chunkBytes {
  2084  			n = chunkBytes
  2085  		}
  2086  		memclrNoHeapPointers(unsafe.Pointer(voff), n)
  2087  	}
  2088  }
  2089  
  2090  // implementation of new builtin
  2091  // compiler (both frontend and SSA backend) knows the signature
  2092  // of this function.
  2093  func newobject(typ *_type) unsafe.Pointer {
  2094  	return mallocgc(typ.Size_, typ, true)
  2095  }
  2096  
  2097  //go:linkname maps_newobject internal/runtime/maps.newobject
  2098  func maps_newobject(typ *_type) unsafe.Pointer {
  2099  	return newobject(typ)
  2100  }
  2101  
  2102  // reflect_unsafe_New is meant for package reflect,
  2103  // but widely used packages access it using linkname.
  2104  // Notable members of the hall of shame include:
  2105  //   - gitee.com/quant1x/gox
  2106  //   - github.com/goccy/json
  2107  //   - github.com/modern-go/reflect2
  2108  //   - github.com/v2pro/plz
  2109  //
  2110  // Do not remove or change the type signature.
  2111  // See go.dev/issue/67401.
  2112  //
  2113  //go:linkname reflect_unsafe_New reflect.unsafe_New
  2114  func reflect_unsafe_New(typ *_type) unsafe.Pointer {
  2115  	return mallocgc(typ.Size_, typ, true)
  2116  }
  2117  
  2118  //go:linkname reflectlite_unsafe_New internal/reflectlite.unsafe_New
  2119  func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
  2120  	return mallocgc(typ.Size_, typ, true)
  2121  }
  2122  
  2123  // newarray allocates an array of n elements of type typ.
  2124  //
  2125  // newarray should be an internal detail,
  2126  // but widely used packages access it using linkname.
  2127  // Notable members of the hall of shame include:
  2128  //   - github.com/RomiChan/protobuf
  2129  //   - github.com/segmentio/encoding
  2130  //   - github.com/ugorji/go/codec
  2131  //
  2132  // Do not remove or change the type signature.
  2133  // See go.dev/issue/67401.
  2134  //
  2135  //go:linkname newarray
  2136  func newarray(typ *_type, n int) unsafe.Pointer {
  2137  	if n == 1 {
  2138  		return mallocgc(typ.Size_, typ, true)
  2139  	}
  2140  	mem, overflow := math.MulUintptr(typ.Size_, uintptr(n))
  2141  	if overflow || mem > maxAlloc || n < 0 {
  2142  		panic(plainError("runtime: allocation size out of range"))
  2143  	}
  2144  	return mallocgc(mem, typ, true)
  2145  }
  2146  
  2147  // reflect_unsafe_NewArray is meant for package reflect,
  2148  // but widely used packages access it using linkname.
  2149  // Notable members of the hall of shame include:
  2150  //   - gitee.com/quant1x/gox
  2151  //   - github.com/bytedance/sonic
  2152  //   - github.com/goccy/json
  2153  //   - github.com/modern-go/reflect2
  2154  //   - github.com/segmentio/encoding
  2155  //   - github.com/segmentio/kafka-go
  2156  //   - github.com/v2pro/plz
  2157  //
  2158  // Do not remove or change the type signature.
  2159  // See go.dev/issue/67401.
  2160  //
  2161  //go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray
  2162  func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
  2163  	return newarray(typ, n)
  2164  }
  2165  
  2166  //go:linkname maps_newarray internal/runtime/maps.newarray
  2167  func maps_newarray(typ *_type, n int) unsafe.Pointer {
  2168  	return newarray(typ, n)
  2169  }
  2170  
  2171  // profilealloc resets the current mcache's nextSample counter and
  2172  // records a memory profile sample.
  2173  //
  2174  // The caller must be non-preemptible and have a P.
  2175  func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
  2176  	c := getMCache(mp)
  2177  	if c == nil {
  2178  		throw("profilealloc called without a P or outside bootstrapping")
  2179  	}
  2180  	c.memProfRate = MemProfileRate
  2181  	c.nextSample = nextSample()
  2182  	mProf_Malloc(mp, x, size)
  2183  }
  2184  
  2185  // nextSample returns the next sampling point for heap profiling. The goal is
  2186  // to sample allocations on average every MemProfileRate bytes, but with a
  2187  // completely random distribution over the allocation timeline; this
  2188  // corresponds to a Poisson process with parameter MemProfileRate. In Poisson
  2189  // processes, the distance between two samples follows the exponential
  2190  // distribution (exp(MemProfileRate)), so the best return value is a random
  2191  // number taken from an exponential distribution whose mean is MemProfileRate.
  2192  func nextSample() int64 {
  2193  	if MemProfileRate == 0 {
  2194  		// Basically never sample.
  2195  		return math.MaxInt64
  2196  	}
  2197  	if MemProfileRate == 1 {
  2198  		// Sample immediately.
  2199  		return 0
  2200  	}
  2201  	return int64(fastexprand(MemProfileRate))
  2202  }
  2203  
  2204  // fastexprand returns a random number from an exponential distribution with
  2205  // the specified mean.
  2206  func fastexprand(mean int) int32 {
  2207  	// Avoid overflow. Maximum possible step is
  2208  	// -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
  2209  	switch {
  2210  	case mean > 0x7000000:
  2211  		mean = 0x7000000
  2212  	case mean == 0:
  2213  		return 0
  2214  	}
  2215  
  2216  	// Take a random sample of the exponential distribution exp(-mean*x).
  2217  	// The probability distribution function is mean*exp(-mean*x), so the CDF is
  2218  	// p = 1 - exp(-mean*x), so
  2219  	// q = 1 - p == exp(-mean*x)
  2220  	// log_e(q) = -mean*x
  2221  	// -log_e(q)/mean = x
  2222  	// x = -log_e(q) * mean
  2223  	// x = log_2(q) * (-log_e(2)) * mean    ; Using log_2 for efficiency
  2224  	const randomBitCount = 26
  2225  	q := cheaprandn(1<<randomBitCount) + 1
  2226  	qlog := fastlog2(float64(q)) - randomBitCount
  2227  	if qlog > 0 {
  2228  		qlog = 0
  2229  	}
  2230  	const minusLog2 = -0.6931471805599453 // -ln(2)
  2231  	return int32(qlog*(minusLog2*float64(mean))) + 1
  2232  }
  2233  
  2234  type persistentAlloc struct {
  2235  	base *notInHeap
  2236  	off  uintptr
  2237  }
  2238  
  2239  var globalAlloc struct {
  2240  	mutex
  2241  	persistentAlloc
  2242  }
  2243  
  2244  // persistentChunkSize is the number of bytes we allocate when we grow
  2245  // a persistentAlloc.
  2246  const persistentChunkSize = 256 << 10
  2247  
  2248  // persistentChunks is a list of all the persistent chunks we have
  2249  // allocated. The list is maintained through the first word in the
  2250  // persistent chunk. This is updated atomically.
  2251  var persistentChunks *notInHeap
  2252  
  2253  // Wrapper around sysAlloc that can allocate small chunks.
  2254  // There is no associated free operation.
  2255  // Intended for things like function/type/debug-related persistent data.
  2256  // If align is 0, uses default align (currently 8).
  2257  // The returned memory will be zeroed.
  2258  // sysStat must be non-nil.
  2259  //
  2260  // Consider marking persistentalloc'd types not in heap by embedding
  2261  // internal/runtime/sys.NotInHeap.
  2262  //
  2263  // nosplit because it is used during write barriers and must not be preempted.
  2264  //
  2265  //go:nosplit
  2266  func persistentalloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
  2267  	var p *notInHeap
  2268  	systemstack(func() {
  2269  		p = persistentalloc1(size, align, sysStat)
  2270  	})
  2271  	return unsafe.Pointer(p)
  2272  }
  2273  
  2274  // Must run on system stack because stack growth can (re)invoke it.
  2275  // See issue 9174.
  2276  //
  2277  //go:systemstack
  2278  func persistentalloc1(size, align uintptr, sysStat *sysMemStat) *notInHeap {
  2279  	const (
  2280  		maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
  2281  	)
  2282  
  2283  	if size == 0 {
  2284  		throw("persistentalloc: size == 0")
  2285  	}
  2286  	if align != 0 {
  2287  		if align&(align-1) != 0 {
  2288  			throw("persistentalloc: align is not a power of 2")
  2289  		}
  2290  		if align > pageSize {
  2291  			throw("persistentalloc: align is too large")
  2292  		}
  2293  	} else {
  2294  		align = 8
  2295  	}
  2296  
  2297  	if size >= maxBlock {
  2298  		return (*notInHeap)(sysAlloc(size, sysStat, "immortal metadata"))
  2299  	}
  2300  
  2301  	mp := acquirem()
  2302  	var persistent *persistentAlloc
  2303  	if mp != nil && mp.p != 0 {
  2304  		persistent = &mp.p.ptr().palloc
  2305  	} else {
  2306  		lock(&globalAlloc.mutex)
  2307  		persistent = &globalAlloc.persistentAlloc
  2308  	}
  2309  	persistent.off = alignUp(persistent.off, align)
  2310  	if persistent.off+size > persistentChunkSize || persistent.base == nil {
  2311  		persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys, "immortal metadata"))
  2312  		if persistent.base == nil {
  2313  			if persistent == &globalAlloc.persistentAlloc {
  2314  				unlock(&globalAlloc.mutex)
  2315  			}
  2316  			throw("runtime: cannot allocate memory")
  2317  		}
  2318  
  2319  		// Add the new chunk to the persistentChunks list.
  2320  		for {
  2321  			chunks := uintptr(unsafe.Pointer(persistentChunks))
  2322  			*(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
  2323  			if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
  2324  				break
  2325  			}
  2326  		}
  2327  		persistent.off = alignUp(goarch.PtrSize, align)
  2328  	}
  2329  	p := persistent.base.add(persistent.off)
  2330  	persistent.off += size
  2331  	releasem(mp)
  2332  	if persistent == &globalAlloc.persistentAlloc {
  2333  		unlock(&globalAlloc.mutex)
  2334  	}
  2335  
  2336  	if sysStat != &memstats.other_sys {
  2337  		sysStat.add(int64(size))
  2338  		memstats.other_sys.add(-int64(size))
  2339  	}
  2340  	return p
  2341  }
  2342  
  2343  // inPersistentAlloc reports whether p points to memory allocated by
  2344  // persistentalloc. This must be nosplit because it is called by the
  2345  // cgo checker code, which is called by the write barrier code.
  2346  //
  2347  //go:nosplit
  2348  func inPersistentAlloc(p uintptr) bool {
  2349  	chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
  2350  	for chunk != 0 {
  2351  		if p >= chunk && p < chunk+persistentChunkSize {
  2352  			return true
  2353  		}
  2354  		chunk = *(*uintptr)(unsafe.Pointer(chunk))
  2355  	}
  2356  	return false
  2357  }
  2358  
  2359  // linearAlloc is a simple linear allocator that pre-reserves a region
  2360  // of memory and then optionally maps that region into the Ready state
  2361  // as needed.
  2362  //
  2363  // The caller is responsible for locking.
  2364  type linearAlloc struct {
  2365  	next   uintptr // next free byte
  2366  	mapped uintptr // one byte past end of mapped space
  2367  	end    uintptr // end of reserved space
  2368  
  2369  	mapMemory bool // transition memory from Reserved to Ready if true
  2370  }
  2371  
  2372  func (l *linearAlloc) init(base, size uintptr, mapMemory bool) {
  2373  	if base+size < base {
  2374  		// Chop off the last byte. The runtime isn't prepared
  2375  		// to deal with situations where the bounds could overflow.
  2376  		// Leave that memory reserved, though, so we don't map it
  2377  		// later.
  2378  		size -= 1
  2379  	}
  2380  	l.next, l.mapped = base, base
  2381  	l.end = base + size
  2382  	l.mapMemory = mapMemory
  2383  }
  2384  
  2385  func (l *linearAlloc) alloc(size, align uintptr, sysStat *sysMemStat, vmaName string) unsafe.Pointer {
  2386  	p := alignUp(l.next, align)
  2387  	if p+size > l.end {
  2388  		return nil
  2389  	}
  2390  	l.next = p + size
  2391  	if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
  2392  		if l.mapMemory {
  2393  			// Transition from Reserved to Prepared to Ready.
  2394  			n := pEnd - l.mapped
  2395  			sysMap(unsafe.Pointer(l.mapped), n, sysStat, vmaName)
  2396  			sysUsed(unsafe.Pointer(l.mapped), n, n)
  2397  		}
  2398  		l.mapped = pEnd
  2399  	}
  2400  	return unsafe.Pointer(p)
  2401  }
  2402  
  2403  // notInHeap is off-heap memory allocated by a lower-level allocator
  2404  // like sysAlloc or persistentAlloc.
  2405  //
  2406  // In general, it's better to use real types which embed
  2407  // internal/runtime/sys.NotInHeap, but this serves as a generic type
  2408  // for situations where that isn't possible (like in the allocators).
  2409  //
  2410  // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
  2411  type notInHeap struct{ _ sys.NotInHeap }
  2412  
  2413  func (p *notInHeap) add(bytes uintptr) *notInHeap {
  2414  	return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))
  2415  }
  2416  
  2417  // redZoneSize computes the size of the redzone for a given allocation.
  2418  // Refer to the implementation of the compiler-rt.
  2419  func redZoneSize(userSize uintptr) uintptr {
  2420  	switch {
  2421  	case userSize <= (64 - 16):
  2422  		return 16 << 0
  2423  	case userSize <= (128 - 32):
  2424  		return 16 << 1
  2425  	case userSize <= (512 - 64):
  2426  		return 16 << 2
  2427  	case userSize <= (4096 - 128):
  2428  		return 16 << 3
  2429  	case userSize <= (1<<14)-256:
  2430  		return 16 << 4
  2431  	case userSize <= (1<<15)-512:
  2432  		return 16 << 5
  2433  	case userSize <= (1<<16)-1024:
  2434  		return 16 << 6
  2435  	default:
  2436  		return 16 << 7
  2437  	}
  2438  }
  2439  

View as plain text