Commit 3cea2efd96 for golang
commit 3cea2efd966cc583755e902b07d93908e7b8768a
Author: Amangeldy Kadyl <lex0.kz@gmail.com>
Date: Thu Nov 26 11:42:04 2026 +0000
runtime: don't lose queued cleanups when destroying a P
The sweeper queues ready cleanups into a block owned by the current P.
A block is pushed onto the full list when it fills up, and partially
filled blocks are pushed by cleanupQueue.flush when the last sweeper of
the cycle is done. flush only looks at the Ps in allp.
runtime.GOMAXPROCS stops the world with stopTheWorldGC, which waits
for gcsema. The GC releases gcsema at the end of mark termination, not
after the sweep, so procresize can run in the middle of the sweep
phase. When it decreases the number of Ps, (*p).destroy leaves
pp.cleanups attached to the dead P, which is no longer in allp. The
cleanups in that block don't run until GOMAXPROCS is raised above that
P's ID again, which may never happen.
For example, a cleanup that re-arms itself on every GC cycle can stop
running for good after GOMAXPROCS decreases. Since Go 1.25 the runtime
can also lower GOMAXPROCS by itself when the CPU affinity or cgroup CPU
limit goes down, through the same stopTheWorldGC, so this can happen
without any call to runtime.GOMAXPROCS.
Fix this by pushing the destroyed P's block onto the full list in
destroy. The world is stopped and gcphase is _GCoff there, so nothing
else can touch the block, and the scheduler wakes the cleanup
goroutines as usual once the world restarts.
For the test, split cleanupQueue.enqueue into enqueue and enqueueOn,
which queues a cleanup on a given P and checks that the world is
stopped or the caller is pinned to that P.
Fixes #83361
Change-Id: Iceecc7367cc7c35aa61e61514171171a837f111a
GitHub-Last-Rev: 821d5e60d63766081abae8d37b7f8126cc016341
GitHub-Pull-Request: golang/go#83381
Reviewed-on: https://go-review.googlesource.com/c/go/+/867324
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Keith Randall <khr@golang.org>
diff --git a/src/runtime/export_test.go b/src/runtime/export_test.go
index b85c2fec42..7ac35383f3 100644
--- a/src/runtime/export_test.go
+++ b/src/runtime/export_test.go
@@ -1923,6 +1923,32 @@ func BlockUntilEmptyCleanupQueue(timeout int64) bool {
return gcCleanups.blockUntilEmpty(timeout)
}
+// QueueCleanupOnP queues f in the cleanup block of P id.
+func QueueCleanupOnP(id int, f func()) {
+ // Make sure there's a cleanup goroutine, like AddCleanup does.
+ if gcCleanups.needG() {
+ gcCleanups.createGs()
+ }
+ c := cleanupFn{
+ call: callCleanupNoArg,
+ fn: *(**funcval)(unsafe.Pointer(&f)),
+ }
+
+ // With gcsema held the GC isn't marking, and with the world
+ // stopped no sweeper is running.
+ stw := stopTheWorldGC(stwForTestQueueCleanupOnP)
+ if id < 0 || id >= len(allp) {
+ throw("QueueCleanupOnP: invalid P id")
+ }
+ gcCleanups.enqueueOn(allp[id], c)
+ startTheWorldGC(stw)
+}
+
+func callCleanupNoArg(fn *funcval, _ unsafe.Pointer) {
+ f := *(*func())(unsafe.Pointer(&fn))
+ f()
+}
+
func FrameStartLine(f *Frame) int {
return f.startLine
}
diff --git a/src/runtime/lockrank_off.go b/src/runtime/lockrank_off.go
index 571e24e693..2448c712ff 100644
--- a/src/runtime/lockrank_off.go
+++ b/src/runtime/lockrank_off.go
@@ -74,3 +74,7 @@ func assertWorldStopped() {
//go:nosplit
func assertWorldStoppedOrLockHeld(l *mutex) {
}
+
+//go:nosplit
+func assertWorldStoppedOrPinnedTo(pp *p) {
+}
diff --git a/src/runtime/lockrank_on.go b/src/runtime/lockrank_on.go
index 6dd0ee8756..69621c8001 100644
--- a/src/runtime/lockrank_on.go
+++ b/src/runtime/lockrank_on.go
@@ -398,3 +398,28 @@ func assertWorldStoppedOrLockHeld(l *mutex) {
throw("no world stop or required lock!")
})
}
+
+// assertWorldStoppedOrPinnedTo throws if the world is not stopped and the
+// caller is not pinned to pp, that is, not running on pp with preemption
+// disabled.
+//
+// nosplit to ensure it can be called in as many contexts as possible.
+//
+//go:nosplit
+func assertWorldStoppedOrPinnedTo(pp *p) {
+ if checkWorldStopped() {
+ return
+ }
+
+ mp := getg().m
+ if mp.locks > 0 && mp.p.ptr() == pp {
+ return
+ }
+
+ // Crash from system stack to avoid splits that may cause
+ // additional issues.
+ systemstack(func() {
+ print("caller requires world stop or to be pinned to P ", pp.id, "\n")
+ throw("no world stop and not pinned to P")
+ })
+}
diff --git a/src/runtime/mcleanup.go b/src/runtime/mcleanup.go
index 19b6f241b0..6d4f2570e6 100644
--- a/src/runtime/mcleanup.go
+++ b/src/runtime/mcleanup.go
@@ -461,7 +461,21 @@ func (q *cleanupQueue) tryTakeWork() bool {
// Called by the sweeper, and only the sweeper.
func (q *cleanupQueue) enqueue(c cleanupFn) {
mp := acquirem()
- pp := mp.p.ptr()
+ q.enqueueOn(mp.p.ptr(), c)
+ releasem(mp)
+}
+
+// enqueueOn is like enqueue, but queues c in pp's cleanup block instead
+// of the current P's.
+//
+// Don't use this unless the caller is pinned to pp (running on pp and
+// non-preemptible) or the world is stopped. Nothing else synchronizes
+// access to pp's block. Like enqueue, it also must only be called during
+// the sweep phase (gcphase == _GCoff), and a stopped world alone doesn't
+// guarantee that.
+func (q *cleanupQueue) enqueueOn(pp *p, c cleanupFn) {
+ assertWorldStoppedOrPinnedTo(pp)
+
b := pp.cleanups
if b == nil {
if q.flushed.Load() {
@@ -486,7 +500,6 @@ func (q *cleanupQueue) enqueue(c cleanupFn) {
q.addWork(1)
}
pp.cleanupsQueued++
- releasem(mp)
}
// dequeue pops a block of cleanups from the queue. Blocks until one is available
diff --git a/src/runtime/mcleanup_test.go b/src/runtime/mcleanup_test.go
index 0dc9b07ed6..1d6540c207 100644
--- a/src/runtime/mcleanup_test.go
+++ b/src/runtime/mcleanup_test.go
@@ -377,6 +377,33 @@ func TestCleanupLost(t *testing.T) {
}
}
+// Cleanups queued on a P must still run if GOMAXPROCS goes down and
+// the P is destroyed before the sweep ends. See go.dev/issue/83361.
+func TestCleanupQueuedOnDestroyedP(t *testing.T) {
+ defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))
+ if runtime.GOMAXPROCS(-1) < 2 {
+ t.Skip("need GOMAXPROCS >= 2")
+ }
+
+ // Finish any sweep in progress and flush leftover blocks first.
+ // Otherwise this can pass without the fix.
+ runtime.GC()
+
+ var ran atomic.Bool
+ runtime.QueueCleanupOnP(1, func() { ran.Store(true) })
+ runtime.GOMAXPROCS(1)
+
+ // BlockUntilEmptyCleanupQueue needs a flush, so run one more cycle.
+ runtime.GC()
+ timeout := 10 * time.Second
+ if !runtime.BlockUntilEmptyCleanupQueue(int64(timeout)) {
+ t.Fatalf("failed to drain cleanup queue within %s", timeout)
+ }
+ if !ran.Load() {
+ t.Error("cleanup queued on a destroyed P did not run")
+ }
+}
+
func TestCleanupUnreachablePointer(t *testing.T) {
defer func() {
if recover() == nil {
diff --git a/src/runtime/proc.go b/src/runtime/proc.go
index 26d630737f..c41d880267 100644
--- a/src/runtime/proc.go
+++ b/src/runtime/proc.go
@@ -1486,6 +1486,7 @@ const (
stwForTestReadMemStatsSlow // "ReadMemStatsSlow (test)"
stwForTestPageCachePagesLeaked // "PageCachePagesLeaked (test)"
stwForTestResetDebugLog // "ResetDebugLog (test)"
+ stwForTestQueueCleanupOnP // "QueueCleanupOnP (test)"
)
func (r stwReason) String() string {
@@ -1517,6 +1518,7 @@ var stwReasonStrings = [...]string{
stwForTestReadMemStatsSlow: "ReadMemStatsSlow (test)",
stwForTestPageCachePagesLeaked: "PageCachePagesLeaked (test)",
stwForTestResetDebugLog: "ResetDebugLog (test)",
+ stwForTestQueueCleanupOnP: "QueueCleanupOnP (test)",
}
// worldStop provides context from the stop-the-world required by the
@@ -6113,6 +6115,14 @@ func (pp *p) destroy() {
pp.raceprocctx = 0
}
pp.gcAssistTime = 0
+ // Push the partially filled cleanup block, if any. We may be in
+ // the middle of the sweep, and flush only looks at allp, so nobody
+ // would pick the block up otherwise.
+ if b := pp.cleanups; b != nil {
+ gcCleanups.full.push(&b.lfnode)
+ gcCleanups.addWork(1)
+ pp.cleanups = nil
+ }
gcCleanups.queued += pp.cleanupsQueued
pp.cleanupsQueued = 0
sched.goroutinesCreated.Add(int64(pp.goroutinesCreated))