Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/mgcscavenge.go

Documentation: runtime

     1  // Copyright 2019 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  // Scavenging free pages.
     6  //
     7  // This file implements scavenging (the release of physical pages backing mapped
     8  // memory) of free and unused pages in the heap as a way to deal with page-level
     9  // fragmentation and reduce the RSS of Go applications.
    10  //
    11  // Scavenging in Go happens on two fronts: there's the background
    12  // (asynchronous) scavenger and the heap-growth (synchronous) scavenger.
    13  //
    14  // The former happens on a goroutine much like the background sweeper which is
    15  // soft-capped at using scavengePercent of the mutator's time, based on
    16  // order-of-magnitude estimates of the costs of scavenging. The background
    17  // scavenger's primary goal is to bring the estimated heap RSS of the
    18  // application down to a goal.
    19  //
    20  // That goal is defined as:
    21  //   (retainExtraPercent+100) / 100 * (next_gc / last_next_gc) * last_heap_inuse
    22  //
    23  // Essentially, we wish to have the application's RSS track the heap goal, but
    24  // the heap goal is defined in terms of bytes of objects, rather than pages like
    25  // RSS. As a result, we need to take into account for fragmentation internal to
    26  // spans. next_gc / last_next_gc defines the ratio between the current heap goal
    27  // and the last heap goal, which tells us by how much the heap is growing and
    28  // shrinking. We estimate what the heap will grow to in terms of pages by taking
    29  // this ratio and multiplying it by heap_inuse at the end of the last GC, which
    30  // allows us to account for this additional fragmentation. Note that this
    31  // procedure makes the assumption that the degree of fragmentation won't change
    32  // dramatically over the next GC cycle. Overestimating the amount of
    33  // fragmentation simply results in higher memory use, which will be accounted
    34  // for by the next pacing up date. Underestimating the fragmentation however
    35  // could lead to performance degradation. Handling this case is not within the
    36  // scope of the scavenger. Situations where the amount of fragmentation balloons
    37  // over the course of a single GC cycle should be considered pathologies,
    38  // flagged as bugs, and fixed appropriately.
    39  //
    40  // An additional factor of retainExtraPercent is added as a buffer to help ensure
    41  // that there's more unscavenged memory to allocate out of, since each allocation
    42  // out of scavenged memory incurs a potentially expensive page fault.
    43  //
    44  // The goal is updated after each GC and the scavenger's pacing parameters
    45  // (which live in mheap_) are updated to match. The pacing parameters work much
    46  // like the background sweeping parameters. The parameters define a line whose
    47  // horizontal axis is time and vertical axis is estimated heap RSS, and the
    48  // scavenger attempts to stay below that line at all times.
    49  //
    50  // The synchronous heap-growth scavenging happens whenever the heap grows in
    51  // size, for some definition of heap-growth. The intuition behind this is that
    52  // the application had to grow the heap because existing fragments were
    53  // not sufficiently large to satisfy a page-level memory allocation, so we
    54  // scavenge those fragments eagerly to offset the growth in RSS that results.
    55  
    56  package runtime
    57  
    58  import (
    59  	"runtime/internal/atomic"
    60  	"runtime/internal/sys"
    61  	"unsafe"
    62  )
    63  
    64  const (
    65  	// The background scavenger is paced according to these parameters.
    66  	//
    67  	// scavengePercent represents the portion of mutator time we're willing
    68  	// to spend on scavenging in percent.
    69  	scavengePercent = 1 // 1%
    70  
    71  	// retainExtraPercent represents the amount of memory over the heap goal
    72  	// that the scavenger should keep as a buffer space for the allocator.
    73  	//
    74  	// The purpose of maintaining this overhead is to have a greater pool of
    75  	// unscavenged memory available for allocation (since using scavenged memory
    76  	// incurs an additional cost), to account for heap fragmentation and
    77  	// the ever-changing layout of the heap.
    78  	retainExtraPercent = 10
    79  
    80  	// maxPagesPerPhysPage is the maximum number of supported runtime pages per
    81  	// physical page, based on maxPhysPageSize.
    82  	maxPagesPerPhysPage = maxPhysPageSize / pageSize
    83  
    84  	// scavengeCostRatio is the approximate ratio between the costs of using previously
    85  	// scavenged memory and scavenging memory.
    86  	//
    87  	// For most systems the cost of scavenging greatly outweighs the costs
    88  	// associated with using scavenged memory, making this constant 0. On other systems
    89  	// (especially ones where "sysUsed" is not just a no-op) this cost is non-trivial.
    90  	//
    91  	// This ratio is used as part of multiplicative factor to help the scavenger account
    92  	// for the additional costs of using scavenged memory in its pacing.
    93  	scavengeCostRatio = 0.7 * sys.GoosDarwin
    94  
    95  	// scavengeReservationShards determines the amount of memory the scavenger
    96  	// should reserve for scavenging at a time. Specifically, the amount of
    97  	// memory reserved is (heap size in bytes) / scavengeReservationShards.
    98  	scavengeReservationShards = 64
    99  )
   100  
   101  // heapRetained returns an estimate of the current heap RSS.
   102  func heapRetained() uint64 {
   103  	return atomic.Load64(&memstats.heap_sys) - atomic.Load64(&memstats.heap_released)
   104  }
   105  
   106  // gcPaceScavenger updates the scavenger's pacing, particularly
   107  // its rate and RSS goal.
   108  //
   109  // The RSS goal is based on the current heap goal with a small overhead
   110  // to accommodate non-determinism in the allocator.
   111  //
   112  // The pacing is based on scavengePageRate, which applies to both regular and
   113  // huge pages. See that constant for more information.
   114  //
   115  // mheap_.lock must be held or the world must be stopped.
   116  func gcPaceScavenger() {
   117  	// If we're called before the first GC completed, disable scavenging.
   118  	// We never scavenge before the 2nd GC cycle anyway (we don't have enough
   119  	// information about the heap yet) so this is fine, and avoids a fault
   120  	// or garbage data later.
   121  	if memstats.last_next_gc == 0 {
   122  		mheap_.scavengeGoal = ^uint64(0)
   123  		return
   124  	}
   125  	// Compute our scavenging goal.
   126  	goalRatio := float64(memstats.next_gc) / float64(memstats.last_next_gc)
   127  	retainedGoal := uint64(float64(memstats.last_heap_inuse) * goalRatio)
   128  	// Add retainExtraPercent overhead to retainedGoal. This calculation
   129  	// looks strange but the purpose is to arrive at an integer division
   130  	// (e.g. if retainExtraPercent = 12.5, then we get a divisor of 8)
   131  	// that also avoids the overflow from a multiplication.
   132  	retainedGoal += retainedGoal / (1.0 / (retainExtraPercent / 100.0))
   133  	// Align it to a physical page boundary to make the following calculations
   134  	// a bit more exact.
   135  	retainedGoal = (retainedGoal + uint64(physPageSize) - 1) &^ (uint64(physPageSize) - 1)
   136  
   137  	// Represents where we are now in the heap's contribution to RSS in bytes.
   138  	//
   139  	// Guaranteed to always be a multiple of physPageSize on systems where
   140  	// physPageSize <= pageSize since we map heap_sys at a rate larger than
   141  	// any physPageSize and released memory in multiples of the physPageSize.
   142  	//
   143  	// However, certain functions recategorize heap_sys as other stats (e.g.
   144  	// stack_sys) and this happens in multiples of pageSize, so on systems
   145  	// where physPageSize > pageSize the calculations below will not be exact.
   146  	// Generally this is OK since we'll be off by at most one regular
   147  	// physical page.
   148  	retainedNow := heapRetained()
   149  
   150  	// If we're already below our goal, or within one page of our goal, then disable
   151  	// the background scavenger. We disable the background scavenger if there's
   152  	// less than one physical page of work to do because it's not worth it.
   153  	if retainedNow <= retainedGoal || retainedNow-retainedGoal < uint64(physPageSize) {
   154  		mheap_.scavengeGoal = ^uint64(0)
   155  		return
   156  	}
   157  	mheap_.scavengeGoal = retainedGoal
   158  }
   159  
   160  // Sleep/wait state of the background scavenger.
   161  var scavenge struct {
   162  	lock       mutex
   163  	g          *g
   164  	parked     bool
   165  	timer      *timer
   166  	sysmonWake uint32 // Set atomically.
   167  }
   168  
   169  // readyForScavenger signals sysmon to wake the scavenger because
   170  // there may be new work to do.
   171  //
   172  // There may be a significant delay between when this function runs
   173  // and when the scavenger is kicked awake, but it may be safely invoked
   174  // in contexts where wakeScavenger is unsafe to call directly.
   175  func readyForScavenger() {
   176  	atomic.Store(&scavenge.sysmonWake, 1)
   177  }
   178  
   179  // wakeScavenger immediately unparks the scavenger if necessary.
   180  //
   181  // May run without a P, but it may allocate, so it must not be called
   182  // on any allocation path.
   183  //
   184  // mheap_.lock, scavenge.lock, and sched.lock must not be held.
   185  func wakeScavenger() {
   186  	lock(&scavenge.lock)
   187  	if scavenge.parked {
   188  		// Notify sysmon that it shouldn't bother waking up the scavenger.
   189  		atomic.Store(&scavenge.sysmonWake, 0)
   190  
   191  		// Try to stop the timer but we don't really care if we succeed.
   192  		// It's possible that either a timer was never started, or that
   193  		// we're racing with it.
   194  		// In the case that we're racing with there's the low chance that
   195  		// we experience a spurious wake-up of the scavenger, but that's
   196  		// totally safe.
   197  		stopTimer(scavenge.timer)
   198  
   199  		// Unpark the goroutine and tell it that there may have been a pacing
   200  		// change. Note that we skip the scheduler's runnext slot because we
   201  		// want to avoid having the scavenger interfere with the fair
   202  		// scheduling of user goroutines. In effect, this schedules the
   203  		// scavenger at a "lower priority" but that's OK because it'll
   204  		// catch up on the work it missed when it does get scheduled.
   205  		scavenge.parked = false
   206  
   207  		// Ready the goroutine by injecting it. We use injectglist instead
   208  		// of ready or goready in order to allow us to run this function
   209  		// without a P. injectglist also avoids placing the goroutine in
   210  		// the current P's runnext slot, which is desireable to prevent
   211  		// the scavenger from interfering with user goroutine scheduling
   212  		// too much.
   213  		var list gList
   214  		list.push(scavenge.g)
   215  		injectglist(&list)
   216  	}
   217  	unlock(&scavenge.lock)
   218  }
   219  
   220  // scavengeSleep attempts to put the scavenger to sleep for ns.
   221  //
   222  // Note that this function should only be called by the scavenger.
   223  //
   224  // The scavenger may be woken up earlier by a pacing change, and it may not go
   225  // to sleep at all if there's a pending pacing change.
   226  //
   227  // Returns the amount of time actually slept.
   228  func scavengeSleep(ns int64) int64 {
   229  	lock(&scavenge.lock)
   230  
   231  	// Set the timer.
   232  	//
   233  	// This must happen here instead of inside gopark
   234  	// because we can't close over any variables without
   235  	// failing escape analysis.
   236  	start := nanotime()
   237  	resetTimer(scavenge.timer, start+ns)
   238  
   239  	// Mark ourself as asleep and go to sleep.
   240  	scavenge.parked = true
   241  	goparkunlock(&scavenge.lock, waitReasonSleep, traceEvGoSleep, 2)
   242  
   243  	// Return how long we actually slept for.
   244  	return nanotime() - start
   245  }
   246  
   247  // Background scavenger.
   248  //
   249  // The background scavenger maintains the RSS of the application below
   250  // the line described by the proportional scavenging statistics in
   251  // the mheap struct.
   252  func bgscavenge(c chan int) {
   253  	scavenge.g = getg()
   254  
   255  	lockInit(&scavenge.lock, lockRankScavenge)
   256  	lock(&scavenge.lock)
   257  	scavenge.parked = true
   258  
   259  	scavenge.timer = new(timer)
   260  	scavenge.timer.f = func(_ interface{}, _ uintptr) {
   261  		wakeScavenger()
   262  	}
   263  
   264  	c <- 1
   265  	goparkunlock(&scavenge.lock, waitReasonGCScavengeWait, traceEvGoBlock, 1)
   266  
   267  	// Exponentially-weighted moving average of the fraction of time this
   268  	// goroutine spends scavenging (that is, percent of a single CPU).
   269  	// It represents a measure of scheduling overheads which might extend
   270  	// the sleep or the critical time beyond what's expected. Assume no
   271  	// overhead to begin with.
   272  	//
   273  	// TODO(mknyszek): Consider making this based on total CPU time of the
   274  	// application (i.e. scavengePercent * GOMAXPROCS). This isn't really
   275  	// feasible now because the scavenger acquires the heap lock over the
   276  	// scavenging operation, which means scavenging effectively blocks
   277  	// allocators and isn't scalable. However, given a scalable allocator,
   278  	// it makes sense to also make the scavenger scale with it; if you're
   279  	// allocating more frequently, then presumably you're also generating
   280  	// more work for the scavenger.
   281  	const idealFraction = scavengePercent / 100.0
   282  	scavengeEWMA := float64(idealFraction)
   283  
   284  	for {
   285  		released := uintptr(0)
   286  
   287  		// Time in scavenging critical section.
   288  		crit := float64(0)
   289  
   290  		// Run on the system stack since we grab the heap lock,
   291  		// and a stack growth with the heap lock means a deadlock.
   292  		systemstack(func() {
   293  			lock(&mheap_.lock)
   294  
   295  			// If background scavenging is disabled or if there's no work to do just park.
   296  			retained, goal := heapRetained(), mheap_.scavengeGoal
   297  			if retained <= goal {
   298  				unlock(&mheap_.lock)
   299  				return
   300  			}
   301  
   302  			// Scavenge one page, and measure the amount of time spent scavenging.
   303  			start := nanotime()
   304  			released = mheap_.pages.scavenge(physPageSize, true)
   305  			mheap_.pages.scav.released += released
   306  			crit = float64(nanotime() - start)
   307  
   308  			unlock(&mheap_.lock)
   309  		})
   310  
   311  		if released == 0 {
   312  			lock(&scavenge.lock)
   313  			scavenge.parked = true
   314  			goparkunlock(&scavenge.lock, waitReasonGCScavengeWait, traceEvGoBlock, 1)
   315  			continue
   316  		}
   317  
   318  		if released < physPageSize {
   319  			// If this happens, it means that we may have attempted to release part
   320  			// of a physical page, but the likely effect of that is that it released
   321  			// the whole physical page, some of which may have still been in-use.
   322  			// This could lead to memory corruption. Throw.
   323  			throw("released less than one physical page of memory")
   324  		}
   325  
   326  		// On some platforms we may see crit as zero if the time it takes to scavenge
   327  		// memory is less than the minimum granularity of its clock (e.g. Windows).
   328  		// In this case, just assume scavenging takes 10 ┬Ás per regular physical page
   329  		// (determined empirically), and conservatively ignore the impact of huge pages
   330  		// on timing.
   331  		//
   332  		// We shouldn't ever see a crit value less than zero unless there's a bug of
   333  		// some kind, either on our side or in the platform we're running on, but be
   334  		// defensive in that case as well.
   335  		const approxCritNSPerPhysicalPage = 10e3
   336  		if crit <= 0 {
   337  			crit = approxCritNSPerPhysicalPage * float64(released/physPageSize)
   338  		}
   339  
   340  		// Multiply the critical time by 1 + the ratio of the costs of using
   341  		// scavenged memory vs. scavenging memory. This forces us to pay down
   342  		// the cost of reusing this memory eagerly by sleeping for a longer period
   343  		// of time and scavenging less frequently. More concretely, we avoid situations
   344  		// where we end up scavenging so often that we hurt allocation performance
   345  		// because of the additional overheads of using scavenged memory.
   346  		crit *= 1 + scavengeCostRatio
   347  
   348  		// If we spent more than 10 ms (for example, if the OS scheduled us away, or someone
   349  		// put their machine to sleep) in the critical section, bound the time we use to
   350  		// calculate at 10 ms to avoid letting the sleep time get arbitrarily high.
   351  		const maxCrit = 10e6
   352  		if crit > maxCrit {
   353  			crit = maxCrit
   354  		}
   355  
   356  		// Compute the amount of time to sleep, assuming we want to use at most
   357  		// scavengePercent of CPU time. Take into account scheduling overheads
   358  		// that may extend the length of our sleep by multiplying by how far
   359  		// off we are from the ideal ratio. For example, if we're sleeping too
   360  		// much, then scavengeEMWA < idealFraction, so we'll adjust the sleep time
   361  		// down.
   362  		adjust := scavengeEWMA / idealFraction
   363  		sleepTime := int64(adjust * crit / (scavengePercent / 100.0))
   364  
   365  		// Go to sleep.
   366  		slept := scavengeSleep(sleepTime)
   367  
   368  		// Compute the new ratio.
   369  		fraction := crit / (crit + float64(slept))
   370  
   371  		// Set a lower bound on the fraction.
   372  		// Due to OS-related anomalies we may "sleep" for an inordinate amount
   373  		// of time. Let's avoid letting the ratio get out of hand by bounding
   374  		// the sleep time we use in our EWMA.
   375  		const minFraction = 1 / 1000
   376  		if fraction < minFraction {
   377  			fraction = minFraction
   378  		}
   379  
   380  		// Update scavengeEWMA by merging in the new crit/slept ratio.
   381  		const alpha = 0.5
   382  		scavengeEWMA = alpha*fraction + (1-alpha)*scavengeEWMA
   383  	}
   384  }
   385  
   386  // scavenge scavenges nbytes worth of free pages, starting with the
   387  // highest address first. Successive calls continue from where it left
   388  // off until the heap is exhausted. Call scavengeStartGen to bring it
   389  // back to the top of the heap.
   390  //
   391  // Returns the amount of memory scavenged in bytes.
   392  //
   393  // s.mheapLock must be held, but may be temporarily released if
   394  // mayUnlock == true.
   395  //
   396  // Must run on the system stack because s.mheapLock must be held.
   397  //
   398  //go:systemstack
   399  func (s *pageAlloc) scavenge(nbytes uintptr, mayUnlock bool) uintptr {
   400  	var (
   401  		addrs addrRange
   402  		gen   uint32
   403  	)
   404  	released := uintptr(0)
   405  	for released < nbytes {
   406  		if addrs.size() == 0 {
   407  			if addrs, gen = s.scavengeReserve(); addrs.size() == 0 {
   408  				break
   409  			}
   410  		}
   411  		r, a := s.scavengeOne(addrs, nbytes-released, mayUnlock)
   412  		released += r
   413  		addrs = a
   414  	}
   415  	// Only unreserve the space which hasn't been scavenged or searched
   416  	// to ensure we always make progress.
   417  	s.scavengeUnreserve(addrs, gen)
   418  	return released
   419  }
   420  
   421  // printScavTrace prints a scavenge trace line to standard error.
   422  //
   423  // released should be the amount of memory released since the last time this
   424  // was called, and forced indicates whether the scavenge was forced by the
   425  // application.
   426  func printScavTrace(gen uint32, released uintptr, forced bool) {
   427  	printlock()
   428  	print("scav ", gen, " ",
   429  		released>>10, " KiB work, ",
   430  		atomic.Load64(&memstats.heap_released)>>10, " KiB total, ",
   431  		(atomic.Load64(&memstats.heap_inuse)*100)/heapRetained(), "% util",
   432  	)
   433  	if forced {
   434  		print(" (forced)")
   435  	}
   436  	println()
   437  	printunlock()
   438  }
   439  
   440  // scavengeStartGen starts a new scavenge generation, resetting
   441  // the scavenger's search space to the full in-use address space.
   442  //
   443  // s.mheapLock must be held.
   444  //
   445  // Must run on the system stack because s.mheapLock must be held.
   446  //
   447  //go:systemstack
   448  func (s *pageAlloc) scavengeStartGen() {
   449  	if debug.scavtrace > 0 {
   450  		printScavTrace(s.scav.gen, s.scav.released, false)
   451  	}
   452  	s.inUse.cloneInto(&s.scav.inUse)
   453  
   454  	// Pick the new starting address for the scavenger cycle.
   455  	var startAddr offAddr
   456  	if s.scav.scavLWM.lessThan(s.scav.freeHWM) {
   457  		// The "free" high watermark exceeds the "scavenged" low watermark,
   458  		// so there are free scavengable pages in parts of the address space
   459  		// that the scavenger already searched, the high watermark being the
   460  		// highest one. Pick that as our new starting point to ensure we
   461  		// see those pages.
   462  		startAddr = s.scav.freeHWM
   463  	} else {
   464  		// The "free" high watermark does not exceed the "scavenged" low
   465  		// watermark. This means the allocator didn't free any memory in
   466  		// the range we scavenged last cycle, so we might as well continue
   467  		// scavenging from where we were.
   468  		startAddr = s.scav.scavLWM
   469  	}
   470  	s.scav.inUse.removeGreaterEqual(startAddr.addr())
   471  
   472  	// reservationBytes may be zero if s.inUse.totalBytes is small, or if
   473  	// scavengeReservationShards is large. This case is fine as the scavenger
   474  	// will simply be turned off, but it does mean that scavengeReservationShards,
   475  	// in concert with pallocChunkBytes, dictates the minimum heap size at which
   476  	// the scavenger triggers. In practice this minimum is generally less than an
   477  	// arena in size, so virtually every heap has the scavenger on.
   478  	s.scav.reservationBytes = alignUp(s.inUse.totalBytes, pallocChunkBytes) / scavengeReservationShards
   479  	s.scav.gen++
   480  	s.scav.released = 0
   481  	s.scav.freeHWM = minOffAddr
   482  	s.scav.scavLWM = maxOffAddr
   483  }
   484  
   485  // scavengeReserve reserves a contiguous range of the address space
   486  // for scavenging. The maximum amount of space it reserves is proportional
   487  // to the size of the heap. The ranges are reserved from the high addresses
   488  // first.
   489  //
   490  // Returns the reserved range and the scavenge generation number for it.
   491  //
   492  // s.mheapLock must be held.
   493  //
   494  // Must run on the system stack because s.mheapLock must be held.
   495  //
   496  //go:systemstack
   497  func (s *pageAlloc) scavengeReserve() (addrRange, uint32) {
   498  	// Start by reserving the minimum.
   499  	r := s.scav.inUse.removeLast(s.scav.reservationBytes)
   500  
   501  	// Return early if the size is zero; we don't want to use
   502  	// the bogus address below.
   503  	if r.size() == 0 {
   504  		return r, s.scav.gen
   505  	}
   506  
   507  	// The scavenger requires that base be aligned to a
   508  	// palloc chunk because that's the unit of operation for
   509  	// the scavenger, so align down, potentially extending
   510  	// the range.
   511  	newBase := alignDown(r.base.addr(), pallocChunkBytes)
   512  
   513  	// Remove from inUse however much extra we just pulled out.
   514  	s.scav.inUse.removeGreaterEqual(newBase)
   515  	r.base = offAddr{newBase}
   516  	return r, s.scav.gen
   517  }
   518  
   519  // scavengeUnreserve returns an unscavenged portion of a range that was
   520  // previously reserved with scavengeReserve.
   521  //
   522  // s.mheapLock must be held.
   523  //
   524  // Must run on the system stack because s.mheapLock must be held.
   525  //
   526  //go:systemstack
   527  func (s *pageAlloc) scavengeUnreserve(r addrRange, gen uint32) {
   528  	if r.size() == 0 || gen != s.scav.gen {
   529  		return
   530  	}
   531  	if r.base.addr()%pallocChunkBytes != 0 {
   532  		throw("unreserving unaligned region")
   533  	}
   534  	s.scav.inUse.add(r)
   535  }
   536  
   537  // scavengeOne walks over address range work until it finds
   538  // a contiguous run of pages to scavenge. It will try to scavenge
   539  // at most max bytes at once, but may scavenge more to avoid
   540  // breaking huge pages. Once it scavenges some memory it returns
   541  // how much it scavenged in bytes.
   542  //
   543  // Returns the number of bytes scavenged and the part of work
   544  // which was not yet searched.
   545  //
   546  // work's base address must be aligned to pallocChunkBytes.
   547  //
   548  // s.mheapLock must be held, but may be temporarily released if
   549  // mayUnlock == true.
   550  //
   551  // Must run on the system stack because s.mheapLock must be held.
   552  //
   553  //go:systemstack
   554  func (s *pageAlloc) scavengeOne(work addrRange, max uintptr, mayUnlock bool) (uintptr, addrRange) {
   555  	// Defensively check if we've recieved an empty address range.
   556  	// If so, just return.
   557  	if work.size() == 0 {
   558  		// Nothing to do.
   559  		return 0, work
   560  	}
   561  	// Check the prerequisites of work.
   562  	if work.base.addr()%pallocChunkBytes != 0 {
   563  		throw("scavengeOne called with unaligned work region")
   564  	}
   565  	// Calculate the maximum number of pages to scavenge.
   566  	//
   567  	// This should be alignUp(max, pageSize) / pageSize but max can and will
   568  	// be ^uintptr(0), so we need to be very careful not to overflow here.
   569  	// Rather than use alignUp, calculate the number of pages rounded down
   570  	// first, then add back one if necessary.
   571  	maxPages := max / pageSize
   572  	if max%pageSize != 0 {
   573  		maxPages++
   574  	}
   575  
   576  	// Calculate the minimum number of pages we can scavenge.
   577  	//
   578  	// Because we can only scavenge whole physical pages, we must
   579  	// ensure that we scavenge at least minPages each time, aligned
   580  	// to minPages*pageSize.
   581  	minPages := physPageSize / pageSize
   582  	if minPages < 1 {
   583  		minPages = 1
   584  	}
   585  
   586  	// Helpers for locking and unlocking only if mayUnlock == true.
   587  	lockHeap := func() {
   588  		if mayUnlock {
   589  			lock(s.mheapLock)
   590  		}
   591  	}
   592  	unlockHeap := func() {
   593  		if mayUnlock {
   594  			unlock(s.mheapLock)
   595  		}
   596  	}
   597  
   598  	// Fast path: check the chunk containing the top-most address in work,
   599  	// starting at that address's page index in the chunk.
   600  	//
   601  	// Note that work.end() is exclusive, so get the chunk we care about
   602  	// by subtracting 1.
   603  	maxAddr := work.limit.addr() - 1
   604  	maxChunk := chunkIndex(maxAddr)
   605  	if s.summary[len(s.summary)-1][maxChunk].max() >= uint(minPages) {
   606  		// We only bother looking for a candidate if there at least
   607  		// minPages free pages at all.
   608  		base, npages := s.chunkOf(maxChunk).findScavengeCandidate(chunkPageIndex(maxAddr), minPages, maxPages)
   609  
   610  		// If we found something, scavenge it and return!
   611  		if npages != 0 {
   612  			work.limit = offAddr{s.scavengeRangeLocked(maxChunk, base, npages)}
   613  			return uintptr(npages) * pageSize, work
   614  		}
   615  	}
   616  	// Update the limit to reflect the fact that we checked maxChunk already.
   617  	work.limit = offAddr{chunkBase(maxChunk)}
   618  
   619  	// findCandidate finds the next scavenge candidate in work optimistically.
   620  	//
   621  	// Returns the candidate chunk index and true on success, and false on failure.
   622  	//
   623  	// The heap need not be locked.
   624  	findCandidate := func(work addrRange) (chunkIdx, bool) {
   625  		// Iterate over this work's chunks.
   626  		for i := chunkIndex(work.limit.addr() - 1); i >= chunkIndex(work.base.addr()); i-- {
   627  			// If this chunk is totally in-use or has no unscavenged pages, don't bother
   628  			// doing a more sophisticated check.
   629  			//
   630  			// Note we're accessing the summary and the chunks without a lock, but
   631  			// that's fine. We're being optimistic anyway.
   632  
   633  			// Check quickly if there are enough free pages at all.
   634  			if s.summary[len(s.summary)-1][i].max() < uint(minPages) {
   635  				continue
   636  			}
   637  
   638  			// Run over the chunk looking harder for a candidate. Again, we could
   639  			// race with a lot of different pieces of code, but we're just being
   640  			// optimistic. Make sure we load the l2 pointer atomically though, to
   641  			// avoid races with heap growth. It may or may not be possible to also
   642  			// see a nil pointer in this case if we do race with heap growth, but
   643  			// just defensively ignore the nils. This operation is optimistic anyway.
   644  			l2 := (*[1 << pallocChunksL2Bits]pallocData)(atomic.Loadp(unsafe.Pointer(&s.chunks[i.l1()])))
   645  			if l2 != nil && l2[i.l2()].hasScavengeCandidate(minPages) {
   646  				return i, true
   647  			}
   648  		}
   649  		return 0, false
   650  	}
   651  
   652  	// Slow path: iterate optimistically over the in-use address space
   653  	// looking for any free and unscavenged page. If we think we see something,
   654  	// lock and verify it!
   655  	for work.size() != 0 {
   656  		unlockHeap()
   657  
   658  		// Search for the candidate.
   659  		candidateChunkIdx, ok := findCandidate(work)
   660  
   661  		// Lock the heap. We need to do this now if we found a candidate or not.
   662  		// If we did, we'll verify it. If not, we need to lock before returning
   663  		// anyway.
   664  		lockHeap()
   665  
   666  		if !ok {
   667  			// We didn't find a candidate, so we're done.
   668  			work.limit = work.base
   669  			break
   670  		}
   671  
   672  		// Find, verify, and scavenge if we can.
   673  		chunk := s.chunkOf(candidateChunkIdx)
   674  		base, npages := chunk.findScavengeCandidate(pallocChunkPages-1, minPages, maxPages)
   675  		if npages > 0 {
   676  			work.limit = offAddr{s.scavengeRangeLocked(candidateChunkIdx, base, npages)}
   677  			return uintptr(npages) * pageSize, work
   678  		}
   679  
   680  		// We were fooled, so let's continue from where we left off.
   681  		work.limit = offAddr{chunkBase(candidateChunkIdx)}
   682  	}
   683  	return 0, work
   684  }
   685  
   686  // scavengeRangeLocked scavenges the given region of memory.
   687  // The region of memory is described by its chunk index (ci),
   688  // the starting page index of the region relative to that
   689  // chunk (base), and the length of the region in pages (npages).
   690  //
   691  // Returns the base address of the scavenged region.
   692  //
   693  // s.mheapLock must be held.
   694  func (s *pageAlloc) scavengeRangeLocked(ci chunkIdx, base, npages uint) uintptr {
   695  	s.chunkOf(ci).scavenged.setRange(base, npages)
   696  
   697  	// Compute the full address for the start of the range.
   698  	addr := chunkBase(ci) + uintptr(base)*pageSize
   699  
   700  	// Update the scavenge low watermark.
   701  	if oAddr := (offAddr{addr}); oAddr.lessThan(s.scav.scavLWM) {
   702  		s.scav.scavLWM = oAddr
   703  	}
   704  
   705  	// Only perform the actual scavenging if we're not in a test.
   706  	// It's dangerous to do so otherwise.
   707  	if s.test {
   708  		return addr
   709  	}
   710  	sysUnused(unsafe.Pointer(addr), uintptr(npages)*pageSize)
   711  
   712  	// Update global accounting only when not in test, otherwise
   713  	// the runtime's accounting will be wrong.
   714  	mSysStatInc(&memstats.heap_released, uintptr(npages)*pageSize)
   715  	return addr
   716  }
   717  
   718  // fillAligned returns x but with all zeroes in m-aligned
   719  // groups of m bits set to 1 if any bit in the group is non-zero.
   720  //
   721  // For example, fillAligned(0x0100a3, 8) == 0xff00ff.
   722  //
   723  // Note that if m == 1, this is a no-op.
   724  //
   725  // m must be a power of 2 <= maxPagesPerPhysPage.
   726  func fillAligned(x uint64, m uint) uint64 {
   727  	apply := func(x uint64, c uint64) uint64 {
   728  		// The technique used it here is derived from
   729  		// https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
   730  		// and extended for more than just bytes (like nibbles
   731  		// and uint16s) by using an appropriate constant.
   732  		//
   733  		// To summarize the technique, quoting from that page:
   734  		// "[It] works by first zeroing the high bits of the [8]
   735  		// bytes in the word. Subsequently, it adds a number that
   736  		// will result in an overflow to the high bit of a byte if
   737  		// any of the low bits were initially set. Next the high
   738  		// bits of the original word are ORed with these values;
   739  		// thus, the high bit of a byte is set iff any bit in the
   740  		// byte was set. Finally, we determine if any of these high
   741  		// bits are zero by ORing with ones everywhere except the
   742  		// high bits and inverting the result."
   743  		return ^((((x & c) + c) | x) | c)
   744  	}
   745  	// Transform x to contain a 1 bit at the top of each m-aligned
   746  	// group of m zero bits.
   747  	switch m {
   748  	case 1:
   749  		return x
   750  	case 2:
   751  		x = apply(x, 0x5555555555555555)
   752  	case 4:
   753  		x = apply(x, 0x7777777777777777)
   754  	case 8:
   755  		x = apply(x, 0x7f7f7f7f7f7f7f7f)
   756  	case 16:
   757  		x = apply(x, 0x7fff7fff7fff7fff)
   758  	case 32:
   759  		x = apply(x, 0x7fffffff7fffffff)
   760  	case 64: // == maxPagesPerPhysPage
   761  		x = apply(x, 0x7fffffffffffffff)
   762  	default:
   763  		throw("bad m value")
   764  	}
   765  	// Now, the top bit of each m-aligned group in x is set
   766  	// that group was all zero in the original x.
   767  
   768  	// From each group of m bits subtract 1.
   769  	// Because we know only the top bits of each
   770  	// m-aligned group are set, we know this will
   771  	// set each group to have all the bits set except
   772  	// the top bit, so just OR with the original
   773  	// result to set all the bits.
   774  	return ^((x - (x >> (m - 1))) | x)
   775  }
   776  
   777  // hasScavengeCandidate returns true if there's any min-page-aligned groups of
   778  // min pages of free-and-unscavenged memory in the region represented by this
   779  // pallocData.
   780  //
   781  // min must be a non-zero power of 2 <= maxPagesPerPhysPage.
   782  func (m *pallocData) hasScavengeCandidate(min uintptr) bool {
   783  	if min&(min-1) != 0 || min == 0 {
   784  		print("runtime: min = ", min, "\n")
   785  		throw("min must be a non-zero power of 2")
   786  	} else if min > maxPagesPerPhysPage {
   787  		print("runtime: min = ", min, "\n")
   788  		throw("min too large")
   789  	}
   790  
   791  	// The goal of this search is to see if the chunk contains any free and unscavenged memory.
   792  	for i := len(m.scavenged) - 1; i >= 0; i-- {
   793  		// 1s are scavenged OR non-free => 0s are unscavenged AND free
   794  		//
   795  		// TODO(mknyszek): Consider splitting up fillAligned into two
   796  		// functions, since here we technically could get by with just
   797  		// the first half of its computation. It'll save a few instructions
   798  		// but adds some additional code complexity.
   799  		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   800  
   801  		// Quickly skip over chunks of non-free or scavenged pages.
   802  		if x != ^uint64(0) {
   803  			return true
   804  		}
   805  	}
   806  	return false
   807  }
   808  
   809  // findScavengeCandidate returns a start index and a size for this pallocData
   810  // segment which represents a contiguous region of free and unscavenged memory.
   811  //
   812  // searchIdx indicates the page index within this chunk to start the search, but
   813  // note that findScavengeCandidate searches backwards through the pallocData. As a
   814  // a result, it will return the highest scavenge candidate in address order.
   815  //
   816  // min indicates a hard minimum size and alignment for runs of pages. That is,
   817  // findScavengeCandidate will not return a region smaller than min pages in size,
   818  // or that is min pages or greater in size but not aligned to min. min must be
   819  // a non-zero power of 2 <= maxPagesPerPhysPage.
   820  //
   821  // max is a hint for how big of a region is desired. If max >= pallocChunkPages, then
   822  // findScavengeCandidate effectively returns entire free and unscavenged regions.
   823  // If max < pallocChunkPages, it may truncate the returned region such that size is
   824  // max. However, findScavengeCandidate may still return a larger region if, for
   825  // example, it chooses to preserve huge pages, or if max is not aligned to min (it
   826  // will round up). That is, even if max is small, the returned size is not guaranteed
   827  // to be equal to max. max is allowed to be less than min, in which case it is as if
   828  // max == min.
   829  func (m *pallocData) findScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
   830  	if min&(min-1) != 0 || min == 0 {
   831  		print("runtime: min = ", min, "\n")
   832  		throw("min must be a non-zero power of 2")
   833  	} else if min > maxPagesPerPhysPage {
   834  		print("runtime: min = ", min, "\n")
   835  		throw("min too large")
   836  	}
   837  	// max may not be min-aligned, so we might accidentally truncate to
   838  	// a max value which causes us to return a non-min-aligned value.
   839  	// To prevent this, align max up to a multiple of min (which is always
   840  	// a power of 2). This also prevents max from ever being less than
   841  	// min, unless it's zero, so handle that explicitly.
   842  	if max == 0 {
   843  		max = min
   844  	} else {
   845  		max = alignUp(max, min)
   846  	}
   847  
   848  	i := int(searchIdx / 64)
   849  	// Start by quickly skipping over blocks of non-free or scavenged pages.
   850  	for ; i >= 0; i-- {
   851  		// 1s are scavenged OR non-free => 0s are unscavenged AND free
   852  		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   853  		if x != ^uint64(0) {
   854  			break
   855  		}
   856  	}
   857  	if i < 0 {
   858  		// Failed to find any free/unscavenged pages.
   859  		return 0, 0
   860  	}
   861  	// We have something in the 64-bit chunk at i, but it could
   862  	// extend further. Loop until we find the extent of it.
   863  
   864  	// 1s are scavenged OR non-free => 0s are unscavenged AND free
   865  	x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   866  	z1 := uint(sys.LeadingZeros64(^x))
   867  	run, end := uint(0), uint(i)*64+(64-z1)
   868  	if x<<z1 != 0 {
   869  		// After shifting out z1 bits, we still have 1s,
   870  		// so the run ends inside this word.
   871  		run = uint(sys.LeadingZeros64(x << z1))
   872  	} else {
   873  		// After shifting out z1 bits, we have no more 1s.
   874  		// This means the run extends to the bottom of the
   875  		// word so it may extend into further words.
   876  		run = 64 - z1
   877  		for j := i - 1; j >= 0; j-- {
   878  			x := fillAligned(m.scavenged[j]|m.pallocBits[j], uint(min))
   879  			run += uint(sys.LeadingZeros64(x))
   880  			if x != 0 {
   881  				// The run stopped in this word.
   882  				break
   883  			}
   884  		}
   885  	}
   886  
   887  	// Split the run we found if it's larger than max but hold on to
   888  	// our original length, since we may need it later.
   889  	size := run
   890  	if size > uint(max) {
   891  		size = uint(max)
   892  	}
   893  	start := end - size
   894  
   895  	// Each huge page is guaranteed to fit in a single palloc chunk.
   896  	//
   897  	// TODO(mknyszek): Support larger huge page sizes.
   898  	// TODO(mknyszek): Consider taking pages-per-huge-page as a parameter
   899  	// so we can write tests for this.
   900  	if physHugePageSize > pageSize && physHugePageSize > physPageSize {
   901  		// We have huge pages, so let's ensure we don't break one by scavenging
   902  		// over a huge page boundary. If the range [start, start+size) overlaps with
   903  		// a free-and-unscavenged huge page, we want to grow the region we scavenge
   904  		// to include that huge page.
   905  
   906  		// Compute the huge page boundary above our candidate.
   907  		pagesPerHugePage := uintptr(physHugePageSize / pageSize)
   908  		hugePageAbove := uint(alignUp(uintptr(start), pagesPerHugePage))
   909  
   910  		// If that boundary is within our current candidate, then we may be breaking
   911  		// a huge page.
   912  		if hugePageAbove <= end {
   913  			// Compute the huge page boundary below our candidate.
   914  			hugePageBelow := uint(alignDown(uintptr(start), pagesPerHugePage))
   915  
   916  			if hugePageBelow >= end-run {
   917  				// We're in danger of breaking apart a huge page since start+size crosses
   918  				// a huge page boundary and rounding down start to the nearest huge
   919  				// page boundary is included in the full run we found. Include the entire
   920  				// huge page in the bound by rounding down to the huge page size.
   921  				size = size + (start - hugePageBelow)
   922  				start = hugePageBelow
   923  			}
   924  		}
   925  	}
   926  	return start, size
   927  }
   928  

View as plain text