← Writing

Stopping a Goroutine Anywhere

33 min readSystemsGORuntimeSchedulerGcPreemption
Contents

A Go 1.13 program starts a goroutine that runs a tight arithmetic loop for about a second, a loop that calls no functions. Then another goroutine asks for a garbage collection. The collection waits 1.1 seconds before it can begin, and so does everything else in the program that needs the world stopped. On one processor it is worse: a goroutine that sleeps for 10 milliseconds wakes up 1.15 seconds later. The loop is doing nothing wrong. It simply never reaches a point where the runtime is able to ask it to stop. Go 1.14, released last month, changes that: the same collection now starts within a millisecond, because the runtime has learned to interrupt a goroutine at almost any instruction, by sending its thread a signal.

This post is about how a Go runtime gets a running goroutine to stop, and why it has to. It starts with the way Go has always done it, through the stack check at the top of every function that Part 1 of this series took apart, shows the one case where that fails, and then looks at Go 1.14’s asynchronous preemption: the signal it uses, what it does in the thread it lands in, and what it costs. Java and Erlang solve the same problem in two quite different ways, and both are measured. The post ends with two other 1.14 changes that touch the stack and the heap: defer, which now compiles to almost nothing, and a new page allocator.

This is Part 6 of a series on how Go manages the stack and the heap. Part 1 showed the stack check and its stackPreempt value, and Part 4 the collector’s stops of the world. It is written for Go programmers who have used goroutines. Everything here ran on Go 1.14.1 and Go 1.13.9, both released on 19 March, on an Ubuntu 18.04 userland, with OpenJDK 11 and Erlang/OTP 20 for the comparisons. The note at the end says what was measured and how.

Why a runtime needs to stop a goroutine

This section is the background. If you know what a safe point is, skip it.

There are two reasons a Go runtime needs a running goroutine to stop.

The first is scheduling. Go runs many goroutines on a few operating-system threads, one goroutine at a time on each of GOMAXPROCS processors. If a goroutine never gives its processor up, the goroutines waiting for that processor never run. The operating system cannot help: it preempts threads, but the thread is running the Go scheduler’s choice of goroutine, and the kernel has no idea there are others waiting.

The second is the garbage collector. Part 4 showed that each cycle stops the world twice, briefly, and that marking scans every goroutine’s stack. To scan a stack precisely, the collector needs to know which words in each frame are pointers, and that information, the stack maps of Part 1, exists only at particular points in the code. So the collector cannot just freeze a thread wherever it happens to be. It has to ask each goroutine to stop at a point where its stack can be read, and wait until it does.

A point where a goroutine can be stopped and its state fully understood is called a safe point. The question is how to get a running goroutine to one, quickly, without slowing it down the rest of the time. There are two broad answers. Cooperative preemption puts checks into the compiled code, and the goroutine stops itself when a check finds that someone asked. Asynchronous preemption interrupts the goroutine from outside, wherever it is, and works out after the fact whether that place is safe.

How Go stopped a goroutine before 1.14

Part 1 showed the check that every Go function starts with: compare the stack pointer with g.stackguard0, and call morestack if the stack is too small. It also showed the constant that makes that check do double duty:

	// Goroutine preemption request.
	// Stored into g->stackguard0 to cause split stack check failure.
	// Must be greater than any real sp.
	// 0xfffffade in hex.
	stackPreempt = uintptrMask & -1314

To preempt a goroutine, the runtime stores stackPreempt into its stackguard0. The next time the goroutine calls a function, the stack check fails, morestack runs, notices that the stack is fine and the request was a preemption, and hands the processor to the scheduler. It costs nothing extra, because the check is there anyway. The runtime’s background monitor thread, sysmon, makes the request for any goroutine that has been running for more than a time slice, set in proc.go:

const forcePreemptNS = 10 * 1000 * 1000 // 10ms

and the collector makes the same request of every goroutine when it needs to stop the world.

The flaw is in “the next time the goroutine calls a function”. A loop that calls nothing never runs a function prologue, so it never sees the request. Here is one:

package main

import (
	"fmt"
	"os"
	"runtime"
	"time"
)

var sink int

// spin runs a loop with no function calls in it, so it never reaches a
// function prologue and never checks for a preemption request there.
//go:noinline
func spin(n int) int {
	s := 0
	for i := 0; i < n; i++ {
		s += i ^ (s >> 3)
	}
	return s
}

func main() {
	const n = 2000000000
	name := runtime.Version() + os.Getenv("TAG")

	// 1. One processor: a goroutine spins; how late does a 10 ms sleep end?
	runtime.GOMAXPROCS(1)
	t := time.Now()
	go func() { sink = spin(n) }()
	time.Sleep(10 * time.Millisecond) // the spinner gets the only processor
	fmt.Printf("%-28s GOMAXPROCS=1: 10 ms sleep took %8.1f ms\n", name, float64(time.Since(t).Microseconds())/1000)

	// 2. Four processors: a goroutine spins; how long does a collection wait?
	runtime.GOMAXPROCS(4)
	time.Sleep(3 * time.Second) // let the first spinner finish
	go func() { sink = spin(n) }()
	time.Sleep(10 * time.Millisecond)
	t = time.Now()
	runtime.GC()
	fmt.Printf("%-28s GOMAXPROCS=4: runtime.GC() took %8.1f ms\n", name, float64(time.Since(t).Microseconds())/1000)
}

Two billion iterations take this machine about 1.1 seconds. The first test gives the spinner the only processor and then sleeps for 10 ms. The second gives the program four processors, starts a spinner, and asks for a collection. Three runs on Go 1.13.9:

$ go build -o spin-1.13.9 spin.go && for r in 1 2 3; do ./spin-1.13.9; done
go1.13.9                     GOMAXPROCS=1: 10 ms sleep took   1151.0 ms
go1.13.9                     GOMAXPROCS=4: runtime.GC() took   1144.8 ms
go1.13.9                     GOMAXPROCS=1: 10 ms sleep took   1138.1 ms
go1.13.9                     GOMAXPROCS=4: runtime.GC() took   1126.9 ms
go1.13.9                     GOMAXPROCS=1: 10 ms sleep took   1152.4 ms
go1.13.9                     GOMAXPROCS=4: runtime.GC() took   1122.7 ms

On one processor, the sleeping goroutine’s timer fired after 10 ms, but there was nothing to run it on: the spinner held the processor and sysmon’s request went unanswered for 1.1 seconds, the whole life of the loop. On four processors there were three idle processors, and it made no difference. A collection has to stop every goroutine before it begins, so it waited for the one that could not be stopped, and for those 1.1 seconds every other goroutine that needed the collection, or allocated enough to need its help, waited with it.

Notice what did not hold the collection up: goroutines that were asleep, blocked on a channel, or waiting in a system call. Those are stopped already, as far as the collector is concerned. A goroutine that is blocked has saved its state at a point where its stack maps are exact, and one in a system call or in C code called through cgo has left Go code entirely: the runtime treats the call as a stop and scans the Go frames beneath it, while the thread goes on running the C. So C code that runs for a second never delays a collection, even before 1.14. Only a goroutine running Go code can, and only if that code never reaches a check.

Loops like this are rare in ordinary Go code, which calls functions constantly. They are not rare in the code that matters most for speed: a checksum, a hash, a decoder, a numerical kernel, a hand-unrolled search, anything the compiler inlined into a single loop. And the stall is invisible in a profile, which shows only the loop working hard.

Asynchronous preemption

Go 1.14’s release notes describe the change in two sentences: “Goroutines are now asynchronously preemptible. As a result, loops without function calls no longer potentially deadlock the scheduler or significantly delay garbage collection.” The design is in a comment at the top of the new src/runtime/preempt.go:

// A goroutine can be preempted at any safe-point. Currently, there
// are a few categories of safe-points:
//
// 1. A blocked safe-point occurs for the duration that a goroutine is
//    descheduled, blocked on synchronization, or in a system call.
//
// 2. Synchronous safe-points occur when a running goroutine checks
//    for a preemption request.
//
// 3. Asynchronous safe-points occur at any instruction in user code
//    where the goroutine can be safely paused and a conservative
//    stack and register scan can find stack roots. The runtime can
//    stop a goroutine at an async safe-point using a signal.

and, further down:

// Preemption at asynchronous safe-points is implemented by suspending
// the thread using an OS mechanism (e.g., signals) and inspecting its
// state to determine if the goroutine was at an asynchronous
// safe-point. Since the thread suspension itself is generally
// asynchronous, it also checks if the running goroutine wants to be
// preempted, since this could have changed. If all conditions are
// satisfied, it adjusts the signal context to make it look like the
// signaled thread just called asyncPreempt and resumes the thread.
// asyncPreempt spills all registers and enters the scheduler.

So the old mechanism stays, and the new one is added on top. preemptone, which sysmon and the collector call for each goroutine they want stopped, now does both:

	gp.preempt = true

	// Every call in a go routine checks for stack overflow by
	// comparing the current stack pointer to gp->stackguard0.
	// Setting gp->stackguard0 to StackPreempt folds
	// preemption into the normal stack overflow check.
	gp.stackguard0 = stackPreempt

	// Request an async preemption of this P.
	if preemptMSupported && debug.asyncpreemptoff == 0 {
		_p_.preempt = true
		preemptM(mp)
	}

preemptM sends a signal to the thread running the goroutine. The signal handler looks at where the thread was interrupted. If that instruction is an asynchronous safe point, it rewrites the saved registers so that, when the handler returns, the thread looks as if it had just called the function asyncPreempt. That function saves every register on the goroutine’s stack and calls into the scheduler, like a function call the goroutine never made. When the goroutine is scheduled again, it restores the registers and carries on from the interrupted instruction.

The difficulty is in “a conservative stack and register scan”. At an arbitrary instruction there is no stack map telling the collector which registers and which slots of the innermost frame hold pointers. So for that one frame the collector treats every word that looks like a pointer into the heap as if it were one. It may keep a little garbage alive for one more cycle, and nothing is ever freed while still in use. Every frame further down the stack is paused at a call, where the stack maps are exact. Part 1 noted that Go’s collector became precise for stacks in Go 1.3; since 1.14 it is precise everywhere except the top frame of a goroutine stopped by a signal. Some instructions are still not safe, such as the middle of a write-barrier sequence (Part 4) or runtime code that must not be interrupted. A signal that lands there is simply ignored, and the runtime tries again later.

The signal is SIGURG, chosen by a process of elimination that src/runtime/signal_unix.go sets out in full:

// There's no good way to choose this signal, but there are some
// heuristics:
//
// 1. It should be a signal that's passed-through by debuggers by
// default. On Linux, this is SIGALRM, SIGURG, SIGCHLD, SIGIO,
// SIGVTALRM, SIGPROF, and SIGWINCH, plus some glibc-internal signals.
//
// 2. It shouldn't be used internally by libc in mixed Go/C binaries
// because libc may assume it's the only thing that can handle these
// signals. For example SIGCANCEL or SIGSETXID.
//
// 3. It should be a signal that can happen spuriously without
// consequences. For example, SIGALRM is a bad choice because the
// signal handler can't tell if it was caused by the real process
// alarm or not (arguably this means the signal is broken, but I
// digress). SIGUSR1 and SIGUSR2 are also bad because those are often
// used in meaningful ways by applications.
//
// 4. We need to deal with platforms without real-time signals (like
// macOS), so those are out.
//
// We use SIGURG because it meets all of these criteria, is extremely
// unlikely to be used by an application for its "real" meaning (both
// because out-of-band data is basically unused and because SIGURG
// doesn't report which socket has the condition, making it pretty
// useless), and even if it is, the application has to be ready for
// spurious SIGURG. SIGIO wouldn't be a bad choice either, but is more
// likely to be used for real.
const sigPreempt = _SIGURG

The same program on Go 1.14.1, and again with the new mechanism switched off with GODEBUG=asyncpreemptoff=1:

$ go build -o spin-1.14.1 spin.go
$ for r in 1 2 3; do ./spin-1.14.1; TAG=" asyncpreemptoff=1" GODEBUG=asyncpreemptoff=1 ./spin-1.14.1; done
go1.14.1                     GOMAXPROCS=1: 10 ms sleep took     14.6 ms
go1.14.1                     GOMAXPROCS=4: runtime.GC() took      0.7 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=1: 10 ms sleep took   1162.5 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=4: runtime.GC() took   1128.3 ms
go1.14.1                     GOMAXPROCS=1: 10 ms sleep took     15.2 ms
go1.14.1                     GOMAXPROCS=4: runtime.GC() took      0.5 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=1: 10 ms sleep took   1133.9 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=4: runtime.GC() took   1138.4 ms
go1.14.1                     GOMAXPROCS=1: 10 ms sleep took     15.2 ms
go1.14.1                     GOMAXPROCS=4: runtime.GC() took      0.8 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=1: 10 ms sleep took   1136.9 ms
go1.14.1 asyncpreemptoff=1   GOMAXPROCS=4: runtime.GC() took   1135.6 ms

The collection that waited 1.1 seconds now takes under a millisecond: the collector signals the spinning thread, the thread steps into the scheduler at the next instruction, and the cycle starts. The 10 ms sleep ends after about 15 ms, and the extra 5 is sysmon’s doing. Nobody asked for the spinner to stop there; the only reason it was stopped is that it had used up its time slice. sysmon is a thread of its own, outside the scheduler, which wakes up, looks at every processor, and goes back to sleep, and in 1.14 it sleeps on a sliding scale:

		if idle == 0 { // start with 20us sleep...
			delay = 20
		} else if idle > 50 { // start doubling the sleep after 1ms...
			delay *= 2
		}
		if delay > 10*1000 { // up to 10ms
			delay = 10 * 1000
		}
		usleep(delay)

It starts by checking every 20 microseconds and, once a millisecond has passed with nothing to do, doubles the interval each time up to 10 ms. On one of those checks it finds that the spinner’s processor has run the same goroutine for more than forcePreemptNS, and calls preemptone. So the spinner cannot be stopped before 10 ms, and is stopped at the first check after that. This program is young when it happens, and sysmon is still lengthening its sleeps, which is presumably why the answer was the same 15 ms in every run; I did not trace sysmon itself to confirm it. The collection in the second test does not wait for sysmon. It calls preemptone itself for every running goroutine the moment it wants the world stopped, which is why it took under a millisecond.

One more 1.14 change sits under the first test, in the timer that ends the sleep. The release notes: “Internal timers, used by time.After, time.Tick, net.Conn.SetDeadline, and friends, are more efficient, with less lock contention and fewer context switches. This is a performance improvement that should not cause any user visible changes.” The test above measures when the sleeping goroutine woke, not when its timer fired, so it cannot separate the two changes; on one processor held by a spinner, neither the timer nor the goroutine can run until the spinner is stopped. A program that sleeps or sets deadlines on a busy machine is exercising both changes at once, and should not credit the whole improvement to one of them. And with asyncpreemptoff=1, 1.14 behaved like 1.13 in both tests, which is what the setting is for: a way back if the signals cause a problem.

How long a loop with no function calls holds the runtime off

Milliseconds, log scale, median of three runs. The loop runs for about 1.1 seconds.

got control back while the loop ranwaited for the loop to end

A 10 ms sleep on one processor, with the loop running

Go 1.13.9
1,151 ms
Go 1.14.1
15.2 ms
Go 1.14.1 asyncpreemptoff=1
1,137 ms
Erlang/OTP 20, 1 scheduler
10.6 ms

Stopping every thread for a collection, with the loop running

Go 1.13.9
1,127 ms
Go 1.14.1
0.7 ms
Go 1.14.1 asyncpreemptoff=1
1,136 ms
Java 11, Parallel
1,228 ms
Java 11, G1
1,231 ms
Java 11, Parallel + counted-loop safepoints
6.1 ms

Hover or focus a row for all three runs.

Catching a preemption in the act

The spinner’s machine code shows why the old mechanism could never reach it. On Go 1.14.1:

$ go tool objdump -s 'main\.spin$' spin-1.14.1
TEXT main.spin(SB) /work/go-p6/spin.go
  spin.go:17		0x49c2b0		488b442408		MOVQ 0x8(SP), AX
  spin.go:17		0x49c2b5		31c9			XORL CX, CX
  spin.go:17		0x49c2b7		31d2			XORL DX, DX
  spin.go:17		0x49c2b9		eb15			JMP 0x49c2d0
  spin.go:17		0x49c2bb		488d5901		LEAQ 0x1(CX), BX
  spin.go:18		0x49c2bf		4889d6			MOVQ DX, SI
  spin.go:18		0x49c2c2		48c1fa03		SARQ $0x3, DX
  spin.go:18		0x49c2c6		4831d1			XORQ DX, CX
  spin.go:18		0x49c2c9		488d1431		LEAQ 0(CX)(SI*1), DX
  spin.go:17		0x49c2cd		4889d9			MOVQ BX, CX
  spin.go:17		0x49c2d0		4839c1			CMPQ AX, CX
  spin.go:17		0x49c2d3		7ce6			JL 0x49c2bb
  spin.go:20		0x49c2d5		4889542410		MOVQ DX, 0x10(SP)
  spin.go:20		0x49c2da		c3			RET

Fourteen instructions, and the loop is the eight from 0x49c2bb to 0x49c2d3: registers only, no call, no memory access, no check. The function has no prologue at all. It calls nothing and needs no frame, so it is one of the NOSPLIT leaves of Part 1, and the stack check that cooperative preemption depends on is not even in the function, let alone in the loop.

So where does a signal stop it? This program runs the spinner on the only processor and lets main sleep. On 1.14 main gets the processor back while the spinner is still in its loop, and it then panics on purpose, with the traceback set to show every goroutine and the runtime’s own frames:

package main

import (
	"runtime"
	"runtime/debug"
	"time"
)

var sink int

//go:noinline
func spin(n int) int {
	s := 0
	for i := 0; i < n; i++ {
		s += i ^ (s >> 3)
	}
	return s
}

// With one processor, main can only run again if the spinner is
// preempted. When it does, it crashes on purpose, and the traceback
// shows where the spinner was stopped.
func main() {
	runtime.GOMAXPROCS(1)
	go func() { sink = spin(2000000000) }()
	time.Sleep(10 * time.Millisecond)
	debug.SetTraceback("system") // all goroutines, runtime frames included
	panic("main ran while the spinner was still spinning")
}

The spinner’s goroutine in the Go 1.14.1 traceback:

goroutine 5 [runnable]:
runtime.asyncPreempt2()
	/opt/go/1.14.1/src/runtime/preempt.go:308 +0x62 fp=0xc00005e630 sp=0xc00005e610 pc=0x42d0c2
runtime.asyncPreempt()
	/opt/go/1.14.1/src/runtime/preempt_amd64.s:50 +0xdb fp=0xc00005e7b8 sp=0xc00005e630 pc=0x45836b
main.spin(0x77359400, 0x0)
	/work/go-p6/caught.go:15 +0x19 fp=0xc00005e7c0 sp=0xc00005e7b8 pc=0x465b99
main.main.func1()
	/work/go-p6/caught.go:25 +0x2a fp=0xc00005e7e0 sp=0xc00005e7c0 pc=0x465c6a
runtime.goexit()
	/opt/go/1.14.1/src/runtime/asm_amd64.s:1373 +0x1 fp=0xc00005e7e8 sp=0xc00005e7e0 pc=0x456a41
created by main.main
	/work/go-p6/caught.go:25 +0x42

Read from the bottom up. The goroutine is in main.spin, called with 0x77359400, two billion, 0x19 bytes into the function: inside the loop. And on top of main.spin is a call it never made: runtime.asyncPreempt, exactly as the comment in preempt.go describes. The signal handler rewrote the thread’s state so that it looks as if spin had called asyncPreempt at that instruction. The frame asyncPreempt built is 0x188 bytes, 392 (from sp=0xc00005e630 to fp=0xc00005e7b8), which is where it saved every register of the interrupted loop. asyncPreempt2 then parked the goroutine, and it stays runnable, ready to return through asyncPreempt, restore the registers and carry on at +0x19 as if nothing had happened.

The same program on Go 1.13.9, with debug.SetTraceback("all") in an earlier run:

goroutine 6 [runnable]:
runtime.goexit1()
	/opt/go/1.13.9/src/runtime/proc.go:2657 +0x6b
runtime.goexit()
	/opt/go/1.13.9/src/runtime/asm_amd64.s:1358 +0x6
created by main.main
	/work/go-p6/caught.go:25 +0x42

There main got the processor back only when the spinner had finished: its goroutine is already on its way out, in goexit1. (The panic message is untrue on 1.13, which is the point.)

How many signals does this cost? strace can count the ones the first program receives, across both of its tests:

$ for v in 1.13.9 1.14.1; do strace -f -e trace=none -o sig-$v.txt ./spin-$v > /dev/null; echo "$v: SIGURG received $(grep -c 'SIGURG' sig-$v.txt), all signals $(grep -c -- '--- SIG' sig-$v.txt)"; done
1.13.9: SIGURG received 0, all signals 0
1.14.1: SIGURG received 62, all signals 62
$ grep -m2 SIGURG sig-1.14.1.txt
730   --- SIGURG {si_signo=SIGURG, si_code=SI_TKILL, si_pid=730, si_uid=0} ---
730   --- SIGURG {si_signo=SIGURG, si_code=SI_TKILL, si_pid=730, si_uid=0} ---

Sixty-two signals in a program that ran for about three seconds, each one SI_TKILL: sent by the process to one of its own threads with tgkill. They come when something needs a goroutine stopped: a time slice running out, or a collection starting. Here most of them were sysmon stopping the spinners at the end of each time slice, so the count grows with how long goroutines run without yielding: roughly one every 10 to 20 ms for each of them. The program built with 1.13 received none. Each of those 62 is a moment when a system call on the receiving thread could have been interrupted, which is where the EINTR warning below comes from.

Those signals can cause problems of their own, and the release notes warn about one: “programs built with Go 1.14 will receive more signals than programs built with earlier releases. This means that programs that use packages like syscall or golang.org/x/sys/unix will see more slow system calls fail with EINTR errors.” The runtime installs its handlers with SA_RESTART, so the kernel restarts most interrupted system calls, an ordinary read from a pipe among them, without the program noticing. But some calls are never restarted, whatever the flag: waits with a timeout, such as nanosleep, poll, select and epoll_wait (the list is in man 7 signal). If a signal arrives while a thread is in one of those, the call returns the error EINTR instead of a result. The standard library’s own wrappers retry, but a program making raw system calls through syscall, or C code called through cgo, sees the error and has to retry itself. C libraries that never expected a signal can fail the same way. The fix is the same loop C programmers have always written around such calls:

for {
	n, err := syscall.EpollWait(epfd, events, -1)
	if err == syscall.EINTR {
		continue // interrupted by a signal before any event arrived: wait again
	}
	// handle n and err
	break
}

That is the cost of being able to stop a goroutine anywhere: the runtime now sends signals to its own threads routinely, and anything running on those threads has to put up with them.

The same problem in Java and Erlang

Java has the same problem and has had it for twenty years. HotSpot stops threads for its collector at safepoints, and its JIT compiler puts a safepoint poll, a load from a page the JVM can make unreadable, into compiled code at method returns and loop back-edges. When it wants to stop the world, it protects the page, and each thread faults at its next poll and stops. But a poll on every iteration of a tight loop costs time, so C2, the optimising compiler, leaves the poll out of counted loops, loops over an int with a known bound, on the theory that they finish quickly. A counted loop of two billion iterations does not.

The same loop in Java:

public class Spin {
    static int sink;

    // A counted int loop with no calls in it.
    static int spin(int n) {
        int s = 0;
        for (int i = 0; i < n; i++) {
            s += i ^ (s >> 3);
        }
        return s;
    }

    public static void main(String[] args) throws Exception {
        for (int w = 0; w < 20; w++) sink += spin(10_000_000); // let the JIT compile spin
        Thread t = new Thread(() -> { sink += spin(Integer.MAX_VALUE); });
        t.start();
        Thread.sleep(10);
        long t0 = System.nanoTime();
        System.gc(); // needs every thread at a safepoint
        System.out.printf("%-28s System.gc() took %8.1f ms%n", args[0], (System.nanoTime() - t0) / 1e6);
        t.join();
    }
}

Two flags decide the answer. UseCountedLoopSafepoints puts polls back into counted loops, and LoopStripMiningIter, added in JDK 10, keeps them cheap by splitting a long counted loop into an inner loop without a poll and an outer one with it. Their defaults on OpenJDK 11 depend on the collector:

$ for gc in Parallel G1; do java -XX:+Use${gc}GC -XX:+PrintFlagsFinal -version | grep -E ' UseCountedLoopSafepoints | LoopStripMiningIter '; done
    uintx LoopStripMiningIter                      = 0                                      {C2 product} {default}
     bool UseCountedLoopSafepoints                 = false                                  {C2 product} {default}
    uintx LoopStripMiningIter                      = 1000                                   {C2 product} {default}
     bool UseCountedLoopSafepoints                 = true                                   {C2 product} {default}

Three runs each, under the Parallel collector, under G1, and under Parallel with counted-loop safepoints turned on:

$ javac Spin.java
$ for r in 1 2 3; do for gc in Parallel G1; do java -XX:+Use${gc}GC Spin "Java 11 $gc"; done; java -XX:+UseParallelGC -XX:+UseCountedLoopSafepoints Spin "Java 11 Parallel +CountedLoop"; done
Java 11 Parallel             System.gc() took   1227.7 ms
Java 11 G1                   System.gc() took   1230.7 ms
Java 11 Parallel +CountedLoop System.gc() took      6.1 ms
Java 11 Parallel             System.gc() took   1234.6 ms
Java 11 G1                   System.gc() took   1234.7 ms
Java 11 Parallel +CountedLoop System.gc() took      6.0 ms
Java 11 Parallel             System.gc() took   1214.8 ms
Java 11 G1                   System.gc() took   1215.4 ms
Java 11 Parallel +CountedLoop System.gc() took      6.2 ms

(The +CountedLoop runs also print a warning that LoopStripMiningIter was raised to 1, which is omitted here.) Under Parallel, the collection waited 1.2 seconds, the whole loop, exactly as on Go 1.13. With counted-loop safepoints on, it took 6 ms. Under G1 I expected the defaults above to give the same 6 ms, and they did not: the collection waited 1.2 seconds there too. The JVM’s own safepoint log agrees that the time was spent waiting for the thread:

$ java -XX:+UseG1GC -Xlog:safepoint Spin "Java 11 G1" | grep -E 'Total|System.gc'
[0.026s][info][safepoint] Total time for which application threads were stopped: 0.0000833 seconds, Stopping threads took: 0.0000209 seconds
[0.028s][info][safepoint] Total time for which application threads were stopped: 0.0001179 seconds, Stopping threads took: 0.0000663 seconds
[1.416s][info][safepoint] Total time for which application threads were stopped: 1.2483283 seconds, Stopping threads took: 1.2450746 seconds
Java 11 G1                   System.gc() took   1248.5 ms

“Stopping threads took: 1.2450746 seconds.” I did not find out why the strip-mined loop did not reach a poll sooner. What the runs do show is the difference between the two designs. Java’s answer is still cooperative: polls the compiler chooses to insert, and flags that decide where. Go 1.14’s is not: it does not depend on what the compiler put in the loop.

Erlang never had the problem. Its processes are scheduled by reductions: every function call costs a process one reduction, and after a fixed budget of them (a few thousand) the scheduler switches to another process. Since Erlang has no loops, only recursion, every iteration of every loop is a function call, and every one is counted. The same busy loop, on a single scheduler:

-module(spin).
-export([main/0]).

%% A tail-recursive loop: each iteration is a function call, and every
%% call costs the process a reduction.
spin(0, S) -> S;
spin(N, S) -> spin(N - 1, (S + (N bxor (S bsr 3))) band 16#FFFFFF).

main() ->
    Self = self(),
    T0 = erlang:monotonic_time(microsecond),
    spawn(fun() -> Self ! {done, spin(100000000, 0)} end),
    receive after 10 -> ok end,
    T1 = erlang:monotonic_time(microsecond),
    io:format("~p scheduler(s): 10 ms timer fired after ~.1f ms~n",
              [erlang:system_info(schedulers_online), (T1 - T0) / 1000]),
    receive {done, _} -> ok end,
    T2 = erlang:monotonic_time(microsecond),
    io:format("the busy process finished after ~.1f ms~n", [(T2 - T0) / 1000]),
    init:stop().
$ erlc spin.erl && for r in 1 2 3; do erl +S 1 -noshell -s spin main; done
1 scheduler(s): 10 ms timer fired after 10.6 ms
the busy process finished after 629.1 ms
1 scheduler(s): 10 ms timer fired after 10.6 ms
the busy process finished after 635.3 ms
1 scheduler(s): 10 ms timer fired after 10.8 ms
the busy process finished after 641.0 ms

The 10 ms timer fired after 10.6 ms, while a process on the only scheduler spent 630 ms in a loop. (The first version of this program kept the running sum unbounded; it turned into an ever-larger integer and ran for minutes. The band keeps it to 24 bits.) Erlang pays for this with a counter decrement on every call, all the time; Go’s compiled code pays only at function entry, in the stack check it needs anyway.

C and Rust have neither problem, because they have no collector to stop the world for and no scheduler of their own: their threads are preempted by the kernel, which can stop any thread at any instruction. A library that adds green threads or a collector to either language inherits the problem along with them.

Defer, ten times cheaper

Go 1.14 also finished a change to defer that had been under way since 1.13. A defer has to arrange for a call to happen when the function returns, even if it returns by a panic, and for most of Go’s history that meant a record allocated on the heap, filled in, and linked into a list on the goroutine, for the runtime to walk at the end. Go 1.13’s release notes: “This release improves performance of most uses of defer by 30%”. Go 1.14’s: “This release improves the performance of most uses of defer to incur almost zero overhead compared to calling the deferred function directly. As a result, defer can now be used in performance-critical code without overhead concerns.”

The canonical case is a mutex released by defer:

package def

import (
	"sync"
	"testing"
)

var mu sync.Mutex
var x, sink int

// The same critical section, unlocked with and without defer.
func withDefer() int {
	mu.Lock()
	defer mu.Unlock()
	return x
}

func withoutDefer() int {
	mu.Lock()
	v := x
	mu.Unlock()
	return v
}

func BenchmarkWithDefer(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sink += withDefer()
	}
}

func BenchmarkWithoutDefer(b *testing.B) {
	for i := 0; i < b.N; i++ {
		sink += withoutDefer()
	}
}

Medians of five runs on three releases, in nanoseconds per call:

with deferwithoutdefer costs
Go 1.12.1029.811.318.5 ns
Go 1.13.925.39.5815.7 ns
Go 1.14.111.49.591.8 ns

What changed is visible in the calls each release compiles withDefer into:

$ for v in 1.12.10 1.13.9 1.14.1; do echo "-- $v"; go$v test -c -o d.test && go tool objdump -s '\.withDefer$' d.test | grep -E 'CALL|TEXT'; done
-- 1.12.10
TEXT _/tmp/p6e.withDefer(SB) /tmp/p6e/def_test.go
		e8aa14f7ff		CALL sync.(*Mutex).Lock(SB)
		e886b4f3ff		CALL runtime.deferproc(SB)
		e800bdf3ff		CALL runtime.deferreturn(SB)
		e8f0bcf3ff		CALL runtime.deferreturn(SB)
		e8d171f6ff		CALL runtime.morestack_noctxt(SB)
-- 1.13.9
TEXT _/tmp/p6e.withDefer(SB) /tmp/p6e/def_test.go
		e84f55f3ff		CALL runtime.deferprocStack(SB)
		e8595df3ff		CALL runtime.deferreturn(SB)
		e8495df3ff		CALL runtime.deferreturn(SB)
		e82ffbf6ff		CALL sync.(*Mutex).lockSlow(SB)
		e8b81af6ff		CALL runtime.morestack_noctxt(SB)
-- 1.14.1
TEXT _/tmp/p6e.withDefer(SB) /tmp/p6e/def_test.go
		e84418f7ff		CALL sync.(*Mutex).Unlock(SB)
		e86a15f7ff		CALL sync.(*Mutex).lockSlow(SB)
		e87366f3ff		CALL runtime.deferreturn(SB)
		e8f459f6ff		CALL runtime.morestack_noctxt(SB)

(The listing passes each line through a sed that strips the addresses, not shown.) Go 1.12 calls runtime.deferproc, which allocates the defer record on the heap, and runtime.deferreturn to run it. Go 1.13 calls runtime.deferprocStack instead: the record now lives in the function’s own frame, which escape analysis (Part 2) can prove for a defer that runs once, so the heap allocation is gone but the runtime still walks the record at return. (1.13 also inlined Lock’s fast path, which is why lockSlow appears and the “without” column fell too.) Go 1.14 does not register anything with the runtime. The compiler asks for this itself, as its -d=defer debugging flag reports:

$ go1.14.1 test -c -o /dev/null -gcflags=-d=defer
# _/tmp/p6d [_/tmp/p6d.test]
./def_test.go:14:2: open-coded defer

An open-coded defer is compiled in place: the function keeps a byte of flags in its frame, one bit per defer statement, sets the bit when the defer runs, and at each return checks the bits and calls the deferred functions directly. The whole of withDefer on 1.14.1:

$ go1.14.1 tool objdump -s '\.withDefer$' d.test
TEXT _/tmp/p6e.withDefer(SB) /tmp/p6e/def_test.go
  def_test.go:12	0x4fa5f0		64488b0c25f8ffffff	MOVQ FS:0xfffffff8, CX
  def_test.go:12	0x4fa5f9		483b6110		CMPQ 0x10(CX), SP
  def_test.go:12	0x4fa5fd		0f86a4000000		JBE 0x4fa6a7
  def_test.go:12	0x4fa603		4883ec28		SUBQ $0x28, SP
  def_test.go:12	0x4fa607		48896c2420		MOVQ BP, 0x20(SP)
  def_test.go:12	0x4fa60c		488d6c2420		LEAQ 0x20(SP), BP
  def_test.go:12	0x4fa611		0f57c0			XORPS X0, X0
  def_test.go:12	0x4fa614		0f11442410		MOVUPS X0, 0x10(SP)
  def_test.go:12	0x4fa619		c644240f00		MOVB $0x0, 0xf(SP)
  def_test.go:12	0x4fa61e		48c744243000000000	MOVQ $0x0, 0x30(SP)
  mutex.go:74		0x4fa627		31c0			XORL AX, AX
  mutex.go:74		0x4fa629		488d0db07b1600		LEAQ _/tmp/p6e.mu(SB), CX
  mutex.go:74		0x4fa630		ba01000000		MOVL $0x1, DX
  mutex.go:74		0x4fa635		f00fb111		LOCK CMPXCHGL DX, 0(CX)
  mutex.go:74		0x4fa639		0f94c1			SETE CL
  mutex.go:74		0x4fa63c		84c9			TESTL CL, CL
  mutex.go:74		0x4fa63e		7446			JE 0x4fa686
  def_test.go:14	0x4fa640		488d0551f10400		LEAQ 0x4f151(IP), AX
  def_test.go:14	0x4fa647		4889442418		MOVQ AX, 0x18(SP)
  def_test.go:14	0x4fa64c		488d058d7b1600		LEAQ _/tmp/p6e.mu(SB), AX
  def_test.go:14	0x4fa653		4889442410		MOVQ AX, 0x10(SP)
  def_test.go:14	0x4fa658		c644240f01		MOVB $0x1, 0xf(SP)
  def_test.go:15	0x4fa65d		488b058c7b1600		MOVQ _/tmp/p6e.x(SB), AX
  def_test.go:15	0x4fa664		4889442430		MOVQ AX, 0x30(SP)
  def_test.go:15	0x4fa669		c644240f00		MOVB $0x0, 0xf(SP)
  def_test.go:15	0x4fa66e		488b442410		MOVQ 0x10(SP), AX
  def_test.go:15	0x4fa673		48890424		MOVQ AX, 0(SP)
  def_test.go:15	0x4fa677		e84418f7ff		CALL sync.(*Mutex).Unlock(SB)
  def_test.go:15	0x4fa67c		488b6c2420		MOVQ 0x20(SP), BP
  def_test.go:15	0x4fa681		4883c428		ADDQ $0x28, SP
  def_test.go:15	0x4fa685		c3			RET
  mutex.go:81		0x4fa686		488d05537b1600		LEAQ _/tmp/p6e.mu(SB), AX
  mutex.go:81		0x4fa68d		48890424		MOVQ AX, 0(SP)
  mutex.go:81		0x4fa691		e86a15f7ff		CALL sync.(*Mutex).lockSlow(SB)
  def_test.go:13	0x4fa696		eba8			JMP 0x4fa640
  def_test.go:13	0x4fa698		e87366f3ff		CALL runtime.deferreturn(SB)
  def_test.go:13	0x4fa69d		488b6c2420		MOVQ 0x20(SP), BP
  def_test.go:13	0x4fa6a2		4883c428		ADDQ $0x28, SP
  def_test.go:13	0x4fa6a6		c3			RET
  def_test.go:12	0x4fa6a7		e8f459f6ff		CALL runtime.morestack_noctxt(SB)
  def_test.go:12	0x4fa6ac		e93fffffff		JMP _/tmp/p6e.withDefer(SB)

Line 14, the defer, stores the deferred function and its argument (mu) into the frame, at 0x18(SP) and 0x10(SP), and sets bit 0 of the flag byte at 0xf(SP) with MOVB $0x1. Line 15, the return, clears the bit and calls Unlock directly, then returns. No runtime call at all on the normal path. The runtime.deferreturn block at 0x4fa698 is reached by no jump in the function: it is where the runtime resumes the function if a panic is recovered during it, and only then are the recorded function and argument used to run the deferred call from the runtime. What remains of the cost is 1.8 ns: the stores, the bit, and a real call to Unlock, which the version without defer inlines and the deferred call cannot.

One defer mu.Unlock(), three releases

The calls in the compiled function, and what the defer added to each call of it.

Go 1.12.10
heap-allocated defer record
  • sync.(*Mutex).Lock
  • runtime.deferproc
  • runtime.deferreturn
  • runtime.deferreturn
+18.5 ns
Go 1.13.9
defer record in the stack frame
  • runtime.deferprocStack
  • runtime.deferreturn
  • runtime.deferreturn
  • sync.(*Mutex).lockSlow
+15.7 ns
Go 1.14.1
open-coded: Unlock called directly
  • sync.(*Mutex).Unlock
  • sync.(*Mutex).lockSlow
  • runtime.deferreturn
+1.8 ns

Calls into the runtime's defer machinery are in copper. In 1.14 the one left, runtime.deferreturn, sits on a path only a recovered panic takes; the normal return calls Unlock directly.

Open coding has limits, set in the compiler’s ssa.go: a defer inside a loop, more than eight defer statements in one function (maxOpenDefers = 8, one bit each), more than 15 return statements multiplied by defers, or a function with extra code at its exits, such as copying heap-allocated results, all fall back to the older paths. And the stack-allocated records of 1.13 rely on escape analysis, so a function where it fails still pays for the heap.

A page allocator with less locking

The last 1.14 change is in the allocator of Part 3, at its lowest level: the mheap’s search for free pages, which Part 3 showed as free lists and a tree under one lock. Go 1.14 replaced it with a bitmap of every page in the address space, searched through a radix tree of summaries (“the number of contiguous free pages at the start and end of the region it represents, and the maximum number of contiguous free pages found anywhere in that region”, in the words of the new mpagealloc.go), which needs far less locking. The release notes: “The page allocator is more efficient and incurs significantly less lock contention at high values of GOMAXPROCS. This is most noticeable as lower latency and higher throughput for large allocations being done in parallel and at a high rate.”

Part 3’s allocation benchmark, run again on both releases for the large sizes, where every allocation goes to the page allocator, medians of five runs in nanoseconds:

Size1.13.9 serial1.14.1 serial1.13.9 parallel, 24 threads1.14.1 parallel, 24 threads
32 KB + 12,3982,8692,3381,768
64 KB4,5014,8042,6342,108
1 MB44,93545,43322,93722,553

In parallel, large allocations got 20 to 24% faster at 32 and 64 KB, which is the contention the notes describe. At a megabyte there was no difference, and I did not establish why. In a single thread they got slower, by 20% just past 32 KB, a cost the notes do not mention. I did not profile where it comes from.

What this means for Go code

Tight loops are safe on 1.14. A goroutine in a loop with no function calls no longer stalls the scheduler or delays a collection. Code that added runtime.Gosched() calls to long loops for this reason no longer needs them, on every platform except the few the release notes exclude (windows/arm, darwin/arm, js/wasm and plan9).

Raw system calls must retry on EINTR. A program that makes system calls through syscall or golang.org/x/sys/unix, or calls C code that does, will see more of them interrupted, and has to loop. GODEBUG=asyncpreemptoff=1 turns the signals off while that code is being fixed.

defer is free enough. At 1.8 ns, the reason to avoid defer in a hot function is gone, except in the cases open coding does not cover: loops, and functions with many defers or many returns.

Latency is about the slowest goroutine, not the average one. A stop of the world waits for the last goroutine to stop. Part 4 measured the pauses as short, and they are, as long as every goroutine can be stopped promptly. Before 1.14, one loop could make a pause as long as itself. (Collections cause latency in other ways too: in February, Discord’s engineering blog described moving a service from Go to Rust after the collection that Go forces every two minutes, scanning a large cache, caused latency spikes. That was the tracing cost of Part 4, not a goroutine that could not be stopped, and the service ran an older Go.)

A note on the evidence

What ran. Go 1.14.1 and Go 1.13.9, both released on 19 March 2020, and Go 1.12.10 for the defer comparison (the official linux-amd64 archives, each checked against its published SHA-256), on an Ubuntu 18.04 userland as released, in a chroot on a 24-thread x86-64 machine under the host’s Linux kernel. Signals and their delivery are the kernel’s, so the preemption timings depend on it; the scheduler and collector behaviour they show do not. Java is OpenJDK 11.0.1+13 (AdoptOpenJDK, October 2018). Erlang is OTP 20.2 from Ubuntu 18.04.

What was measured. Every preemption figure is three runs, all shown. The defer and allocation figures are medians of five runs of each benchmark in one sitting with nothing else running. The machine code is the disassembly of the test binaries as built; the commands above are abbreviated (go$v for /opt/go/$v/bin/go, and a sed that strips addresses from the call listing).

The traceback and the signal count are single runs; strace 4.21 is Ubuntu 18.04’s, and the counts depend on how often the runtime needed a goroutine stopped in that run.

What changed in the writing. The first version of spin.go read the clock after a runtime.Gosched() call meant to let the spinner start. On Go 1.13 that call does not return until the spinner finishes, so the measured sleep came out at 10 ms in two runs of three, the delay hidden before the stopwatch started. The version above reads the clock first. The first Erlang loop’s running sum was unbounded, as noted above, and the run was stopped.

What is not explained. Why G1’s default loop strip mining did not bound the time to safepoint on OpenJDK 11.0.1, and why single-threaded allocations past 32 KB got slower on Go 1.14.1, are both reported as measured and not diagnosed.

What is quoted. Runtime source is from the go1.14.1 tag (preempt.go, signal_unix.go, proc.go) and, for forcePreemptNS, go1.13.8, where it is the same; the release notes are from doc/go1.13.html and doc/go1.14.html. Discord’s post is “Why Discord is switching from Go to Rust”, February 2020.

More