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
56package runtime
57
58import (
59	"runtime/internal/atomic"
60	"runtime/internal/sys"
61	"unsafe"
62)
63
64const (
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.
97func 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.
111func 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.
157var 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.
168func 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.
201func 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.
225func 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		// Multiply the critical time by 1 + the ratio of the costs of using
290		// scavenged memory vs. scavenging memory. This forces us to pay down
291		// the cost of reusing this memory eagerly by sleeping for a longer period
292		// of time and scavenging less frequently. More concretely, we avoid situations
293		// where we end up scavenging so often that we hurt allocation performance
294		// because of the additional overheads of using scavenged memory.
295		crit *= 1 + scavengeCostRatio
296
297		// If we spent more than 10 ms (for example, if the OS scheduled us away, or someone
298		// put their machine to sleep) in the critical section, bound the time we use to
299		// calculate at 10 ms to avoid letting the sleep time get arbitrarily high.
300		const maxCrit = 10e6
301		if crit > maxCrit {
302			crit = maxCrit
303		}
304
305		// Compute the amount of time to sleep, assuming we want to use at most
306		// scavengePercent of CPU time. Take into account scheduling overheads
307		// that may extend the length of our sleep by multiplying by how far
308		// off we are from the ideal ratio. For example, if we're sleeping too
309		// much, then scavengeEMWA < idealFraction, so we'll adjust the sleep time
310		// down.
311		adjust := scavengeEWMA / idealFraction
312		sleepTime := int64(adjust * crit / (scavengePercent / 100.0))
313
314		// Go to sleep.
315		slept := scavengeSleep(sleepTime)
316
317		// Compute the new ratio.
318		fraction := crit / (crit + float64(slept))
319
320		// Set a lower bound on the fraction.
321		// Due to OS-related anomalies we may "sleep" for an inordinate amount
322		// of time. Let's avoid letting the ratio get out of hand by bounding
323		// the sleep time we use in our EWMA.
324		const minFraction = 1 / 1000
325		if fraction < minFraction {
326			fraction = minFraction
327		}
328
329		// Update scavengeEWMA by merging in the new crit/slept ratio.
330		const alpha = 0.5
331		scavengeEWMA = alpha*fraction + (1-alpha)*scavengeEWMA
332	}
333}
334
335// scavenge scavenges nbytes worth of free pages, starting with the
336// highest address first. Successive calls continue from where it left
337// off until the heap is exhausted. Call resetScavengeAddr to bring it
338// back to the top of the heap.
339//
340// Returns the amount of memory scavenged in bytes.
341//
342// If locked == false, s.mheapLock must not be locked. If locked == true,
343// s.mheapLock must be locked.
344//
345// Must run on the system stack because scavengeOne must run on the
346// system stack.
347//
348//go:systemstack
349func (s *pageAlloc) scavenge(nbytes uintptr, locked bool) uintptr {
350	released := uintptr(0)
351	for released < nbytes {
352		r := s.scavengeOne(nbytes-released, locked)
353		if r == 0 {
354			// Nothing left to scavenge! Give up.
355			break
356		}
357		released += r
358	}
359	return released
360}
361
362// printScavTrace prints a scavenge trace line to standard error.
363//
364// released should be the amount of memory released since the last time this
365// was called, and forced indicates whether the scavenge was forced by the
366// application.
367func printScavTrace(released uintptr, forced bool) {
368	printlock()
369	print("scav ",
370		released>>10, " KiB work, ",
371		atomic.Load64(&memstats.heap_released)>>10, " KiB total, ",
372		(atomic.Load64(&memstats.heap_inuse)*100)/heapRetained(), "% util",
373	)
374	if forced {
375		print(" (forced)")
376	}
377	println()
378	printunlock()
379}
380
381// resetScavengeAddr sets the scavenge start address to the top of the heap's
382// address space. This should be called each time the scavenger's pacing
383// changes.
384//
385// s.mheapLock must be held.
386func (s *pageAlloc) resetScavengeAddr() {
387	released := atomic.Loaduintptr(&s.scavReleased)
388	if debug.scavtrace > 0 {
389		printScavTrace(released, false)
390	}
391	// Subtract from scavReleased instead of just setting it to zero because
392	// the scavenger could have increased scavReleased concurrently with the
393	// load above, and we may miss an update by just blindly zeroing the field.
394	atomic.Xadduintptr(&s.scavReleased, -released)
395	s.scavAddr = chunkBase(s.end) - 1
396}
397
398// scavengeOne starts from s.scavAddr and walks down the heap until it finds
399// a contiguous run of pages to scavenge. It will try to scavenge at most
400// max bytes at once, but may scavenge more to avoid breaking huge pages. Once
401// it scavenges some memory it returns how much it scavenged and updates s.scavAddr
402// appropriately. s.scavAddr must be reset manually and externally.
403//
404// Should it exhaust the heap, it will return 0 and set s.scavAddr to minScavAddr.
405//
406// If locked == false, s.mheapLock must not be locked.
407// If locked == true, s.mheapLock must be locked.
408//
409// Must be run on the system stack because it either acquires the heap lock
410// or executes with the heap lock acquired.
411//
412//go:systemstack
413func (s *pageAlloc) scavengeOne(max uintptr, locked bool) uintptr {
414	// Calculate the maximum number of pages to scavenge.
415	//
416	// This should be alignUp(max, pageSize) / pageSize but max can and will
417	// be ^uintptr(0), so we need to be very careful not to overflow here.
418	// Rather than use alignUp, calculate the number of pages rounded down
419	// first, then add back one if necessary.
420	maxPages := max / pageSize
421	if max%pageSize != 0 {
422		maxPages++
423	}
424
425	// Calculate the minimum number of pages we can scavenge.
426	//
427	// Because we can only scavenge whole physical pages, we must
428	// ensure that we scavenge at least minPages each time, aligned
429	// to minPages*pageSize.
430	minPages := physPageSize / pageSize
431	if minPages < 1 {
432		minPages = 1
433	}
434
435	// Helpers for locking and unlocking only if locked == false.
436	lockHeap := func() {
437		if !locked {
438			lock(s.mheapLock)
439		}
440	}
441	unlockHeap := func() {
442		if !locked {
443			unlock(s.mheapLock)
444		}
445	}
446
447	lockHeap()
448	ci := chunkIndex(s.scavAddr)
449	if ci < s.start {
450		unlockHeap()
451		return 0
452	}
453
454	// Check the chunk containing the scav addr, starting at the addr
455	// and see if there are any free and unscavenged pages.
456	//
457	// Only check this if s.scavAddr is covered by any address range
458	// in s.inUse, so that we know our check of the summary is safe.
459	if s.inUse.contains(s.scavAddr) && s.summary[len(s.summary)-1][ci].max() >= uint(minPages) {
460		// We only bother looking for a candidate if there at least
461		// minPages free pages at all. It's important that we only
462		// continue if the summary says we can because that's how
463		// we can tell if parts of the address space are unused.
464		// See the comment on s.chunks in mpagealloc.go.
465		base, npages := s.chunkOf(ci).findScavengeCandidate(chunkPageIndex(s.scavAddr), minPages, maxPages)
466
467		// If we found something, scavenge it and return!
468		if npages != 0 {
469			s.scavengeRangeLocked(ci, base, npages)
470			unlockHeap()
471			return uintptr(npages) * pageSize
472		}
473	}
474
475	// getInUseRange returns the highest range in the
476	// intersection of [0, addr] and s.inUse.
477	//
478	// s.mheapLock must be held.
479	getInUseRange := func(addr uintptr) addrRange {
480		top := s.inUse.findSucc(addr)
481		if top == 0 {
482			return addrRange{}
483		}
484		r := s.inUse.ranges[top-1]
485		// addr is inclusive, so treat it as such when
486		// updating the limit, which is exclusive.
487		if r.limit > addr+1 {
488			r.limit = addr + 1
489		}
490		return r
491	}
492
493	// Slow path: iterate optimistically over the in-use address space
494	// looking for any free and unscavenged page. If we think we see something,
495	// lock and verify it!
496	//
497	// We iterate over the address space by taking ranges from inUse.
498newRange:
499	for {
500		r := getInUseRange(s.scavAddr)
501		if r.size() == 0 {
502			break
503		}
504		unlockHeap()
505
506		// Iterate over all of the chunks described by r.
507		// Note that r.limit is the exclusive upper bound, but what
508		// we want is the top chunk instead, inclusive, so subtract 1.
509		bot, top := chunkIndex(r.base), chunkIndex(r.limit-1)
510		for i := top; i >= bot; i-- {
511			// If this chunk is totally in-use or has no unscavenged pages, don't bother
512			// doing a  more sophisticated check.
513			//
514			// Note we're accessing the summary and the chunks without a lock, but
515			// that's fine. We're being optimistic anyway.
516
517			// Check quickly if there are enough free pages at all.
518			if s.summary[len(s.summary)-1][i].max() < uint(minPages) {
519				continue
520			}
521
522			// Run over the chunk looking harder for a candidate. Again, we could
523			// race with a lot of different pieces of code, but we're just being
524			// optimistic. Make sure we load the l2 pointer atomically though, to
525			// avoid races with heap growth. It may or may not be possible to also
526			// see a nil pointer in this case if we do race with heap growth, but
527			// just defensively ignore the nils. This operation is optimistic anyway.
528			l2 := (*[1 << pallocChunksL2Bits]pallocData)(atomic.Loadp(unsafe.Pointer(&s.chunks[i.l1()])))
529			if l2 == nil || !l2[i.l2()].hasScavengeCandidate(minPages) {
530				continue
531			}
532
533			// We found a candidate, so let's lock and verify it.
534			lockHeap()
535
536			// Find, verify, and scavenge if we can.
537			chunk := s.chunkOf(i)
538			base, npages := chunk.findScavengeCandidate(pallocChunkPages-1, minPages, maxPages)
539			if npages > 0 {
540				// We found memory to scavenge! Mark the bits and report that up.
541				// scavengeRangeLocked will update scavAddr for us, also.
542				s.scavengeRangeLocked(i, base, npages)
543				unlockHeap()
544				return uintptr(npages) * pageSize
545			}
546
547			// We were fooled, let's take this opportunity to move the scavAddr
548			// all the way down to where we searched as scavenged for future calls
549			// and keep iterating. Then, go get a new range.
550			s.scavAddr = chunkBase(i-1) + pallocChunkPages*pageSize - 1
551			continue newRange
552		}
553		lockHeap()
554
555		// Move the scavenger down the heap, past everything we just searched.
556		// Since we don't check if scavAddr moved while twe let go of the heap lock,
557		// it's possible that it moved down and we're moving it up here. This
558		// raciness could result in us searching parts of the heap unnecessarily.
559		// TODO(mknyszek): Remove this racy behavior through explicit address
560		// space reservations, which are difficult to do with just scavAddr.
561		s.scavAddr = r.base - 1
562	}
563	// We reached the end of the in-use address space and couldn't find anything,
564	// so signal that there's nothing left to scavenge.
565	s.scavAddr = minScavAddr
566	unlockHeap()
567
568	return 0
569}
570
571// scavengeRangeLocked scavenges the given region of memory.
572//
573// s.mheapLock must be held.
574func (s *pageAlloc) scavengeRangeLocked(ci chunkIdx, base, npages uint) {
575	s.chunkOf(ci).scavenged.setRange(base, npages)
576
577	// Compute the full address for the start of the range.
578	addr := chunkBase(ci) + uintptr(base)*pageSize
579
580	// Update the scav pointer.
581	s.scavAddr = addr - 1
582
583	// Only perform the actual scavenging if we're not in a test.
584	// It's dangerous to do so otherwise.
585	if s.test {
586		return
587	}
588	sysUnused(unsafe.Pointer(addr), uintptr(npages)*pageSize)
589
590	// Update global accounting only when not in test, otherwise
591	// the runtime's accounting will be wrong.
592	mSysStatInc(&memstats.heap_released, uintptr(npages)*pageSize)
593}
594
595// fillAligned returns x but with all zeroes in m-aligned
596// groups of m bits set to 1 if any bit in the group is non-zero.
597//
598// For example, fillAligned(0x0100a3, 8) == 0xff00ff.
599//
600// Note that if m == 1, this is a no-op.
601//
602// m must be a power of 2 <= maxPagesPerPhysPage.
603func fillAligned(x uint64, m uint) uint64 {
604	apply := func(x uint64, c uint64) uint64 {
605		// The technique used it here is derived from
606		// https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
607		// and extended for more than just bytes (like nibbles
608		// and uint16s) by using an appropriate constant.
609		//
610		// To summarize the technique, quoting from that page:
611		// "[It] works by first zeroing the high bits of the [8]
612		// bytes in the word. Subsequently, it adds a number that
613		// will result in an overflow to the high bit of a byte if
614		// any of the low bits were initially set. Next the high
615		// bits of the original word are ORed with these values;
616		// thus, the high bit of a byte is set iff any bit in the
617		// byte was set. Finally, we determine if any of these high
618		// bits are zero by ORing with ones everywhere except the
619		// high bits and inverting the result."
620		return ^((((x & c) + c) | x) | c)
621	}
622	// Transform x to contain a 1 bit at the top of each m-aligned
623	// group of m zero bits.
624	switch m {
625	case 1:
626		return x
627	case 2:
628		x = apply(x, 0x5555555555555555)
629	case 4:
630		x = apply(x, 0x7777777777777777)
631	case 8:
632		x = apply(x, 0x7f7f7f7f7f7f7f7f)
633	case 16:
634		x = apply(x, 0x7fff7fff7fff7fff)
635	case 32:
636		x = apply(x, 0x7fffffff7fffffff)
637	case 64: // == maxPagesPerPhysPage
638		x = apply(x, 0x7fffffffffffffff)
639	default:
640		throw("bad m value")
641	}
642	// Now, the top bit of each m-aligned group in x is set
643	// that group was all zero in the original x.
644
645	// From each group of m bits subtract 1.
646	// Because we know only the top bits of each
647	// m-aligned group are set, we know this will
648	// set each group to have all the bits set except
649	// the top bit, so just OR with the original
650	// result to set all the bits.
651	return ^((x - (x >> (m - 1))) | x)
652}
653
654// hasScavengeCandidate returns true if there's any min-page-aligned groups of
655// min pages of free-and-unscavenged memory in the region represented by this
656// pallocData.
657//
658// min must be a non-zero power of 2 <= maxPagesPerPhysPage.
659func (m *pallocData) hasScavengeCandidate(min uintptr) bool {
660	if min&(min-1) != 0 || min == 0 {
661		print("runtime: min = ", min, "\n")
662		throw("min must be a non-zero power of 2")
663	} else if min > maxPagesPerPhysPage {
664		print("runtime: min = ", min, "\n")
665		throw("min too large")
666	}
667
668	// The goal of this search is to see if the chunk contains any free and unscavenged memory.
669	for i := len(m.scavenged) - 1; i >= 0; i-- {
670		// 1s are scavenged OR non-free => 0s are unscavenged AND free
671		//
672		// TODO(mknyszek): Consider splitting up fillAligned into two
673		// functions, since here we technically could get by with just
674		// the first half of its computation. It'll save a few instructions
675		// but adds some additional code complexity.
676		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
677
678		// Quickly skip over chunks of non-free or scavenged pages.
679		if x != ^uint64(0) {
680			return true
681		}
682	}
683	return false
684}
685
686// findScavengeCandidate returns a start index and a size for this pallocData
687// segment which represents a contiguous region of free and unscavenged memory.
688//
689// searchIdx indicates the page index within this chunk to start the search, but
690// note that findScavengeCandidate searches backwards through the pallocData. As a
691// a result, it will return the highest scavenge candidate in address order.
692//
693// min indicates a hard minimum size and alignment for runs of pages. That is,
694// findScavengeCandidate will not return a region smaller than min pages in size,
695// or that is min pages or greater in size but not aligned to min. min must be
696// a non-zero power of 2 <= maxPagesPerPhysPage.
697//
698// max is a hint for how big of a region is desired. If max >= pallocChunkPages, then
699// findScavengeCandidate effectively returns entire free and unscavenged regions.
700// If max < pallocChunkPages, it may truncate the returned region such that size is
701// max. However, findScavengeCandidate may still return a larger region if, for
702// example, it chooses to preserve huge pages, or if max is not aligned to min (it
703// will round up). That is, even if max is small, the returned size is not guaranteed
704// to be equal to max. max is allowed to be less than min, in which case it is as if
705// max == min.
706func (m *pallocData) findScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
707	if min&(min-1) != 0 || min == 0 {
708		print("runtime: min = ", min, "\n")
709		throw("min must be a non-zero power of 2")
710	} else if min > maxPagesPerPhysPage {
711		print("runtime: min = ", min, "\n")
712		throw("min too large")
713	}
714	// max may not be min-aligned, so we might accidentally truncate to
715	// a max value which causes us to return a non-min-aligned value.
716	// To prevent this, align max up to a multiple of min (which is always
717	// a power of 2). This also prevents max from ever being less than
718	// min, unless it's zero, so handle that explicitly.
719	if max == 0 {
720		max = min
721	} else {
722		max = alignUp(max, min)
723	}
724
725	i := int(searchIdx / 64)
726	// Start by quickly skipping over blocks of non-free or scavenged pages.
727	for ; i >= 0; i-- {
728		// 1s are scavenged OR non-free => 0s are unscavenged AND free
729		x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
730		if x != ^uint64(0) {
731			break
732		}
733	}
734	if i < 0 {
735		// Failed to find any free/unscavenged pages.
736		return 0, 0
737	}
738	// We have something in the 64-bit chunk at i, but it could
739	// extend further. Loop until we find the extent of it.
740
741	// 1s are scavenged OR non-free => 0s are unscavenged AND free
742	x := fillAligned(m.scavenged[i]|m.pallocBits[i], uint(min))
743	z1 := uint(sys.LeadingZeros64(^x))
744	run, end := uint(0), uint(i)*64+(64-z1)
745	if x<<z1 != 0 {
746		// After shifting out z1 bits, we still have 1s,
747		// so the run ends inside this word.
748		run = uint(sys.LeadingZeros64(x << z1))
749	} else {
750		// After shifting out z1 bits, we have no more 1s.
751		// This means the run extends to the bottom of the
752		// word so it may extend into further words.
753		run = 64 - z1
754		for j := i - 1; j >= 0; j-- {
755			x := fillAligned(m.scavenged[j]|m.pallocBits[j], uint(min))
756			run += uint(sys.LeadingZeros64(x))
757			if x != 0 {
758				// The run stopped in this word.
759				break
760			}
761		}
762	}
763
764	// Split the run we found if it's larger than max but hold on to
765	// our original length, since we may need it later.
766	size := run
767	if size > uint(max) {
768		size = uint(max)
769	}
770	start := end - size
771
772	// Each huge page is guaranteed to fit in a single palloc chunk.
773	//
774	// TODO(mknyszek): Support larger huge page sizes.
775	// TODO(mknyszek): Consider taking pages-per-huge-page as a parameter
776	// so we can write tests for this.
777	if physHugePageSize > pageSize && physHugePageSize > physPageSize {
778		// We have huge pages, so let's ensure we don't break one by scavenging
779		// over a huge page boundary. If the range [start, start+size) overlaps with
780		// a free-and-unscavenged huge page, we want to grow the region we scavenge
781		// to include that huge page.
782
783		// Compute the huge page boundary above our candidate.
784		pagesPerHugePage := uintptr(physHugePageSize / pageSize)
785		hugePageAbove := uint(alignUp(uintptr(start), pagesPerHugePage))
786
787		// If that boundary is within our current candidate, then we may be breaking
788		// a huge page.
789		if hugePageAbove <= end {
790			// Compute the huge page boundary below our candidate.
791			hugePageBelow := uint(alignDown(uintptr(start), pagesPerHugePage))
792
793			if hugePageBelow >= end-run {
794				// We're in danger of breaking apart a huge page since start+size crosses
795				// a huge page boundary and rounding down start to the nearest huge
796				// page boundary is included in the full run we found. Include the entire
797				// huge page in the bound by rounding down to the huge page size.
798				size = size + (start - hugePageBelow)
799				start = hugePageBelow
800			}
801		}
802	}
803	return start, size
804}
805