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  
    96  // heapRetained returns an estimate of the current heap RSS.
    97  func heapRetained() uint64 {
    98  	return atomic.Load64(&memstats.heap_sys) - atomic.Load64(&memstats.heap_released)
    99  }
   100  
   101  // gcPaceScavenger updates the scavenger's pacing, particularly
   102  // its rate and RSS goal.
   103  //
   104  // The RSS goal is based on the current heap goal with a small overhead
   105  // to accommodate non-determinism in the allocator.
   106  //
   107  // The pacing is based on scavengePageRate, which applies to both regular and
   108  // huge pages. See that constant for more information.
   109  //
   110  // mheap_.lock must be held or the world must be stopped.
   111  func gcPaceScavenger() {
   112  	// If we're called before the first GC completed, disable scavenging.
   113  	// We never scavenge before the 2nd GC cycle anyway (we don't have enough
   114  	// information about the heap yet) so this is fine, and avoids a fault
   115  	// or garbage data later.
   116  	if memstats.last_next_gc == 0 {
   117  		mheap_.scavengeGoal = ^uint64(0)
   118  		return
   119  	}
   120  	// Compute our scavenging goal.
   121  	goalRatio := float64(memstats.next_gc) / float64(memstats.last_next_gc)
   122  	retainedGoal := uint64(float64(memstats.last_heap_inuse) * goalRatio)
   123  	// Add retainExtraPercent overhead to retainedGoal. This calculation
   124  	// looks strange but the purpose is to arrive at an integer division
   125  	// (e.g. if retainExtraPercent = 12.5, then we get a divisor of 8)
   126  	// that also avoids the overflow from a multiplication.
   127  	retainedGoal += retainedGoal / (1.0 / (retainExtraPercent / 100.0))
   128  	// Align it to a physical page boundary to make the following calculations
   129  	// a bit more exact.
   130  	retainedGoal = (retainedGoal + uint64(physPageSize) - 1) &^ (uint64(physPageSize) - 1)
   131  
   132  	// Represents where we are now in the heap's contribution to RSS in bytes.
   133  	//
   134  	// Guaranteed to always be a multiple of physPageSize on systems where
   135  	// physPageSize <= pageSize since we map heap_sys at a rate larger than
   136  	// any physPageSize and released memory in multiples of the physPageSize.
   137  	//
   138  	// However, certain functions recategorize heap_sys as other stats (e.g.
   139  	// stack_sys) and this happens in multiples of pageSize, so on systems
   140  	// where physPageSize > pageSize the calculations below will not be exact.
   141  	// Generally this is OK since we'll be off by at most one regular
   142  	// physical page.
   143  	retainedNow := heapRetained()
   144  
   145  	// If we're already below our goal, or within one page of our goal, then disable
   146  	// the background scavenger. We disable the background scavenger if there's
   147  	// less than one physical page of work to do because it's not worth it.
   148  	if retainedNow <= retainedGoal || retainedNow-retainedGoal < uint64(physPageSize) {
   149  		mheap_.scavengeGoal = ^uint64(0)
   150  		return
   151  	}
   152  	mheap_.scavengeGoal = retainedGoal
   153  	mheap_.pages.resetScavengeAddr()
   154  }
   155  
   156  // Sleep/wait state of the background scavenger.
   157  var scavenge struct {
   158  	lock   mutex
   159  	g      *g
   160  	parked bool
   161  	timer  *timer
   162  }
   163  
   164  // wakeScavenger unparks the scavenger if necessary. It must be called
   165  // after any pacing update.
   166  //
   167  // mheap_.lock and scavenge.lock must not be held.
   168  func wakeScavenger() {
   169  	lock(&scavenge.lock)
   170  	if scavenge.parked {
   171  		// Try to stop the timer but we don't really care if we succeed.
   172  		// It's possible that either a timer was never started, or that
   173  		// we're racing with it.
   174  		// In the case that we're racing with there's the low chance that
   175  		// we experience a spurious wake-up of the scavenger, but that's
   176  		// totally safe.
   177  		stopTimer(scavenge.timer)
   178  
   179  		// Unpark the goroutine and tell it that there may have been a pacing
   180  		// change. Note that we skip the scheduler's runnext slot because we
   181  		// want to avoid having the scavenger interfere with the fair
   182  		// scheduling of user goroutines. In effect, this schedules the
   183  		// scavenger at a "lower priority" but that's OK because it'll
   184  		// catch up on the work it missed when it does get scheduled.
   185  		scavenge.parked = false
   186  		systemstack(func() {
   187  			ready(scavenge.g, 0, false)
   188  		})
   189  	}
   190  	unlock(&scavenge.lock)
   191  }
   192  
   193  // scavengeSleep attempts to put the scavenger to sleep for ns.
   194  //
   195  // Note that this function should only be called by the scavenger.
   196  //
   197  // The scavenger may be woken up earlier by a pacing change, and it may not go
   198  // to sleep at all if there's a pending pacing change.
   199  //
   200  // Returns the amount of time actually slept.
   201  func scavengeSleep(ns int64) int64 {
   202  	lock(&scavenge.lock)
   203  
   204  	// Set the timer.
   205  	//
   206  	// This must happen here instead of inside gopark
   207  	// because we can't close over any variables without
   208  	// failing escape analysis.
   209  	start := nanotime()
   210  	resetTimer(scavenge.timer, start+ns)
   211  
   212  	// Mark ourself as asleep and go to sleep.
   213  	scavenge.parked = true
   214  	goparkunlock(&scavenge.lock, waitReasonSleep, traceEvGoSleep, 2)
   215  
   216  	// Return how long we actually slept for.
   217  	return nanotime() - start
   218  }
   219  
   220  // Background scavenger.
   221  //
   222  // The background scavenger maintains the RSS of the application below
   223  // the line described by the proportional scavenging statistics in
   224  // the mheap struct.
   225  func bgscavenge(c chan int) {
   226  	scavenge.g = getg()
   227  
   228  	lock(&scavenge.lock)
   229  	scavenge.parked = true
   230  
   231  	scavenge.timer = new(timer)
   232  	scavenge.timer.f = func(_ interface{}, _ uintptr) {
   233  		wakeScavenger()
   234  	}
   235  
   236  	c <- 1
   237  	goparkunlock(&scavenge.lock, waitReasonGCScavengeWait, traceEvGoBlock, 1)
   238  
   239  	// Exponentially-weighted moving average of the fraction of time this
   240  	// goroutine spends scavenging (that is, percent of a single CPU).
   241  	// It represents a measure of scheduling overheads which might extend
   242  	// the sleep or the critical time beyond what's expected. Assume no
   243  	// overhead to begin with.
   244  	//
   245  	// TODO(mknyszek): Consider making this based on total CPU time of the
   246  	// application (i.e. scavengePercent * GOMAXPROCS). This isn't really
   247  	// feasible now because the scavenger acquires the heap lock over the
   248  	// scavenging operation, which means scavenging effectively blocks
   249  	// allocators and isn't scalable. However, given a scalable allocator,
   250  	// it makes sense to also make the scavenger scale with it; if you're
   251  	// allocating more frequently, then presumably you're also generating
   252  	// more work for the scavenger.
   253  	const idealFraction = scavengePercent / 100.0
   254  	scavengeEWMA := float64(idealFraction)
   255  
   256  	for {
   257  		released := uintptr(0)
   258  
   259  		// Time in scavenging critical section.
   260  		crit := float64(0)
   261  
   262  		// Run on the system stack since we grab the heap lock,
   263  		// and a stack growth with the heap lock means a deadlock.
   264  		systemstack(func() {
   265  			lock(&mheap_.lock)
   266  
   267  			// If background scavenging is disabled or if there's no work to do just park.
   268  			retained, goal := heapRetained(), mheap_.scavengeGoal
   269  			if retained <= goal {
   270  				unlock(&mheap_.lock)
   271  				return
   272  			}
   273  			unlock(&mheap_.lock)
   274  
   275  			// Scavenge one page, and measure the amount of time spent scavenging.
   276  			start := nanotime()
   277  			released = mheap_.pages.scavengeOne(physPageSize, false)
   278  			atomic.Xadduintptr(&mheap_.pages.scavReleased, released)
   279  			crit = float64(nanotime() - start)
   280  		})
   281  
   282  		if released == 0 {
   283  			lock(&scavenge.lock)
   284  			scavenge.parked = true
   285  			goparkunlock(&scavenge.lock, waitReasonGCScavengeWait, traceEvGoBlock, 1)
   286  			continue
   287  		}
   288  
   289  		if released < physPageSize {
   290  			// If this happens, it means that we may have attempted to release part
   291  			// of a physical page, but the likely effect of that is that it released
   292  			// the whole physical page, some of which may have still been in-use.
   293  			// This could lead to memory corruption. Throw.
   294  			throw("released less than one physical page of memory")
   295  		}
   296  
   297  		// On some platforms we may see crit as zero if the time it takes to scavenge
   298  		// memory is less than the minimum granularity of its clock (e.g. Windows).
   299  		// In this case, just assume scavenging takes 10 ┬Ás per regular physical page
   300  		// (determined empirically), and conservatively ignore the impact of huge pages
   301  		// on timing.
   302  		//
   303  		// We shouldn't ever see a crit value less than zero unless there's a bug of
   304  		// some kind, either on our side or in the platform we're running on, but be
   305  		// defensive in that case as well.
   306  		const approxCritNSPerPhysicalPage = 10e3
   307  		if crit <= 0 {
   308  			crit = approxCritNSPerPhysicalPage * float64(released/physPageSize)
   309  		}
   310  
   311  		// Multiply the critical time by 1 + the ratio of the costs of using
   312  		// scavenged memory vs. scavenging memory. This forces us to pay down
   313  		// the cost of reusing this memory eagerly by sleeping for a longer period
   314  		// of time and scavenging less frequently. More concretely, we avoid situations
   315  		// where we end up scavenging so often that we hurt allocation performance
   316  		// because of the additional overheads of using scavenged memory.
   317  		crit *= 1 + scavengeCostRatio
   318  
   319  		// If we spent more than 10 ms (for example, if the OS scheduled us away, or someone
   320  		// put their machine to sleep) in the critical section, bound the time we use to
   321  		// calculate at 10 ms to avoid letting the sleep time get arbitrarily high.
   322  		const maxCrit = 10e6
   323  		if crit > maxCrit {
   324  			crit = maxCrit
   325  		}
   326  
   327  		// Compute the amount of time to sleep, assuming we want to use at most
   328  		// scavengePercent of CPU time. Take into account scheduling overheads
   329  		// that may extend the length of our sleep by multiplying by how far
   330  		// off we are from the ideal ratio. For example, if we're sleeping too
   331  		// much, then scavengeEMWA < idealFraction, so we'll adjust the sleep time
   332  		// down.
   333  		adjust := scavengeEWMA / idealFraction
   334  		sleepTime := int64(adjust * crit / (scavengePercent / 100.0))
   335  
   336  		// Go to sleep.
   337  		slept := scavengeSleep(sleepTime)
   338  
   339  		// Compute the new ratio.
   340  		fraction := crit / (crit + float64(slept))
   341  
   342  		// Set a lower bound on the fraction.
   343  		// Due to OS-related anomalies we may "sleep" for an inordinate amount
   344  		// of time. Let's avoid letting the ratio get out of hand by bounding
   345  		// the sleep time we use in our EWMA.
   346  		const minFraction = 1 / 1000
   347  		if fraction < minFraction {
   348  			fraction = minFraction
   349  		}
   350  
   351  		// Update scavengeEWMA by merging in the new crit/slept ratio.
   352  		const alpha = 0.5
   353  		scavengeEWMA = alpha*fraction + (1-alpha)*scavengeEWMA
   354  	}
   355  }
   356  
   357  // scavenge scavenges nbytes worth of free pages, starting with the
   358  // highest address first. Successive calls continue from where it left
   359  // off until the heap is exhausted. Call resetScavengeAddr to bring it
   360  // back to the top of the heap.
   361  //
   362  // Returns the amount of memory scavenged in bytes.
   363  //
   364  // If locked == false, s.mheapLock must not be locked. If locked == true,
   365  // s.mheapLock must be locked.
   366  //
   367  // Must run on the system stack because scavengeOne must run on the
   368  // system stack.
   369  //
   370  //go:systemstack
   371  func (s *pageAlloc) scavenge(nbytes uintptr, locked bool) uintptr {
   372  	released := uintptr(0)
   373  	for released < nbytes {
   374  		r := s.scavengeOne(nbytes-released, locked)
   375  		if r == 0 {
   376  			// Nothing left to scavenge! Give up.
   377  			break
   378  		}
   379  		released += r
   380  	}
   381  	return released
   382  }
   383  
   384  // printScavTrace prints a scavenge trace line to standard error.
   385  //
   386  // released should be the amount of memory released since the last time this
   387  // was called, and forced indicates whether the scavenge was forced by the
   388  // application.
   389  func printScavTrace(released uintptr, forced bool) {
   390  	printlock()
   391  	print("scav ",
   392  		released>>10, " KiB work, ",
   393  		atomic.Load64(&memstats.heap_released)>>10, " KiB total, ",
   394  		(atomic.Load64(&memstats.heap_inuse)*100)/heapRetained(), "% util",
   395  	)
   396  	if forced {
   397  		print(" (forced)")
   398  	}
   399  	println()
   400  	printunlock()
   401  }
   402  
   403  // resetScavengeAddr sets the scavenge start address to the top of the heap's
   404  // address space. This should be called each time the scavenger's pacing
   405  // changes.
   406  //
   407  // s.mheapLock must be held.
   408  func (s *pageAlloc) resetScavengeAddr() {
   409  	released := atomic.Loaduintptr(&s.scavReleased)
   410  	if debug.scavtrace > 0 {
   411  		printScavTrace(released, false)
   412  	}
   413  	// Subtract from scavReleased instead of just setting it to zero because
   414  	// the scavenger could have increased scavReleased concurrently with the
   415  	// load above, and we may miss an update by just blindly zeroing the field.
   416  	atomic.Xadduintptr(&s.scavReleased, -released)
   417  	s.scavAddr = chunkBase(s.end) - 1
   418  }
   419  
   420  // scavengeOne starts from s.scavAddr and walks down the heap until it finds
   421  // a contiguous run of pages to scavenge. It will try to scavenge at most
   422  // max bytes at once, but may scavenge more to avoid breaking huge pages. Once
   423  // it scavenges some memory it returns how much it scavenged and updates s.scavAddr
   424  // appropriately. s.scavAddr must be reset manually and externally.
   425  //
   426  // Should it exhaust the heap, it will return 0 and set s.scavAddr to minScavAddr.
   427  //
   428  // If locked == false, s.mheapLock must not be locked.
   429  // If locked == true, s.mheapLock must be locked.
   430  //
   431  // Must be run on the system stack because it either acquires the heap lock
   432  // or executes with the heap lock acquired.
   433  //
   434  //go:systemstack
   435  func (s *pageAlloc) scavengeOne(max uintptr, locked bool) uintptr {
   436  	// Calculate the maximum number of pages to scavenge.
   437  	//
   438  	// This should be alignUp(max, pageSize) / pageSize but max can and will
   439  	// be ^uintptr(0), so we need to be very careful not to overflow here.
   440  	// Rather than use alignUp, calculate the number of pages rounded down
   441  	// first, then add back one if necessary.
   442  	maxPages := max / pageSize
   443  	if max%pageSize != 0 {
   444  		maxPages++
   445  	}
   446  
   447  	// Calculate the minimum number of pages we can scavenge.
   448  	//
   449  	// Because we can only scavenge whole physical pages, we must
   450  	// ensure that we scavenge at least minPages each time, aligned
   451  	// to minPages*pageSize.
   452  	minPages := physPageSize / pageSize
   453  	if minPages < 1 {
   454  		minPages = 1
   455  	}
   456  
   457  	// Helpers for locking and unlocking only if locked == false.
   458  	lockHeap := func() {
   459  		if !locked {
   460  			lock(s.mheapLock)
   461  		}
   462  	}
   463  	unlockHeap := func() {
   464  		if !locked {
   465  			unlock(s.mheapLock)
   466  		}
   467  	}
   468  
   469  	lockHeap()
   470  	ci := chunkIndex(s.scavAddr)
   471  	if ci < s.start {
   472  		unlockHeap()
   473  		return 0
   474  	}
   475  
   476  	// Check the chunk containing the scav addr, starting at the addr
   477  	// and see if there are any free and unscavenged pages.
   478  	//
   479  	// Only check this if s.scavAddr is covered by any address range
   480  	// in s.inUse, so that we know our check of the summary is safe.
   481  	if s.inUse.contains(s.scavAddr) && s.summary[len(s.summary)-1][ci].max() >= uint(minPages) {
   482  		// We only bother looking for a candidate if there at least
   483  		// minPages free pages at all. It's important that we only
   484  		// continue if the summary says we can because that's how
   485  		// we can tell if parts of the address space are unused.
   486  		// See the comment on s.chunks in mpagealloc.go.
   487  		base, npages := s.chunkOf(ci).findScavengeCandidate(chunkPageIndex(s.scavAddr), minPages, maxPages)
   488  
   489  		// If we found something, scavenge it and return!
   490  		if npages != 0 {
   491  			s.scavengeRangeLocked(ci, base, npages)
   492  			unlockHeap()
   493  			return uintptr(npages) * pageSize
   494  		}
   495  	}
   496  
   497  	// getInUseRange returns the highest range in the
   498  	// intersection of [0, addr] and s.inUse.
   499  	//
   500  	// s.mheapLock must be held.
   501  	getInUseRange := func(addr uintptr) addrRange {
   502  		top := s.inUse.findSucc(addr)
   503  		if top == 0 {
   504  			return addrRange{}
   505  		}
   506  		r := s.inUse.ranges[top-1]
   507  		// addr is inclusive, so treat it as such when
   508  		// updating the limit, which is exclusive.
   509  		if r.limit > addr+1 {
   510  			r.limit = addr + 1
   511  		}
   512  		return r
   513  	}
   514  
   515  	// Slow path: iterate optimistically over the in-use address space
   516  	// looking for any free and unscavenged page. If we think we see something,
   517  	// lock and verify it!
   518  	//
   519  	// We iterate over the address space by taking ranges from inUse.
   520  newRange:
   521  	for {
   522  		r := getInUseRange(s.scavAddr)
   523  		if r.size() == 0 {
   524  			break
   525  		}
   526  		unlockHeap()
   527  
   528  		// Iterate over all of the chunks described by r.
   529  		// Note that r.limit is the exclusive upper bound, but what
   530  		// we want is the top chunk instead, inclusive, so subtract 1.
   531  		bot, top := chunkIndex(r.base), chunkIndex(r.limit-1)
   532  		for i := top; i >= bot; i-- {
   533  			// If this chunk is totally in-use or has no unscavenged pages, don't bother
   534  			// doing a  more sophisticated check.
   535  			//
   536  			// Note we're accessing the summary and the chunks without a lock, but
   537  			// that's fine. We're being optimistic anyway.
   538  
   539  			// Check quickly if there are enough free pages at all.
   540  			if s.summary[len(s.summary)-1][i].max() < uint(minPages) {
   541  				continue
   542  			}
   543  
   544  			// Run over the chunk looking harder for a candidate. Again, we could
   545  			// race with a lot of different pieces of code, but we're just being
   546  			// optimistic. Make sure we load the l2 pointer atomically though, to
   547  			// avoid races with heap growth. It may or may not be possible to also
   548  			// see a nil pointer in this case if we do race with heap growth, but
   549  			// just defensively ignore the nils. This operation is optimistic anyway.
   550  			l2 := (*[1 << pallocChunksL2Bits]pallocData)(atomic.Loadp(unsafe.Pointer(&s.chunks[i.l1()])))
   551  			if l2 == nil || !l2[i.l2()].hasScavengeCandidate(minPages) {
   552  				continue
   553  			}
   554  
   555  			// We found a candidate, so let's lock and verify it.
   556  			lockHeap()
   557  
   558  			// Find, verify, and scavenge if we can.
   559  			chunk := s.chunkOf(i)
   560  			base, npages := chunk.findScavengeCandidate(pallocChunkPages-1, minPages, maxPages)
   561  			if npages > 0 {
   562  				// We found memory to scavenge! Mark the bits and report that up.
   563  				// scavengeRangeLocked will update scavAddr for us, also.
   564  				s.scavengeRangeLocked(i, base, npages)
   565  				unlockHeap()
   566  				return uintptr(npages) * pageSize
   567  			}
   568  
   569  			// We were fooled, let's take this opportunity to move the scavAddr
   570  			// all the way down to where we searched as scavenged for future calls
   571  			// and keep iterating. Then, go get a new range.
   572  			s.scavAddr = chunkBase(i-1) + pallocChunkPages*pageSize - 1
   573  			continue newRange
   574  		}
   575  		lockHeap()
   576  
   577  		// Move the scavenger down the heap, past everything we just searched.
   578  		// Since we don't check if scavAddr moved while twe let go of the heap lock,
   579  		// it's possible that it moved down and we're moving it up here. This
   580  		// raciness could result in us searching parts of the heap unnecessarily.
   581  		// TODO(mknyszek): Remove this racy behavior through explicit address
   582  		// space reservations, which are difficult to do with just scavAddr.
   583  		s.scavAddr = r.base - 1
   584  	}
   585  	// We reached the end of the in-use address space and couldn't find anything,
   586  	// so signal that there's nothing left to scavenge.
   587  	s.scavAddr = minScavAddr
   588  	unlockHeap()
   589  
   590  	return 0
   591  }
   592  
   593  // scavengeRangeLocked scavenges the given region of memory.
   594  //
   595  // s.mheapLock must be held.
   596  func (s *pageAlloc) scavengeRangeLocked(ci chunkIdx, base, npages uint) {
   597  	s.chunkOf(ci).scavenged.setRange(base, npages)
   598  
   599  	// Compute the full address for the start of the range.
   600  	addr := chunkBase(ci) + uintptr(base)*pageSize
   601  
   602  	// Update the scav pointer.
   603  	s.scavAddr = addr - 1
   604  
   605  	// Only perform the actual scavenging if we're not in a test.
   606  	// It's dangerous to do so otherwise.
   607  	if s.test {
   608  		return
   609  	}
   610  	sysUnused(unsafe.Pointer(addr), uintptr(npages)*pageSize)
   611  
   612  	// Update global accounting only when not in test, otherwise
   613  	// the runtime's accounting will be wrong.
   614  	mSysStatInc(&memstats.heap_released, uintptr(npages)*pageSize)
   615  }
   616  
   617  // fillAligned returns x but with all zeroes in m-aligned
   618  // groups of m bits set to 1 if any bit in the group is non-zero.
   619  //
   620  // For example, fillAligned(0x0100a3, 8) == 0xff00ff.
   621  //
   622  // Note that if m == 1, this is a no-op.
   623  //
   624  // m must be a power of 2 <= maxPagesPerPhysPage.
   625  func fillAligned(x uint64, m uint) uint64 {
   626  	apply := func(x uint64, c uint64) uint64 {
   627  		// The technique used it here is derived from
   628  		// https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
   629  		// and extended for more than just bytes (like nibbles
   630  		// and uint16s) by using an appropriate constant.
   631  		//
   632  		// To summarize the technique, quoting from that page:
   633  		// "[It] works by first zeroing the high bits of the [8]
   634  		// bytes in the word. Subsequently, it adds a number that
   635  		// will result in an overflow to the high bit of a byte if
   636  		// any of the low bits were initially set. Next the high
   637  		// bits of the original word are ORed with these values;
   638  		// thus, the high bit of a byte is set iff any bit in the
   639  		// byte was set. Finally, we determine if any of these high
   640  		// bits are zero by ORing with ones everywhere except the
   641  		// high bits and inverting the result."
   642  		return ^((((x & c) + c) | x) | c)
   643  	}
   644  	// Transform x to contain a 1 bit at the top of each m-aligned
   645  	// group of m zero bits.
   646  	switch m {
   647  	case 1:
   648  		return x
   649  	case 2:
   650  		x = apply(x, 0x5555555555555555)
   651  	case 4:
   652  		x = apply(x, 0x7777777777777777)
   653  	case 8:
   654  		x = apply(x, 0x7f7f7f7f7f7f7f7f)
   655  	case 16:
   656  		x = apply(x, 0x7fff7fff7fff7fff)
   657  	case 32:
   658  		x = apply(x, 0x7fffffff7fffffff)
   659  	case 64: // == maxPagesPerPhysPage
   660  		x = apply(x, 0x7fffffffffffffff)
   661  	default:
   662  		throw("bad m value")
   663  	}
   664  	// Now, the top bit of each m-aligned group in x is set
   665  	// that group was all zero in the original x.
   666  
   667  	// From each group of m bits subtract 1.
   668  	// Because we know only the top bits of each
   669  	// m-aligned group are set, we know this will
   670  	// set each group to have all the bits set except
   671  	// the top bit, so just OR with the original
   672  	// result to set all the bits.
   673  	return ^((x - (x >> (m - 1))) | x)
   674  }
   675  
   676  // hasScavengeCandidate returns true if there's any min-page-aligned groups of
   677  // min pages of free-and-unscavenged memory in the region represented by this
   678  // pallocData.
   679  //
   680  // min must be a non-zero power of 2 <= maxPagesPerPhysPage.
   681  func (m *pallocData) hasScavengeCandidate(min uintptr) bool {
   682  	if min&(min-1) != 0 || min == 0 {
   683  		print("runtime: min = ", min, "\n")
   684  		throw("min must be a non-zero power of 2")
   685  	} else if min > maxPagesPerPhysPage {
   686  		print("runtime: min = ", min, "\n")
   687  		throw("min too large")
   688  	}
   689  
   690  	// The goal of this search is to see if the chunk contains any free and unscavenged memory.
   691  	for i := len(m.scavenged) - 1; i >= 0; i-- {
   692  		// 1s are scavenged OR non-free => 0s are unscavenged AND free
   693  		//
   694  		// TODO(mknyszek): Consider splitting up fillAligned into two
   695  		// functions, since here we technically could get by with just
   696  		// the first half of its computation. It'll save a few instructions
   697  		// but adds some additional code complexity.
   698  		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   699  
   700  		// Quickly skip over chunks of non-free or scavenged pages.
   701  		if x != ^uint64(0) {
   702  			return true
   703  		}
   704  	}
   705  	return false
   706  }
   707  
   708  // findScavengeCandidate returns a start index and a size for this pallocData
   709  // segment which represents a contiguous region of free and unscavenged memory.
   710  //
   711  // searchIdx indicates the page index within this chunk to start the search, but
   712  // note that findScavengeCandidate searches backwards through the pallocData. As a
   713  // a result, it will return the highest scavenge candidate in address order.
   714  //
   715  // min indicates a hard minimum size and alignment for runs of pages. That is,
   716  // findScavengeCandidate will not return a region smaller than min pages in size,
   717  // or that is min pages or greater in size but not aligned to min. min must be
   718  // a non-zero power of 2 <= maxPagesPerPhysPage.
   719  //
   720  // max is a hint for how big of a region is desired. If max >= pallocChunkPages, then
   721  // findScavengeCandidate effectively returns entire free and unscavenged regions.
   722  // If max < pallocChunkPages, it may truncate the returned region such that size is
   723  // max. However, findScavengeCandidate may still return a larger region if, for
   724  // example, it chooses to preserve huge pages, or if max is not aligned to min (it
   725  // will round up). That is, even if max is small, the returned size is not guaranteed
   726  // to be equal to max. max is allowed to be less than min, in which case it is as if
   727  // max == min.
   728  func (m *pallocData) findScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
   729  	if min&(min-1) != 0 || min == 0 {
   730  		print("runtime: min = ", min, "\n")
   731  		throw("min must be a non-zero power of 2")
   732  	} else if min > maxPagesPerPhysPage {
   733  		print("runtime: min = ", min, "\n")
   734  		throw("min too large")
   735  	}
   736  	// max may not be min-aligned, so we might accidentally truncate to
   737  	// a max value which causes us to return a non-min-aligned value.
   738  	// To prevent this, align max up to a multiple of min (which is always
   739  	// a power of 2). This also prevents max from ever being less than
   740  	// min, unless it's zero, so handle that explicitly.
   741  	if max == 0 {
   742  		max = min
   743  	} else {
   744  		max = alignUp(max, min)
   745  	}
   746  
   747  	i := int(searchIdx / 64)
   748  	// Start by quickly skipping over blocks of non-free or scavenged pages.
   749  	for ; i >= 0; i-- {
   750  		// 1s are scavenged OR non-free => 0s are unscavenged AND free
   751  		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   752  		if x != ^uint64(0) {
   753  			break
   754  		}
   755  	}
   756  	if i < 0 {
   757  		// Failed to find any free/unscavenged pages.
   758  		return 0, 0
   759  	}
   760  	// We have something in the 64-bit chunk at i, but it could
   761  	// extend further. Loop until we find the extent of it.
   762  
   763  	// 1s are scavenged OR non-free => 0s are unscavenged AND free
   764  	x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
   765  	z1 := uint(sys.LeadingZeros64(^x))
   766  	run, end := uint(0), uint(i)*64+(64-z1)
   767  	if x<<z1 != 0 {
   768  		// After shifting out z1 bits, we still have 1s,
   769  		// so the run ends inside this word.
   770  		run = uint(sys.LeadingZeros64(x << z1))
   771  	} else {
   772  		// After shifting out z1 bits, we have no more 1s.
   773  		// This means the run extends to the bottom of the
   774  		// word so it may extend into further words.
   775  		run = 64 - z1
   776  		for j := i - 1; j >= 0; j-- {
   777  			x := fillAligned(m.scavenged[j]|m.pallocBits[j], uint(min))
   778  			run += uint(sys.LeadingZeros64(x))
   779  			if x != 0 {
   780  				// The run stopped in this word.
   781  				break
   782  			}
   783  		}
   784  	}
   785  
   786  	// Split the run we found if it's larger than max but hold on to
   787  	// our original length, since we may need it later.
   788  	size := run
   789  	if size > uint(max) {
   790  		size = uint(max)
   791  	}
   792  	start := end - size
   793  
   794  	// Each huge page is guaranteed to fit in a single palloc chunk.
   795  	//
   796  	// TODO(mknyszek): Support larger huge page sizes.
   797  	// TODO(mknyszek): Consider taking pages-per-huge-page as a parameter
   798  	// so we can write tests for this.
   799  	if physHugePageSize > pageSize && physHugePageSize > physPageSize {
   800  		// We have huge pages, so let's ensure we don't break one by scavenging
   801  		// over a huge page boundary. If the range [start, start+size) overlaps with
   802  		// a free-and-unscavenged huge page, we want to grow the region we scavenge
   803  		// to include that huge page.
   804  
   805  		// Compute the huge page boundary above our candidate.
   806  		pagesPerHugePage := uintptr(physHugePageSize / pageSize)
   807  		hugePageAbove := uint(alignUp(uintptr(start), pagesPerHugePage))
   808  
   809  		// If that boundary is within our current candidate, then we may be breaking
   810  		// a huge page.
   811  		if hugePageAbove <= end {
   812  			// Compute the huge page boundary below our candidate.
   813  			hugePageBelow := uint(alignDown(uintptr(start), pagesPerHugePage))
   814  
   815  			if hugePageBelow >= end-run {
   816  				// We're in danger of breaking apart a huge page since start+size crosses
   817  				// a huge page boundary and rounding down start to the nearest huge
   818  				// page boundary is included in the full run we found. Include the entire
   819  				// huge page in the bound by rounding down to the huge page size.
   820  				size = size + (start - hugePageBelow)
   821  				start = hugePageBelow
   822  			}
   823  		}
   824  	}
   825  	return start, size
   826  }
   827  

View as plain text