The Allocator Under Every new

Contents
Ask Go’s heap for 33 bytes and it hands back 48. Ask for 32,769 and it hands back 40,960. Keep every second one of a million small integers and you free nothing at all. And until August, a C library that mapped 64 kilobytes of memory in the wrong place could kill a Go program as soon as its heap grew into that place, with an error that blamed neither. Go 1.11, released on 24 August, fixed the last of these by changing where the heap lives. The others are how Go’s allocator is designed, and they are worth knowing.
The previous part of this series was about which variables the compiler sends to the heap. This one
is about what happens when they get there: the allocator behind every new, every escaping
variable and every make. It measures the sizes the allocator really hands out and sets them beside
three C allocators, shows the shortcut Go takes for very small objects and the memory that shortcut
keeps alive, times allocation from 16 bytes to a megabyte, and then runs a small program that
crashes on Go 1.10 and does not on Go 1.11, to show what the new heap layout is for.
This is Part 3 of a series on how Go manages the stack and the heap. Part 1 covered goroutine stacks and Part 2 escape analysis. It is written for Go programmers who have written a little C. Everything here ran on Go 1.11.1, released on 1 October, and for comparison on Go 1.10.4, the latest 1.10 release, on an Ubuntu 18.04 userland with its glibc 2.27, TCMalloc 2.5 and jemalloc 3.6.0. The note at the end says what was measured and how.
What an allocator has to solve
This section is the theory. If you know what size classes and internal fragmentation are, skip to the next one.
malloc(n) has a hard job. Requests come in every size, in any order, and are freed in any order.
The allocator has to find a free block of at least n bytes quickly, and it has to avoid wasting
memory, which can happen in two ways:
- Internal fragmentation is memory inside a block that the program did not ask for: hand back 48 bytes for a 33-byte request, and 15 are wasted.
- External fragmentation is free memory that cannot be used because it is in pieces too small for the requests that arrive: a megabyte free in total, but no free piece bigger than 100 bytes.
The classic C allocator design, the one in glibc, keeps blocks of any size, splits them to fit a request, and merges neighbours when they are freed. That keeps internal fragmentation low, at the cost of a header next to every block (to know its size and its neighbours) and of searching free lists.
The other family, which includes Google’s TCMalloc, divides requests into size classes. Every request is rounded up to one of a fixed set of sizes, and each size has its own pool of blocks, all exactly that size, carved from pages that hold only that size. Finding a block is then trivial (take any free one from the right pool) and needs no per-block header, because the page knows the size of everything in it. The price is internal fragmentation, which the choice of classes keeps to a bounded fraction. External fragmentation becomes a question of whole pages: a page can be given back only when every block in it is free.
Multithreaded programs add a third problem: a single allocator with a single lock does not scale. So TCMalloc (the “T” is for thread-caching) gives each thread a cache of free blocks of every class, which it can take from without a lock, and only goes to a shared, locked structure when its cache runs dry.
Go’s allocator
Go’s allocator is a TCMalloc descendant. The comment at the top of src/runtime/malloc.go in Go
1.11.1 says so, and then describes the whole design:
// Memory allocator.
//
// This was originally based on tcmalloc, but has diverged quite a bit.
// http://goog-perftools.sourceforge.net/doc/tcmalloc.html
// The main allocator works in runs of pages.
// Small allocation sizes (up to and including 32 kB) are
// rounded to one of about 70 size classes, each of which
// has its own free set of objects of exactly that size.
// Any free page of memory can be split into a set of objects
// of one size class, which are then managed using a free bitmap.
//
// The allocator's data structures are:
//
// fixalloc: a free-list allocator for fixed-size off-heap objects,
// used to manage storage used by the allocator.
// mheap: the malloc heap, managed at page (8192-byte) granularity.
// mspan: a run of pages managed by the mheap.
// mcentral: collects all spans of a given size class.
// mcache: a per-P cache of mspans with free space.
// mstats: allocation statistics.
//
// Allocating a small object proceeds up a hierarchy of caches:
//
// 1. Round the size up to one of the small size classes
// and look in the corresponding mspan in this P's mcache.
// Scan the mspan's free bitmap to find a free slot.
// If there is a free slot, allocate it.
// This can all be done without acquiring a lock.
//
// 2. If the mspan has no free slots, obtain a new mspan
// from the mcentral's list of mspans of the required size
// class that have free space.
// Obtaining a whole span amortizes the cost of locking
// the mcentral.
//
// 3. If the mcentral's mspan list is empty, obtain a run
// of pages from the mheap to use for the mspan.
//
// 4. If the mheap is empty or has no page runs large enough,
// allocate a new group of pages (at least 1MB) from the
// operating system. Allocating a large run of pages
// amortizes the cost of talking to the operating system.
The vocabulary:
- A span (
mspan) is a run of one or more 8 KB pages. A span holding small objects is cut into equal slots of one size class, with a bitmap that says which slots are free. - The mcache is the per-thread cache, except that it belongs to a P, the Go scheduler’s logical
processor (
GOMAXPROCSof them), rather than to an operating-system thread. It holds one span of each span class (each size class twice over, for the two kinds of span described below), so a goroutine allocating a small object takes a slot from its P’s span without any lock. - The mcentral of each span class keeps the spans of that class that still have free slots, so a P whose span is full can swap it for another. That takes a lock, one per span class, once per span rather than once per object.
- The mheap owns all the pages. It hands runs of pages to the mcentrals as new spans, takes them back when they empty, and asks the operating system for more.
Large objects, those over 32 KB, skip the first two levels. Each one gets a span of its own, straight from the mheap, rounded up to whole 8 KB pages, under the mheap’s lock.
Go adds two things TCMalloc does not have, both because Go has a garbage collector. First, the
allocator has to tell the collector which words of each object are pointers, so spans come in two
kinds per size class: scan spans for objects that contain pointers and noscan spans for those
that do not, which the collector never has to look inside. Second, there is no free. Nothing is
returned to a span until the collector finds it unreachable, and the slot is then marked free in the
bitmap when the span is next swept.
One allocation, step by step
Follow a single make([]byte, 33) through mallocgc in Go 1.11.1. The slice’s backing array is 33
bytes with no pointers in it, so it is a small, noscan object, and too big for the tiny path. The first
step turns the size into a size class with two table lookups, one for sizes up to 1,016 bytes and
one for the rest:
var sizeclass uint8
if size <= smallSizeMax-8 {
sizeclass = size_to_class8[(size+smallSizeDiv-1)/smallSizeDiv]
} else {
sizeclass = size_to_class128[(size-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
}
size = uintptr(class_to_size[sizeclass])
spc := makeSpanClass(sizeclass, noscan)
span := c.alloc[spc]
smallSizeDiv is 8, so the index is (33 + 7) / 8 = 5, and entry 5 of size_to_class8 is 4. Class
4 is 48 bytes: size becomes 48, and from here on the object is 48 bytes. No division, no search,
just two array reads, because sizeclasses.go precomputes the answer for every 8-byte step.
The span class folds in the scan/noscan distinction, from mheap.go:
func makeSpanClass(sizeclass uint8, noscan bool) spanClass {
return spanClass(sizeclass<<1) | spanClass(bool2int(noscan))
}
Class 4, noscan, is span class 9, and c.alloc[9] is this P’s current span of 48-byte objects
without pointers. That span is one 8 KB page cut into 170 slots, with 32 bytes left over at the end
(the “tail waste” column of the table above). Finding a free slot in it is the job of nextFreeFast:
func nextFreeFast(s *mspan) gclinkptr {
theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
if theBit < 64 {
result := s.freeindex + uintptr(theBit)
if result < s.nelems {
freeidx := result + 1
if freeidx%64 == 0 && freeidx != s.nelems {
return 0
}
s.allocCache >>= uint(theBit + 1)
s.freeindex = freeidx
s.allocCount++
return gclinkptr(result*s.elemsize + s.base())
}
}
return 0
}
allocCache is 64 bits of the span’s allocation bitmap, inverted so that a 1 means “free”, covering
the 64 slots from freeindex on. sys.Ctz64 counts its trailing zeros, which on amd64 is a single
instruction (BSF) that finds the first free slot. The slot’s address is its index times 48 plus the
span’s base. The function shifts the cache past the slot it used and returns. On the common path, a
small allocation in Go is a table lookup, one bit-scan instruction, a multiply and an add, all on data
that belongs to this P, with no lock and no atomic operation.
When the 64 cached bits run out, or the span is full, nextFreeFast returns 0 and mallocgc falls
back to c.nextFree(spc). That reloads the cache from the span’s bitmap or, when the span has no free
slot left, calls c.refill(spc). The refill hands the full span back to the mcentral for span class 9
and takes another span that has free slots, under the mcentral’s lock, sweeping spans of that class
first if the collector has left some unswept. If the mcentral has none, it asks the mheap for a fresh
page, and the mheap, if it has no free pages, asks the operating system. Each level is rarer than the
one before it, which is the point of the hierarchy.
Two more steps follow the slot. If the span has been used before, the slot may hold an old object’s
bytes, and mallocgc clears it:
if needzero && span.needzero != 0 {
memclrNoHeapPointers(unsafe.Pointer(v), size)
}
A span of fresh pages from the operating system is already zero, so needzero is false and nothing is
cleared. And because this object is noscan, there is no pointer bitmap to write: for an object with
pointers, heapBitsSetType would now record which of its words the collector must follow.
The sizes it really hands out
The size classes are generated by a program and written into src/runtime/sizeclasses.go, with a
table at the top:
// class bytes/obj bytes/span objects tail waste max waste
// 1 8 8192 1024 0 87.50%
// 2 16 8192 512 0 43.75%
// 3 32 8192 256 0 46.88%
// 4 48 8192 170 32 31.52%
// 5 64 8192 128 0 23.44%
// 6 80 8192 102 32 19.07%
// 7 96 8192 85 32 15.95%
// 8 112 8192 73 16 13.56%
// 9 128 8192 64 0 11.72%
// 10 144 8192 56 128 11.82%
There are 66 classes (67 counting class 0, which means “large”), from 8 bytes to 32,768. “Max waste” is the worst case: a request one byte over the class below. Class 3, for instance, holds 32-byte objects, and gets requests from 17 to 32 bytes, because there is no 24-byte class. A 17-byte object wastes 15 of its 32.
The table describes the classes. To see what a program really pays, this program allocates thousands
of byte slices of each size, with no pointers in them, and divides the growth of TotalAlloc by the
count:
package main
import (
"fmt"
"runtime"
)
var keep [][]byte
// perObject allocates n byte slices of the given length and reports how
// many bytes of heap each one really took. The slices hold no pointers,
// so under 16 bytes the tiny allocator may pack them; the program
// skips that range (see tiny.go).
func perObject(size, n int) uint64 {
keep = make([][]byte, n)
runtime.GC()
var a, b runtime.MemStats
runtime.ReadMemStats(&a)
for i := range keep {
keep[i] = make([]byte, size)
}
runtime.ReadMemStats(&b)
return (b.TotalAlloc - a.TotalAlloc) / uint64(n)
}
func main() {
fmt.Println(runtime.Version())
sizes := []int{17, 24, 25, 32, 33, 48, 49, 64, 65, 80, 100, 128, 129, 200, 256, 257, 300, 500, 512, 513,
640, 700, 1000, 1024, 1025, 1500, 2000, 2048, 2049, 3000, 4096, 4097, 5000, 6000, 8192, 8193,
10000, 13000, 16384, 16385, 20000, 24576, 27264, 28000, 32768, 32769, 40000, 65536, 65537}
for _, s := range sizes {
n := 20000
if s > 4096 {
n = 2000
}
got := perObject(s, n)
fmt.Printf("%6d -> %6d waste %5.1f%%\n", s, got, 100*float64(got-uint64(s))/float64(got))
}
}
Selected lines of its output on Go 1.11.1 (the full run is in the figure below):
$ go run classes.go
go1.11.1
17 -> 32 waste 46.9%
32 -> 32 waste 0.0%
33 -> 48 waste 31.2%
65 -> 80 waste 18.8%
129 -> 144 waste 10.4%
1025 -> 1152 waste 11.0%
4097 -> 4864 waste 15.8%
8193 -> 9472 waste 13.5%
32768 -> 32768 waste 0.0%
32769 -> 40960 waste 20.0%
65537 -> 73728 waste 11.1%
...
Every class size matches the table. (The waste figures are smaller than the table’s “max waste”,
which also counts the unused tail of each span.) The two that deserve a second look are at the class boundaries. A
33-byte object costs 48 bytes, so adding one bool to a 32-byte struct makes every instance half as
big again. And 32,769 bytes is one byte past the largest small class, so it becomes a large object of
whole 8 KB pages: 40,960 bytes, 20% of it wasted. (Go 1.10.4 printed the same table, apart from a
rounding difference in one figure: the size classes did not change between the two releases.)
How much of each block is wasted
Go's 66 size classes, then whole 8 KB pages above 32 KB. The line is the class table; the dots are measured.
Hover or focus the chart, then use the arrow keys to step through the measured sizes.
Three C allocators, same requests
The same question can be put to the C allocators on the same machine. malloc_usable_size reports
how big the block malloc chose really is, and running one small program under each allocator in
turn (TCMalloc and jemalloc replace malloc when they are preloaded):
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
/* How many bytes does the allocator actually hand back for each request?
malloc_usable_size reports the usable size of the block it chose. */
int main(void) {
static const size_t sizes[] = {17, 24, 25, 32, 33, 48, 49, 64, 65, 100, 129, 257, 513, 1025,
2049, 4097, 8193, 16385, 32769, 65537};
for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
void *p = malloc(sizes[i]);
printf("%6zu -> %6zu\n", sizes[i], malloc_usable_size(p));
}
return 0;
}
$ gcc -O2 -o usable usable.c
$ ./usable
$ LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4 ./usable
$ LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1 ./usable
Side by side with Go:
| Request | Go 1.11 | TCMalloc 2.5 | jemalloc 3.6 | glibc 2.27 |
|---|---|---|---|---|
| 17 | 32 | 32 | 32 | 24 |
| 25 | 32 | 32 | 32 | 40 |
| 33 | 48 | 48 | 48 | 40 |
| 65 | 80 | 80 | 80 | 72 |
| 129 | 144 | 144 | 160 | 136 |
| 257 | 288 | 288 | 320 | 264 |
| 513 | 576 | 576 | 640 | 520 |
| 1,025 | 1,152 | 1,152 | 1,280 | 1,032 |
| 2,049 | 2,304 | 2,304 | 2,560 | 2,056 |
| 4,097 | 4,864 | 4,608 | 8,192 | 4,104 |
| 8,193 | 9,472 | 9,216 | 12,288 | 8,200 |
| 16,385 | 18,432 | 20,480 | 20,480 | 16,392 |
| 32,769 | 40,960 | 40,960 | 36,864 | 32,776 |
| 65,537 | 73,728 | 73,728 | 69,632 | 65,544 |
Go and TCMalloc agree exactly up to 2 KB, which is the ancestry showing. Above 4 KB they part: “diverged quite a bit”, as the comment says, and Go’s classes are generated by its own program with its own limit on waste. jemalloc rounds harder in the middle range, up to 4,097 → 8,192, and less hard for large objects, because it works in 4 KB pages rather than 8 KB ones.
glibc has no fixed set of classes in the way the others do, and its numbers look smallest for most requests. But they are not what it uses. Every glibc block carries an 8-byte header holding its size, and a block is the request plus that header, rounded up to a multiple of 16. A 17-byte request takes a 32-byte block, of which 24 are usable: exactly as much memory as Go’s 32-byte slot.
Two more points of comparison, from runtimes with collectors. CPython’s small-object allocator,
pymalloc, also uses size classes, every 8 bytes up to 512, in 4 KB pools. And the JVM and .NET do
something quite different: their collectors move objects, copying the survivors out of the space where new
objects are made, so that space is always one contiguous run. (Large objects and long-lived ones
are handled differently.) Allocation there is a bump pointer: each thread gets a
private buffer (a TLAB, in HotSpot’s terms) and allocating means adding the object’s size to a
pointer. There are no size classes, and an object takes exactly its size, rounded to 8 bytes (the
32-byte Java object of Part 2 was 16 bytes of fields, a 12-byte header and 4 of padding). Go cannot
do that, because its collector never moves anything, and why it does not is the subject of the next
part.
The tiny allocator
Go has one more trick, which TCMalloc does not. The smallest class is 8 bytes, but a program makes
enormous numbers of objects smaller than that, or not much bigger: a boxed int, a short string’s
bytes, a bool that escaped. So mallocgc has a special path for objects that are under 16 bytes
and contain no pointers:
if size <= maxSmallSize {
if noscan && size < maxTinySize {
// Tiny allocator.
//
// Tiny allocator combines several tiny allocation requests
// into a single memory block. The resulting memory block
// is freed when all subobjects are unreachable. The subobjects
// must be noscan (don't have pointers), this ensures that
// the amount of potentially wasted memory is bounded.
Each P keeps one 16-byte block open. A tiny request is placed at the next suitably aligned offset in
that block if it fits, and only when it does not is a new 16-byte block taken from the 16-byte class.
So two 8-byte integers share one block, and four 4-byte ones do. It cuts the memory of very small
objects by up to half or more, and it is why Part 2’s boxed integer showed 8 B/op rather than 16.
The comment states the catch: “The resulting memory block is freed when all subobjects are unreachable.” This program shows it, and contrasts it with an 8-byte object that holds a pointer, which is not allowed on the tiny path:
package main
import (
"fmt"
"runtime"
)
const n = 1 << 20
var ints []*int64 // 8-byte objects with no pointers in them: tiny allocator
var ptrs []**int64 // 8-byte objects that hold a pointer: size class 8, not tiny
func heap() (alloc, inuse uint64) {
runtime.GC()
var m runtime.MemStats
runtime.ReadMemStats(&m)
return m.HeapAlloc, m.HeapInuse
}
func report(what string, f func()) {
a0, i0 := heap()
f()
a1, i1 := heap()
fmt.Printf("%-34s HeapAlloc %+7.2f MB HeapInuse %+7.2f MB\n", what,
float64(int64(a1)-int64(a0))/(1<<20), float64(int64(i1)-int64(i0))/(1<<20))
}
func main() {
fmt.Println(runtime.Version())
report("1M new(int64), all kept", func() {
ints = make([]*int64, n)
for i := range ints {
ints[i] = new(int64)
}
})
report("drop every other one", func() {
for i := 0; i < n; i += 2 {
ints[i] = nil
}
})
report("drop all of them", func() { ints = nil })
report("1M new(*int64), all kept", func() {
ptrs = make([]**int64, n)
for i := range ptrs {
ptrs[i] = new(*int64)
}
})
report("drop every other one", func() {
for i := 0; i < n; i += 2 {
ptrs[i] = nil
}
})
report("drop all of them", func() { ptrs = nil })
}
$ go run tiny.go
go1.11.1
1M new(int64), all kept HeapAlloc +16.01 MB HeapInuse +15.98 MB
drop every other one HeapAlloc +0.00 MB HeapInuse +0.01 MB
drop all of them HeapAlloc -16.00 MB HeapInuse -15.98 MB
1M new(*int64), all kept HeapAlloc +16.00 MB HeapInuse +15.99 MB
drop every other one HeapAlloc -4.00 MB HeapInuse +0.00 MB
drop all of them HeapAlloc -12.00 MB HeapInuse -15.99 MB
HeapAlloc counts bytes in live objects (or, for the tiny allocator, live blocks). HeapInuse
counts bytes in spans that hold anything live. The million int64s took 8 MB (the other 8 MB of
each line is the slice of pointers to them), because they went into half a million 16-byte blocks,
two to a block. Dropping every other one freed nothing: each block lost one of its two integers
and kept the other, so every block was still reachable. Only dropping all of them freed the memory.
The pointer-holding objects cannot share blocks, so they took their own 8-byte slots, also 8 MB.
Dropping every other one freed 4 MB of objects, as it should. But HeapInuse did not move: every
8 KB span still held some live objects, half of its slots, so no span could go back to the heap. That
is external fragmentation at the level of spans, and it applies to every size class. Go’s collector
never moves objects to fill the gaps, so a span half full of survivors stays allocated until the
last of them dies.
So a program that allocates many small values and keeps a scattered fraction of them can hold far more memory than its live data suggests. The data the program can still reach may be a few kilobytes, scattered across megabytes of blocks and spans that cannot be given back.
Large objects, and freeing without free
An object over 32 KB never touches the mcache or the mcentral. largeAlloc asks the mheap directly for
a run of whole pages (5 pages, 40,960 bytes, for the 32,769-byte request), on the system stack and
under the mheap’s single lock. The mheap keeps its free page runs in two structures, declared at the
top of mheap.go:
free [_MaxMHeapList]mSpanList // free lists of given length up to _MaxMHeapList
freelarge mTreap // free treap of length >= _MaxMHeapList
_MaxMHeapList is 128 pages, 1 MB. A request for n pages first looks in the list of free runs of
exactly n pages, then n + 1, and so on up to 127; a run longer than needed is split and the rest
goes back on the list of its new length. Requests of 1 MB and more, or when the lists have nothing,
go to the treap, a balanced tree of the big free runs ordered by size, which finds the smallest run
that fits. Only when both fail does the heap grow, by asking the operating system for more.
The way memory comes back is the other half of the design comment at the top of malloc.go, the part
that describes sweeping:
// Sweeping an mspan and freeing objects on it proceeds up a similar
// hierarchy:
//
// 1. If the mspan is being swept in response to allocation, it
// is returned to the mcache to satisfy the allocation.
//
// 2. Otherwise, if the mspan still has allocated objects in it,
// it is placed on the mcentral free list for the mspan's size
// class.
//
// 3. Otherwise, if all objects in the mspan are free, the mspan
// is now "idle", so it is returned to the mheap and no longer
// has a size class.
// This may coalesce it with adjacent idle mspans.
//
// 4. If an mspan remains idle for long enough, return its pages
// to the operating system.
A Go program never frees anything itself. After each collection, every span is marked as needing a sweep. Sweeping a span means looking at the mark bits the collector just set, one per slot, and treating every slot that was not marked as free: the span’s new allocation bitmap is simply its mark bitmap. No object is visited and nothing is written into the freed slots, which is why a reused slot has to be cleared when it is handed out again. A span is swept either by a background goroutine or, lazily, by whichever goroutine next needs a span of that class, so the cost of freeing is spread over later allocations.
Step 3 is where the tiny allocator’s leftover integers and the half-empty spans above come in. A span becomes idle, and its pages free for any other size class, only when every slot in it is free. One surviving object holds the whole span. Step 4 is how memory finally leaves the process, and it has its own story, for another part of this series.
What it costs
go test -bench gives the cost of an allocation by size. Each benchmark allocates a byte slice
(stored in a global, or, in the parallel runs, made with a size the compiler does not know), so it is
heap-allocated and becomes garbage at the next iteration. The serial
runs use one goroutine and the parallel ones all 24 hardware threads:
package cost
import (
"fmt"
"testing"
)
var sink []byte
func BenchmarkAlloc(b *testing.B) {
for _, size := range []int{16, 64, 256, 1024, 4096, 16384, 32768, 32769, 65536, 1 << 20} {
b.Run(fmt.Sprintf("serial/%d", size), func(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = make([]byte, size)
}
})
b.Run(fmt.Sprintf("parallel/%d", size), func(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
var local []byte
for pb.Next() {
local = make([]byte, size)
}
_ = local
})
})
}
}
Medians of five runs on Go 1.11.1, in nanoseconds per allocation (for the parallel runs, wall-clock time divided by all the allocations made by all the threads):
| Size | serial | parallel, 24 threads |
|---|---|---|
| 16 B | 8.34 | 2.95 |
| 64 B | 13.1 | 11.4 |
| 256 B | 34.6 | 46.7 |
| 1 KB | 130 | 180 |
| 4 KB | 547 | 722 |
| 16 KB | 1,761 | 1,654 |
| 32 KB | 2,953 | 1,894 |
| 32 KB + 1 | 3,496 | 2,140 |
| 64 KB | 5,302 | 2,538 |
| 1 MB | 48,777 | 26,376 |
These are not the cost of finding a slot. They include zeroing recycled memory, which Go always does, and the garbage collector’s work, which every allocation of garbage brings closer. From 256 bytes to 4 KB the serial cost is almost exactly proportional to the size, about 0.13 ns a byte, which says the bytes are what cost, not the bookkeeping. Above that it grows more slowly, down to 0.05 ns a byte at a megabyte. One byte past 32 KB costs 18% more than 32 KB exactly: it leaves the size classes for the large-object path, and is rounded up to 40,960 bytes.
The parallel column is the surprise. Twenty-four threads allocating 256-byte to 4 KB objects got less done in total than one thread did, and even the best case, 16 bytes, was only 2.8 times faster than one thread. There are three candidates, and I did not profile to tell them apart. The per-P caches avoid locks only while a span has free slots: a 4 KB span holds two 4 KB objects and a 1 KB span eight, so those sizes go back to a locked mcentral every few allocations, and large objects take the mheap’s lock every time. All the threads are also making garbage as fast as they can, for one collector to clean up, and all of them share one memory bus to zero what they allocate. Whichever it is, allocating heavily on every core at once does not scale, which is reason enough to make the allocations unnecessary, as Part 2 showed how to do.
Go 1.11: where the heap lives
Go 1.11, released on 24 August, has one line about memory in its release notes:
The runtime now uses a sparse heap layout so there is no longer a limit to the size of the Go heap (previously, the limit was 512GiB). This also fixes rare “address space conflict” failures in mixed Go/C binaries or binaries compiled with -race.
To see what that means, start with Go 1.10’s layout. At start-up, mallocinit laid out one region of
address space at 0xc000000000 for everything the heap would ever need: a table of span pointers
(512 MB), the collector’s bitmap (16 GB), and then the heap arena itself (512 GB). The arena began
where the bitmap ended, at 0xc000000000 + 512 MB + 16 GB, which is 0xc420000000. That is why
every heap and stack address in the first two parts of this series began with 0xc420.
But Go 1.10 did not really reserve those 528 GB. From src/runtime/mem_linux.go:
func sysReserve(v unsafe.Pointer, n uintptr, reserved *bool) unsafe.Pointer {
// On 64-bit, people with ulimit -v set complain if we reserve too
// much address space. Instead, assume that the reservation is okay
// if we can reserve at least 64K and check the assumption in SysMap.
// Only user-mode Linux (UML) rejects these requests.
if sys.PtrSize == 8 && uint64(n) > 1<<32 {
p, err := mmap_fixed(v, 64<<10, _PROT_NONE, _MAP_ANON|_MAP_PRIVATE, -1, 0)
if p != v || err != 0 {
if err == 0 {
munmap(p, 64<<10)
}
return nil
}
munmap(p, 64<<10)
*reserved = false
return v
}
It checked that the first 64 KB were free, gave them back, and assumed the rest would stay free.
Every time the heap grew, sysMap asked the kernel for the next piece at exactly the next address,
and if the kernel put it anywhere else, because something else was already there, Go gave up:
if p != v || err != 0 {
print("runtime: address space conflict: map(", v, ") = ", p, " (err ", err, ")\n")
throw("runtime: address space conflict")
}
In a pure Go program nothing else maps memory there. In a program that links C code through cgo,
anything can: a C library’s mmap, a thread stack, a memory-mapped file. This program does it on
purpose, with one ordinary C mapping 256 MB above where each version’s heap starts:
package main
/*
#include <stdint.h>
#include <sys/mman.h>
// Map 64 KB at the requested address, if it is free. No MAP_FIXED:
// this is an ordinary C mapping that happens to land where asked.
static void *grab(uintptr_t at) {
return mmap((void *)at, 1 << 16, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
*/
import "C"
import (
"fmt"
"runtime"
)
var keep [][]byte
func main() {
fmt.Println(runtime.Version())
// One mapping 256 MB above where Go 1.10's heap starts, one 256 MB
// above where Go 1.11's starts.
for _, at := range []uintptr{0xc430000000, 0xc010000000} {
fmt.Printf("C mapped 64 KB at %p\n", C.grab(C.uintptr_t(at)))
}
for i := 1; i <= 8; i++ {
keep = append(keep, make([]byte, 64<<20))
fmt.Printf("heap holds %d MB, the last block at %p\n", i*64, &keep[i-1][0])
}
}
On Go 1.10.4:
$ go build -o conflict-1.10.4 conflict.go && ./conflict-1.10.4
go1.10.4
C mapped 64 KB at 0xc430000000
C mapped 64 KB at 0xc010000000
heap holds 64 MB, the last block at 0xc4200d2000
heap holds 128 MB, the last block at 0xc424122000
heap holds 192 MB, the last block at 0xc428122000
runtime: address space conflict: map(0xc42c200000) = 0x7e8084000000 (err 0)
fatal error: runtime: address space conflict
runtime stack:
runtime.throw(0x4b8ed1, 0x1f)
/opt/go/1.10.4/src/runtime/panic.go:616 +0x81
runtime.sysMap(0xc42c200000, 0x4000000, 0x41e000, 0x748f38)
/opt/go/1.10.4/src/runtime/mem_linux.go:220 +0x1ef
...
The heap grew upwards from 0xc420000000 in 64 MB steps until the next step would have overlapped
the C mapping at 0xc430000000. The kernel, asked for 0xc42c200000, placed the memory at
0x7e8084000000 instead, and the runtime, which needed its heap contiguous, died. Nothing in the
error mentions C.
On Go 1.11.1, the same program:
$ go build -o conflict-1.11.1 conflict.go && ./conflict-1.11.1
go1.11.1
C mapped 64 KB at 0xc430000000
C mapped 64 KB at 0xc010000000
heap holds 64 MB, the last block at 0xc0000aa000
heap holds 128 MB, the last block at 0xc004106000
heap holds 192 MB, the last block at 0xc00810e000
heap holds 256 MB, the last block at 0x1c000000000
heap holds 320 MB, the last block at 0x1c004000000
heap holds 384 MB, the last block at 0x1c008000000
heap holds 448 MB, the last block at 0x1c00c000000
heap holds 512 MB, the last block at 0x1c010000000
The heap starts lower, at 0xc000000000, and when it reaches the C mapping at 0xc010000000 it
simply carries on somewhere else, at 0x1c000000000, and the program finishes. The new layout is
described in a comment in 1.11’s malloc.go:
// The heap consists of a set of arenas, which are 64MB on 64-bit and
// 4MB on 32-bit (heapArenaBytes). Each arena's start address is also
// aligned to the arena size.
//
// Each arena has an associated heapArena object that stores the
// metadata for that arena: the heap bitmap for all words in the arena
// and the span map for all pages in the arena. heapArena objects are
// themselves allocated off-heap.
//
// Since arenas are aligned, the address space can be viewed as a
// series of arena frames. The arena map (mheap_.arenas) maps from
// arena frame number to *heapArena, or nil for parts of the address
// space not backed by the Go heap. The arena map is structured as a
// two-level array consisting of a "L1" arena map and many "L2" arena
// maps; however, since arenas are large, on many architectures, the
// arena map consists of a single, large L2 map.
//
// The arena map covers the entire possible address space, allowing
// the Go heap to use any part of the address space. The allocator
// attempts to keep arenas contiguous so that large spans (and hence
// large objects) can cross arenas.
The same cgo program on two releases
Each step allocates 64 MB more. The C program mapped 64 KB at each copper mark first.
The heap is now a set of independent 64 MB arenas, each carrying its own metadata, wherever the kernel can place them. To find the arena for any address, the runtime divides the address by 64 MB and looks the quotient up in the arena map. With 48-bit addresses on amd64 there are 2²² possible arenas, so the map is an array of 4,194,304 pointers, 32 MB, mapped at start-up and almost entirely never touched, since only the entries for arenas in use are ever written. So a small Go program has a larger virtual size on 1.11 than on 1.10, with the same resident memory:
package main
import (
"fmt"
"io/ioutil"
"runtime"
"strings"
)
var keep [][]byte
func main() {
fmt.Println(runtime.Version())
for i := 0; i < 64; i++ {
keep = append(keep, make([]byte, 1<<20)) // 64 MB of heap
}
b, _ := ioutil.ReadFile("/proc/self/status")
for _, l := range strings.Split(string(b), "\n") {
if strings.HasPrefix(l, "VmSize") || strings.HasPrefix(l, "VmRSS") {
fmt.Println(l)
}
}
m, _ := ioutil.ReadFile("/proc/self/maps")
fmt.Print(string(m))
}
$ ./maps-1.10.4 | head -3
go1.10.4
VmSize: 73752 kB
VmRSS: 4532 kB
$ ./maps-1.11.1 | head -3
go1.11.1
VmSize: 172464 kB
VmRSS: 4576 kB
(The resident size is small because the 64 MB of slices were never written: fresh memory from the
kernel is already zero, so the runtime does not clear it.) In the rest of the output, the maps, the
1.10 heap is one mapping of about 68 MB from 0xc41fdf0000 to 0xc424200000: 66 MB of arena from
0xc420000000, plus the part of the bitmap just below it, which grows downwards. The 1.11 heap is
two whole 64 MB arenas from 0xc000000000, and a separate 38 MB mapping holds the arena map and the
arenas’ metadata.
The address space is not reserved up front any more, so nothing can conflict with it, and nothing limits the heap to 512 GB. The price is one extra lookup whenever the runtime needs an object’s metadata: the arena map first, then the arena.
What this means for Go code
Struct sizes have thresholds. An object costs its size class, not its size. A struct of 33 bytes costs as much as one of 48. When a type is allocated by the million, its size relative to the class boundaries (8, 16, 32, 48, 64, 80, 96, 112, 128…) matters more than its exact size.
Small, scattered survivors keep memory alive. A tiny block lives as long as any value in it, and a span lives as long as any object in it. Keeping a few values from a large batch of small allocations can keep most of the batch’s memory allocated. Copying the survivors into a fresh slice, and dropping the batch, lets the whole batch go.
Allocation costs bytes. Beyond a few hundred bytes, the cost of an allocation is roughly the cost of zeroing it plus the collection it brings on, and heavy allocation on many cores at once scaled badly here.
cgo programs should be on Go 1.11. The address-space conflict is rare, but it is fatal, and it depends on where C code happens to put its memory, which is not something a Go programmer controls.
A note on the evidence
What ran. Go 1.11.1 and Go 1.10.4 (go1.11.1.linux-amd64.tar.gz and
go1.10.4.linux-amd64.tar.gz, each checked against its published SHA-256), released on 1 October and
24 August 2018, on an Ubuntu 18.04 userland as released: glibc 2.27, gcc 7.3.0, and from its release
pocket libtcmalloc-minimal4 2.5 (gperftools) and libjemalloc1 3.6.0. Everything ran in a chroot
on a 24-thread x86-64 machine under the host’s Linux kernel. The address-space results depend on
where that kernel places mappings, and the 64-bit virtual address layout it gives a process.
What was measured. The size and tiny-allocator figures are from single runs, and they are counts,
not timings: they came out the same on both Go releases. The allocation costs are medians of five
runs of each benchmark in one sitting with nothing else running. The cgo program ran once on each
release; the crash and the relocation are deterministic given the C mappings, and the addresses are
the ones it printed. Every program was then extracted from this page and compared byte for byte with
the code that ran, and all but the benchmark were run again. The counts repeated. The addresses inside
the first arena moved by a few pages, the kernel put 1.10’s displaced mapping somewhere else
(0x7d1e68000000), 1.11’s virtual size came out 256 KB smaller, and the arena addresses and the
point of the crash did not change.
What is quoted. All runtime source is from the go1.11.1 and go1.10.4 tags (malloc.go,
sizeclasses.go, mem_linux.go, mheap.go); the size classes are identical in both. The release
note is from doc/go1.11.html at the go1.11.1 tag. pymalloc’s classes are from CPython 3.6’s
Objects/obmalloc.c (8-byte alignment, a 512-byte threshold, 4 KB pools).
What is not explained. Why 24 allocating threads achieve less than one for mid-sized objects is reported as measured, not diagnosed: the collector and memory bandwidth are the likely limits, and I did not profile to tell them apart.
The Allocator Under Every new