Source file src/runtime/mgcsweep.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  // Garbage collector: sweeping
     6  
     7  // The sweeper consists of two different algorithms:
     8  //
     9  // * The object reclaimer finds and frees unmarked slots in spans. It
    10  //   can free a whole span if none of the objects are marked, but that
    11  //   isn't its goal. This can be driven either synchronously by
    12  //   mcentral.cacheSpan for mcentral spans, or asynchronously by
    13  //   sweepone, which looks at all the mcentral lists.
    14  //
    15  // * The span reclaimer looks for spans that contain no marked objects
    16  //   and frees whole spans. This is a separate algorithm because
    17  //   freeing whole spans is the hardest task for the object reclaimer,
    18  //   but is critical when allocating new spans. The entry point for
    19  //   this is mheap_.reclaim and it's driven by a sequential scan of
    20  //   the page marks bitmap in the heap arenas.
    21  //
    22  // Both algorithms ultimately call mspan.sweep, which sweeps a single
    23  // heap span.
    24  
    25  package runtime
    26  
    27  import (
    28  	"internal/runtime/atomic"
    29  	"unsafe"
    30  )
    31  
    32  var sweep sweepdata
    33  
    34  // State of background sweep.
    35  type sweepdata struct {
    36  	lock   mutex
    37  	g      *g
    38  	parked bool
    39  
    40  	// active tracks outstanding sweepers and the sweep
    41  	// termination condition.
    42  	active activeSweep
    43  
    44  	// centralIndex is the current unswept span class.
    45  	// It represents an index into the mcentral span
    46  	// sets. Accessed and updated via its load and
    47  	// update methods. Not protected by a lock.
    48  	//
    49  	// Reset at mark termination.
    50  	// Used by mheap.nextSpanForSweep.
    51  	centralIndex sweepClass
    52  }
    53  
    54  // sweepClass is a spanClass and one bit to represent whether we're currently
    55  // sweeping partial or full spans.
    56  type sweepClass uint32
    57  
    58  const (
    59  	numSweepClasses            = numSpanClasses * 2
    60  	sweepClassDone  sweepClass = sweepClass(^uint32(0))
    61  )
    62  
    63  func (s *sweepClass) load() sweepClass {
    64  	return sweepClass(atomic.Load((*uint32)(s)))
    65  }
    66  
    67  func (s *sweepClass) update(sNew sweepClass) {
    68  	// Only update *s if its current value is less than sNew,
    69  	// since *s increases monotonically.
    70  	sOld := s.load()
    71  	for sOld < sNew && !atomic.Cas((*uint32)(s), uint32(sOld), uint32(sNew)) {
    72  		sOld = s.load()
    73  	}
    74  	// TODO(mknyszek): This isn't the only place we have
    75  	// an atomic monotonically increasing counter. It would
    76  	// be nice to have an "atomic max" which is just implemented
    77  	// as the above on most architectures. Some architectures
    78  	// like RISC-V however have native support for an atomic max.
    79  }
    80  
    81  func (s *sweepClass) clear() {
    82  	atomic.Store((*uint32)(s), 0)
    83  }
    84  
    85  // split returns the underlying span class as well as
    86  // whether we're interested in the full or partial
    87  // unswept lists for that class, indicated as a boolean
    88  // (true means "full").
    89  func (s sweepClass) split() (spc spanClass, full bool) {
    90  	return spanClass(s >> 1), s&1 == 0
    91  }
    92  
    93  // nextSpanForSweep finds and pops the next span for sweeping from the
    94  // central sweep buffers. It returns ownership of the span to the caller.
    95  // Returns nil if no such span exists.
    96  func (h *mheap) nextSpanForSweep() *mspan {
    97  	sg := h.sweepgen
    98  	for sc := sweep.centralIndex.load(); sc < numSweepClasses; sc++ {
    99  		spc, full := sc.split()
   100  		c := &h.central[spc].mcentral
   101  		var s *mspan
   102  		if full {
   103  			s = c.fullUnswept(sg).pop()
   104  		} else {
   105  			s = c.partialUnswept(sg).pop()
   106  		}
   107  		if s != nil {
   108  			// Write down that we found something so future sweepers
   109  			// can start from here.
   110  			sweep.centralIndex.update(sc)
   111  			return s
   112  		}
   113  	}
   114  	// Write down that we found nothing.
   115  	sweep.centralIndex.update(sweepClassDone)
   116  	return nil
   117  }
   118  
   119  const sweepDrainedMask = 1 << 31
   120  
   121  // activeSweep is a type that captures whether sweeping
   122  // is done, and whether there are any outstanding sweepers.
   123  //
   124  // Every potential sweeper must call begin() before they look
   125  // for work, and end() after they've finished sweeping.
   126  type activeSweep struct {
   127  	// state is divided into two parts.
   128  	//
   129  	// The top bit (masked by sweepDrainedMask) is a boolean
   130  	// value indicating whether all the sweep work has been
   131  	// drained from the queue.
   132  	//
   133  	// The rest of the bits are a counter, indicating the
   134  	// number of outstanding concurrent sweepers.
   135  	state atomic.Uint32
   136  }
   137  
   138  // begin registers a new sweeper. Returns a sweepLocker
   139  // for acquiring spans for sweeping. Any outstanding sweeper blocks
   140  // sweep termination.
   141  //
   142  // If the sweepLocker is invalid, the caller can be sure that all
   143  // outstanding sweep work has been drained, so there is nothing left
   144  // to sweep. Note that there may be sweepers currently running, so
   145  // this does not indicate that all sweeping has completed.
   146  //
   147  // Even if the sweepLocker is invalid, its sweepGen is always valid.
   148  func (a *activeSweep) begin() sweepLocker {
   149  	for {
   150  		state := a.state.Load()
   151  		if state&sweepDrainedMask != 0 {
   152  			return sweepLocker{mheap_.sweepgen, false}
   153  		}
   154  		if a.state.CompareAndSwap(state, state+1) {
   155  			return sweepLocker{mheap_.sweepgen, true}
   156  		}
   157  	}
   158  }
   159  
   160  // end deregisters a sweeper. Must be called once for each time
   161  // begin is called if the sweepLocker is valid.
   162  func (a *activeSweep) end(sl sweepLocker) {
   163  	if sl.sweepGen != mheap_.sweepgen {
   164  		throw("sweeper left outstanding across sweep generations")
   165  	}
   166  	for {
   167  		state := a.state.Load()
   168  		if (state&^sweepDrainedMask)-1 >= sweepDrainedMask {
   169  			throw("mismatched begin/end of activeSweep")
   170  		}
   171  		if a.state.CompareAndSwap(state, state-1) {
   172  			if state-1 != sweepDrainedMask {
   173  				return
   174  			}
   175  			// We're the last sweeper, and there's nothing left to sweep.
   176  			if debug.gcpacertrace > 0 {
   177  				live := gcController.heapLive.Load()
   178  				print("pacer: sweep done at heap size ", live>>20, "MB; allocated ", (live-mheap_.sweepHeapLiveBasis)>>20, "MB during sweep; swept ", mheap_.pagesSwept.Load(), " pages at ", mheap_.sweepPagesPerByte, " pages/byte\n")
   179  			}
   180  			// Now that sweeping is completely done, flush remaining cleanups.
   181  			gcCleanups.flush()
   182  			return
   183  		}
   184  	}
   185  }
   186  
   187  // markDrained marks the active sweep cycle as having drained
   188  // all remaining work. This is safe to be called concurrently
   189  // with all other methods of activeSweep, though may race.
   190  //
   191  // Returns true if this call was the one that actually performed
   192  // the mark.
   193  func (a *activeSweep) markDrained() bool {
   194  	for {
   195  		state := a.state.Load()
   196  		if state&sweepDrainedMask != 0 {
   197  			return false
   198  		}
   199  		if a.state.CompareAndSwap(state, state|sweepDrainedMask) {
   200  			return true
   201  		}
   202  	}
   203  }
   204  
   205  // sweepers returns the current number of active sweepers.
   206  func (a *activeSweep) sweepers() uint32 {
   207  	return a.state.Load() &^ sweepDrainedMask
   208  }
   209  
   210  // isDone returns true if all sweep work has been drained and no more
   211  // outstanding sweepers exist. That is, when the sweep phase is
   212  // completely done.
   213  func (a *activeSweep) isDone() bool {
   214  	return a.state.Load() == sweepDrainedMask
   215  }
   216  
   217  // reset sets up the activeSweep for the next sweep cycle.
   218  //
   219  // The world must be stopped.
   220  func (a *activeSweep) reset() {
   221  	assertWorldStopped()
   222  	a.state.Store(0)
   223  }
   224  
   225  // finishsweep_m ensures that all spans are swept.
   226  //
   227  // The world must be stopped. This ensures there are no sweeps in
   228  // progress.
   229  //
   230  //go:nowritebarrier
   231  func finishsweep_m() {
   232  	assertWorldStopped()
   233  
   234  	// Sweeping must be complete before marking commences.
   235  	//
   236  	// gcStart picks up any unswept spans prior to commencing, which
   237  	// ensures there are no unswept spans in the presence of a single GC.
   238  	// However, in the case of gcStart racing with another GC, there are
   239  	// edge cases that allow finishsweep_m to observe unswept spans. For
   240  	// example,
   241  	//
   242  	// - gcStart sweeps remaining spans prior to taking work.startSema.
   243  	//   While blocked waiting, another goroutine could take the lock and
   244  	//   complete an entire GC cycle. When the original goroutine finally
   245  	//   unblocks there are now unswept spans from the subsequent GC cycle.
   246  	//
   247  	// - Mark termination makes most sweep work prior to startTheWorld, but
   248  	//   it calls prepareForSweep after restarting the world, which adds more
   249  	//   work. A concurrent gcStart call could finish all of the initial work
   250  	//   before prepareForSweep adds more, and thus gcStart doesn't see it
   251  	//   until after taking work.startSema.
   252  	for sweepone() != ^uintptr(0) {
   253  	}
   254  
   255  	// Make sure there aren't any outstanding sweepers left.
   256  	// At this point, with the world stopped, it means one of two
   257  	// things. Either we were able to preempt a sweeper, or that
   258  	// a sweeper didn't call sweep.active.end when it should have.
   259  	// Both cases indicate a bug, so throw.
   260  	if sweep.active.sweepers() != 0 {
   261  		throw("active sweepers found at start of mark phase")
   262  	}
   263  
   264  	// Reset all the unswept buffers, which should be empty.
   265  	// Do this in sweep termination as opposed to mark termination
   266  	// so that we can catch unswept spans and reclaim blocks as
   267  	// soon as possible.
   268  	sg := mheap_.sweepgen
   269  	for i := range mheap_.central {
   270  		c := &mheap_.central[i].mcentral
   271  		c.partialUnswept(sg).reset()
   272  		c.fullUnswept(sg).reset()
   273  	}
   274  
   275  	// Sweeping is done, so there won't be any new memory to
   276  	// scavenge for a bit.
   277  	//
   278  	// If the scavenger isn't already awake, wake it up. There's
   279  	// definitely work for it to do at this point.
   280  	scavenger.wake()
   281  
   282  	nextMarkBitArenaEpoch()
   283  }
   284  
   285  func bgsweep(c chan int) {
   286  	sweep.g = getg()
   287  
   288  	lockInit(&sweep.lock, lockRankSweep)
   289  	lock(&sweep.lock)
   290  	sweep.parked = true
   291  	c <- 1
   292  	goparkunlock(&sweep.lock, waitReasonGCSweepWait, traceBlockGCSweep, 1)
   293  
   294  	for {
   295  		// bgsweep attempts to be a "low priority" goroutine by intentionally
   296  		// yielding time. It's OK if it doesn't run, because goroutines allocating
   297  		// memory will sweep and ensure that all spans are swept before the next
   298  		// GC cycle. We really only want to run when we're idle.
   299  		//
   300  		// However, calling Gosched after each span swept produces a tremendous
   301  		// amount of tracing events, sometimes up to 50% of events in a trace. It's
   302  		// also inefficient to call into the scheduler so much because sweeping a
   303  		// single span is in general a very fast operation, taking as little as 30 ns
   304  		// on modern hardware. (See #54767.)
   305  		//
   306  		// As a result, bgsweep sweeps in batches, and only calls into the scheduler
   307  		// at the end of every batch. Furthermore, it only yields its time if there
   308  		// isn't spare idle time available on other cores. If there's available idle
   309  		// time, helping to sweep can reduce allocation latencies by getting ahead of
   310  		// the proportional sweeper and having spans ready to go for allocation.
   311  		const sweepBatchSize = 10
   312  		nSwept := 0
   313  		for sweepone() != ^uintptr(0) {
   314  			nSwept++
   315  			if nSwept%sweepBatchSize == 0 {
   316  				goschedIfBusy()
   317  			}
   318  		}
   319  		for freeSomeWbufs(true) {
   320  			// N.B. freeSomeWbufs is already batched internally.
   321  			goschedIfBusy()
   322  		}
   323  		freeDeadSpanSPMCs()
   324  		lock(&sweep.lock)
   325  		if !isSweepDone() {
   326  			// This can happen if a GC runs between
   327  			// gosweepone returning ^0 above
   328  			// and the lock being acquired.
   329  			unlock(&sweep.lock)
   330  			// This goroutine must preempt when we have no work to do
   331  			// but isSweepDone returns false because of another existing sweeper.
   332  			// See issue #73499.
   333  			goschedIfBusy()
   334  			continue
   335  		}
   336  		sweep.parked = true
   337  		goparkunlock(&sweep.lock, waitReasonGCSweepWait, traceBlockGCSweep, 1)
   338  	}
   339  }
   340  
   341  // sweepLocker acquires sweep ownership of spans.
   342  type sweepLocker struct {
   343  	// sweepGen is the sweep generation of the heap.
   344  	sweepGen uint32
   345  	valid    bool
   346  }
   347  
   348  // sweepLocked represents sweep ownership of a span.
   349  type sweepLocked struct {
   350  	*mspan
   351  }
   352  
   353  // tryAcquire attempts to acquire sweep ownership of span s. If it
   354  // successfully acquires ownership, it blocks sweep completion.
   355  func (l *sweepLocker) tryAcquire(s *mspan) (sweepLocked, bool) {
   356  	if !l.valid {
   357  		throw("use of invalid sweepLocker")
   358  	}
   359  	// Check before attempting to CAS.
   360  	if atomic.Load(&s.sweepgen) != l.sweepGen-2 {
   361  		return sweepLocked{}, false
   362  	}
   363  	// Attempt to acquire sweep ownership of s.
   364  	if !atomic.Cas(&s.sweepgen, l.sweepGen-2, l.sweepGen-1) {
   365  		return sweepLocked{}, false
   366  	}
   367  	return sweepLocked{s}, true
   368  }
   369  
   370  // sweepone sweeps some unswept heap span and returns the number of pages returned
   371  // to the heap, or ^uintptr(0) if there was nothing to sweep.
   372  func sweepone() uintptr {
   373  	gp := getg()
   374  
   375  	// Increment locks to ensure that the goroutine is not preempted
   376  	// in the middle of sweep thus leaving the span in an inconsistent state for next GC
   377  	gp.m.locks++
   378  
   379  	// TODO(austin): sweepone is almost always called in a loop;
   380  	// lift the sweepLocker into its callers.
   381  	sl := sweep.active.begin()
   382  	if !sl.valid {
   383  		gp.m.locks--
   384  		return ^uintptr(0)
   385  	}
   386  
   387  	// Find a span to sweep.
   388  	npages := ^uintptr(0)
   389  	var noMoreWork bool
   390  	for {
   391  		s := mheap_.nextSpanForSweep()
   392  		if s == nil {
   393  			noMoreWork = sweep.active.markDrained()
   394  			break
   395  		}
   396  		if state := s.state.get(); state != mSpanInUse {
   397  			// This can happen if direct sweeping already
   398  			// swept this span, but in that case the sweep
   399  			// generation should always be up-to-date.
   400  			if !(s.sweepgen == sl.sweepGen || s.sweepgen == sl.sweepGen+3) {
   401  				print("runtime: bad span s.state=", state, " s.sweepgen=", s.sweepgen, " sweepgen=", sl.sweepGen, "\n")
   402  				throw("non in-use span in unswept list")
   403  			}
   404  			continue
   405  		}
   406  		if s, ok := sl.tryAcquire(s); ok {
   407  			// Sweep the span we found.
   408  			npages = s.npages
   409  			if s.sweep(false) {
   410  				// Whole span was freed. Count it toward the
   411  				// page reclaimer credit since these pages can
   412  				// now be used for span allocation.
   413  				mheap_.reclaimCredit.Add(npages)
   414  			} else {
   415  				// Span is still in-use, so this returned no
   416  				// pages to the heap and the span needs to
   417  				// move to the swept in-use list.
   418  				npages = 0
   419  			}
   420  			break
   421  		}
   422  	}
   423  	sweep.active.end(sl)
   424  
   425  	if noMoreWork {
   426  		// The sweep list is empty. There may still be
   427  		// concurrent sweeps running, but we're at least very
   428  		// close to done sweeping.
   429  
   430  		// Move the scavenge gen forward (signaling
   431  		// that there's new work to do) and wake the scavenger.
   432  		//
   433  		// The scavenger is signaled by the last sweeper because once
   434  		// sweeping is done, we will definitely have useful work for
   435  		// the scavenger to do, since the scavenger only runs over the
   436  		// heap once per GC cycle. This update is not done during sweep
   437  		// termination because in some cases there may be a long delay
   438  		// between sweep done and sweep termination (e.g. not enough
   439  		// allocations to trigger a GC) which would be nice to fill in
   440  		// with scavenging work.
   441  		if debug.scavtrace > 0 {
   442  			systemstack(func() {
   443  				lock(&mheap_.lock)
   444  
   445  				// Get released stats.
   446  				releasedBg := mheap_.pages.scav.releasedBg.Load()
   447  				releasedEager := mheap_.pages.scav.releasedEager.Load()
   448  
   449  				// Print the line.
   450  				printScavTrace(releasedBg, releasedEager, false)
   451  
   452  				// Update the stats.
   453  				mheap_.pages.scav.releasedBg.Add(-releasedBg)
   454  				mheap_.pages.scav.releasedEager.Add(-releasedEager)
   455  				unlock(&mheap_.lock)
   456  			})
   457  		}
   458  		scavenger.ready()
   459  	}
   460  
   461  	gp.m.locks--
   462  	return npages
   463  }
   464  
   465  // isSweepDone reports whether all spans are swept.
   466  //
   467  // Note that this condition may transition from false to true at any
   468  // time as the sweeper runs. It may transition from true to false if a
   469  // GC runs; to prevent that the caller must be non-preemptible or must
   470  // somehow block GC progress.
   471  func isSweepDone() bool {
   472  	return sweep.active.isDone()
   473  }
   474  
   475  // Returns only when span s has been swept.
   476  //
   477  //go:nowritebarrier
   478  func (s *mspan) ensureSwept() {
   479  	// Caller must disable preemption.
   480  	// Otherwise when this function returns the span can become unswept again
   481  	// (if GC is triggered on another goroutine).
   482  	gp := getg()
   483  	if gp.m.locks == 0 && gp.m.mallocing == 0 && gp != gp.m.g0 {
   484  		throw("mspan.ensureSwept: m is not locked")
   485  	}
   486  
   487  	// Avoid registering a sweeper if the span is already swept.
   488  	// Preemption is disabled, so the sweep generation cannot change.
   489  	sweepgen := mheap_.sweepgen
   490  	if spangen := atomic.Load(&s.sweepgen); spangen == sweepgen || spangen == sweepgen+3 {
   491  		return
   492  	}
   493  
   494  	// If this operation fails, then that means that there are
   495  	// no more spans to be swept. In this case, either s has already
   496  	// been swept, or is about to be acquired for sweeping and swept.
   497  	sl := sweep.active.begin()
   498  	if sl.valid {
   499  		// The caller must be sure that the span is a mSpanInUse span.
   500  		if s, ok := sl.tryAcquire(s); ok {
   501  			s.sweep(false)
   502  			sweep.active.end(sl)
   503  			return
   504  		}
   505  		sweep.active.end(sl)
   506  	}
   507  
   508  	// Unfortunately we can't sweep the span ourselves. Somebody else
   509  	// got to it first. We don't have efficient means to wait, but that's
   510  	// OK, it will be swept fairly soon.
   511  	for {
   512  		spangen := atomic.Load(&s.sweepgen)
   513  		if spangen == sl.sweepGen || spangen == sl.sweepGen+3 {
   514  			break
   515  		}
   516  		osyield()
   517  	}
   518  }
   519  
   520  // sweep frees or collects finalizers for blocks not marked in the mark phase.
   521  // It clears the mark bits in preparation for the next GC round.
   522  // Returns true if the span was returned to heap.
   523  // If preserve=true, don't return it to heap nor relink in mcentral lists;
   524  // caller takes care of it.
   525  func (sl *sweepLocked) sweep(preserve bool) bool {
   526  	// It's critical that we enter this function with preemption disabled,
   527  	// GC must not start while we are in the middle of this function.
   528  	gp := getg()
   529  	if gp.m.locks == 0 && gp.m.mallocing == 0 && gp != gp.m.g0 {
   530  		throw("mspan.sweep: m is not locked")
   531  	}
   532  
   533  	s := sl.mspan
   534  	if !preserve {
   535  		// We'll release ownership of this span. Nil it out to
   536  		// prevent the caller from accidentally using it.
   537  		sl.mspan = nil
   538  	}
   539  
   540  	sweepgen := mheap_.sweepgen
   541  	if state := s.state.get(); state != mSpanInUse || s.sweepgen != sweepgen-1 {
   542  		print("mspan.sweep: state=", state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "\n")
   543  		throw("mspan.sweep: bad span state")
   544  	}
   545  
   546  	trace := traceAcquire()
   547  	if trace.ok() {
   548  		trace.GCSweepSpan(s.npages * pageSize)
   549  		traceRelease(trace)
   550  	}
   551  
   552  	mheap_.pagesSwept.Add(int64(s.npages))
   553  
   554  	spc := s.spanclass
   555  	size := s.elemsize
   556  
   557  	// The allocBits indicate which unmarked objects don't need to be
   558  	// processed since they were free at the end of the last GC cycle
   559  	// and were not allocated since then.
   560  	// If the allocBits index is >= s.freeindex and the bit
   561  	// is not marked then the object remains unallocated
   562  	// since the last GC.
   563  	// This situation is analogous to being on a freelist.
   564  
   565  	// Unlink & free special records for any objects we're about to free.
   566  	// Two complications here:
   567  	// 1. An object can have both finalizer and profile special records.
   568  	//    In such case we need to queue finalizer for execution,
   569  	//    mark the object as live and preserve the profile special.
   570  	// 2. A tiny object can have several finalizers setup for different offsets.
   571  	//    If such object is not marked, we need to queue all finalizers at once.
   572  	// Both 1 and 2 are possible at the same time.
   573  	hadSpecials := s.specials != nil
   574  	siter := newSpecialsIter(s)
   575  	for siter.valid() {
   576  		// A finalizer can be set for an inner byte of an object, find object beginning.
   577  		objIndex := siter.s.offset / size
   578  		p := s.base() + objIndex*size
   579  		mbits := s.markBitsForIndex(objIndex)
   580  		if !mbits.isMarked() {
   581  			// This object is not marked and has at least one special record.
   582  			// Pass 1: see if it has a finalizer.
   583  			hasFinAndRevived := false
   584  			endOffset := p - s.base() + size
   585  			for tmp := siter.s; tmp != nil && tmp.offset < endOffset; tmp = tmp.next {
   586  				if tmp.kind == _KindSpecialFinalizer {
   587  					// Stop freeing of object if it has a finalizer.
   588  					mbits.setMarkedNonAtomic()
   589  					hasFinAndRevived = true
   590  					break
   591  				}
   592  			}
   593  			if hasFinAndRevived {
   594  				// Pass 2: queue all finalizers and clear any weak handles. Weak handles are cleared
   595  				// before finalization as specified by the weak package. See the documentation
   596  				// for that package for more details.
   597  				for siter.valid() && siter.s.offset < endOffset {
   598  					// Find the exact byte for which the special was setup
   599  					// (as opposed to object beginning).
   600  					special := siter.s
   601  					p := s.base() + special.offset
   602  					if special.kind == _KindSpecialFinalizer || special.kind == _KindSpecialWeakHandle {
   603  						siter.unlinkAndNext()
   604  						freeSpecial(special, unsafe.Pointer(p), size)
   605  					} else {
   606  						// All other specials only apply when an object is freed,
   607  						// so just keep the special record.
   608  						siter.next()
   609  					}
   610  				}
   611  			} else {
   612  				// Pass 2: the object is truly dead, free (and handle) all specials.
   613  				for siter.valid() && siter.s.offset < endOffset {
   614  					// Find the exact byte for which the special was setup
   615  					// (as opposed to object beginning).
   616  					special := siter.s
   617  					p := s.base() + special.offset
   618  					siter.unlinkAndNext()
   619  					freeSpecial(special, unsafe.Pointer(p), size)
   620  				}
   621  			}
   622  		} else {
   623  			// object is still live
   624  			if siter.s.kind == _KindSpecialReachable {
   625  				special := siter.unlinkAndNext()
   626  				(*specialReachable)(unsafe.Pointer(special)).reachable = true
   627  				freeSpecial(special, unsafe.Pointer(p), size)
   628  			} else {
   629  				// keep special record
   630  				siter.next()
   631  			}
   632  		}
   633  	}
   634  	if hadSpecials && s.specials == nil {
   635  		spanHasNoSpecials(s)
   636  	}
   637  
   638  	if traceAllocFreeEnabled() || debug.clobberfree != 0 || raceenabled || msanenabled || asanenabled {
   639  		// Find all newly freed objects.
   640  		mbits := s.markBitsForBase()
   641  		abits := s.allocBitsForIndex(0)
   642  		for i := uintptr(0); i < uintptr(s.nelems); i++ {
   643  			if !mbits.isMarked() && (abits.index < uintptr(s.freeindex) || abits.isMarked()) {
   644  				x := s.base() + i*s.elemsize
   645  				if traceAllocFreeEnabled() {
   646  					trace := traceAcquire()
   647  					if trace.ok() {
   648  						trace.HeapObjectFree(x)
   649  						traceRelease(trace)
   650  					}
   651  				}
   652  				if debug.clobberfree != 0 {
   653  					clobberfree(unsafe.Pointer(x), size)
   654  				}
   655  				// User arenas are handled on explicit free.
   656  				if raceenabled && !s.isUserArenaChunk {
   657  					racefree(unsafe.Pointer(x), size)
   658  				}
   659  				if msanenabled && !s.isUserArenaChunk {
   660  					msanfree(unsafe.Pointer(x), size)
   661  				}
   662  				if asanenabled && !s.isUserArenaChunk {
   663  					asanpoison(unsafe.Pointer(x), size)
   664  				}
   665  				if valgrindenabled && !s.isUserArenaChunk {
   666  					valgrindFree(unsafe.Pointer(x))
   667  				}
   668  			}
   669  			mbits.advance()
   670  			abits.advance()
   671  		}
   672  	}
   673  
   674  	// Copy over and clear the inline mark bits if necessary.
   675  	if gcUsesSpanInlineMarkBits(s.elemsize) {
   676  		s.moveInlineMarks(s.gcmarkBits)
   677  	}
   678  
   679  	// Check for zombie objects.
   680  	if s.freeindex < s.nelems {
   681  		// Everything < freeindex is allocated and hence
   682  		// cannot be zombies.
   683  		//
   684  		// Check the first bitmap byte, where we have to be
   685  		// careful with freeindex.
   686  		obj := uintptr(s.freeindex)
   687  		if (*s.gcmarkBits.bytep(obj / 8)&^*s.allocBits.bytep(obj / 8))>>(obj%8) != 0 {
   688  			s.reportZombies()
   689  		}
   690  		// Check remaining bytes.
   691  		for i := obj/8 + 1; i < divRoundUp(uintptr(s.nelems), 8); i++ {
   692  			if *s.gcmarkBits.bytep(i)&^*s.allocBits.bytep(i) != 0 {
   693  				s.reportZombies()
   694  			}
   695  		}
   696  	}
   697  
   698  	// Count the number of free objects in this span.
   699  	nalloc := uint16(s.countAlloc())
   700  	nfreed := s.allocCount - nalloc
   701  	if nalloc > s.allocCount {
   702  		// The zombie check above should have caught this in
   703  		// more detail.
   704  		print("runtime: nelems=", s.nelems, " nalloc=", nalloc, " previous allocCount=", s.allocCount, " nfreed=", nfreed, "\n")
   705  		throw("sweep increased allocation count")
   706  	}
   707  
   708  	s.allocCount = nalloc
   709  	s.freeindex = 0 // reset allocation index to start of span.
   710  	s.freeIndexForScan = 0
   711  	if traceEnabled() {
   712  		getg().m.p.ptr().trace.reclaimed += uintptr(nfreed) * s.elemsize
   713  	}
   714  
   715  	// gcmarkBits becomes the allocBits.
   716  	// get a fresh cleared gcmarkBits in preparation for next GC
   717  	s.allocBits = s.gcmarkBits
   718  	s.gcmarkBits = newMarkBits(uintptr(s.nelems))
   719  
   720  	// refresh pinnerBits if they exists
   721  	if s.pinnerBits != nil {
   722  		s.refreshPinnerBits()
   723  	}
   724  
   725  	// Initialize alloc bits cache.
   726  	s.refillAllocCache(0)
   727  
   728  	// The span must be in our exclusive ownership until we update sweepgen,
   729  	// check for potential races.
   730  	if state := s.state.get(); state != mSpanInUse || s.sweepgen != sweepgen-1 {
   731  		print("mspan.sweep: state=", state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "\n")
   732  		throw("mspan.sweep: bad span state after sweep")
   733  	}
   734  	if s.sweepgen == sweepgen+1 || s.sweepgen == sweepgen+3 {
   735  		throw("swept cached span")
   736  	}
   737  
   738  	// We need to set s.sweepgen = h.sweepgen only when all blocks are swept,
   739  	// because of the potential for a concurrent free/SetFinalizer.
   740  	//
   741  	// But we need to set it before we make the span available for allocation
   742  	// (return it to heap or mcentral), because allocation code assumes that a
   743  	// span is already swept if available for allocation.
   744  	//
   745  	// Serialization point.
   746  	// At this point the mark bits are cleared and allocation ready
   747  	// to go so release the span.
   748  	atomic.Store(&s.sweepgen, sweepgen)
   749  
   750  	if s.isUserArenaChunk {
   751  		if preserve {
   752  			// This is a case that should never be handled by a sweeper that
   753  			// preserves the span for reuse.
   754  			throw("sweep: tried to preserve a user arena span")
   755  		}
   756  		if nalloc > 0 {
   757  			// There still exist pointers into the span or the span hasn't been
   758  			// freed yet. It's not ready to be reused. Put it back on the
   759  			// full swept list for the next cycle.
   760  			mheap_.central[spc].mcentral.fullSwept(sweepgen).push(s)
   761  			return false
   762  		}
   763  
   764  		// It's only at this point that the sweeper doesn't actually need to look
   765  		// at this arena anymore, so subtract from pagesInUse now.
   766  		mheap_.pagesInUse.Add(-s.npages)
   767  		s.state.set(mSpanDead)
   768  
   769  		// The arena is ready to be recycled. Remove it from the quarantine list
   770  		// and place it on the ready list. Don't add it back to any sweep lists.
   771  		systemstack(func() {
   772  			// It's the arena code's responsibility to get the chunk on the quarantine
   773  			// list by the time all references to the chunk are gone.
   774  			if s.list != &mheap_.userArena.quarantineList {
   775  				throw("user arena span is on the wrong list")
   776  			}
   777  			lock(&mheap_.lock)
   778  			mheap_.userArena.quarantineList.remove(s)
   779  			mheap_.userArena.readyList.insert(s)
   780  			unlock(&mheap_.lock)
   781  		})
   782  		return false
   783  	}
   784  
   785  	if spc.sizeclass() != 0 {
   786  		// Handle spans for small objects.
   787  		if nfreed > 0 {
   788  			// Only mark the span as needing zeroing if we've freed any
   789  			// objects, because a fresh span that had been allocated into,
   790  			// wasn't totally filled, but then swept, still has all of its
   791  			// free slots zeroed.
   792  			s.needzero = 1
   793  			stats := memstats.heapStats.acquire()
   794  			atomic.Xadd64(&stats.smallFreeCount[spc.sizeclass()], int64(nfreed))
   795  			memstats.heapStats.release()
   796  
   797  			// Count the frees in the inconsistent, internal stats.
   798  			gcController.totalFree.Add(int64(nfreed) * int64(s.elemsize))
   799  		}
   800  		if !preserve {
   801  			// The caller may not have removed this span from whatever
   802  			// unswept set its on but taken ownership of the span for
   803  			// sweeping by updating sweepgen. If this span still is in
   804  			// an unswept set, then the mcentral will pop it off the
   805  			// set, check its sweepgen, and ignore it.
   806  			if nalloc == 0 {
   807  				// Free totally free span directly back to the heap.
   808  				mheap_.freeSpan(s)
   809  				return true
   810  			}
   811  			// Return span back to the right mcentral list.
   812  			if nalloc == s.nelems {
   813  				mheap_.central[spc].mcentral.fullSwept(sweepgen).push(s)
   814  			} else {
   815  				mheap_.central[spc].mcentral.partialSwept(sweepgen).push(s)
   816  			}
   817  		}
   818  	} else if !preserve {
   819  		// Handle spans for large objects.
   820  		if nfreed != 0 {
   821  			// Free large object span to heap.
   822  
   823  			// Count the free in the consistent, external stats.
   824  			//
   825  			// Do this before freeSpan, which might update heapStats' inHeap
   826  			// value. If it does so, then metrics that subtract object footprint
   827  			// from inHeap might overflow. See #67019.
   828  			stats := memstats.heapStats.acquire()
   829  			atomic.Xadd64(&stats.largeFreeCount, 1)
   830  			atomic.Xadd64(&stats.largeFree, int64(size))
   831  			memstats.heapStats.release()
   832  
   833  			// Count the free in the inconsistent, internal stats.
   834  			gcController.totalFree.Add(int64(size))
   835  
   836  			// NOTE(rsc,dvyukov): The original implementation of efence
   837  			// in CL 22060046 used sysFree instead of sysFault, so that
   838  			// the operating system would eventually give the memory
   839  			// back to us again, so that an efence program could run
   840  			// longer without running out of memory. Unfortunately,
   841  			// calling sysFree here without any kind of adjustment of the
   842  			// heap data structures means that when the memory does
   843  			// come back to us, we have the wrong metadata for it, either in
   844  			// the mspan structures or in the garbage collection bitmap.
   845  			// Using sysFault here means that the program will run out of
   846  			// memory fairly quickly in efence mode, but at least it won't
   847  			// have mysterious crashes due to confused memory reuse.
   848  			// It should be possible to switch back to sysFree if we also
   849  			// implement and then call some kind of mheap.deleteSpan.
   850  			if debug.efence > 0 {
   851  				s.limit = 0 // prevent mlookup from finding this span
   852  				sysFault(unsafe.Pointer(s.base()), size)
   853  			} else {
   854  				mheap_.freeSpan(s)
   855  			}
   856  			return true
   857  		}
   858  
   859  		// Add a large span directly onto the full+swept list.
   860  		mheap_.central[spc].mcentral.fullSwept(sweepgen).push(s)
   861  	}
   862  	return false
   863  }
   864  
   865  // reportZombies reports any marked but free objects in s and throws.
   866  //
   867  // This generally means one of the following:
   868  //
   869  // 1. User code converted a pointer to a uintptr and then back
   870  // unsafely, and a GC ran while the uintptr was the only reference to
   871  // an object.
   872  //
   873  // 2. User code (or a compiler bug) constructed a bad pointer that
   874  // points to a free slot, often a past-the-end pointer.
   875  //
   876  // 3. The GC two cycles ago missed a pointer and freed a live object,
   877  // but it was still live in the last cycle, so this GC cycle found a
   878  // pointer to that object and marked it.
   879  func (s *mspan) reportZombies() {
   880  	printlock()
   881  	print("runtime: marked free object in span ", s, ", elemsize=", s.elemsize, " freeindex=", s.freeindex, " (bad use of unsafe.Pointer or having race conditions? try -d=checkptr or -race)\n")
   882  	// Inline mark bits have already been moved to gcmarkBits by sweep, so
   883  	// read gcmarkBits directly rather than through markBitsForBase, which
   884  	// would read the now-cleared inline mark bits.
   885  	mbits := markBits{&s.gcmarkBits.x, uint8(1), 0}
   886  	abits := s.allocBitsForIndex(0)
   887  	for i := uintptr(0); i < uintptr(s.nelems); i++ {
   888  		addr := s.base() + i*s.elemsize
   889  		print(hex(addr))
   890  		alloc := i < uintptr(s.freeindex) || abits.isMarked()
   891  		if alloc {
   892  			print(" alloc")
   893  		} else {
   894  			print(" free ")
   895  		}
   896  		if mbits.isMarked() {
   897  			print(" marked  ")
   898  		} else {
   899  			print(" unmarked")
   900  		}
   901  		zombie := mbits.isMarked() && !alloc
   902  		if zombie {
   903  			print(" zombie")
   904  		}
   905  		print("\n")
   906  		if zombie {
   907  			length := s.elemsize
   908  			if length > 1024 {
   909  				length = 1024
   910  			}
   911  			hexdumpWords(addr, length, nil)
   912  		}
   913  		mbits.advance()
   914  		abits.advance()
   915  	}
   916  	throw("found pointer to free object")
   917  }
   918  
   919  // deductSweepCredit deducts sweep credit for allocating a span of
   920  // size spanBytes. This must be performed *before* the span is
   921  // allocated to ensure the system has enough credit. If necessary, it
   922  // performs sweeping to prevent going in to debt. If the caller will
   923  // also sweep pages (e.g., for a large allocation), it can pass a
   924  // non-zero callerSweepPages to leave that many pages unswept.
   925  //
   926  // deductSweepCredit makes a worst-case assumption that all spanBytes
   927  // bytes of the ultimately allocated span will be available for object
   928  // allocation.
   929  //
   930  // deductSweepCredit is the core of the "proportional sweep" system.
   931  // It uses statistics gathered by the garbage collector to perform
   932  // enough sweeping so that all pages are swept during the concurrent
   933  // sweep phase between GC cycles.
   934  //
   935  // mheap_ must NOT be locked.
   936  func deductSweepCredit(spanBytes uintptr, callerSweepPages uintptr) {
   937  	if mheap_.sweepPagesPerByte == 0 {
   938  		// Proportional sweep is done or disabled.
   939  		return
   940  	}
   941  
   942  	trace := traceAcquire()
   943  	if trace.ok() {
   944  		trace.GCSweepStart()
   945  		traceRelease(trace)
   946  	}
   947  
   948  	// Fix debt if necessary.
   949  retry:
   950  	sweptBasis := mheap_.pagesSweptBasis.Load()
   951  	live := gcController.heapLive.Load()
   952  	liveBasis := mheap_.sweepHeapLiveBasis
   953  	newHeapLive := spanBytes
   954  	if liveBasis < live {
   955  		// Only do this subtraction when we don't overflow. Otherwise, pagesTarget
   956  		// might be computed as something really huge, causing us to get stuck
   957  		// sweeping here until the next mark phase.
   958  		//
   959  		// Overflow can happen here if gcPaceSweeper is called concurrently with
   960  		// sweeping (i.e. not during a STW, like it usually is) because this code
   961  		// is intentionally racy. A concurrent call to gcPaceSweeper can happen
   962  		// if a GC tuning parameter is modified and we read an older value of
   963  		// heapLive than what was used to set the basis.
   964  		//
   965  		// This state should be transient, so it's fine to just let newHeapLive
   966  		// be a relatively small number. We'll probably just skip this attempt to
   967  		// sweep.
   968  		//
   969  		// See issue #57523.
   970  		newHeapLive += uintptr(live - liveBasis)
   971  	}
   972  	pagesTarget := int64(mheap_.sweepPagesPerByte*float64(newHeapLive)) - int64(callerSweepPages)
   973  	for pagesTarget > int64(mheap_.pagesSwept.Load()-sweptBasis) {
   974  		if sweepone() == ^uintptr(0) {
   975  			mheap_.sweepPagesPerByte = 0
   976  			break
   977  		}
   978  		if mheap_.pagesSweptBasis.Load() != sweptBasis {
   979  			// Sweep pacing changed. Recompute debt.
   980  			goto retry
   981  		}
   982  	}
   983  
   984  	trace = traceAcquire()
   985  	if trace.ok() {
   986  		trace.GCSweepDone()
   987  		traceRelease(trace)
   988  	}
   989  }
   990  
   991  // clobberfree sets the memory content at x to bad content, for debugging
   992  // purposes.
   993  func clobberfree(x unsafe.Pointer, size uintptr) {
   994  	// size (span.elemsize) is always a multiple of 4.
   995  	for i := uintptr(0); i < size; i += 4 {
   996  		*(*uint32)(add(x, i)) = 0xdeadbeef
   997  	}
   998  }
   999  
  1000  // gcPaceSweeper updates the sweeper's pacing parameters.
  1001  //
  1002  // Must be called whenever the GC's pacing is updated.
  1003  //
  1004  // The world must be stopped, or mheap_.lock must be held.
  1005  func gcPaceSweeper(trigger uint64) {
  1006  	assertWorldStoppedOrLockHeld(&mheap_.lock)
  1007  
  1008  	// Update sweep pacing.
  1009  	if isSweepDone() {
  1010  		mheap_.sweepPagesPerByte = 0
  1011  	} else {
  1012  		// Concurrent sweep needs to sweep all of the in-use
  1013  		// pages by the time the allocated heap reaches the GC
  1014  		// trigger. Compute the ratio of in-use pages to sweep
  1015  		// per byte allocated, accounting for the fact that
  1016  		// some might already be swept.
  1017  		heapLiveBasis := gcController.heapLive.Load()
  1018  		heapDistance := int64(trigger) - int64(heapLiveBasis)
  1019  		// Add a little margin so rounding errors and
  1020  		// concurrent sweep are less likely to leave pages
  1021  		// unswept when GC starts.
  1022  		heapDistance -= 1024 * 1024
  1023  		if heapDistance < pageSize {
  1024  			// Avoid setting the sweep ratio extremely high
  1025  			heapDistance = pageSize
  1026  		}
  1027  		pagesSwept := mheap_.pagesSwept.Load()
  1028  		pagesInUse := mheap_.pagesInUse.Load()
  1029  		sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
  1030  		if sweepDistancePages <= 0 {
  1031  			mheap_.sweepPagesPerByte = 0
  1032  		} else {
  1033  			mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
  1034  			mheap_.sweepHeapLiveBasis = heapLiveBasis
  1035  			// Write pagesSweptBasis last, since this
  1036  			// signals concurrent sweeps to recompute
  1037  			// their debt.
  1038  			mheap_.pagesSweptBasis.Store(pagesSwept)
  1039  		}
  1040  	}
  1041  }
  1042  

View as plain text