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

View as plain text