← Writing

Memory the Runtime Keeps

32 min readSystemsGORuntimeMemoryLinuxMadvise
Contents

A Go 1.13 program builds up a gigabyte of heap, drops it, and collects the garbage. Three minutes later the runtime reports that it has given all of that gigabyte back to the operating system. The kernel still counts every byte of it against the program: top shows 1,058 megabytes resident, and it goes on showing 1,058 for as long as anyone watches. Then another program on the same machine asks for memory, and within seconds the Go program’s resident set drops to 38 megabytes, without the Go program doing anything at all. Both the runtime and top were telling the truth.

This post is about how a Go program gives memory back, which turns out to be three separate questions with three separate answers. When does the runtime decide a piece of the heap is no longer needed? How does it tell the kernel? And when does the kernel actually take it? The answers changed twice in the last year, in Go 1.12 and in Go 1.13, and this post runs Go 1.11, 1.12 and 1.13 side by side on the same kernel to show each change. Along the way it looks at a change to sync.Pool in 1.13, at the “heap ballast” trick some services use to make the collector run less often, and at how glibc’s malloc answers the same questions for C.

This is Part 5 of a series on how Go manages the stack and the heap. Part 3 covered the allocator and its spans, and Part 4 the garbage collector. It is written for Go programmers who have looked at top and wondered. The programs ran on Go 1.13.1 and 1.12.10, both released on 25 September, and Go 1.11.13, the last 1.11 release, inside a virtual machine booting Ubuntu 18.04’s own 4.15 kernel. The note at the end says what was measured and how.

What “giving memory back” means

This section is the background. If you know what RSS, madvise and lazy freeing are, skip it.

A process’s memory comes from the kernel in two steps. First the process reserves address space, with mmap: a range of addresses it may use. Nothing physical is behind them yet. Then, the first time the process writes to each 4 KB page of that range, the kernel finds a free page of physical memory and maps it in. The pages that are currently backed by physical memory make up the process’s resident set size, or RSS. That is the number top shows as RES, ps as RSS, and /proc/<pid>/status as VmRSS. It is what the process costs the machine.

So freeing memory inside a program is not the same as giving it back. When Go’s collector frees an object, or free frees a block in C, the memory goes back to the allocator, inside the process, ready for reuse. The physical pages stay mapped and stay in RSS. To give them back, the allocator has to tell the kernel, with a system call, that it no longer needs the contents of a range of pages.

On Linux that call is madvise, which gives the kernel advice about a range of memory, and there are two pieces of advice that matter here:

  • MADV_DONTNEED: “I don’t need these pages.” The kernel unmaps them at once. RSS drops immediately. If the process touches the range again, it gets fresh zeroed pages, at the cost of a page fault for each.
  • MADV_FREE, added in Linux 4.5 (2016): “You may take these pages if you need them.” The kernel marks them as freeable but leaves them mapped. RSS does not change. If memory gets short, the kernel reclaims them, cheaply, since their contents need not be saved. If the process writes to them first, the kernel cancels the advice and the process keeps the page with no fault at all.

MADV_FREE is cheaper on both sides: the call itself does less work, and memory the program reuses soon never has to be faulted back in. Its cost is that RSS stops meaning what people think it means.

When the runtime decides

Part 3 described how memory leaves Go’s heap, in the comment at the top of malloc.go: a span whose objects are all free becomes idle and goes back to the mheap, and “If an mspan remains idle for long enough, return its pages to the operating system.” Releasing those idle pages is called scavenging, and until Go 1.13 “long enough” meant five minutes. In Go 1.11’s proc.go, the system monitor thread (sysmon), which wakes up periodically for housekeeping, sets the limit:

	scavengelimit := int64(5 * 60 * 1e9)

and scavenges whenever scavengelimit/2 has passed since its last scavenge. Every two and a half minutes sysmon asks the heap to release spans that have been idle for more than five minutes. A program whose heap shrinks by a gigabyte keeps that gigabyte in RSS for between five and seven and a half minutes, whatever else is happening on the machine.

Go 1.13, released last month, replaced that with a background scavenger, a goroutine that runs continuously and returns memory as soon as the heap has more than it needs. Its file, src/runtime/mgcscavenge.go, begins:

// Scavenging in Go happens on two fronts: there's the background
// (asynchronous) scavenger and the heap-growth (synchronous) scavenger.
//
// The former happens on a goroutine much like the background sweeper which is
// soft-capped at using scavengePercent of the mutator's time, based on
// order-of-magnitude estimates of the costs of scavenging. The background
// scavenger's primary goal is to bring the estimated heap RSS of the
// application down to a goal.
//
// That goal is defined as (retainExtraPercent+100) / 100 * next_gc.

with these constants:

	scavengePercent         = 1    // 1%
	scavengePageLatency     = 10e3 // 10µs
	scavengeHugePageLatency = 10e3 // 10µs
	scavengePagePeriod      = scavengePageLatency / (scavengePercent / 100.0)
	scavengeHugePagePeriod  = scavengePageLatency / (scavengePercent / 100.0)

and retainExtraPercent = 10. The scavenger aims to keep the heap’s memory at 110% of the next collection’s goal, and gives itself 1% of the program’s time to get there. Releasing one page is estimated at 10 microseconds, so 1% of the time means one page every millisecond: about 4 MB a second for ordinary 4 KB pages, and much faster where the kernel backs the heap with 2 MB huge pages, which are released one at a time at the same rate. The 1.13 release notes put it plainly: “Previously, the runtime could retain memory for five or more minutes following a spike in the heap size. It will now begin returning it promptly after the heap shrinks.”

How the runtime tells the kernel

All of this ends in one function, sysUnused in src/runtime/mem_linux.go. In Go 1.12 and 1.13 it finishes like this:

	var advise uint32
	if debug.madvdontneed != 0 {
		advise = _MADV_DONTNEED
	} else {
		advise = atomic.Load(&adviseUnused)
	}
	if errno := madvise(v, n, int32(advise)); advise == _MADV_FREE && errno != 0 {
		// MADV_FREE was added in Linux 4.5. Fall back to MADV_DONTNEED if it is
		// not supported.
		atomic.Store(&adviseUnused, _MADV_DONTNEED)
		madvise(v, n, _MADV_DONTNEED)
	}

adviseUnused starts as MADV_FREE. Go 1.11 used MADV_DONTNEED. Go 1.12 switched, and said in its release notes: “On Linux, the runtime now uses MADV_FREE to release unused memory. This is more efficient but may result in higher reported RSS. The kernel will reclaim the unused data when it is needed. To revert to the Go 1.11 behavior (MADV_DONTNEED), set the environment variable GODEBUG=madvdontneed=1.”

So a Go 1.12 or 1.13 program on a kernel since 4.5 releases memory in a way that does not change its RSS. The 1.13 notes say this too: “on many OSes, including Linux, the OS itself reclaims memory lazily, so process RSS will not decrease until the system is under memory pressure.”

Three releases, one gigabyte

This program writes a gigabyte of heap, one byte in every page so that every page is really resident, drops it, collects it, and then reports its RSS and the runtime’s own counters at intervals for seven minutes:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"strings"
	"time"
)

var keep [][]byte

// rss returns VmRSS from /proc/self/status, in MB.
func rss() int {
	b, _ := ioutil.ReadFile("/proc/self/status")
	for _, l := range strings.Split(string(b), "\n") {
		if strings.HasPrefix(l, "VmRSS:") {
			var kb int
			fmt.Sscanf(strings.TrimSpace(l[6:]), "%d", &kb)
			return kb >> 10
		}
	}
	return -1
}

func report(name string, t0 time.Time) {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%-22s t=%4.0fs  RSS %5d MB  HeapInuse %5d  HeapIdle %5d  HeapReleased %5d MB\n",
		name, time.Since(t0).Seconds(), rss(), m.HeapInuse>>20, m.HeapIdle>>20, m.HeapReleased>>20)
}

func main() {
	name := runtime.Version() + os.Getenv("TAG")
	for i := 0; i < 1024; i++ { // 1 GB of heap, every page written
		b := make([]byte, 1<<20)
		for j := 0; j < len(b); j += 4096 {
			b[j] = 1
		}
		keep = append(keep, b)
	}
	t0 := time.Now()
	report(name, t0)
	keep = nil
	runtime.GC() // the gigabyte is garbage now, and swept
	for _, s := range []int{0, 1, 5, 30, 60, 120, 180, 240, 300, 330, 360, 390, 420} {
		time.Sleep(time.Until(t0.Add(time.Duration(s) * time.Second)))
		report(name, t0)
	}
}

The three MemStats fields are the runtime’s view of its heap: HeapInuse is memory in spans that hold objects, HeapIdle memory in idle spans, and HeapReleased the part of HeapIdle it has returned to the kernel with madvise.

Four copies ran at the same time in a virtual machine with 6 GB of memory, booting Ubuntu 18.04’s release kernel, 4.15.0-20: built with Go 1.11.13, with Go 1.12.10, with Go 1.12.10 again under GODEBUG=madvdontneed=1, and with Go 1.13.1. After 400 seconds a small C program allocated and wrote 5,000 MB, more than the machine had free, to force the kernel to find memory somewhere:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* Allocate and touch N megabytes, hold them, then exit: memory pressure
   for everything else on the machine. */
int main(int argc, char **argv) {
    long mb = atol(argv[1]), i;
    for (i = 0; i < mb; i++) {
        char *p = malloc(1 << 20);
        if (p == NULL) break;
        for (long j = 0; j < (1 << 20); j += 4096) p[j] = 1;
    }
    printf("pressure: %ld MB allocated and touched\n", i);
    fflush(stdout);
    sleep(30);
    return 0;
}

The script that ran inside the virtual machine:

uname -r; sysctl -w vm.overcommit_memory=1; free -m | head -2
./scav-1.11.13 > s1.txt &
./scav-1.12.10 > s2.txt &
TAG=" madvdontneed=1" GODEBUG=madvdontneed=1 ./scav-1.12.10 > s3.txt &
./scav-1.13.1 > s4.txt &
sleep 400
free -m | head -2
(sleep 12; echo "-- during pressure"; free -m | head -2) &
./pressure 5000

(vm.overcommit_memory=1 lets the pressure program’s allocations succeed and leaves it to the kernel to find pages when they are written. Without it, the kernel refused the allocations outright, because it does not count lazily freed pages as available when it decides whether to allow one.)

Go 1.11.13, every sample after the drop:

$ cat s1.txt
go1.11.13              t=   0s  RSS  1058 MB  HeapInuse  1024  HeapIdle    63  HeapReleased     0 MB
go1.11.13              t=   0s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t=   1s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t=   5s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t=  30s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t=  60s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 120s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 180s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 240s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 300s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 330s  RSS    38 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.11.13              t= 360s  RSS    38 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.11.13              t= 390s  RSS    38 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.11.13              t= 420s  RSS    38 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB

The first line is the peak; from the second on, the gigabyte is garbage and collected, so HeapInuse is 0 and HeapIdle 1,087 MB. For five and a half minutes nothing happens. Then sysmon’s five-minute rule fires, the runtime calls madvise(MADV_DONTNEED), and RSS falls from 1,058 MB to 38 at once. (At 330 seconds the counter had not caught up with the release it was in the middle of; by 360 it says 1,083 MB.)

The timing is the sysmon arithmetic. The spans became idle at 0 seconds. Sysmon looks every two and a half minutes, and the first look after a span has been idle for five minutes releases it, so the release had to come somewhere between 300 and 450 seconds. It came between 300 and 330 seconds in all three runs of this experiment. (HeapIdle is 1,087 MB rather than 1,024 because the heap had grown in steps on the way up, and the steps left 63 MB of spans idle before the drop.)

Go 1.12.10 at the same moments, and the same release under madvdontneed=1:

$ grep -hE 't= *(300|330|360|390|420)s' s2.txt s3.txt
go1.12.10              t= 300s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.12.10              t= 330s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.12.10              t= 360s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB
go1.12.10              t= 390s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB
go1.12.10              t= 420s  RSS   592 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB
go1.12.10 madvdontneed=1 t= 300s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     0 MB
go1.12.10 madvdontneed=1 t= 330s  RSS  1054 MB  HeapInuse     0  HeapIdle  1087  HeapReleased     4 MB
go1.12.10 madvdontneed=1 t= 360s  RSS    93 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB
go1.12.10 madvdontneed=1 t= 390s  RSS    93 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB
go1.12.10 madvdontneed=1 t= 420s  RSS    93 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1028 MB

Go 1.12 kept the same five-minute rule, and at 360 seconds the runtime reports 1,028 MB released. But RSS does not move: it used MADV_FREE, the pages stay mapped, and the kernel goes on counting them. The same binary under madvdontneed=1 released the same memory at the same point, between 330 and 360 seconds (at 330 it had begun: 4 MB released, RSS 1,054 MB), and its RSS fell to 93 MB.

Then the pressure program wrote its 5,000 MB into a machine that had about 3.6 GB free. The machine during the pressure:

-- during pressure
              total        used        free      shared  buff/cache   available
Mem:           5960        5824         117           0          18         420

5,000 MB of pressure on top of the 2,299 MB that was in use before it adds up to more than the machine has. The kernel found the difference in the pages Go 1.12 had marked MADV_FREE: by the next sample, at 420 seconds, the 1.12 program’s RSS had fallen from 1,058 to 592 MB, without the program making a single call.

And Go 1.13.1:

$ cat s4.txt
go1.13.1               t=   0s  RSS  1058 MB  HeapInuse  1024  HeapIdle    63  HeapReleased    63 MB
go1.13.1               t=   0s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased    64 MB
go1.13.1               t=   1s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased    66 MB
go1.13.1               t=   5s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased    84 MB
go1.13.1               t=  30s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased   182 MB
go1.13.1               t=  60s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased   298 MB
go1.13.1               t= 120s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased   532 MB
go1.13.1               t= 180s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 240s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 300s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 330s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 360s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 390s  RSS  1058 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB
go1.13.1               t= 420s  RSS    38 MB  HeapInuse     0  HeapIdle  1087  HeapReleased  1083 MB

The background scavenger starts at once, and its constants predict its pace almost exactly. One 4 KB page per millisecond is 3.9 MB a second. Between 5 and 30 seconds it released 98 MB, 3.9 MB a second; between 30 and 60 seconds 116 MB, 3.9 a second; between 60 and 120 seconds 234 MB, 3.9 a second again. Then it sped up, releasing the last 551 MB in under a minute, and the whole gigabyte is reported released by 180 seconds, two minutes before Go 1.11 would even have started. And RSS does not move for seven minutes, because 1.13 still uses MADV_FREE. Under pressure, the kernel took nearly all of it: 1,058 MB to 38, where from the 1.12 program it had taken about half, 1,058 to 592, by the same sample. I did not establish why the kernel reclaimed one more fully than the other; the sample came a few seconds into the pressure, while reclaim was still going on.

One gigabyte freed by four Go releases

Each process dropped 1 GB of heap at 0 s. Ubuntu 18.04's 4.15 kernel, sampled to 420 s; memory pressure from about 400 s.

RSS, what the kernel countsHeapReleased, what the runtime says it gave back

Hover or focus a panel for its numbers.

Put side by side, there are three separate events in the life of a freed gigabyte, and the three releases put them in different places:

Runtime decides to releaseHow it tells the kernelRSS falls
Go 1.11after 5 minutes idle (sysmon)MADV_DONTNEEDat once: 330 s
Go 1.12after 5 minutes idle (sysmon)MADV_FREEonly under memory pressure
Go 1.12, madvdontneed=1after 5 minutes idle (sysmon)MADV_DONTNEEDat once: 360 s
Go 1.13promptly, at about 1% of the program’s timeMADV_FREEonly under memory pressure

That is the leak in this part: the number everyone watches, RSS, stopped measuring what a Go program needs in Go 1.12, and Go 1.13 made the runtime release memory sooner without changing that. A Go 1.13 service whose heap spikes and recovers will show its peak RSS until the machine needs the memory, and the monitoring that alerts on RSS, or the container limit that kills on it, will see the peak.

Container limits deserve a sentence of their own. A memory cgroup has its own reclaim: when a container reaches its limit, the kernel reclaims within that container, and lazily freed pages are the cheapest thing it can take. So a Go 1.12 or 1.13 program near its container limit should get its MADV_FREE pages taken back rather than be killed, though I did not test a container here. Anything that reads RSS from outside, a dashboard or an autoscaler, still sees the peak.

There are three ways to see the truth. GODEBUG=madvdontneed=1 puts back the old behaviour, at some cost in page faults when the memory is reused. runtime/debug.FreeOSMemory forces a collection and returns everything it can at once. And the runtime’s own HeapReleased says how much of HeapIdle it has handed back: HeapSys - HeapReleased is a better measure of what the heap costs than RSS. In /proc/<pid>/smaps, on kernels since 4.12, lazily freed memory is counted in the LazyFree field of each mapping, which says how much of RSS the kernel could take back without asking.

What MADV_FREE buys

If MADV_FREE makes RSS misleading, why did Go 1.12 switch to it? Because memory a program gives back is often memory it wants again soon, and the two kinds of advice make that very different. This program fills a gigabyte, drops it, and calls debug.FreeOSMemory, which forces a collection and returns everything idle to the kernel at once, without waiting for any scavenger. Then it fills the same gigabyte again, counting the page faults the second fill takes with getrusage:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"runtime/debug"
	"strings"
	"syscall"
	"time"
)

var keep [][]byte

func rss() string {
	b, _ := ioutil.ReadFile("/proc/self/status")
	for _, l := range strings.Split(string(b), "\n") {
		if strings.HasPrefix(l, "VmRSS:") {
			return strings.TrimSpace(l[6:])
		}
	}
	return "?"
}

func minflt() int64 {
	var ru syscall.Rusage
	syscall.Getrusage(syscall.RUSAGE_SELF, &ru)
	return ru.Minflt
}

// fill allocates 1 GB in 1 MB slices and writes every page.
func fill() {
	for i := 0; i < 1024; i++ {
		b := make([]byte, 1<<20)
		for j := 0; j < len(b); j += 4096 {
			b[j] = 1
		}
		keep = append(keep, b)
	}
}

func main() {
	name := runtime.Version() + os.Getenv("TAG")
	fill()
	keep = nil
	debug.FreeOSMemory() // collect, and return everything idle to the kernel now
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%-24s after FreeOSMemory: HeapReleased %4d MB, RSS %s\n", name, m.HeapReleased>>20, rss())
	f0, t0 := minflt(), time.Now()
	fill() // the same gigabyte again
	fmt.Printf("%-24s refill: %7d page faults, %4d ms, RSS %s\n", name, minflt()-f0, time.Since(t0)/time.Millisecond, rss())
}

The first of three runs in the same virtual machine (the other two differed by a few page faults and a few milliseconds):

go1.11.13                after FreeOSMemory: HeapReleased 1087 MB, RSS 35056 kB
go1.11.13                refill:  262156 page faults,  337 ms, RSS 1083912 kB
go1.12.10                after FreeOSMemory: HeapReleased 1087 MB, RSS 1083736 kB
go1.12.10                refill:     260 page faults,  251 ms, RSS 1084752 kB
go1.12.10 madvdontneed=1 after FreeOSMemory: HeapReleased 1087 MB, RSS 35432 kB
go1.12.10 madvdontneed=1 refill:  262165 page faults,  337 ms, RSS 1084032 kB
go1.13.1                 after FreeOSMemory: HeapReleased 1087 MB, RSS 1083972 kB
go1.13.1                 refill:      12 page faults,  261 ms, RSS 1083972 kB

Every release handed back all 1,087 MB. With MADV_DONTNEED, the kernel took the pages at once, RSS fell to 35 MB, and filling the gigabyte again cost 262,156 page faults: one for each of the 262,144 pages in a gigabyte, plus a handful. With MADV_FREE, RSS did not move, and the refill cost between about a hundred and 260 faults on 1.12 and a dozen or fewer on 1.13. Writing to a lazily freed page simply cancels the advice. The refill was about a quarter faster, 251 ms against 337. For a program whose heap goes up and down, that is a page fault saved for every page of every swing, which is the efficiency the 1.12 release notes promised, paid for with a number that looks wrong.

Note also what debug.FreeOSMemory does on 1.12 and 1.13: everything is returned, HeapReleased says so, and RSS still reads 1,084 MB. Calling it to make a dashboard look better no longer works.

Reading the runtime’s own numbers

Since RSS cannot be trusted for this, the runtime’s counters are worth knowing precisely. Of the heap fields in runtime.MemStats:

  • HeapSys is all the address space the heap has obtained from the operating system, used or not.
  • HeapInuse is the part in spans that hold at least one object. It is never smaller than the live data, and Part 3 showed how much bigger fragmentation can make it.
  • HeapIdle is HeapSys - HeapInuse: spans with nothing in them, kept for reuse.
  • HeapReleased is the part of HeapIdle the runtime has given back with madvise.

So HeapSys - HeapReleased is the memory the heap is holding on to, as far as the runtime is concerned, and HeapIdle - HeapReleased is what the scavenger could still return. On Go 1.11, or with madvdontneed=1, the first figure tracks RSS closely. On 1.12 and 1.13 RSS stays higher by the released pages until the kernel takes them, and /proc/<pid>/smaps shows how much: each mapping has a LazyFree line, the memory in it that has been advised MADV_FREE and not yet reclaimed. Summing those lines and subtracting the total from RSS gives the number top would show if the kernel took everything it could.

The scavenger can also be watched as it works. Part 4 used GODEBUG=gctrace=1 for the collector’s one line per cycle, and in Go 1.11 the same setting also makes the runtime report its releases, in a format documented in src/runtime/extern.go (I did not check how later releases print it):

	Setting gctrace to any value > 0 also causes the garbage collector
	to emit a summary when memory is released back to the system.
	This process of returning memory to the system is called scavenging.
	The format of this summary is subject to change.
	Currently it is:
		scvg#: # MB released  printed only if non-zero
		scvg#: inuse: # idle: # sys: # released: # consumed: # (MB)

The released and consumed figures there are the same accounting as HeapReleased and HeapSys - HeapReleased, printed at each of sysmon’s scavenges. A program that shows released growing while its RSS stays flat is running into exactly the MADV_FREE behaviour above, and is not leaking.

Huge pages, the other way RSS lies

sysUnused has one more job, visible at the top of the function in all three releases. Linux can back memory with 2 MB transparent huge pages instead of 4 KB ones, and a background kernel thread, khugepaged, merges small pages into huge ones where it can. The comment explains the trouble that causes for a program that returns memory:

	// By default, Linux's "transparent huge page" support will
	// merge pages into a huge page if there's even a single
	// present regular page, undoing the effects of madvise(adviseUnused)
	// below. On amd64, that means khugepaged can turn a single
	// 4KB page to 2MB, bloating the process's RSS by as much as
	// 512X. (See issue #8832 and Linux kernel bug
	// https://bugzilla.kernel.org/show_bug.cgi?id=93111)

One page still in use inside a 2 MB region can pull the other 511 back into memory. So when the runtime releases memory, it also marks the huge pages at the edges of the released range with MADV_NOHUGEPAGE, and only those, because changing the flag splits the kernel’s record of the mapping and a process may have only about 65,000 of them. The result is a compromise the comment spells out: most of the heap keeps the speed of huge pages, and released memory is not quietly refilled. The 1.13 scavenger’s constants give huge pages the same per-page time as small ones, so where the heap is backed by huge pages it releases 512 times as much per step. That would explain why it got through the gigabyte above faster after the first two minutes, though I did not check which parts of the heap were huge pages.

A pool that survives one collection

Go 1.13 changed one more thing about memory kept for later, in sync.Pool. A pool is a cache of objects that a program can reuse instead of allocating new ones. Before 1.13 every garbage collection emptied every pool completely, which meant that a busy program refilled its pools from scratch after each cycle, a burst of allocation right after every collection. The 1.13 release notes: “Pool no longer needs to be completely repopulated after every GC. It now retains some objects across GCs, as opposed to releasing all objects, reducing load spikes for heavy users of Pool.”

The mechanism is a victim cache, a second copy of the pool’s storage, from src/sync/pool.go:

	victim     unsafe.Pointer // local from previous cycle
	victimSize uintptr        // size of victims array

At each collection, instead of clearing the pool, the runtime moves its contents to the victim cache and clears the old victim cache. Get tries the pool, then the victims. An object that is not used for two whole cycles is gone; one that is used within one cycle survives. This program counts how many objects the pool has to make with New:

package main

import (
	"fmt"
	"runtime"
	"sync"
)

var made int
var pool = sync.Pool{New: func() interface{} { made++; return new([64]byte) }}

// cycle takes n objects from the pool and puts them all back, and
// reports how many of them the pool had to make with New.
func cycle(n int) int {
	before := made
	objs := make([]interface{}, n)
	for i := range objs {
		objs[i] = pool.Get()
	}
	for _, o := range objs {
		pool.Put(o)
	}
	return made - before
}

func main() {
	fmt.Println(runtime.Version())
	fmt.Println("first use:          made", cycle(100), "of 100")
	runtime.GC()
	fmt.Println("after one GC:       made", cycle(100), "of 100")
	runtime.GC()
	runtime.GC()
	fmt.Println("after two more GCs: made", cycle(100), "of 100")
}
$ /opt/go/1.12.10/bin/go run pool.go; /opt/go/1.13.1/bin/go run pool.go
go1.12.10
first use:          made 100 of 100
after one GC:       made 100 of 100
after two more GCs: made 100 of 100
go1.13.1
first use:          made 100 of 100
after one GC:       made 0 of 100
after two more GCs: made 100 of 100

How many of 100 objects the pool had to make again

Take 100 objects from a sync.Pool, put them all back, then collect garbage between rounds.

first use
after one GC
after two more GCs
Go 1.12
100 newpool empty at start
100 newevery GC empties the pool
100 newemptied again
Go 1.13
100 newpool empty at start
0 newthe GC moved them to the victim cache, and Get found them there
100 newtwo GCs without use: victim cache cleared

On 1.12 one collection threw away all hundred objects. On 1.13 all hundred came back from the victim cache. Two collections without use emptied it on both. The pool now holds memory a little longer, up to two cycles, which is exactly what makes it useful between them.

The ballast, and what it really costs

Part 4 showed that a Go program with a small live heap runs many collections, because the next one is due when the heap has doubled. In April, Twitch’s engineering blog described a way around that, in “Go memory ballast: How I learnt to stop worrying and love the heap”, by Ross Engers: allocate one very large byte slice at start-up and never touch it. The collector counts it as live heap, so the heap goal rises, and collections become rare. Because the slice is never written, the kernel never backs its pages with memory. This program measures both claims:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"runtime"
	"strings"
	"time"
)

var live [][]byte // 10 MB that stays live, no pointers
var sink *[8]int64

func rss() string {
	b, _ := ioutil.ReadFile("/proc/self/status")
	for _, l := range strings.Split(string(b), "\n") {
		if strings.HasPrefix(l, "VmRSS:") {
			return strings.TrimSpace(l[6:])
		}
	}
	return "?"
}

func main() {
	var ballast []byte
	if len(os.Args) > 1 {
		ballast = make([]byte, 1<<30) // 1 GB, allocated and never written
	}
	for i := 0; i < 10; i++ {
		live = append(live, make([]byte, 1<<20))
	}
	runtime.GC()
	before := rss() // the ballast, if any, is allocated but not yet written
	var a, b runtime.MemStats
	runtime.ReadMemStats(&a)
	t := time.Now()
	for i := 0; i < 30000000; i++ {
		sink = new([8]int64) // 30 million 64-byte objects: 1.9 GB of garbage
	}
	el := time.Since(t)
	runtime.ReadMemStats(&b)
	fmt.Printf("ballast %-5v churn %.2f s  GCs %4d  HeapSys %5d MB  RSS before churn %s, after %s\n",
		ballast != nil, el.Seconds(), b.NumGC-a.NumGC, b.HeapSys>>20, before, rss())
	runtime.KeepAlive(ballast)
}
$ go build ballast.go && for r in 1 2 3; do ./ballast; ./ballast with; done
ballast false churn 0.31 s  GCs  178  HeapSys    63 MB  RSS before churn 2720 kB, after 15428 kB
ballast true  churn 0.45 s  GCs    1  HeapSys  2047 MB  RSS before churn 36564 kB, after 957284 kB
ballast false churn 0.31 s  GCs  176  HeapSys    63 MB  RSS before churn 2648 kB, after 16568 kB
ballast true  churn 0.32 s  GCs    1  HeapSys  2047 MB  RSS before churn 36504 kB, after 957452 kB
ballast false churn 0.31 s  GCs  179  HeapSys    63 MB  RSS before churn 2684 kB, after 16500 kB
ballast true  churn 0.45 s  GCs    1  HeapSys  2047 MB  RSS before churn 36540 kB, after 957400 kB

The first claim holds: 1.9 GB of garbage took about 178 collections without the ballast and one with it. The second holds only for the ballast itself. Before the churn, the process with a 1 GB ballast was resident at 36 MB, against 2.7 MB without: most of the gigabyte was never touched, though something about allocating it cost 34 MB, which I did not identify. But after the churn, the process was resident at 957 MB. The ballast moved the heap goal to about 2 GB, so about a gigabyte of the garbage piled up, in real, written pages, before the one collection; the rest reused the memory that collection freed. Without the ballast the same garbage was collected every 10 MB or so and the process never went above 17 MB.

So a ballast does not make collections free. It trades them for memory, exactly as raising GOGC does: fewer collections, a higher peak. Its advantage over GOGC is that the extra headroom is a fixed amount rather than a multiple of the live heap, which is what Twitch wanted for a service with a small live heap and a large machine. Its RSS then depends on how much garbage the program makes between the now-rare collections, and if the program makes a lot, that is real memory.

How C’s allocator answers the same questions

glibc’s malloc makes the same decisions with different rules. Blocks of 128 KB and more (the “mmap threshold”, which glibc raises dynamically up to 32 MB as a program frees large blocks) get a mapping of their own, and free returns that mapping to the kernel at once with munmap. Smaller blocks come from the heap, and memory in the middle of the heap stays resident until the program calls malloc_trim, which madvises free pages back. This program writes a gigabyte in blocks of one size, frees all of it, and trims:

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static long rss_mb(void) {
    char line[256]; long kb = -1;
    FILE *f = fopen("/proc/self/status", "r");
    while (fgets(line, sizeof line, f))
        if (!strncmp(line, "VmRSS:", 6)) sscanf(line + 6, "%ld", &kb);
    fclose(f);
    return kb >> 10;
}

/* Allocate 1 GB in blocks of the given size, write every page, free it all,
   and report the resident set before and after freeing, and after malloc_trim. */
static void run(size_t block) {
    size_t n = (1UL << 30) / block;
    char **p = malloc(n * sizeof *p);
    for (size_t i = 0; i < n; i++) {
        p[i] = malloc(block);
        for (size_t j = 0; j < block; j += 4096) p[i][j] = 1;
        p[i][block - 1] = 1;
    }
    long peak = rss_mb();
    for (size_t i = 0; i < n; i++) free(p[i]);
    free(p);
    long after = rss_mb();
    malloc_trim(0);
    printf("blocks of %7zu B: RSS %5ld MB full, %5ld MB after free, %5ld MB after malloc_trim\n",
           block, peak, after, rss_mb());
}

int main(int argc, char **argv) {
    run((size_t)atol(argv[1]));
    return 0;
}
$ gcc -O2 -o cfree cfree.c && for b in 1024 1048576; do ./cfree $b; done
blocks of    1024 B: RSS  1049 MB full,  1041 MB after free,     1 MB after malloc_trim
blocks of 1048576 B: RSS  1029 MB full,     1 MB after free,     1 MB after malloc_trim

A gigabyte freed in megabyte blocks left at once. A gigabyte freed in kilobyte blocks stayed: 1,041 MB resident after every block was freed, until malloc_trim handed it back. glibc on this release has no background thread and no timer: memory goes back when a large block is freed, when the top of the heap is free past a threshold, or when the program asks. A C program with a long-lived heap of small blocks behaves much like Go 1.11 with the five-minute timer removed.

The JVM keeps memory in a third way. Its heap is a range it commits up to -Xmx, and until this year the G1 collector gave committed memory back only after a full collection or a concurrent marking cycle, and a program that is idle has neither. Java 12, released in March, added periodic collections to G1 so that an idle JVM can uncommit memory (JEP 346, “Promptly Return Unused Committed Memory from G1”), the same problem Go 1.13 solved for its heap, from the other side. CPython keeps freed memory in 256 KB arenas that go back to the C library only when completely empty, which the Python series on this site measured in detail.

What this means for Go code

RSS overstates a Go 1.12 or 1.13 program. After the heap shrinks, the memory the runtime released stays in RSS until something on the machine needs it. Use HeapSys - HeapReleased, or the LazyFree lines of smaps, to see what the program really holds, or run with GODEBUG=madvdontneed=1 where something outside the program must see RSS fall.

Go 1.13 releases promptly; Go 1.11 and 1.12 wait five minutes. A heap spike on 1.12 occupies its memory, as far as the runtime is concerned, for five to seven and a half minutes. On 1.13 the scavenger starts at once and works at about a megabyte every quarter of a second, faster where huge pages back the heap.

sync.Pool objects now live for up to two cycles. That is what makes the pool useful between collections. It also means a pool holding large buffers keeps them a cycle longer.

A ballast buys fewer collections with memory. The ballast itself is nearly free. The garbage it lets accumulate is not.

A note on the evidence

What ran. Go 1.13.1, Go 1.12.10 and Go 1.11.13 (the official linux-amd64 archives, each checked against its published SHA-256; 1.13.1 and 1.12.10 were released on 25 September 2019, 1.11.13 on 13 August), on an Ubuntu 18.04 userland as released. The scavenger experiment ran inside a QEMU virtual machine with 4 CPUs and 6 GB of memory, booting Ubuntu 18.04’s release kernel 4.15.0-20-generic, with vm.overcommit_memory=1 set inside the guest. The pool, ballast and glibc programs ran in a chroot under the host’s kernel; none of their results depends on the kernel beyond lazy allocation of untouched pages.

What was measured. The scavenger experiment ran three times. The listings and the figure are the third run, the first in which the pressure program had both the overcommit setting and enough memory to take: in the first run its 3,500 MB fitted in free memory, so the kernel reclaimed nothing, and in the second the guest’s default overcommit policy refused its allocations at about 3.6 GB and it crashed. All three runs agree on when each release returned its memory (300 to 330 seconds for Go 1.11, 330 to 360 for Go 1.12, 180 seconds for Go 1.13) and that RSS stayed at 1,058 MB for 1.12 and 1.13. The third run was stopped by its host about 30 seconds before it would have ended, during the pressure program’s hold; every sample shown had already been written, and only the final free reading was lost. The FreeOSMemory and refill program ran three times on each release, one process at a time, in a second guest with 2 CPUs and 3 GB on the same kernel; the faults and times above are the first run, and the other two are in the data behind the figures. The ballast program ran three times each way; the pool and glibc programs once.

What is quoted. Runtime source is from the go1.13.1, go1.12.10 and go1.11.13 tags (mem_linux.go, mgcscavenge.go, proc.go, sync/pool.go); the release notes from doc/go1.12.html and doc/go1.13.html. Twitch’s post is “Go memory ballast: How I learnt to stop worrying and love the heap”, Ross Engers, 10 April 2019. JEP 346 shipped in Java 12 on 19 March 2019.

What is not explained. Go 1.12 released 1,028 MB of the 1,087 MB idle, Go 1.11 1,083 MB; I did not find out which spans 1.12 left behind. The madvdontneed=1 run settled at 93 MB of RSS rather than the 38 MB of Go 1.11 in the same run (35 MB in the first run). And I did not identify the 34 MB of RSS that allocating the untouched ballast added.

More