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

View as plain text