Source file src/runtime/mheap.go

     1  // Copyright 2009 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  // Page heap.
     6  //
     7  // See malloc.go for overview.
     8  
     9  package runtime
    10  
    11  import (
    12  	"internal/cpu"
    13  	"internal/goarch"
    14  	"runtime/internal/atomic"
    15  	"unsafe"
    16  )
    17  
    18  const (
    19  	// minPhysPageSize is a lower-bound on the physical page size. The
    20  	// true physical page size may be larger than this. In contrast,
    21  	// sys.PhysPageSize is an upper-bound on the physical page size.
    22  	minPhysPageSize = 4096
    23  
    24  	// maxPhysPageSize is the maximum page size the runtime supports.
    25  	maxPhysPageSize = 512 << 10
    26  
    27  	// maxPhysHugePageSize sets an upper-bound on the maximum huge page size
    28  	// that the runtime supports.
    29  	maxPhysHugePageSize = pallocChunkBytes
    30  
    31  	// pagesPerReclaimerChunk indicates how many pages to scan from the
    32  	// pageInUse bitmap at a time. Used by the page reclaimer.
    33  	//
    34  	// Higher values reduce contention on scanning indexes (such as
    35  	// h.reclaimIndex), but increase the minimum latency of the
    36  	// operation.
    37  	//
    38  	// The time required to scan this many pages can vary a lot depending
    39  	// on how many spans are actually freed. Experimentally, it can
    40  	// scan for pages at ~300 GB/ms on a 2.6GHz Core i7, but can only
    41  	// free spans at ~32 MB/ms. Using 512 pages bounds this at
    42  	// roughly 100┬Ás.
    43  	//
    44  	// Must be a multiple of the pageInUse bitmap element size and
    45  	// must also evenly divide pagesPerArena.
    46  	pagesPerReclaimerChunk = 512
    47  
    48  	// physPageAlignedStacks indicates whether stack allocations must be
    49  	// physical page aligned. This is a requirement for MAP_STACK on
    50  	// OpenBSD.
    51  	physPageAlignedStacks = GOOS == "openbsd"
    52  )
    53  
    54  // Main malloc heap.
    55  // The heap itself is the "free" and "scav" treaps,
    56  // but all the other global data is here too.
    57  //
    58  // mheap must not be heap-allocated because it contains mSpanLists,
    59  // which must not be heap-allocated.
    60  //
    61  //go:notinheap
    62  type mheap struct {
    63  	// lock must only be acquired on the system stack, otherwise a g
    64  	// could self-deadlock if its stack grows with the lock held.
    65  	lock mutex
    66  
    67  	_ uint32 // 8-byte align pages so its alignment is consistent with tests.
    68  
    69  	pages pageAlloc // page allocation data structure
    70  
    71  	sweepgen uint32 // sweep generation, see comment in mspan; written during STW
    72  
    73  	// allspans is a slice of all mspans ever created. Each mspan
    74  	// appears exactly once.
    75  	//
    76  	// The memory for allspans is manually managed and can be
    77  	// reallocated and move as the heap grows.
    78  	//
    79  	// In general, allspans is protected by mheap_.lock, which
    80  	// prevents concurrent access as well as freeing the backing
    81  	// store. Accesses during STW might not hold the lock, but
    82  	// must ensure that allocation cannot happen around the
    83  	// access (since that may free the backing store).
    84  	allspans []*mspan // all spans out there
    85  
    86  	// _ uint32 // align uint64 fields on 32-bit for atomics
    87  
    88  	// Proportional sweep
    89  	//
    90  	// These parameters represent a linear function from gcController.heapLive
    91  	// to page sweep count. The proportional sweep system works to
    92  	// stay in the black by keeping the current page sweep count
    93  	// above this line at the current gcController.heapLive.
    94  	//
    95  	// The line has slope sweepPagesPerByte and passes through a
    96  	// basis point at (sweepHeapLiveBasis, pagesSweptBasis). At
    97  	// any given time, the system is at (gcController.heapLive,
    98  	// pagesSwept) in this space.
    99  	//
   100  	// It is important that the line pass through a point we
   101  	// control rather than simply starting at a 0,0 origin
   102  	// because that lets us adjust sweep pacing at any time while
   103  	// accounting for current progress. If we could only adjust
   104  	// the slope, it would create a discontinuity in debt if any
   105  	// progress has already been made.
   106  	pagesInUse         atomic.Uint64 // pages of spans in stats mSpanInUse
   107  	pagesSwept         atomic.Uint64 // pages swept this cycle
   108  	pagesSweptBasis    atomic.Uint64 // pagesSwept to use as the origin of the sweep ratio
   109  	sweepHeapLiveBasis uint64        // value of gcController.heapLive to use as the origin of sweep ratio; written with lock, read without
   110  	sweepPagesPerByte  float64       // proportional sweep ratio; written with lock, read without
   111  	// TODO(austin): pagesInUse should be a uintptr, but the 386
   112  	// compiler can't 8-byte align fields.
   113  
   114  	// Page reclaimer state
   115  
   116  	// reclaimIndex is the page index in allArenas of next page to
   117  	// reclaim. Specifically, it refers to page (i %
   118  	// pagesPerArena) of arena allArenas[i / pagesPerArena].
   119  	//
   120  	// If this is >= 1<<63, the page reclaimer is done scanning
   121  	// the page marks.
   122  	reclaimIndex atomic.Uint64
   123  
   124  	// reclaimCredit is spare credit for extra pages swept. Since
   125  	// the page reclaimer works in large chunks, it may reclaim
   126  	// more than requested. Any spare pages released go to this
   127  	// credit pool.
   128  	reclaimCredit atomic.Uintptr
   129  
   130  	// arenas is the heap arena map. It points to the metadata for
   131  	// the heap for every arena frame of the entire usable virtual
   132  	// address space.
   133  	//
   134  	// Use arenaIndex to compute indexes into this array.
   135  	//
   136  	// For regions of the address space that are not backed by the
   137  	// Go heap, the arena map contains nil.
   138  	//
   139  	// Modifications are protected by mheap_.lock. Reads can be
   140  	// performed without locking; however, a given entry can
   141  	// transition from nil to non-nil at any time when the lock
   142  	// isn't held. (Entries never transitions back to nil.)
   143  	//
   144  	// In general, this is a two-level mapping consisting of an L1
   145  	// map and possibly many L2 maps. This saves space when there
   146  	// are a huge number of arena frames. However, on many
   147  	// platforms (even 64-bit), arenaL1Bits is 0, making this
   148  	// effectively a single-level map. In this case, arenas[0]
   149  	// will never be nil.
   150  	arenas [1 << arenaL1Bits]*[1 << arenaL2Bits]*heapArena
   151  
   152  	// heapArenaAlloc is pre-reserved space for allocating heapArena
   153  	// objects. This is only used on 32-bit, where we pre-reserve
   154  	// this space to avoid interleaving it with the heap itself.
   155  	heapArenaAlloc linearAlloc
   156  
   157  	// arenaHints is a list of addresses at which to attempt to
   158  	// add more heap arenas. This is initially populated with a
   159  	// set of general hint addresses, and grown with the bounds of
   160  	// actual heap arena ranges.
   161  	arenaHints *arenaHint
   162  
   163  	// arena is a pre-reserved space for allocating heap arenas
   164  	// (the actual arenas). This is only used on 32-bit.
   165  	arena linearAlloc
   166  
   167  	// allArenas is the arenaIndex of every mapped arena. This can
   168  	// be used to iterate through the address space.
   169  	//
   170  	// Access is protected by mheap_.lock. However, since this is
   171  	// append-only and old backing arrays are never freed, it is
   172  	// safe to acquire mheap_.lock, copy the slice header, and
   173  	// then release mheap_.lock.
   174  	allArenas []arenaIdx
   175  
   176  	// sweepArenas is a snapshot of allArenas taken at the
   177  	// beginning of the sweep cycle. This can be read safely by
   178  	// simply blocking GC (by disabling preemption).
   179  	sweepArenas []arenaIdx
   180  
   181  	// markArenas is a snapshot of allArenas taken at the beginning
   182  	// of the mark cycle. Because allArenas is append-only, neither
   183  	// this slice nor its contents will change during the mark, so
   184  	// it can be read safely.
   185  	markArenas []arenaIdx
   186  
   187  	// curArena is the arena that the heap is currently growing
   188  	// into. This should always be physPageSize-aligned.
   189  	curArena struct {
   190  		base, end uintptr
   191  	}
   192  
   193  	_ uint32 // ensure 64-bit alignment of central
   194  
   195  	// central free lists for small size classes.
   196  	// the padding makes sure that the mcentrals are
   197  	// spaced CacheLinePadSize bytes apart, so that each mcentral.lock
   198  	// gets its own cache line.
   199  	// central is indexed by spanClass.
   200  	central [numSpanClasses]struct {
   201  		mcentral mcentral
   202  		pad      [cpu.CacheLinePadSize - unsafe.Sizeof(mcentral{})%cpu.CacheLinePadSize]byte
   203  	}
   204  
   205  	spanalloc             fixalloc // allocator for span*
   206  	cachealloc            fixalloc // allocator for mcache*
   207  	specialfinalizeralloc fixalloc // allocator for specialfinalizer*
   208  	specialprofilealloc   fixalloc // allocator for specialprofile*
   209  	specialReachableAlloc fixalloc // allocator for specialReachable
   210  	speciallock           mutex    // lock for special record allocators.
   211  	arenaHintAlloc        fixalloc // allocator for arenaHints
   212  
   213  	unused *specialfinalizer // never set, just here to force the specialfinalizer type into DWARF
   214  }
   215  
   216  var mheap_ mheap
   217  
   218  // A heapArena stores metadata for a heap arena. heapArenas are stored
   219  // outside of the Go heap and accessed via the mheap_.arenas index.
   220  //
   221  //go:notinheap
   222  type heapArena struct {
   223  	// bitmap stores the pointer/scalar bitmap for the words in
   224  	// this arena. See mbitmap.go for a description. Use the
   225  	// heapBits type to access this.
   226  	bitmap [heapArenaBitmapBytes]byte
   227  
   228  	// spans maps from virtual address page ID within this arena to *mspan.
   229  	// For allocated spans, their pages map to the span itself.
   230  	// For free spans, only the lowest and highest pages map to the span itself.
   231  	// Internal pages map to an arbitrary span.
   232  	// For pages that have never been allocated, spans entries are nil.
   233  	//
   234  	// Modifications are protected by mheap.lock. Reads can be
   235  	// performed without locking, but ONLY from indexes that are
   236  	// known to contain in-use or stack spans. This means there
   237  	// must not be a safe-point between establishing that an
   238  	// address is live and looking it up in the spans array.
   239  	spans [pagesPerArena]*mspan
   240  
   241  	// pageInUse is a bitmap that indicates which spans are in
   242  	// state mSpanInUse. This bitmap is indexed by page number,
   243  	// but only the bit corresponding to the first page in each
   244  	// span is used.
   245  	//
   246  	// Reads and writes are atomic.
   247  	pageInUse [pagesPerArena / 8]uint8
   248  
   249  	// pageMarks is a bitmap that indicates which spans have any
   250  	// marked objects on them. Like pageInUse, only the bit
   251  	// corresponding to the first page in each span is used.
   252  	//
   253  	// Writes are done atomically during marking. Reads are
   254  	// non-atomic and lock-free since they only occur during
   255  	// sweeping (and hence never race with writes).
   256  	//
   257  	// This is used to quickly find whole spans that can be freed.
   258  	//
   259  	// TODO(austin): It would be nice if this was uint64 for
   260  	// faster scanning, but we don't have 64-bit atomic bit
   261  	// operations.
   262  	pageMarks [pagesPerArena / 8]uint8
   263  
   264  	// pageSpecials is a bitmap that indicates which spans have
   265  	// specials (finalizers or other). Like pageInUse, only the bit
   266  	// corresponding to the first page in each span is used.
   267  	//
   268  	// Writes are done atomically whenever a special is added to
   269  	// a span and whenever the last special is removed from a span.
   270  	// Reads are done atomically to find spans containing specials
   271  	// during marking.
   272  	pageSpecials [pagesPerArena / 8]uint8
   273  
   274  	// checkmarks stores the debug.gccheckmark state. It is only
   275  	// used if debug.gccheckmark > 0.
   276  	checkmarks *checkmarksMap
   277  
   278  	// zeroedBase marks the first byte of the first page in this
   279  	// arena which hasn't been used yet and is therefore already
   280  	// zero. zeroedBase is relative to the arena base.
   281  	// Increases monotonically until it hits heapArenaBytes.
   282  	//
   283  	// This field is sufficient to determine if an allocation
   284  	// needs to be zeroed because the page allocator follows an
   285  	// address-ordered first-fit policy.
   286  	//
   287  	// Read atomically and written with an atomic CAS.
   288  	zeroedBase uintptr
   289  }
   290  
   291  // arenaHint is a hint for where to grow the heap arenas. See
   292  // mheap_.arenaHints.
   293  //
   294  //go:notinheap
   295  type arenaHint struct {
   296  	addr uintptr
   297  	down bool
   298  	next *arenaHint
   299  }
   300  
   301  // An mspan is a run of pages.
   302  //
   303  // When a mspan is in the heap free treap, state == mSpanFree
   304  // and heapmap(s->start) == span, heapmap(s->start+s->npages-1) == span.
   305  // If the mspan is in the heap scav treap, then in addition to the
   306  // above scavenged == true. scavenged == false in all other cases.
   307  //
   308  // When a mspan is allocated, state == mSpanInUse or mSpanManual
   309  // and heapmap(i) == span for all s->start <= i < s->start+s->npages.
   310  
   311  // Every mspan is in one doubly-linked list, either in the mheap's
   312  // busy list or one of the mcentral's span lists.
   313  
   314  // An mspan representing actual memory has state mSpanInUse,
   315  // mSpanManual, or mSpanFree. Transitions between these states are
   316  // constrained as follows:
   317  //
   318  //   - A span may transition from free to in-use or manual during any GC
   319  //     phase.
   320  //
   321  //   - During sweeping (gcphase == _GCoff), a span may transition from
   322  //     in-use to free (as a result of sweeping) or manual to free (as a
   323  //     result of stacks being freed).
   324  //
   325  //   - During GC (gcphase != _GCoff), a span *must not* transition from
   326  //     manual or in-use to free. Because concurrent GC may read a pointer
   327  //     and then look up its span, the span state must be monotonic.
   328  //
   329  // Setting mspan.state to mSpanInUse or mSpanManual must be done
   330  // atomically and only after all other span fields are valid.
   331  // Likewise, if inspecting a span is contingent on it being
   332  // mSpanInUse, the state should be loaded atomically and checked
   333  // before depending on other fields. This allows the garbage collector
   334  // to safely deal with potentially invalid pointers, since resolving
   335  // such pointers may race with a span being allocated.
   336  type mSpanState uint8
   337  
   338  const (
   339  	mSpanDead   mSpanState = iota
   340  	mSpanInUse             // allocated for garbage collected heap
   341  	mSpanManual            // allocated for manual management (e.g., stack allocator)
   342  )
   343  
   344  // mSpanStateNames are the names of the span states, indexed by
   345  // mSpanState.
   346  var mSpanStateNames = []string{
   347  	"mSpanDead",
   348  	"mSpanInUse",
   349  	"mSpanManual",
   350  	"mSpanFree",
   351  }
   352  
   353  // mSpanStateBox holds an mSpanState and provides atomic operations on
   354  // it. This is a separate type to disallow accidental comparison or
   355  // assignment with mSpanState.
   356  type mSpanStateBox struct {
   357  	s mSpanState
   358  }
   359  
   360  func (b *mSpanStateBox) set(s mSpanState) {
   361  	atomic.Store8((*uint8)(&b.s), uint8(s))
   362  }
   363  
   364  func (b *mSpanStateBox) get() mSpanState {
   365  	return mSpanState(atomic.Load8((*uint8)(&b.s)))
   366  }
   367  
   368  // mSpanList heads a linked list of spans.
   369  //
   370  //go:notinheap
   371  type mSpanList struct {
   372  	first *mspan // first span in list, or nil if none
   373  	last  *mspan // last span in list, or nil if none
   374  }
   375  
   376  //go:notinheap
   377  type mspan struct {
   378  	next *mspan     // next span in list, or nil if none
   379  	prev *mspan     // previous span in list, or nil if none
   380  	list *mSpanList // For debugging. TODO: Remove.
   381  
   382  	startAddr uintptr // address of first byte of span aka s.base()
   383  	npages    uintptr // number of pages in span
   384  
   385  	manualFreeList gclinkptr // list of free objects in mSpanManual spans
   386  
   387  	// freeindex is the slot index between 0 and nelems at which to begin scanning
   388  	// for the next free object in this span.
   389  	// Each allocation scans allocBits starting at freeindex until it encounters a 0
   390  	// indicating a free object. freeindex is then adjusted so that subsequent scans begin
   391  	// just past the newly discovered free object.
   392  	//
   393  	// If freeindex == nelem, this span has no free objects.
   394  	//
   395  	// allocBits is a bitmap of objects in this span.
   396  	// If n >= freeindex and allocBits[n/8] & (1<<(n%8)) is 0
   397  	// then object n is free;
   398  	// otherwise, object n is allocated. Bits starting at nelem are
   399  	// undefined and should never be referenced.
   400  	//
   401  	// Object n starts at address n*elemsize + (start << pageShift).
   402  	freeindex uintptr
   403  	// TODO: Look up nelems from sizeclass and remove this field if it
   404  	// helps performance.
   405  	nelems uintptr // number of object in the span.
   406  
   407  	// Cache of the allocBits at freeindex. allocCache is shifted
   408  	// such that the lowest bit corresponds to the bit freeindex.
   409  	// allocCache holds the complement of allocBits, thus allowing
   410  	// ctz (count trailing zero) to use it directly.
   411  	// allocCache may contain bits beyond s.nelems; the caller must ignore
   412  	// these.
   413  	allocCache uint64
   414  
   415  	// allocBits and gcmarkBits hold pointers to a span's mark and
   416  	// allocation bits. The pointers are 8 byte aligned.
   417  	// There are three arenas where this data is held.
   418  	// free: Dirty arenas that are no longer accessed
   419  	//       and can be reused.
   420  	// next: Holds information to be used in the next GC cycle.
   421  	// current: Information being used during this GC cycle.
   422  	// previous: Information being used during the last GC cycle.
   423  	// A new GC cycle starts with the call to finishsweep_m.
   424  	// finishsweep_m moves the previous arena to the free arena,
   425  	// the current arena to the previous arena, and
   426  	// the next arena to the current arena.
   427  	// The next arena is populated as the spans request
   428  	// memory to hold gcmarkBits for the next GC cycle as well
   429  	// as allocBits for newly allocated spans.
   430  	//
   431  	// The pointer arithmetic is done "by hand" instead of using
   432  	// arrays to avoid bounds checks along critical performance
   433  	// paths.
   434  	// The sweep will free the old allocBits and set allocBits to the
   435  	// gcmarkBits. The gcmarkBits are replaced with a fresh zeroed
   436  	// out memory.
   437  	allocBits  *gcBits
   438  	gcmarkBits *gcBits
   439  
   440  	// sweep generation:
   441  	// if sweepgen == h->sweepgen - 2, the span needs sweeping
   442  	// if sweepgen == h->sweepgen - 1, the span is currently being swept
   443  	// if sweepgen == h->sweepgen, the span is swept and ready to use
   444  	// if sweepgen == h->sweepgen + 1, the span was cached before sweep began and is still cached, and needs sweeping
   445  	// if sweepgen == h->sweepgen + 3, the span was swept and then cached and is still cached
   446  	// h->sweepgen is incremented by 2 after every GC
   447  
   448  	sweepgen              uint32
   449  	divMul                uint32        // for divide by elemsize
   450  	allocCount            uint16        // number of allocated objects
   451  	spanclass             spanClass     // size class and noscan (uint8)
   452  	state                 mSpanStateBox // mSpanInUse etc; accessed atomically (get/set methods)
   453  	needzero              uint8         // needs to be zeroed before allocation
   454  	allocCountBeforeCache uint16        // a copy of allocCount that is stored just before this span is cached
   455  	elemsize              uintptr       // computed from sizeclass or from npages
   456  	limit                 uintptr       // end of data in span
   457  	speciallock           mutex         // guards specials list
   458  	specials              *special      // linked list of special records sorted by offset.
   459  }
   460  
   461  func (s *mspan) base() uintptr {
   462  	return s.startAddr
   463  }
   464  
   465  func (s *mspan) layout() (size, n, total uintptr) {
   466  	total = s.npages << _PageShift
   467  	size = s.elemsize
   468  	if size > 0 {
   469  		n = total / size
   470  	}
   471  	return
   472  }
   473  
   474  // recordspan adds a newly allocated span to h.allspans.
   475  //
   476  // This only happens the first time a span is allocated from
   477  // mheap.spanalloc (it is not called when a span is reused).
   478  //
   479  // Write barriers are disallowed here because it can be called from
   480  // gcWork when allocating new workbufs. However, because it's an
   481  // indirect call from the fixalloc initializer, the compiler can't see
   482  // this.
   483  //
   484  // The heap lock must be held.
   485  //
   486  //go:nowritebarrierrec
   487  func recordspan(vh unsafe.Pointer, p unsafe.Pointer) {
   488  	h := (*mheap)(vh)
   489  	s := (*mspan)(p)
   490  
   491  	assertLockHeld(&h.lock)
   492  
   493  	if len(h.allspans) >= cap(h.allspans) {
   494  		n := 64 * 1024 / goarch.PtrSize
   495  		if n < cap(h.allspans)*3/2 {
   496  			n = cap(h.allspans) * 3 / 2
   497  		}
   498  		var new []*mspan
   499  		sp := (*slice)(unsafe.Pointer(&new))
   500  		sp.array = sysAlloc(uintptr(n)*goarch.PtrSize, &memstats.other_sys)
   501  		if sp.array == nil {
   502  			throw("runtime: cannot allocate memory")
   503  		}
   504  		sp.len = len(h.allspans)
   505  		sp.cap = n
   506  		if len(h.allspans) > 0 {
   507  			copy(new, h.allspans)
   508  		}
   509  		oldAllspans := h.allspans
   510  		*(*notInHeapSlice)(unsafe.Pointer(&h.allspans)) = *(*notInHeapSlice)(unsafe.Pointer(&new))
   511  		if len(oldAllspans) != 0 {
   512  			sysFree(unsafe.Pointer(&oldAllspans[0]), uintptr(cap(oldAllspans))*unsafe.Sizeof(oldAllspans[0]), &memstats.other_sys)
   513  		}
   514  	}
   515  	h.allspans = h.allspans[:len(h.allspans)+1]
   516  	h.allspans[len(h.allspans)-1] = s
   517  }
   518  
   519  // A spanClass represents the size class and noscan-ness of a span.
   520  //
   521  // Each size class has a noscan spanClass and a scan spanClass. The
   522  // noscan spanClass contains only noscan objects, which do not contain
   523  // pointers and thus do not need to be scanned by the garbage
   524  // collector.
   525  type spanClass uint8
   526  
   527  const (
   528  	numSpanClasses = _NumSizeClasses << 1
   529  	tinySpanClass  = spanClass(tinySizeClass<<1 | 1)
   530  )
   531  
   532  func makeSpanClass(sizeclass uint8, noscan bool) spanClass {
   533  	return spanClass(sizeclass<<1) | spanClass(bool2int(noscan))
   534  }
   535  
   536  func (sc spanClass) sizeclass() int8 {
   537  	return int8(sc >> 1)
   538  }
   539  
   540  func (sc spanClass) noscan() bool {
   541  	return sc&1 != 0
   542  }
   543  
   544  // arenaIndex returns the index into mheap_.arenas of the arena
   545  // containing metadata for p. This index combines of an index into the
   546  // L1 map and an index into the L2 map and should be used as
   547  // mheap_.arenas[ai.l1()][ai.l2()].
   548  //
   549  // If p is outside the range of valid heap addresses, either l1() or
   550  // l2() will be out of bounds.
   551  //
   552  // It is nosplit because it's called by spanOf and several other
   553  // nosplit functions.
   554  //
   555  //go:nosplit
   556  func arenaIndex(p uintptr) arenaIdx {
   557  	return arenaIdx((p - arenaBaseOffset) / heapArenaBytes)
   558  }
   559  
   560  // arenaBase returns the low address of the region covered by heap
   561  // arena i.
   562  func arenaBase(i arenaIdx) uintptr {
   563  	return uintptr(i)*heapArenaBytes + arenaBaseOffset
   564  }
   565  
   566  type arenaIdx uint
   567  
   568  func (i arenaIdx) l1() uint {
   569  	if arenaL1Bits == 0 {
   570  		// Let the compiler optimize this away if there's no
   571  		// L1 map.
   572  		return 0
   573  	} else {
   574  		return uint(i) >> arenaL1Shift
   575  	}
   576  }
   577  
   578  func (i arenaIdx) l2() uint {
   579  	if arenaL1Bits == 0 {
   580  		return uint(i)
   581  	} else {
   582  		return uint(i) & (1<<arenaL2Bits - 1)
   583  	}
   584  }
   585  
   586  // inheap reports whether b is a pointer into a (potentially dead) heap object.
   587  // It returns false for pointers into mSpanManual spans.
   588  // Non-preemptible because it is used by write barriers.
   589  //
   590  //go:nowritebarrier
   591  //go:nosplit
   592  func inheap(b uintptr) bool {
   593  	return spanOfHeap(b) != nil
   594  }
   595  
   596  // inHeapOrStack is a variant of inheap that returns true for pointers
   597  // into any allocated heap span.
   598  //
   599  //go:nowritebarrier
   600  //go:nosplit
   601  func inHeapOrStack(b uintptr) bool {
   602  	s := spanOf(b)
   603  	if s == nil || b < s.base() {
   604  		return false
   605  	}
   606  	switch s.state.get() {
   607  	case mSpanInUse, mSpanManual:
   608  		return b < s.limit
   609  	default:
   610  		return false
   611  	}
   612  }
   613  
   614  // spanOf returns the span of p. If p does not point into the heap
   615  // arena or no span has ever contained p, spanOf returns nil.
   616  //
   617  // If p does not point to allocated memory, this may return a non-nil
   618  // span that does *not* contain p. If this is a possibility, the
   619  // caller should either call spanOfHeap or check the span bounds
   620  // explicitly.
   621  //
   622  // Must be nosplit because it has callers that are nosplit.
   623  //
   624  //go:nosplit
   625  func spanOf(p uintptr) *mspan {
   626  	// This function looks big, but we use a lot of constant
   627  	// folding around arenaL1Bits to get it under the inlining
   628  	// budget. Also, many of the checks here are safety checks
   629  	// that Go needs to do anyway, so the generated code is quite
   630  	// short.
   631  	ri := arenaIndex(p)
   632  	if arenaL1Bits == 0 {
   633  		// If there's no L1, then ri.l1() can't be out of bounds but ri.l2() can.
   634  		if ri.l2() >= uint(len(mheap_.arenas[0])) {
   635  			return nil
   636  		}
   637  	} else {
   638  		// If there's an L1, then ri.l1() can be out of bounds but ri.l2() can't.
   639  		if ri.l1() >= uint(len(mheap_.arenas)) {
   640  			return nil
   641  		}
   642  	}
   643  	l2 := mheap_.arenas[ri.l1()]
   644  	if arenaL1Bits != 0 && l2 == nil { // Should never happen if there's no L1.
   645  		return nil
   646  	}
   647  	ha := l2[ri.l2()]
   648  	if ha == nil {
   649  		return nil
   650  	}
   651  	return ha.spans[(p/pageSize)%pagesPerArena]
   652  }
   653  
   654  // spanOfUnchecked is equivalent to spanOf, but the caller must ensure
   655  // that p points into an allocated heap arena.
   656  //
   657  // Must be nosplit because it has callers that are nosplit.
   658  //
   659  //go:nosplit
   660  func spanOfUnchecked(p uintptr) *mspan {
   661  	ai := arenaIndex(p)
   662  	return mheap_.arenas[ai.l1()][ai.l2()].spans[(p/pageSize)%pagesPerArena]
   663  }
   664  
   665  // spanOfHeap is like spanOf, but returns nil if p does not point to a
   666  // heap object.
   667  //
   668  // Must be nosplit because it has callers that are nosplit.
   669  //
   670  //go:nosplit
   671  func spanOfHeap(p uintptr) *mspan {
   672  	s := spanOf(p)
   673  	// s is nil if it's never been allocated. Otherwise, we check
   674  	// its state first because we don't trust this pointer, so we
   675  	// have to synchronize with span initialization. Then, it's
   676  	// still possible we picked up a stale span pointer, so we
   677  	// have to check the span's bounds.
   678  	if s == nil || s.state.get() != mSpanInUse || p < s.base() || p >= s.limit {
   679  		return nil
   680  	}
   681  	return s
   682  }
   683  
   684  // pageIndexOf returns the arena, page index, and page mask for pointer p.
   685  // The caller must ensure p is in the heap.
   686  func pageIndexOf(p uintptr) (arena *heapArena, pageIdx uintptr, pageMask uint8) {
   687  	ai := arenaIndex(p)
   688  	arena = mheap_.arenas[ai.l1()][ai.l2()]
   689  	pageIdx = ((p / pageSize) / 8) % uintptr(len(arena.pageInUse))
   690  	pageMask = byte(1 << ((p / pageSize) % 8))
   691  	return
   692  }
   693  
   694  // Initialize the heap.
   695  func (h *mheap) init() {
   696  	lockInit(&h.lock, lockRankMheap)
   697  	lockInit(&h.speciallock, lockRankMheapSpecial)
   698  
   699  	h.spanalloc.init(unsafe.Sizeof(mspan{}), recordspan, unsafe.Pointer(h), &memstats.mspan_sys)
   700  	h.cachealloc.init(unsafe.Sizeof(mcache{}), nil, nil, &memstats.mcache_sys)
   701  	h.specialfinalizeralloc.init(unsafe.Sizeof(specialfinalizer{}), nil, nil, &memstats.other_sys)
   702  	h.specialprofilealloc.init(unsafe.Sizeof(specialprofile{}), nil, nil, &memstats.other_sys)
   703  	h.specialReachableAlloc.init(unsafe.Sizeof(specialReachable{}), nil, nil, &memstats.other_sys)
   704  	h.arenaHintAlloc.init(unsafe.Sizeof(arenaHint{}), nil, nil, &memstats.other_sys)
   705  
   706  	// Don't zero mspan allocations. Background sweeping can
   707  	// inspect a span concurrently with allocating it, so it's
   708  	// important that the span's sweepgen survive across freeing
   709  	// and re-allocating a span to prevent background sweeping
   710  	// from improperly cas'ing it from 0.
   711  	//
   712  	// This is safe because mspan contains no heap pointers.
   713  	h.spanalloc.zero = false
   714  
   715  	// h->mapcache needs no init
   716  
   717  	for i := range h.central {
   718  		h.central[i].mcentral.init(spanClass(i))
   719  	}
   720  
   721  	h.pages.init(&h.lock, &memstats.gcMiscSys)
   722  }
   723  
   724  // reclaim sweeps and reclaims at least npage pages into the heap.
   725  // It is called before allocating npage pages to keep growth in check.
   726  //
   727  // reclaim implements the page-reclaimer half of the sweeper.
   728  //
   729  // h.lock must NOT be held.
   730  func (h *mheap) reclaim(npage uintptr) {
   731  	// TODO(austin): Half of the time spent freeing spans is in
   732  	// locking/unlocking the heap (even with low contention). We
   733  	// could make the slow path here several times faster by
   734  	// batching heap frees.
   735  
   736  	// Bail early if there's no more reclaim work.
   737  	if h.reclaimIndex.Load() >= 1<<63 {
   738  		return
   739  	}
   740  
   741  	// Disable preemption so the GC can't start while we're
   742  	// sweeping, so we can read h.sweepArenas, and so
   743  	// traceGCSweepStart/Done pair on the P.
   744  	mp := acquirem()
   745  
   746  	if trace.enabled {
   747  		traceGCSweepStart()
   748  	}
   749  
   750  	arenas := h.sweepArenas
   751  	locked := false
   752  	for npage > 0 {
   753  		// Pull from accumulated credit first.
   754  		if credit := h.reclaimCredit.Load(); credit > 0 {
   755  			take := credit
   756  			if take > npage {
   757  				// Take only what we need.
   758  				take = npage
   759  			}
   760  			if h.reclaimCredit.CompareAndSwap(credit, credit-take) {
   761  				npage -= take
   762  			}
   763  			continue
   764  		}
   765  
   766  		// Claim a chunk of work.
   767  		idx := uintptr(h.reclaimIndex.Add(pagesPerReclaimerChunk) - pagesPerReclaimerChunk)
   768  		if idx/pagesPerArena >= uintptr(len(arenas)) {
   769  			// Page reclaiming is done.
   770  			h.reclaimIndex.Store(1 << 63)
   771  			break
   772  		}
   773  
   774  		if !locked {
   775  			// Lock the heap for reclaimChunk.
   776  			lock(&h.lock)
   777  			locked = true
   778  		}
   779  
   780  		// Scan this chunk.
   781  		nfound := h.reclaimChunk(arenas, idx, pagesPerReclaimerChunk)
   782  		if nfound <= npage {
   783  			npage -= nfound
   784  		} else {
   785  			// Put spare pages toward global credit.
   786  			h.reclaimCredit.Add(nfound - npage)
   787  			npage = 0
   788  		}
   789  	}
   790  	if locked {
   791  		unlock(&h.lock)
   792  	}
   793  
   794  	if trace.enabled {
   795  		traceGCSweepDone()
   796  	}
   797  	releasem(mp)
   798  }
   799  
   800  // reclaimChunk sweeps unmarked spans that start at page indexes [pageIdx, pageIdx+n).
   801  // It returns the number of pages returned to the heap.
   802  //
   803  // h.lock must be held and the caller must be non-preemptible. Note: h.lock may be
   804  // temporarily unlocked and re-locked in order to do sweeping or if tracing is
   805  // enabled.
   806  func (h *mheap) reclaimChunk(arenas []arenaIdx, pageIdx, n uintptr) uintptr {
   807  	// The heap lock must be held because this accesses the
   808  	// heapArena.spans arrays using potentially non-live pointers.
   809  	// In particular, if a span were freed and merged concurrently
   810  	// with this probing heapArena.spans, it would be possible to
   811  	// observe arbitrary, stale span pointers.
   812  	assertLockHeld(&h.lock)
   813  
   814  	n0 := n
   815  	var nFreed uintptr
   816  	sl := sweep.active.begin()
   817  	if !sl.valid {
   818  		return 0
   819  	}
   820  	for n > 0 {
   821  		ai := arenas[pageIdx/pagesPerArena]
   822  		ha := h.arenas[ai.l1()][ai.l2()]
   823  
   824  		// Get a chunk of the bitmap to work on.
   825  		arenaPage := uint(pageIdx % pagesPerArena)
   826  		inUse := ha.pageInUse[arenaPage/8:]
   827  		marked := ha.pageMarks[arenaPage/8:]
   828  		if uintptr(len(inUse)) > n/8 {
   829  			inUse = inUse[:n/8]
   830  			marked = marked[:n/8]
   831  		}
   832  
   833  		// Scan this bitmap chunk for spans that are in-use
   834  		// but have no marked objects on them.
   835  		for i := range inUse {
   836  			inUseUnmarked := atomic.Load8(&inUse[i]) &^ marked[i]
   837  			if inUseUnmarked == 0 {
   838  				continue
   839  			}
   840  
   841  			for j := uint(0); j < 8; j++ {
   842  				if inUseUnmarked&(1<<j) != 0 {
   843  					s := ha.spans[arenaPage+uint(i)*8+j]
   844  					if s, ok := sl.tryAcquire(s); ok {
   845  						npages := s.npages
   846  						unlock(&h.lock)
   847  						if s.sweep(false) {
   848  							nFreed += npages
   849  						}
   850  						lock(&h.lock)
   851  						// Reload inUse. It's possible nearby
   852  						// spans were freed when we dropped the
   853  						// lock and we don't want to get stale
   854  						// pointers from the spans array.
   855  						inUseUnmarked = atomic.Load8(&inUse[i]) &^ marked[i]
   856  					}
   857  				}
   858  			}
   859  		}
   860  
   861  		// Advance.
   862  		pageIdx += uintptr(len(inUse) * 8)
   863  		n -= uintptr(len(inUse) * 8)
   864  	}
   865  	sweep.active.end(sl)
   866  	if trace.enabled {
   867  		unlock(&h.lock)
   868  		// Account for pages scanned but not reclaimed.
   869  		traceGCSweepSpan((n0 - nFreed) * pageSize)
   870  		lock(&h.lock)
   871  	}
   872  
   873  	assertLockHeld(&h.lock) // Must be locked on return.
   874  	return nFreed
   875  }
   876  
   877  // spanAllocType represents the type of allocation to make, or
   878  // the type of allocation to be freed.
   879  type spanAllocType uint8
   880  
   881  const (
   882  	spanAllocHeap          spanAllocType = iota // heap span
   883  	spanAllocStack                              // stack span
   884  	spanAllocPtrScalarBits                      // unrolled GC prog bitmap span
   885  	spanAllocWorkBuf                            // work buf span
   886  )
   887  
   888  // manual returns true if the span allocation is manually managed.
   889  func (s spanAllocType) manual() bool {
   890  	return s != spanAllocHeap
   891  }
   892  
   893  // alloc allocates a new span of npage pages from the GC'd heap.
   894  //
   895  // spanclass indicates the span's size class and scannability.
   896  //
   897  // Returns a span that has been fully initialized. span.needzero indicates
   898  // whether the span has been zeroed. Note that it may not be.
   899  func (h *mheap) alloc(npages uintptr, spanclass spanClass) *mspan {
   900  	// Don't do any operations that lock the heap on the G stack.
   901  	// It might trigger stack growth, and the stack growth code needs
   902  	// to be able to allocate heap.
   903  	var s *mspan
   904  	systemstack(func() {
   905  		// To prevent excessive heap growth, before allocating n pages
   906  		// we need to sweep and reclaim at least n pages.
   907  		if !isSweepDone() {
   908  			h.reclaim(npages)
   909  		}
   910  		s = h.allocSpan(npages, spanAllocHeap, spanclass)
   911  	})
   912  	return s
   913  }
   914  
   915  // allocManual allocates a manually-managed span of npage pages.
   916  // allocManual returns nil if allocation fails.
   917  //
   918  // allocManual adds the bytes used to *stat, which should be a
   919  // memstats in-use field. Unlike allocations in the GC'd heap, the
   920  // allocation does *not* count toward heapInUse.
   921  //
   922  // The memory backing the returned span may not be zeroed if
   923  // span.needzero is set.
   924  //
   925  // allocManual must be called on the system stack because it may
   926  // acquire the heap lock via allocSpan. See mheap for details.
   927  //
   928  // If new code is written to call allocManual, do NOT use an
   929  // existing spanAllocType value and instead declare a new one.
   930  //
   931  //go:systemstack
   932  func (h *mheap) allocManual(npages uintptr, typ spanAllocType) *mspan {
   933  	if !typ.manual() {
   934  		throw("manual span allocation called with non-manually-managed type")
   935  	}
   936  	return h.allocSpan(npages, typ, 0)
   937  }
   938  
   939  // setSpans modifies the span map so [spanOf(base), spanOf(base+npage*pageSize))
   940  // is s.
   941  func (h *mheap) setSpans(base, npage uintptr, s *mspan) {
   942  	p := base / pageSize
   943  	ai := arenaIndex(base)
   944  	ha := h.arenas[ai.l1()][ai.l2()]
   945  	for n := uintptr(0); n < npage; n++ {
   946  		i := (p + n) % pagesPerArena
   947  		if i == 0 {
   948  			ai = arenaIndex(base + n*pageSize)
   949  			ha = h.arenas[ai.l1()][ai.l2()]
   950  		}
   951  		ha.spans[i] = s
   952  	}
   953  }
   954  
   955  // allocNeedsZero checks if the region of address space [base, base+npage*pageSize),
   956  // assumed to be allocated, needs to be zeroed, updating heap arena metadata for
   957  // future allocations.
   958  //
   959  // This must be called each time pages are allocated from the heap, even if the page
   960  // allocator can otherwise prove the memory it's allocating is already zero because
   961  // they're fresh from the operating system. It updates heapArena metadata that is
   962  // critical for future page allocations.
   963  //
   964  // There are no locking constraints on this method.
   965  func (h *mheap) allocNeedsZero(base, npage uintptr) (needZero bool) {
   966  	for npage > 0 {
   967  		ai := arenaIndex(base)
   968  		ha := h.arenas[ai.l1()][ai.l2()]
   969  
   970  		zeroedBase := atomic.Loaduintptr(&ha.zeroedBase)
   971  		arenaBase := base % heapArenaBytes
   972  		if arenaBase < zeroedBase {
   973  			// We extended into the non-zeroed part of the
   974  			// arena, so this region needs to be zeroed before use.
   975  			//
   976  			// zeroedBase is monotonically increasing, so if we see this now then
   977  			// we can be sure we need to zero this memory region.
   978  			//
   979  			// We still need to update zeroedBase for this arena, and
   980  			// potentially more arenas.
   981  			needZero = true
   982  		}
   983  		// We may observe arenaBase > zeroedBase if we're racing with one or more
   984  		// allocations which are acquiring memory directly before us in the address
   985  		// space. But, because we know no one else is acquiring *this* memory, it's
   986  		// still safe to not zero.
   987  
   988  		// Compute how far into the arena we extend into, capped
   989  		// at heapArenaBytes.
   990  		arenaLimit := arenaBase + npage*pageSize
   991  		if arenaLimit > heapArenaBytes {
   992  			arenaLimit = heapArenaBytes
   993  		}
   994  		// Increase ha.zeroedBase so it's >= arenaLimit.
   995  		// We may be racing with other updates.
   996  		for arenaLimit > zeroedBase {
   997  			if atomic.Casuintptr(&ha.zeroedBase, zeroedBase, arenaLimit) {
   998  				break
   999  			}
  1000  			zeroedBase = atomic.Loaduintptr(&ha.zeroedBase)
  1001  			// Double check basic conditions of zeroedBase.
  1002  			if zeroedBase <= arenaLimit && zeroedBase > arenaBase {
  1003  				// The zeroedBase moved into the space we were trying to
  1004  				// claim. That's very bad, and indicates someone allocated
  1005  				// the same region we did.
  1006  				throw("potentially overlapping in-use allocations detected")
  1007  			}
  1008  		}
  1009  
  1010  		// Move base forward and subtract from npage to move into
  1011  		// the next arena, or finish.
  1012  		base += arenaLimit - arenaBase
  1013  		npage -= (arenaLimit - arenaBase) / pageSize
  1014  	}
  1015  	return
  1016  }
  1017  
  1018  // tryAllocMSpan attempts to allocate an mspan object from
  1019  // the P-local cache, but may fail.
  1020  //
  1021  // h.lock need not be held.
  1022  //
  1023  // This caller must ensure that its P won't change underneath
  1024  // it during this function. Currently to ensure that we enforce
  1025  // that the function is run on the system stack, because that's
  1026  // the only place it is used now. In the future, this requirement
  1027  // may be relaxed if its use is necessary elsewhere.
  1028  //
  1029  //go:systemstack
  1030  func (h *mheap) tryAllocMSpan() *mspan {
  1031  	pp := getg().m.p.ptr()
  1032  	// If we don't have a p or the cache is empty, we can't do
  1033  	// anything here.
  1034  	if pp == nil || pp.mspancache.len == 0 {
  1035  		return nil
  1036  	}
  1037  	// Pull off the last entry in the cache.
  1038  	s := pp.mspancache.buf[pp.mspancache.len-1]
  1039  	pp.mspancache.len--
  1040  	return s
  1041  }
  1042  
  1043  // allocMSpanLocked allocates an mspan object.
  1044  //
  1045  // h.lock must be held.
  1046  //
  1047  // allocMSpanLocked must be called on the system stack because
  1048  // its caller holds the heap lock. See mheap for details.
  1049  // Running on the system stack also ensures that we won't
  1050  // switch Ps during this function. See tryAllocMSpan for details.
  1051  //
  1052  //go:systemstack
  1053  func (h *mheap) allocMSpanLocked() *mspan {
  1054  	assertLockHeld(&h.lock)
  1055  
  1056  	pp := getg().m.p.ptr()
  1057  	if pp == nil {
  1058  		// We don't have a p so just do the normal thing.
  1059  		return (*mspan)(h.spanalloc.alloc())
  1060  	}
  1061  	// Refill the cache if necessary.
  1062  	if pp.mspancache.len == 0 {
  1063  		const refillCount = len(pp.mspancache.buf) / 2
  1064  		for i := 0; i < refillCount; i++ {
  1065  			pp.mspancache.buf[i] = (*mspan)(h.spanalloc.alloc())
  1066  		}
  1067  		pp.mspancache.len = refillCount
  1068  	}
  1069  	// Pull off the last entry in the cache.
  1070  	s := pp.mspancache.buf[pp.mspancache.len-1]
  1071  	pp.mspancache.len--
  1072  	return s
  1073  }
  1074  
  1075  // freeMSpanLocked free an mspan object.
  1076  //
  1077  // h.lock must be held.
  1078  //
  1079  // freeMSpanLocked must be called on the system stack because
  1080  // its caller holds the heap lock. See mheap for details.
  1081  // Running on the system stack also ensures that we won't
  1082  // switch Ps during this function. See tryAllocMSpan for details.
  1083  //
  1084  //go:systemstack
  1085  func (h *mheap) freeMSpanLocked(s *mspan) {
  1086  	assertLockHeld(&h.lock)
  1087  
  1088  	pp := getg().m.p.ptr()
  1089  	// First try to free the mspan directly to the cache.
  1090  	if pp != nil && pp.mspancache.len < len(pp.mspancache.buf) {
  1091  		pp.mspancache.buf[pp.mspancache.len] = s
  1092  		pp.mspancache.len++
  1093  		return
  1094  	}
  1095  	// Failing that (or if we don't have a p), just free it to
  1096  	// the heap.
  1097  	h.spanalloc.free(unsafe.Pointer(s))
  1098  }
  1099  
  1100  // allocSpan allocates an mspan which owns npages worth of memory.
  1101  //
  1102  // If typ.manual() == false, allocSpan allocates a heap span of class spanclass
  1103  // and updates heap accounting. If manual == true, allocSpan allocates a
  1104  // manually-managed span (spanclass is ignored), and the caller is
  1105  // responsible for any accounting related to its use of the span. Either
  1106  // way, allocSpan will atomically add the bytes in the newly allocated
  1107  // span to *sysStat.
  1108  //
  1109  // The returned span is fully initialized.
  1110  //
  1111  // h.lock must not be held.
  1112  //
  1113  // allocSpan must be called on the system stack both because it acquires
  1114  // the heap lock and because it must block GC transitions.
  1115  //
  1116  //go:systemstack
  1117  func (h *mheap) allocSpan(npages uintptr, typ spanAllocType, spanclass spanClass) (s *mspan) {
  1118  	// Function-global state.
  1119  	gp := getg()
  1120  	base, scav := uintptr(0), uintptr(0)
  1121  	growth := uintptr(0)
  1122  
  1123  	// On some platforms we need to provide physical page aligned stack
  1124  	// allocations. Where the page size is less than the physical page
  1125  	// size, we already manage to do this by default.
  1126  	needPhysPageAlign := physPageAlignedStacks && typ == spanAllocStack && pageSize < physPageSize
  1127  
  1128  	// If the allocation is small enough, try the page cache!
  1129  	// The page cache does not support aligned allocations, so we cannot use
  1130  	// it if we need to provide a physical page aligned stack allocation.
  1131  	pp := gp.m.p.ptr()
  1132  	if !needPhysPageAlign && pp != nil && npages < pageCachePages/4 {
  1133  		c := &pp.pcache
  1134  
  1135  		// If the cache is empty, refill it.
  1136  		if c.empty() {
  1137  			lock(&h.lock)
  1138  			*c = h.pages.allocToCache()
  1139  			unlock(&h.lock)
  1140  		}
  1141  
  1142  		// Try to allocate from the cache.
  1143  		base, scav = c.alloc(npages)
  1144  		if base != 0 {
  1145  			s = h.tryAllocMSpan()
  1146  			if s != nil {
  1147  				goto HaveSpan
  1148  			}
  1149  			// We have a base but no mspan, so we need
  1150  			// to lock the heap.
  1151  		}
  1152  	}
  1153  
  1154  	// For one reason or another, we couldn't get the
  1155  	// whole job done without the heap lock.
  1156  	lock(&h.lock)
  1157  
  1158  	if needPhysPageAlign {
  1159  		// Overallocate by a physical page to allow for later alignment.
  1160  		extraPages := physPageSize / pageSize
  1161  
  1162  		// Find a big enough region first, but then only allocate the
  1163  		// aligned portion. We can't just allocate and then free the
  1164  		// edges because we need to account for scavenged memory, and
  1165  		// that's difficult with alloc.
  1166  		//
  1167  		// Note that we skip updates to searchAddr here. It's OK if
  1168  		// it's stale and higher than normal; it'll operate correctly,
  1169  		// just come with a performance cost.
  1170  		base, _ = h.pages.find(npages + extraPages)
  1171  		if base == 0 {
  1172  			var ok bool
  1173  			growth, ok = h.grow(npages + extraPages)
  1174  			if !ok {
  1175  				unlock(&h.lock)
  1176  				return nil
  1177  			}
  1178  			base, _ = h.pages.find(npages + extraPages)
  1179  			if base == 0 {
  1180  				throw("grew heap, but no adequate free space found")
  1181  			}
  1182  		}
  1183  		base = alignUp(base, physPageSize)
  1184  		scav = h.pages.allocRange(base, npages)
  1185  	}
  1186  	if base == 0 {
  1187  		// Try to acquire a base address.
  1188  		base, scav = h.pages.alloc(npages)
  1189  		if base == 0 {
  1190  			var ok bool
  1191  			growth, ok = h.grow(npages)
  1192  			if !ok {
  1193  				unlock(&h.lock)
  1194  				return nil
  1195  			}
  1196  			base, scav = h.pages.alloc(npages)
  1197  			if base == 0 {
  1198  				throw("grew heap, but no adequate free space found")
  1199  			}
  1200  		}
  1201  	}
  1202  	if s == nil {
  1203  		// We failed to get an mspan earlier, so grab
  1204  		// one now that we have the heap lock.
  1205  		s = h.allocMSpanLocked()
  1206  	}
  1207  	unlock(&h.lock)
  1208  
  1209  HaveSpan:
  1210  	// At this point, both s != nil and base != 0, and the heap
  1211  	// lock is no longer held. Initialize the span.
  1212  	s.init(base, npages)
  1213  	if h.allocNeedsZero(base, npages) {
  1214  		s.needzero = 1
  1215  	}
  1216  	nbytes := npages * pageSize
  1217  	if typ.manual() {
  1218  		s.manualFreeList = 0
  1219  		s.nelems = 0
  1220  		s.limit = s.base() + s.npages*pageSize
  1221  		s.state.set(mSpanManual)
  1222  	} else {
  1223  		// We must set span properties before the span is published anywhere
  1224  		// since we're not holding the heap lock.
  1225  		s.spanclass = spanclass
  1226  		if sizeclass := spanclass.sizeclass(); sizeclass == 0 {
  1227  			s.elemsize = nbytes
  1228  			s.nelems = 1
  1229  			s.divMul = 0
  1230  		} else {
  1231  			s.elemsize = uintptr(class_to_size[sizeclass])
  1232  			s.nelems = nbytes / s.elemsize
  1233  			s.divMul = class_to_divmagic[sizeclass]
  1234  		}
  1235  
  1236  		// Initialize mark and allocation structures.
  1237  		s.freeindex = 0
  1238  		s.allocCache = ^uint64(0) // all 1s indicating all free.
  1239  		s.gcmarkBits = newMarkBits(s.nelems)
  1240  		s.allocBits = newAllocBits(s.nelems)
  1241  
  1242  		// It's safe to access h.sweepgen without the heap lock because it's
  1243  		// only ever updated with the world stopped and we run on the
  1244  		// systemstack which blocks a STW transition.
  1245  		atomic.Store(&s.sweepgen, h.sweepgen)
  1246  
  1247  		// Now that the span is filled in, set its state. This
  1248  		// is a publication barrier for the other fields in
  1249  		// the span. While valid pointers into this span
  1250  		// should never be visible until the span is returned,
  1251  		// if the garbage collector finds an invalid pointer,
  1252  		// access to the span may race with initialization of
  1253  		// the span. We resolve this race by atomically
  1254  		// setting the state after the span is fully
  1255  		// initialized, and atomically checking the state in
  1256  		// any situation where a pointer is suspect.
  1257  		s.state.set(mSpanInUse)
  1258  	}
  1259  
  1260  	// Decide if we need to scavenge in response to what we just allocated.
  1261  	// Specifically, we track the maximum amount of memory to scavenge of all
  1262  	// the alternatives below, assuming that the maximum satisfies *all*
  1263  	// conditions we check (e.g. if we need to scavenge X to satisfy the
  1264  	// memory limit and Y to satisfy heap-growth scavenging, and Y > X, then
  1265  	// it's fine to pick Y, because the memory limit is still satisfied).
  1266  	//
  1267  	// It's fine to do this after allocating because we expect any scavenged
  1268  	// pages not to get touched until we return. Simultaneously, it's important
  1269  	// to do this before calling sysUsed because that may commit address space.
  1270  	bytesToScavenge := uintptr(0)
  1271  	if limit := gcController.memoryLimit.Load(); go119MemoryLimitSupport && !gcCPULimiter.limiting() {
  1272  		// Assist with scavenging to maintain the memory limit by the amount
  1273  		// that we expect to page in.
  1274  		inuse := gcController.mappedReady.Load()
  1275  		// Be careful about overflow, especially with uintptrs. Even on 32-bit platforms
  1276  		// someone can set a really big memory limit that isn't maxInt64.
  1277  		if uint64(scav)+inuse > uint64(limit) {
  1278  			bytesToScavenge = uintptr(uint64(scav) + inuse - uint64(limit))
  1279  		}
  1280  	}
  1281  	if goal := scavenge.gcPercentGoal.Load(); goal != ^uint64(0) && growth > 0 {
  1282  		// We just caused a heap growth, so scavenge down what will soon be used.
  1283  		// By scavenging inline we deal with the failure to allocate out of
  1284  		// memory fragments by scavenging the memory fragments that are least
  1285  		// likely to be re-used.
  1286  		//
  1287  		// Only bother with this because we're not using a memory limit. We don't
  1288  		// care about heap growths as long as we're under the memory limit, and the
  1289  		// previous check for scaving already handles that.
  1290  		if retained := heapRetained(); retained+uint64(growth) > goal {
  1291  			// The scavenging algorithm requires the heap lock to be dropped so it
  1292  			// can acquire it only sparingly. This is a potentially expensive operation
  1293  			// so it frees up other goroutines to allocate in the meanwhile. In fact,
  1294  			// they can make use of the growth we just created.
  1295  			todo := growth
  1296  			if overage := uintptr(retained + uint64(growth) - goal); todo > overage {
  1297  				todo = overage
  1298  			}
  1299  			if todo > bytesToScavenge {
  1300  				bytesToScavenge = todo
  1301  			}
  1302  		}
  1303  	}
  1304  	// There are a few very limited cirumstances where we won't have a P here.
  1305  	// It's OK to simply skip scavenging in these cases. Something else will notice
  1306  	// and pick up the tab.
  1307  	if pp != nil && bytesToScavenge > 0 {
  1308  		// Measure how long we spent scavenging and add that measurement to the assist
  1309  		// time so we can track it for the GC CPU limiter.
  1310  		//
  1311  		// Limiter event tracking might be disabled if we end up here
  1312  		// while on a mark worker.
  1313  		start := nanotime()
  1314  		track := pp.limiterEvent.start(limiterEventScavengeAssist, start)
  1315  
  1316  		// Scavenge, but back out if the limiter turns on.
  1317  		h.pages.scavenge(bytesToScavenge, func() bool {
  1318  			return gcCPULimiter.limiting()
  1319  		})
  1320  
  1321  		// Finish up accounting.
  1322  		now := nanotime()
  1323  		if track {
  1324  			pp.limiterEvent.stop(limiterEventScavengeAssist, now)
  1325  		}
  1326  		h.pages.scav.assistTime.Add(now - start)
  1327  	}
  1328  
  1329  	// Commit and account for any scavenged memory that the span now owns.
  1330  	if scav != 0 {
  1331  		// sysUsed all the pages that are actually available
  1332  		// in the span since some of them might be scavenged.
  1333  		sysUsed(unsafe.Pointer(base), nbytes, scav)
  1334  		gcController.heapReleased.add(-int64(scav))
  1335  	}
  1336  	// Update stats.
  1337  	gcController.heapFree.add(-int64(nbytes - scav))
  1338  	if typ == spanAllocHeap {
  1339  		gcController.heapInUse.add(int64(nbytes))
  1340  	}
  1341  	// Update consistent stats.
  1342  	stats := memstats.heapStats.acquire()
  1343  	atomic.Xaddint64(&stats.committed, int64(scav))
  1344  	atomic.Xaddint64(&stats.released, -int64(scav))
  1345  	switch typ {
  1346  	case spanAllocHeap:
  1347  		atomic.Xaddint64(&stats.inHeap, int64(nbytes))
  1348  	case spanAllocStack:
  1349  		atomic.Xaddint64(&stats.inStacks, int64(nbytes))
  1350  	case spanAllocPtrScalarBits:
  1351  		atomic.Xaddint64(&stats.inPtrScalarBits, int64(nbytes))
  1352  	case spanAllocWorkBuf:
  1353  		atomic.Xaddint64(&stats.inWorkBufs, int64(nbytes))
  1354  	}
  1355  	memstats.heapStats.release()
  1356  
  1357  	// Publish the span in various locations.
  1358  
  1359  	// This is safe to call without the lock held because the slots
  1360  	// related to this span will only ever be read or modified by
  1361  	// this thread until pointers into the span are published (and
  1362  	// we execute a publication barrier at the end of this function
  1363  	// before that happens) or pageInUse is updated.
  1364  	h.setSpans(s.base(), npages, s)
  1365  
  1366  	if !typ.manual() {
  1367  		// Mark in-use span in arena page bitmap.
  1368  		//
  1369  		// This publishes the span to the page sweeper, so
  1370  		// it's imperative that the span be completely initialized
  1371  		// prior to this line.
  1372  		arena, pageIdx, pageMask := pageIndexOf(s.base())
  1373  		atomic.Or8(&arena.pageInUse[pageIdx], pageMask)
  1374  
  1375  		// Update related page sweeper stats.
  1376  		h.pagesInUse.Add(int64(npages))
  1377  	}
  1378  
  1379  	// Make sure the newly allocated span will be observed
  1380  	// by the GC before pointers into the span are published.
  1381  	publicationBarrier()
  1382  
  1383  	return s
  1384  }
  1385  
  1386  // Try to add at least npage pages of memory to the heap,
  1387  // returning how much the heap grew by and whether it worked.
  1388  //
  1389  // h.lock must be held.
  1390  func (h *mheap) grow(npage uintptr) (uintptr, bool) {
  1391  	assertLockHeld(&h.lock)
  1392  
  1393  	// We must grow the heap in whole palloc chunks.
  1394  	// We call sysMap below but note that because we
  1395  	// round up to pallocChunkPages which is on the order
  1396  	// of MiB (generally >= to the huge page size) we
  1397  	// won't be calling it too much.
  1398  	ask := alignUp(npage, pallocChunkPages) * pageSize
  1399  
  1400  	totalGrowth := uintptr(0)
  1401  	// This may overflow because ask could be very large
  1402  	// and is otherwise unrelated to h.curArena.base.
  1403  	end := h.curArena.base + ask
  1404  	nBase := alignUp(end, physPageSize)
  1405  	if nBase > h.curArena.end || /* overflow */ end < h.curArena.base {
  1406  		// Not enough room in the current arena. Allocate more
  1407  		// arena space. This may not be contiguous with the
  1408  		// current arena, so we have to request the full ask.
  1409  		av, asize := h.sysAlloc(ask)
  1410  		if av == nil {
  1411  			inUse := gcController.heapFree.load() + gcController.heapReleased.load() + gcController.heapInUse.load()
  1412  			print("runtime: out of memory: cannot allocate ", ask, "-byte block (", inUse, " in use)\n")
  1413  			return 0, false
  1414  		}
  1415  
  1416  		if uintptr(av) == h.curArena.end {
  1417  			// The new space is contiguous with the old
  1418  			// space, so just extend the current space.
  1419  			h.curArena.end = uintptr(av) + asize
  1420  		} else {
  1421  			// The new space is discontiguous. Track what
  1422  			// remains of the current space and switch to
  1423  			// the new space. This should be rare.
  1424  			if size := h.curArena.end - h.curArena.base; size != 0 {
  1425  				// Transition this space from Reserved to Prepared and mark it
  1426  				// as released since we'll be able to start using it after updating
  1427  				// the page allocator and releasing the lock at any time.
  1428  				sysMap(unsafe.Pointer(h.curArena.base), size, &gcController.heapReleased)
  1429  				// Update stats.
  1430  				stats := memstats.heapStats.acquire()
  1431  				atomic.Xaddint64(&stats.released, int64(size))
  1432  				memstats.heapStats.release()
  1433  				// Update the page allocator's structures to make this
  1434  				// space ready for allocation.
  1435  				h.pages.grow(h.curArena.base, size)
  1436  				totalGrowth += size
  1437  			}
  1438  			// Switch to the new space.
  1439  			h.curArena.base = uintptr(av)
  1440  			h.curArena.end = uintptr(av) + asize
  1441  		}
  1442  
  1443  		// Recalculate nBase.
  1444  		// We know this won't overflow, because sysAlloc returned
  1445  		// a valid region starting at h.curArena.base which is at
  1446  		// least ask bytes in size.
  1447  		nBase = alignUp(h.curArena.base+ask, physPageSize)
  1448  	}
  1449  
  1450  	// Grow into the current arena.
  1451  	v := h.curArena.base
  1452  	h.curArena.base = nBase
  1453  
  1454  	// Transition the space we're going to use from Reserved to Prepared.
  1455  	//
  1456  	// The allocation is always aligned to the heap arena
  1457  	// size which is always > physPageSize, so its safe to
  1458  	// just add directly to heapReleased.
  1459  	sysMap(unsafe.Pointer(v), nBase-v, &gcController.heapReleased)
  1460  
  1461  	// The memory just allocated counts as both released
  1462  	// and idle, even though it's not yet backed by spans.
  1463  	stats := memstats.heapStats.acquire()
  1464  	atomic.Xaddint64(&stats.released, int64(nBase-v))
  1465  	memstats.heapStats.release()
  1466  
  1467  	// Update the page allocator's structures to make this
  1468  	// space ready for allocation.
  1469  	h.pages.grow(v, nBase-v)
  1470  	totalGrowth += nBase - v
  1471  	return totalGrowth, true
  1472  }
  1473  
  1474  // Free the span back into the heap.
  1475  func (h *mheap) freeSpan(s *mspan) {
  1476  	systemstack(func() {
  1477  		lock(&h.lock)
  1478  		if msanenabled {
  1479  			// Tell msan that this entire span is no longer in use.
  1480  			base := unsafe.Pointer(s.base())
  1481  			bytes := s.npages << _PageShift
  1482  			msanfree(base, bytes)
  1483  		}
  1484  		if asanenabled {
  1485  			// Tell asan that this entire span is no longer in use.
  1486  			base := unsafe.Pointer(s.base())
  1487  			bytes := s.npages << _PageShift
  1488  			asanpoison(base, bytes)
  1489  		}
  1490  		h.freeSpanLocked(s, spanAllocHeap)
  1491  		unlock(&h.lock)
  1492  	})
  1493  }
  1494  
  1495  // freeManual frees a manually-managed span returned by allocManual.
  1496  // typ must be the same as the spanAllocType passed to the allocManual that
  1497  // allocated s.
  1498  //
  1499  // This must only be called when gcphase == _GCoff. See mSpanState for
  1500  // an explanation.
  1501  //
  1502  // freeManual must be called on the system stack because it acquires
  1503  // the heap lock. See mheap for details.
  1504  //
  1505  //go:systemstack
  1506  func (h *mheap) freeManual(s *mspan, typ spanAllocType) {
  1507  	s.needzero = 1
  1508  	lock(&h.lock)
  1509  	h.freeSpanLocked(s, typ)
  1510  	unlock(&h.lock)
  1511  }
  1512  
  1513  func (h *mheap) freeSpanLocked(s *mspan, typ spanAllocType) {
  1514  	assertLockHeld(&h.lock)
  1515  
  1516  	switch s.state.get() {
  1517  	case mSpanManual:
  1518  		if s.allocCount != 0 {
  1519  			throw("mheap.freeSpanLocked - invalid stack free")
  1520  		}
  1521  	case mSpanInUse:
  1522  		if s.allocCount != 0 || s.sweepgen != h.sweepgen {
  1523  			print("mheap.freeSpanLocked - span ", s, " ptr ", hex(s.base()), " allocCount ", s.allocCount, " sweepgen ", s.sweepgen, "/", h.sweepgen, "\n")
  1524  			throw("mheap.freeSpanLocked - invalid free")
  1525  		}
  1526  		h.pagesInUse.Add(-int64(s.npages))
  1527  
  1528  		// Clear in-use bit in arena page bitmap.
  1529  		arena, pageIdx, pageMask := pageIndexOf(s.base())
  1530  		atomic.And8(&arena.pageInUse[pageIdx], ^pageMask)
  1531  	default:
  1532  		throw("mheap.freeSpanLocked - invalid span state")
  1533  	}
  1534  
  1535  	// Update stats.
  1536  	//
  1537  	// Mirrors the code in allocSpan.
  1538  	nbytes := s.npages * pageSize
  1539  	gcController.heapFree.add(int64(nbytes))
  1540  	if typ == spanAllocHeap {
  1541  		gcController.heapInUse.add(-int64(nbytes))
  1542  	}
  1543  	// Update consistent stats.
  1544  	stats := memstats.heapStats.acquire()
  1545  	switch typ {
  1546  	case spanAllocHeap:
  1547  		atomic.Xaddint64(&stats.inHeap, -int64(nbytes))
  1548  	case spanAllocStack:
  1549  		atomic.Xaddint64(&stats.inStacks, -int64(nbytes))
  1550  	case spanAllocPtrScalarBits:
  1551  		atomic.Xaddint64(&stats.inPtrScalarBits, -int64(nbytes))
  1552  	case spanAllocWorkBuf:
  1553  		atomic.Xaddint64(&stats.inWorkBufs, -int64(nbytes))
  1554  	}
  1555  	memstats.heapStats.release()
  1556  
  1557  	// Mark the space as free.
  1558  	h.pages.free(s.base(), s.npages, false)
  1559  
  1560  	// Free the span structure. We no longer have a use for it.
  1561  	s.state.set(mSpanDead)
  1562  	h.freeMSpanLocked(s)
  1563  }
  1564  
  1565  // scavengeAll acquires the heap lock (blocking any additional
  1566  // manipulation of the page allocator) and iterates over the whole
  1567  // heap, scavenging every free page available.
  1568  func (h *mheap) scavengeAll() {
  1569  	// Disallow malloc or panic while holding the heap lock. We do
  1570  	// this here because this is a non-mallocgc entry-point to
  1571  	// the mheap API.
  1572  	gp := getg()
  1573  	gp.m.mallocing++
  1574  
  1575  	released := h.pages.scavenge(^uintptr(0), nil)
  1576  
  1577  	gp.m.mallocing--
  1578  
  1579  	if debug.scavtrace > 0 {
  1580  		printScavTrace(released, true)
  1581  	}
  1582  }
  1583  
  1584  //go:linkname runtime_debug_freeOSMemory runtime/debug.freeOSMemory
  1585  func runtime_debug_freeOSMemory() {
  1586  	GC()
  1587  	systemstack(func() { mheap_.scavengeAll() })
  1588  }
  1589  
  1590  // Initialize a new span with the given start and npages.
  1591  func (span *mspan) init(base uintptr, npages uintptr) {
  1592  	// span is *not* zeroed.
  1593  	span.next = nil
  1594  	span.prev = nil
  1595  	span.list = nil
  1596  	span.startAddr = base
  1597  	span.npages = npages
  1598  	span.allocCount = 0
  1599  	span.spanclass = 0
  1600  	span.elemsize = 0
  1601  	span.speciallock.key = 0
  1602  	span.specials = nil
  1603  	span.needzero = 0
  1604  	span.freeindex = 0
  1605  	span.allocBits = nil
  1606  	span.gcmarkBits = nil
  1607  	span.state.set(mSpanDead)
  1608  	lockInit(&span.speciallock, lockRankMspanSpecial)
  1609  }
  1610  
  1611  func (span *mspan) inList() bool {
  1612  	return span.list != nil
  1613  }
  1614  
  1615  // Initialize an empty doubly-linked list.
  1616  func (list *mSpanList) init() {
  1617  	list.first = nil
  1618  	list.last = nil
  1619  }
  1620  
  1621  func (list *mSpanList) remove(span *mspan) {
  1622  	if span.list != list {
  1623  		print("runtime: failed mSpanList.remove span.npages=", span.npages,
  1624  			" span=", span, " prev=", span.prev, " span.list=", span.list, " list=", list, "\n")
  1625  		throw("mSpanList.remove")
  1626  	}
  1627  	if list.first == span {
  1628  		list.first = span.next
  1629  	} else {
  1630  		span.prev.next = span.next
  1631  	}
  1632  	if list.last == span {
  1633  		list.last = span.prev
  1634  	} else {
  1635  		span.next.prev = span.prev
  1636  	}
  1637  	span.next = nil
  1638  	span.prev = nil
  1639  	span.list = nil
  1640  }
  1641  
  1642  func (list *mSpanList) isEmpty() bool {
  1643  	return list.first == nil
  1644  }
  1645  
  1646  func (list *mSpanList) insert(span *mspan) {
  1647  	if span.next != nil || span.prev != nil || span.list != nil {
  1648  		println("runtime: failed mSpanList.insert", span, span.next, span.prev, span.list)
  1649  		throw("mSpanList.insert")
  1650  	}
  1651  	span.next = list.first
  1652  	if list.first != nil {
  1653  		// The list contains at least one span; link it in.
  1654  		// The last span in the list doesn't change.
  1655  		list.first.prev = span
  1656  	} else {
  1657  		// The list contains no spans, so this is also the last span.
  1658  		list.last = span
  1659  	}
  1660  	list.first = span
  1661  	span.list = list
  1662  }
  1663  
  1664  func (list *mSpanList) insertBack(span *mspan) {
  1665  	if span.next != nil || span.prev != nil || span.list != nil {
  1666  		println("runtime: failed mSpanList.insertBack", span, span.next, span.prev, span.list)
  1667  		throw("mSpanList.insertBack")
  1668  	}
  1669  	span.prev = list.last
  1670  	if list.last != nil {
  1671  		// The list contains at least one span.
  1672  		list.last.next = span
  1673  	} else {
  1674  		// The list contains no spans, so this is also the first span.
  1675  		list.first = span
  1676  	}
  1677  	list.last = span
  1678  	span.list = list
  1679  }
  1680  
  1681  // takeAll removes all spans from other and inserts them at the front
  1682  // of list.
  1683  func (list *mSpanList) takeAll(other *mSpanList) {
  1684  	if other.isEmpty() {
  1685  		return
  1686  	}
  1687  
  1688  	// Reparent everything in other to list.
  1689  	for s := other.first; s != nil; s = s.next {
  1690  		s.list = list
  1691  	}
  1692  
  1693  	// Concatenate the lists.
  1694  	if list.isEmpty() {
  1695  		*list = *other
  1696  	} else {
  1697  		// Neither list is empty. Put other before list.
  1698  		other.last.next = list.first
  1699  		list.first.prev = other.last
  1700  		list.first = other.first
  1701  	}
  1702  
  1703  	other.first, other.last = nil, nil
  1704  }
  1705  
  1706  const (
  1707  	_KindSpecialFinalizer = 1
  1708  	_KindSpecialProfile   = 2
  1709  	// _KindSpecialReachable is a special used for tracking
  1710  	// reachability during testing.
  1711  	_KindSpecialReachable = 3
  1712  	// Note: The finalizer special must be first because if we're freeing
  1713  	// an object, a finalizer special will cause the freeing operation
  1714  	// to abort, and we want to keep the other special records around
  1715  	// if that happens.
  1716  )
  1717  
  1718  //go:notinheap
  1719  type special struct {
  1720  	next   *special // linked list in span
  1721  	offset uint16   // span offset of object
  1722  	kind   byte     // kind of special
  1723  }
  1724  
  1725  // spanHasSpecials marks a span as having specials in the arena bitmap.
  1726  func spanHasSpecials(s *mspan) {
  1727  	arenaPage := (s.base() / pageSize) % pagesPerArena
  1728  	ai := arenaIndex(s.base())
  1729  	ha := mheap_.arenas[ai.l1()][ai.l2()]
  1730  	atomic.Or8(&ha.pageSpecials[arenaPage/8], uint8(1)<<(arenaPage%8))
  1731  }
  1732  
  1733  // spanHasNoSpecials marks a span as having no specials in the arena bitmap.
  1734  func spanHasNoSpecials(s *mspan) {
  1735  	arenaPage := (s.base() / pageSize) % pagesPerArena
  1736  	ai := arenaIndex(s.base())
  1737  	ha := mheap_.arenas[ai.l1()][ai.l2()]
  1738  	atomic.And8(&ha.pageSpecials[arenaPage/8], ^(uint8(1) << (arenaPage % 8)))
  1739  }
  1740  
  1741  // Adds the special record s to the list of special records for
  1742  // the object p. All fields of s should be filled in except for
  1743  // offset & next, which this routine will fill in.
  1744  // Returns true if the special was successfully added, false otherwise.
  1745  // (The add will fail only if a record with the same p and s->kind
  1746  // already exists.)
  1747  func addspecial(p unsafe.Pointer, s *special) bool {
  1748  	span := spanOfHeap(uintptr(p))
  1749  	if span == nil {
  1750  		throw("addspecial on invalid pointer")
  1751  	}
  1752  
  1753  	// Ensure that the span is swept.
  1754  	// Sweeping accesses the specials list w/o locks, so we have
  1755  	// to synchronize with it. And it's just much safer.
  1756  	mp := acquirem()
  1757  	span.ensureSwept()
  1758  
  1759  	offset := uintptr(p) - span.base()
  1760  	kind := s.kind
  1761  
  1762  	lock(&span.speciallock)
  1763  
  1764  	// Find splice point, check for existing record.
  1765  	t := &span.specials
  1766  	for {
  1767  		x := *t
  1768  		if x == nil {
  1769  			break
  1770  		}
  1771  		if offset == uintptr(x.offset) && kind == x.kind {
  1772  			unlock(&span.speciallock)
  1773  			releasem(mp)
  1774  			return false // already exists
  1775  		}
  1776  		if offset < uintptr(x.offset) || (offset == uintptr(x.offset) && kind < x.kind) {
  1777  			break
  1778  		}
  1779  		t = &x.next
  1780  	}
  1781  
  1782  	// Splice in record, fill in offset.
  1783  	s.offset = uint16(offset)
  1784  	s.next = *t
  1785  	*t = s
  1786  	spanHasSpecials(span)
  1787  	unlock(&span.speciallock)
  1788  	releasem(mp)
  1789  
  1790  	return true
  1791  }
  1792  
  1793  // Removes the Special record of the given kind for the object p.
  1794  // Returns the record if the record existed, nil otherwise.
  1795  // The caller must FixAlloc_Free the result.
  1796  func removespecial(p unsafe.Pointer, kind uint8) *special {
  1797  	span := spanOfHeap(uintptr(p))
  1798  	if span == nil {
  1799  		throw("removespecial on invalid pointer")
  1800  	}
  1801  
  1802  	// Ensure that the span is swept.
  1803  	// Sweeping accesses the specials list w/o locks, so we have
  1804  	// to synchronize with it. And it's just much safer.
  1805  	mp := acquirem()
  1806  	span.ensureSwept()
  1807  
  1808  	offset := uintptr(p) - span.base()
  1809  
  1810  	var result *special
  1811  	lock(&span.speciallock)
  1812  	t := &span.specials
  1813  	for {
  1814  		s := *t
  1815  		if s == nil {
  1816  			break
  1817  		}
  1818  		// This function is used for finalizers only, so we don't check for
  1819  		// "interior" specials (p must be exactly equal to s->offset).
  1820  		if offset == uintptr(s.offset) && kind == s.kind {
  1821  			*t = s.next
  1822  			result = s
  1823  			break
  1824  		}
  1825  		t = &s.next
  1826  	}
  1827  	if span.specials == nil {
  1828  		spanHasNoSpecials(span)
  1829  	}
  1830  	unlock(&span.speciallock)
  1831  	releasem(mp)
  1832  	return result
  1833  }
  1834  
  1835  // The described object has a finalizer set for it.
  1836  //
  1837  // specialfinalizer is allocated from non-GC'd memory, so any heap
  1838  // pointers must be specially handled.
  1839  //
  1840  //go:notinheap
  1841  type specialfinalizer struct {
  1842  	special special
  1843  	fn      *funcval // May be a heap pointer.
  1844  	nret    uintptr
  1845  	fint    *_type   // May be a heap pointer, but always live.
  1846  	ot      *ptrtype // May be a heap pointer, but always live.
  1847  }
  1848  
  1849  // Adds a finalizer to the object p. Returns true if it succeeded.
  1850  func addfinalizer(p unsafe.Pointer, f *funcval, nret uintptr, fint *_type, ot *ptrtype) bool {
  1851  	lock(&mheap_.speciallock)
  1852  	s := (*specialfinalizer)(mheap_.specialfinalizeralloc.alloc())
  1853  	unlock(&mheap_.speciallock)
  1854  	s.special.kind = _KindSpecialFinalizer
  1855  	s.fn = f
  1856  	s.nret = nret
  1857  	s.fint = fint
  1858  	s.ot = ot
  1859  	if addspecial(p, &s.special) {
  1860  		// This is responsible for maintaining the same
  1861  		// GC-related invariants as markrootSpans in any
  1862  		// situation where it's possible that markrootSpans
  1863  		// has already run but mark termination hasn't yet.
  1864  		if gcphase != _GCoff {
  1865  			base, _, _ := findObject(uintptr(p), 0, 0)
  1866  			mp := acquirem()
  1867  			gcw := &mp.p.ptr().gcw
  1868  			// Mark everything reachable from the object
  1869  			// so it's retained for the finalizer.
  1870  			scanobject(base, gcw)
  1871  			// Mark the finalizer itself, since the
  1872  			// special isn't part of the GC'd heap.
  1873  			scanblock(uintptr(unsafe.Pointer(&s.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
  1874  			releasem(mp)
  1875  		}
  1876  		return true
  1877  	}
  1878  
  1879  	// There was an old finalizer
  1880  	lock(&mheap_.speciallock)
  1881  	mheap_.specialfinalizeralloc.free(unsafe.Pointer(s))
  1882  	unlock(&mheap_.speciallock)
  1883  	return false
  1884  }
  1885  
  1886  // Removes the finalizer (if any) from the object p.
  1887  func removefinalizer(p unsafe.Pointer) {
  1888  	s := (*specialfinalizer)(unsafe.Pointer(removespecial(p, _KindSpecialFinalizer)))
  1889  	if s == nil {
  1890  		return // there wasn't a finalizer to remove
  1891  	}
  1892  	lock(&mheap_.speciallock)
  1893  	mheap_.specialfinalizeralloc.free(unsafe.Pointer(s))
  1894  	unlock(&mheap_.speciallock)
  1895  }
  1896  
  1897  // The described object is being heap profiled.
  1898  //
  1899  //go:notinheap
  1900  type specialprofile struct {
  1901  	special special
  1902  	b       *bucket
  1903  }
  1904  
  1905  // Set the heap profile bucket associated with addr to b.
  1906  func setprofilebucket(p unsafe.Pointer, b *bucket) {
  1907  	lock(&mheap_.speciallock)
  1908  	s := (*specialprofile)(mheap_.specialprofilealloc.alloc())
  1909  	unlock(&mheap_.speciallock)
  1910  	s.special.kind = _KindSpecialProfile
  1911  	s.b = b
  1912  	if !addspecial(p, &s.special) {
  1913  		throw("setprofilebucket: profile already set")
  1914  	}
  1915  }
  1916  
  1917  // specialReachable tracks whether an object is reachable on the next
  1918  // GC cycle. This is used by testing.
  1919  type specialReachable struct {
  1920  	special   special
  1921  	done      bool
  1922  	reachable bool
  1923  }
  1924  
  1925  // specialsIter helps iterate over specials lists.
  1926  type specialsIter struct {
  1927  	pprev **special
  1928  	s     *special
  1929  }
  1930  
  1931  func newSpecialsIter(span *mspan) specialsIter {
  1932  	return specialsIter{&span.specials, span.specials}
  1933  }
  1934  
  1935  func (i *specialsIter) valid() bool {
  1936  	return i.s != nil
  1937  }
  1938  
  1939  func (i *specialsIter) next() {
  1940  	i.pprev = &i.s.next
  1941  	i.s = *i.pprev
  1942  }
  1943  
  1944  // unlinkAndNext removes the current special from the list and moves
  1945  // the iterator to the next special. It returns the unlinked special.
  1946  func (i *specialsIter) unlinkAndNext() *special {
  1947  	cur := i.s
  1948  	i.s = cur.next
  1949  	*i.pprev = i.s
  1950  	return cur
  1951  }
  1952  
  1953  // freeSpecial performs any cleanup on special s and deallocates it.
  1954  // s must already be unlinked from the specials list.
  1955  func freeSpecial(s *special, p unsafe.Pointer, size uintptr) {
  1956  	switch s.kind {
  1957  	case _KindSpecialFinalizer:
  1958  		sf := (*specialfinalizer)(unsafe.Pointer(s))
  1959  		queuefinalizer(p, sf.fn, sf.nret, sf.fint, sf.ot)
  1960  		lock(&mheap_.speciallock)
  1961  		mheap_.specialfinalizeralloc.free(unsafe.Pointer(sf))
  1962  		unlock(&mheap_.speciallock)
  1963  	case _KindSpecialProfile:
  1964  		sp := (*specialprofile)(unsafe.Pointer(s))
  1965  		mProf_Free(sp.b, size)
  1966  		lock(&mheap_.speciallock)
  1967  		mheap_.specialprofilealloc.free(unsafe.Pointer(sp))
  1968  		unlock(&mheap_.speciallock)
  1969  	case _KindSpecialReachable:
  1970  		sp := (*specialReachable)(unsafe.Pointer(s))
  1971  		sp.done = true
  1972  		// The creator frees these.
  1973  	default:
  1974  		throw("bad special kind")
  1975  		panic("not reached")
  1976  	}
  1977  }
  1978  
  1979  // gcBits is an alloc/mark bitmap. This is always used as *gcBits.
  1980  //
  1981  //go:notinheap
  1982  type gcBits uint8
  1983  
  1984  // bytep returns a pointer to the n'th byte of b.
  1985  func (b *gcBits) bytep(n uintptr) *uint8 {
  1986  	return addb((*uint8)(b), n)
  1987  }
  1988  
  1989  // bitp returns a pointer to the byte containing bit n and a mask for
  1990  // selecting that bit from *bytep.
  1991  func (b *gcBits) bitp(n uintptr) (bytep *uint8, mask uint8) {
  1992  	return b.bytep(n / 8), 1 << (n % 8)
  1993  }
  1994  
  1995  const gcBitsChunkBytes = uintptr(64 << 10)
  1996  const gcBitsHeaderBytes = unsafe.Sizeof(gcBitsHeader{})
  1997  
  1998  type gcBitsHeader struct {
  1999  	free uintptr // free is the index into bits of the next free byte.
  2000  	next uintptr // *gcBits triggers recursive type bug. (issue 14620)
  2001  }
  2002  
  2003  //go:notinheap
  2004  type gcBitsArena struct {
  2005  	// gcBitsHeader // side step recursive type bug (issue 14620) by including fields by hand.
  2006  	free uintptr // free is the index into bits of the next free byte; read/write atomically
  2007  	next *gcBitsArena
  2008  	bits [gcBitsChunkBytes - gcBitsHeaderBytes]gcBits
  2009  }
  2010  
  2011  var gcBitsArenas struct {
  2012  	lock     mutex
  2013  	free     *gcBitsArena
  2014  	next     *gcBitsArena // Read atomically. Write atomically under lock.
  2015  	current  *gcBitsArena
  2016  	previous *gcBitsArena
  2017  }
  2018  
  2019  // tryAlloc allocates from b or returns nil if b does not have enough room.
  2020  // This is safe to call concurrently.
  2021  func (b *gcBitsArena) tryAlloc(bytes uintptr) *gcBits {
  2022  	if b == nil || atomic.Loaduintptr(&b.free)+bytes > uintptr(len(b.bits)) {
  2023  		return nil
  2024  	}
  2025  	// Try to allocate from this block.
  2026  	end := atomic.Xadduintptr(&b.free, bytes)
  2027  	if end > uintptr(len(b.bits)) {
  2028  		return nil
  2029  	}
  2030  	// There was enough room.
  2031  	start := end - bytes
  2032  	return &b.bits[start]
  2033  }
  2034  
  2035  // newMarkBits returns a pointer to 8 byte aligned bytes
  2036  // to be used for a span's mark bits.
  2037  func newMarkBits(nelems uintptr) *gcBits {
  2038  	blocksNeeded := uintptr((nelems + 63) / 64)
  2039  	bytesNeeded := blocksNeeded * 8
  2040  
  2041  	// Try directly allocating from the current head arena.
  2042  	head := (*gcBitsArena)(atomic.Loadp(unsafe.Pointer(&gcBitsArenas.next)))
  2043  	if p := head.tryAlloc(bytesNeeded); p != nil {
  2044  		return p
  2045  	}
  2046  
  2047  	// There's not enough room in the head arena. We may need to
  2048  	// allocate a new arena.
  2049  	lock(&gcBitsArenas.lock)
  2050  	// Try the head arena again, since it may have changed. Now
  2051  	// that we hold the lock, the list head can't change, but its
  2052  	// free position still can.
  2053  	if p := gcBitsArenas.next.tryAlloc(bytesNeeded); p != nil {
  2054  		unlock(&gcBitsArenas.lock)
  2055  		return p
  2056  	}
  2057  
  2058  	// Allocate a new arena. This may temporarily drop the lock.
  2059  	fresh := newArenaMayUnlock()
  2060  	// If newArenaMayUnlock dropped the lock, another thread may
  2061  	// have put a fresh arena on the "next" list. Try allocating
  2062  	// from next again.
  2063  	if p := gcBitsArenas.next.tryAlloc(bytesNeeded); p != nil {
  2064  		// Put fresh back on the free list.
  2065  		// TODO: Mark it "already zeroed"
  2066  		fresh.next = gcBitsArenas.free
  2067  		gcBitsArenas.free = fresh
  2068  		unlock(&gcBitsArenas.lock)
  2069  		return p
  2070  	}
  2071  
  2072  	// Allocate from the fresh arena. We haven't linked it in yet, so
  2073  	// this cannot race and is guaranteed to succeed.
  2074  	p := fresh.tryAlloc(bytesNeeded)
  2075  	if p == nil {
  2076  		throw("markBits overflow")
  2077  	}
  2078  
  2079  	// Add the fresh arena to the "next" list.
  2080  	fresh.next = gcBitsArenas.next
  2081  	atomic.StorepNoWB(unsafe.Pointer(&gcBitsArenas.next), unsafe.Pointer(fresh))
  2082  
  2083  	unlock(&gcBitsArenas.lock)
  2084  	return p
  2085  }
  2086  
  2087  // newAllocBits returns a pointer to 8 byte aligned bytes
  2088  // to be used for this span's alloc bits.
  2089  // newAllocBits is used to provide newly initialized spans
  2090  // allocation bits. For spans not being initialized the
  2091  // mark bits are repurposed as allocation bits when
  2092  // the span is swept.
  2093  func newAllocBits(nelems uintptr) *gcBits {
  2094  	return newMarkBits(nelems)
  2095  }
  2096  
  2097  // nextMarkBitArenaEpoch establishes a new epoch for the arenas
  2098  // holding the mark bits. The arenas are named relative to the
  2099  // current GC cycle which is demarcated by the call to finishweep_m.
  2100  //
  2101  // All current spans have been swept.
  2102  // During that sweep each span allocated room for its gcmarkBits in
  2103  // gcBitsArenas.next block. gcBitsArenas.next becomes the gcBitsArenas.current
  2104  // where the GC will mark objects and after each span is swept these bits
  2105  // will be used to allocate objects.
  2106  // gcBitsArenas.current becomes gcBitsArenas.previous where the span's
  2107  // gcAllocBits live until all the spans have been swept during this GC cycle.
  2108  // The span's sweep extinguishes all the references to gcBitsArenas.previous
  2109  // by pointing gcAllocBits into the gcBitsArenas.current.
  2110  // The gcBitsArenas.previous is released to the gcBitsArenas.free list.
  2111  func nextMarkBitArenaEpoch() {
  2112  	lock(&gcBitsArenas.lock)
  2113  	if gcBitsArenas.previous != nil {
  2114  		if gcBitsArenas.free == nil {
  2115  			gcBitsArenas.free = gcBitsArenas.previous
  2116  		} else {
  2117  			// Find end of previous arenas.
  2118  			last := gcBitsArenas.previous
  2119  			for last = gcBitsArenas.previous; last.next != nil; last = last.next {
  2120  			}
  2121  			last.next = gcBitsArenas.free
  2122  			gcBitsArenas.free = gcBitsArenas.previous
  2123  		}
  2124  	}
  2125  	gcBitsArenas.previous = gcBitsArenas.current
  2126  	gcBitsArenas.current = gcBitsArenas.next
  2127  	atomic.StorepNoWB(unsafe.Pointer(&gcBitsArenas.next), nil) // newMarkBits calls newArena when needed
  2128  	unlock(&gcBitsArenas.lock)
  2129  }
  2130  
  2131  // newArenaMayUnlock allocates and zeroes a gcBits arena.
  2132  // The caller must hold gcBitsArena.lock. This may temporarily release it.
  2133  func newArenaMayUnlock() *gcBitsArena {
  2134  	var result *gcBitsArena
  2135  	if gcBitsArenas.free == nil {
  2136  		unlock(&gcBitsArenas.lock)
  2137  		result = (*gcBitsArena)(sysAlloc(gcBitsChunkBytes, &memstats.gcMiscSys))
  2138  		if result == nil {
  2139  			throw("runtime: cannot allocate memory")
  2140  		}
  2141  		lock(&gcBitsArenas.lock)
  2142  	} else {
  2143  		result = gcBitsArenas.free
  2144  		gcBitsArenas.free = gcBitsArenas.free.next
  2145  		memclrNoHeapPointers(unsafe.Pointer(result), gcBitsChunkBytes)
  2146  	}
  2147  	result.next = nil
  2148  	// If result.bits is not 8 byte aligned adjust index so
  2149  	// that &result.bits[result.free] is 8 byte aligned.
  2150  	if uintptr(unsafe.Offsetof(gcBitsArena{}.bits))&7 == 0 {
  2151  		result.free = 0
  2152  	} else {
  2153  		result.free = 8 - (uintptr(unsafe.Pointer(&result.bits[0])) & 7)
  2154  	}
  2155  	return result
  2156  }
  2157  

View as plain text