...
Run Format

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

View as plain text