...

Source file src/runtime/malloc.go

Documentation: runtime

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

View as plain text