Commit 0430a57d41 for golang
commit 0430a57d41854986396feba75619ae86a495869c
Author: Carlos Amedee <carlos@golang.org>
Date: Wed Nov 18 15:26:39 2026 -0500
runtime: pool dead goroutines' continuations under GOWASM=stackswitch
A dead goroutine's continuation currently stays parked in its g's slot
until a new goroutine reuses that g. Because a runnable goroutine
already has its g, continuations parked on the g free lists cannot
serve goroutines queued on other g's: starting many goroutines before
any runs allocates a g and a continuation for each. On the builders,
starting 35,000 goroutines at once fails even if each exits right away:
Wasmtime traps with ENOMEM (vm.max_map_count is 65530), V8 aborts the
process, and BenchmarkCreateGoroutinesSingle fails on both engines.
Pool dead goroutines' continuations together with their table slots in
wasmContFree so the next starting goroutine on any g can reuse them, and
assign slots lazily in wasm_scheduler_loop on a goroutine's first resume
rather than in malg. Remove malg's wasmContAlloc hook (added in CL
858381), which is no longer needed once slots are assigned on first run;
this also returns malg to its code from before that CL in builds without
GOWASM=stackswitch. This design needs no new fields in g and no hook in
newproc1. In cmd/internal/obj/wasm, add an i32 R2 local to wasm_resume
so it can also pop a pooled continuation when an existing slot is null
(a synchronous callback on js).
Starting 100,000 goroutines that exit right away now works on both
engines and leaves the continuation table at its initial 1,024 slots
instead of growing it to 131,072 (one slot per g). Re-enable
internal/sync.TestConcurrentCache, which starts 100,000 goroutines and
now creates 12 continuations. BenchmarkCreateGoroutinesSingle, which
fails at the previous CL, runs at 2.66µs on Wasmtime 50.0.1 and 2.84µs
on Node.js 26.13. Pooled continuations stay allocated for the program's
lifetime, and the limit on concurrently live goroutines is unchanged:
35,000 goroutines blocked at once still fail on both engines.
Compared with the previous CL (benchstat, n=5, runs interleaved),
ChanSync, ChanProdCons0, CreateGoroutines, StackGrowth, and
StackGrowthDeep show no significant change on Node.js 26.13. On
Wasmtime 50.0.1, CreateGoroutines is 8.8% slower and ChanSync 1.8%
slower (p=0.008), in a run where encoding/json, which this CL does not
affect, also moved by 2-5%.
For #81963
Cq-Include-Trybots: luci.golang.try:gotip-js-wasm-stackswitch,gotip-wasip1-wasm_wasmtime-stackswitch
Change-Id: Ie42004190bd93a110ed794adcddcd0286fb94863
Reviewed-on: https://go-review.googlesource.com/c/go/+/865881
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Carlos Amedee <carlos@golang.org>
diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index 8f0de6a1ae..3598f3fb8e 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -1265,7 +1265,7 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
useAssemblyRegMap()
case "wasm_resume":
// R0 is the i32 slot parameter.
- varDecls = []*varDecl{{count: 1, typ: contRef}} // R1
+ varDecls = []*varDecl{{count: 1, typ: contRef}, {count: 1, typ: i32}} // R1, R2
useAssemblyRegMap()
case "wasm_pc_f_loop_export":
varDecls = []*varDecl{{count: 2, typ: i32}}
diff --git a/src/cmd/internal/obj/wasm/wasmobj_test.go b/src/cmd/internal/obj/wasm/wasmobj_test.go
index 8e20ccff6a..3161f75c91 100644
--- a/src/cmd/internal/obj/wasm/wasmobj_test.go
+++ b/src/cmd/internal/obj/wasm/wasmobj_test.go
@@ -455,7 +455,7 @@ func assembleOneDiag(t *testing.T, p *obj.Prog) []string {
}
// TestAssembleContRefLocal checks that wasm_resume declares its R1 local as
-// (ref null $cont) and that Get and Set R1 use it.
+// (ref null $cont), followed by its i32 R2, and that Get and Set R1 use it.
func TestAssembleContRefLocal(t *testing.T) {
setStackSwitch(t, true)
ctxt := obj.Linknew(&Linkwasm)
@@ -469,7 +469,9 @@ func TestAssembleContRefLocal(t *testing.T) {
assemble(ctxt, s, nil)
want := []byte{
- 0x01, 0x01, 0x63, ContinuationTypeIndex, // 1 local declaration: 1 x (ref null $cont)
+ 0x02, // 2 local declarations:
+ 0x01, 0x63, ContinuationTypeIndex, // 1 x (ref null $cont)
+ 0x01, 0x7F, // 1 x i32
0x20, 0x01, // local.get 1
0x22, 0x01, // local.tee 1 (Set R1; Get R1)
0x0B, // end
diff --git a/src/internal/sync/hashtriemap_test.go b/src/internal/sync/hashtriemap_test.go
index 9d41f16929..e2b5046ed6 100644
--- a/src/internal/sync/hashtriemap_test.go
+++ b/src/internal/sync/hashtriemap_test.go
@@ -926,9 +926,6 @@ func init() {
}
}
-// skipConcurrentCache, if set, is the reason to skip TestConcurrentCache.
-var skipConcurrentCache string
-
// TestConcurrentCache tests HashTrieMap in a scenario where it is used as
// the basis of a memory-efficient concurrent cache. We're specifically
// looking to make sure that CompareAndSwap and CompareAndDelete are
@@ -937,9 +934,6 @@ var skipConcurrentCache string
//
// This test is a regression test for issue #70970.
func TestConcurrentCache(t *testing.T) {
- if skipConcurrentCache != "" {
- t.Skip(skipConcurrentCache)
- }
t.Parallel()
type dummy [32]byte
diff --git a/src/internal/sync/stackswitch_wasm_test.go b/src/internal/sync/stackswitch_wasm_test.go
deleted file mode 100644
index f2e38fd07a..0000000000
--- a/src/internal/sync/stackswitch_wasm_test.go
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2026 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-//go:build wasm.stackswitch
-
-package sync_test
-
-func init() {
- // TODO(#81963): remove once dead goroutines' continuations are pooled
- // across g's. Until then, each g gets its own continuation, and this
- // test's 100,000 goroutines exhaust engine memory.
- skipConcurrentCache = "continuations are not pooled across g's under GOWASM=stackswitch yet"
-}
diff --git a/src/runtime/export_stackswitch_test.go b/src/runtime/export_stackswitch_test.go
index 235ac2b6d1..2b5d3229ff 100644
--- a/src/runtime/export_stackswitch_test.go
+++ b/src/runtime/export_stackswitch_test.go
@@ -12,3 +12,17 @@ var WasmContTableGrow = wasmContTableGrow
func WasmContSlot() int32 {
return getg().wasmCont.index
}
+
+// WasmContSlotOfM0G0 returns m0.g0's continuation table slot, which is
+// unused: m0.g0 has no continuation.
+func WasmContSlotOfM0G0() int32 { return m0.g0.wasmCont.index }
+
+// WasmContSlots returns the number of continuation table slots assigned
+// so far.
+func WasmContSlots() int32 { return wasmContLast }
+
+// WasmContPooled returns the number of continuations in the pool.
+func WasmContPooled() int32 { return wasmContPooled }
+
+// WasmContCreated returns the number of continuations created so far.
+func WasmContCreated() int32 { return wasmContCreated }
diff --git a/src/runtime/proc.go b/src/runtime/proc.go
index c41d880267..24a402be2e 100644
--- a/src/runtime/proc.go
+++ b/src/runtime/proc.go
@@ -5357,9 +5357,6 @@ func syscall_runtime_AfterExec() {
// Allocate a new g, with a stack big enough for stacksize bytes.
func malg(stacksize int32) *g {
newg := new(g)
- // Give newg its WebAssembly continuation table slot (GOWASM=stackswitch),
- // which it keeps for its lifetime, including on free lists.
- wasmContAlloc(newg)
if stacksize >= 0 {
stacksize = round2(stackSystem + stacksize)
systemstack(func() {
diff --git a/src/runtime/stackswitch_stub.go b/src/runtime/stackswitch_stub.go
index 62332d9118..d00d0fa321 100644
--- a/src/runtime/stackswitch_stub.go
+++ b/src/runtime/stackswitch_stub.go
@@ -10,5 +10,3 @@ package runtime
// (GOWASM=stackswitch). It's empty in every other
// build, so it adds nothing to the g.
type wasmContPerG struct{}
-
-func wasmContAlloc(gp *g) {}
diff --git a/src/runtime/stackswitch_wasm.s b/src/runtime/stackswitch_wasm.s
index b814512839..a6885336e2 100644
--- a/src/runtime/stackswitch_wasm.s
+++ b/src/runtime/stackswitch_wasm.s
@@ -36,10 +36,20 @@ TEXT ·wasmContTableGrow(SB), NOSPLIT, $0-12
// between goroutines (g1 -> g0 -> g2) is one $yield suspend and one resume.
// On each $yield, the yielded continuation is stored back into the slot of
// the goroutine just resumed; if PAUSE == 0, the loop resumes the goroutine
-// now in g.
+// now in g. A goroutine that has not run yet has no slot: this loop calls
+// wasmContStart to give it one first, saving CTXT (the new goroutine's
+// closure context, loaded by gogo) on the operand stack across the call.
TEXT wasm_scheduler_loop(SB), NOSPLIT, $0
loop:
Loop
+ I32Load (g_wasmCont+wasmContPerG_index)(g)
+ I32Eqz
+ If
+ Get CTXT
+ CALLNORESUME runtime·wasmContStart(SB)
+ Set CTXT
+ End
+
// Push the slot twice (Tee and Get): g may change before
// wasm_resume returns, so the first copy stays on the stack for
// TableSet.
@@ -59,13 +69,26 @@ loop:
Return
+// FREE_SLOT pushes the address of wasmContFree[wasmContPooled].
+#define FREE_SLOT \
+ I32Const $runtime·wasmContFree(SB); \
+ I32Load $0; \
+ I32Const $runtime·wasmContPooled(SB); \
+ I32Load $0; \
+ I32Const $4; \
+ I32Mul; \
+ I32Add
+
// wasm_resume resumes the continuation in wasmContTable slot R0 (signature
// (slot i32) -> (ref null $cont)) and returns the continuation that
// suspends on $yield, which the caller stores back into the slot. If the
-// slot is null, the goroutine has no continuation yet: wasm_resume creates
-// one that starts at wasm_goentry (ContNew). Otherwise it clears the slot:
-// resuming consumes the continuation, so the slot must not keep the
-// reference. Either way, a slot is null while its goroutine runs.
+// slot is null (a new slot, or on js a synchronous callback), wasm_resume
+// takes a continuation from the pool (see wasmContFree) if non-empty, or
+// creates one starting at wasm_goentry (ContNew); a pooled continuation is
+// parked in RESUME_AFTER_G0 and unwinds to wasm_goentry. If the slot is
+// non-null, wasm_resume clears it: resuming consumes the continuation, so
+// the slot must not keep the reference. Either way, a slot is null while its
+// goroutine runs.
//
// Resume transfers control to wasm_goentry (for a new continuation) or to
// where the continuation last suspended. When that code suspends on $yield,
@@ -80,9 +103,38 @@ TEXT wasm_resume(SB), NOSPLIT, $0
Get R1
RefIsNull
If
- RefFunc wasm_goentry(SB)
- ContNew
- Set R1
+ I32Const $runtime·wasmContPooled(SB)
+ I32Load $0
+ If
+ // wasmContPooled--; R2 = wasmContFree[wasmContPooled].
+ I32Const $runtime·wasmContPooled(SB)
+ I32Const $runtime·wasmContPooled(SB)
+ I32Load $0
+ I32Const $1
+ I32Sub
+ I32Store $0
+ FREE_SLOT
+ I32Load $0
+ Set R2
+
+ // R1 = the continuation in slot R2, which becomes null.
+ Get R2
+ TableGet $const_wasmContTable
+ Set R1
+ Get R2
+ RefNull
+ TableSet $const_wasmContTable
+ Else
+ RefFunc wasm_goentry(SB)
+ ContNew
+ Set R1
+ I32Const $runtime·wasmContCreated(SB)
+ I32Const $runtime·wasmContCreated(SB)
+ I32Load $0
+ I32Const $1
+ I32Add
+ I32Store $0
+ End
Else
Get R0
RefNull
@@ -259,6 +311,47 @@ entry:
End
UNDEF
+// FREE_END pushes the address of wasmContFree[len(wasmContFree)].
+#define FREE_END \
+ I32Const $runtime·wasmContFree(SB); \
+ I32Load $0; \
+ I32Const $runtime·wasmContFree+8(SB); \
+ I32Load $0; \
+ I32Const $4; \
+ I32Mul; \
+ I32Add
+
+// POOL_PUSH pools the dead g gp's slot and about-to-suspend continuation:
+// it inserts gp.wasmCont.index at wasmContFree[wasmContPooled] (moving any
+// null slot there to the end), increments wasmContPooled and
+// len(wasmContFree), and resets gp.wasmCont.index to 0. When this
+// continuation suspends, wasm_scheduler_loop stores it in gp's old slot,
+// now in the pool.
+#define POOL_PUSH(gp) \
+ FREE_END; \
+ FREE_SLOT; \
+ I32Load $0; \
+ I32Store $0; \
+ FREE_SLOT; \
+ I32Load (g_wasmCont+wasmContPerG_index)(gp); \
+ I32Store $0; \
+ Get gp; \
+ I32WrapI64; \
+ I32Const $0; \
+ I32Store $(g_wasmCont+wasmContPerG_index); \
+ I32Const $runtime·wasmContFree+8(SB); \
+ I32Const $runtime·wasmContFree+8(SB); \
+ I64Load $0; \
+ I64Const $1; \
+ I64Add; \
+ I64Store $0; \
+ I32Const $runtime·wasmContPooled(SB); \
+ I32Const $runtime·wasmContPooled(SB); \
+ I32Load $0; \
+ I32Const $1; \
+ I32Add; \
+ I32Store $0
+
// RESUME_AFTER_G0 finishes a switch to g0 whose code unwound back here (via
// gogo or, on js, runtime.exit). owner is the g that this Wasm stack belongs
// to; pc and goid are owner.sched.pc and owner.goid saved before switching.
@@ -267,14 +360,20 @@ entry:
// unwinding to wasm_goentry, which yields to wasm_scheduler_loop. Otherwise,
// if gogo switched to another goroutine, it suspends this continuation,
// which wasm_scheduler_loop stores in owner's slot and resumes when owner
-// runs again.
+// runs again. If owner is still _Gdead (goexit0's scheduling may already
+// have reused owner for a new goroutine, which then resumes this
+// continuation itself) and wasmContFree has room (which it always does; see
+// wasmContFree), it first pools this continuation with owner's slot
+// (POOL_PUSH) so any goroutine may reuse it; otherwise it stays in owner's
+// slot.
//
// A goroutine dies here in mcall(goexit0) (from runtime.goexit or
// runtime.Goexit) or mcall(coroswitch_m) (coroutine exit): as on other
// architectures, its frames are abandoned, not unwound. When a new goroutine
-// reuses owner, it resumes this continuation with a new goid, so
-// RESUME_AFTER_G0 returns 1 to unwind the dead frames to wasm_goentry, which
-// starts the new goroutine at g.sched.pc. Nothing re-enters the dead frames.
+// reuses this continuation, on owner or another g, it resumes it with a new
+// goid, so RESUME_AFTER_G0 returns 1 to unwind the dead frames to
+// wasm_goentry, which starts the new goroutine at g.sched.pc. Nothing
+// re-enters the dead frames.
//
// If g.sched.pc changed (a recovered panic), RESUME_AFTER_G0 also returns 1
// to unwind to wasm_goentry, which restarts at g.sched.pc. Otherwise it
@@ -293,6 +392,18 @@ entry:
Get owner; \
I64Ne; \
If; \
+ I32Load g_atomicstatus(owner); \
+ I32Const $const__Gdead; \
+ I32Eq; \
+ I32Const $runtime·wasmContFree+8(SB); \
+ I32Load $0; \
+ I32Const $runtime·wasmContFree+16(SB); \
+ I32Load $0; \
+ I32LtU; \
+ I32And; \
+ If; \
+ POOL_PUSH(owner); \
+ End; \
Suspend $const_wasmYieldTag; \
End; \
Get pc; \
diff --git a/src/runtime/stackswitch_wasm_test.go b/src/runtime/stackswitch_wasm_test.go
index 92cd395fb4..4cd402090e 100644
--- a/src/runtime/stackswitch_wasm_test.go
+++ b/src/runtime/stackswitch_wasm_test.go
@@ -18,6 +18,72 @@ import (
"time"
)
+// blockedSlots starts n goroutines that block until release is closed and
+// returns their continuation table slots.
+func blockedSlots(n int, release chan struct{}) []int32 {
+ slots := make(chan int32)
+ for range n {
+ go func() {
+ slots <- runtime.WasmContSlot()
+ <-release
+ }()
+ }
+ s := make([]int32, n)
+ for i := range s {
+ s[i] = <-slots
+ }
+ return s
+}
+
+// TestWasmContSlotsDistinct checks that live goroutines have distinct slots
+// within the table, and that none uses slot 0 (m0.g0's unused zero index).
+func TestWasmContSlotsDistinct(t *testing.T) {
+ if got := runtime.WasmContSlotOfM0G0(); got != 0 {
+ t.Errorf("m0.g0 has slot %d, want 0", got)
+ }
+ release := make(chan struct{})
+ defer close(release)
+ slots := append(blockedSlots(100, release), runtime.WasmContSlot())
+ size := runtime.WasmContTableSize()
+ seen := make(map[int32]bool)
+ for _, s := range slots {
+ if s == 0 || s >= size {
+ t.Errorf("slot %d: want in [1, %d)", s, size)
+ }
+ if seen[s] {
+ t.Errorf("slot %d assigned to two live goroutines", s)
+ }
+ seen[s] = true
+ }
+}
+
+// wasmContTableGrown is set once TestWasmContTableGrows has run. Repeated
+// runs (-count) skip: each would need more goroutines than the last.
+var wasmContTableGrown bool
+
+// TestWasmContTableGrows blocks more goroutines than the table has slots,
+// so that their first resumes must grow the table, and checks that every
+// slot fits.
+func TestWasmContTableGrows(t *testing.T) {
+ if wasmContTableGrown {
+ t.Skip("table already grown by an earlier run")
+ }
+ wasmContTableGrown = true
+ initSize := runtime.WasmContTableSize()
+ release := make(chan struct{})
+ defer close(release)
+ slots := blockedSlots(int(initSize)+10, release)
+ size := runtime.WasmContTableSize()
+ if size <= initSize {
+ t.Fatalf("table size %d did not grow past %d", size, initSize)
+ }
+ for _, s := range slots {
+ if s >= size {
+ t.Fatalf("slot %d does not fit in the table (size %d)", s, size)
+ }
+ }
+}
+
// TestWasmContReuseAfterExitAndPanic checks that a recycled g and its
// continuation work across normal return, runtime.Goexit, and panic/recover.
func TestWasmContReuseAfterExitAndPanic(t *testing.T) {
@@ -186,3 +252,62 @@ func TestWasmTraceGoEnd(t *testing.T) {
t.Errorf("%d goroutines traced as ending, want at least %d", ended, n)
}
}
+
+// TestWasmContPool checks that starting goroutines reuse pooled
+// continuations and slots from dead goroutines instead of creating new
+// ones, both when many goroutines are queued before running (as in
+// internal/sync.TestConcurrentCache) and across concurrent bursts.
+func TestWasmContPool(t *testing.T) {
+ base := runtime.NumGoroutine()
+
+ // Many goroutines started at once, which run one after another.
+ created, slots := runtime.WasmContCreated(), runtime.WasmContSlots()
+ const n = 20000
+ var wg sync.WaitGroup
+ wg.Add(n)
+ for range n {
+ go wg.Done()
+ }
+ wg.Wait()
+ waitGoroutines(t, base)
+ if d := runtime.WasmContCreated() - created; d > n/100 {
+ t.Errorf("%d goroutines created %d continuations, want at most %d", n, d, n/100)
+ }
+ // Slots are assigned when goroutines first run, not to every g.
+ if d := runtime.WasmContSlots() - slots; d > n/100 {
+ t.Errorf("%d goroutines added %d table slots, want at most %d", n, d, n/100)
+ }
+
+ // Block m goroutines at once, let them exit into the pool, then block
+ // m more to check reuse.
+ const m = 500
+ release := make(chan struct{})
+ blockedSlots(m, release)
+ close(release)
+ waitGoroutines(t, base)
+ if p := runtime.WasmContPooled(); p < m*9/10 {
+ t.Errorf("%d continuations in the pool after %d goroutines exited, want at least %d", p, m, m*9/10)
+ }
+ created = runtime.WasmContCreated()
+ release = make(chan struct{})
+ blockedSlots(m, release)
+ close(release)
+ waitGoroutines(t, base)
+ if d := runtime.WasmContCreated() - created; d > m/10 {
+ t.Errorf("%d goroutines created %d continuations with a populated pool, want at most %d", m, d, m/10)
+ }
+
+ // The pooled continuations work across stack growth, panics,
+ // runtime.Goexit and garbage collections, which free the Go stacks of
+ // dead g's but not their continuations.
+ runtime.GC()
+ done := make(chan bool)
+ for range 100 {
+ go func() {
+ useStackKB(16)
+ done <- true
+ }()
+ <-done
+ }
+ TestWasmContReuseAfterExitAndPanic(t)
+}
diff --git a/src/runtime/stackswitch_wasmx.go b/src/runtime/stackswitch_wasmx.go
index 4d4f0a927c..5a6d65aaba 100644
--- a/src/runtime/stackswitch_wasmx.go
+++ b/src/runtime/stackswitch_wasmx.go
@@ -9,29 +9,42 @@
// With stack switching, a g's WebAssembly execution stack is a continuation,
// a reference of type (ref null $cont). Reference values are opaque and
// cannot be stored in linear memory, so they cannot live in a g. Instead the
-// linker declares a continuation table, wasm table wasmContTable, and every
-// g owns one slot of it, recorded in g.wasmCont.index. A slot holds the g's
-// suspended continuation, or null if it has none: the g has not started yet,
-// or wasm_resume has taken the continuation out to resume it. (On js, a
-// synchronous callback leaves its continuation in the slot of the g that
-// called into JavaScript; see wasm_export_resume.)
+// linker declares a continuation table, wasm table wasmContTable, and each
+// live g whose goroutine has started owns one slot of it, recorded in
+// g.wasmCont.index. A slot holds the g's suspended continuation, or null if
+// it has none: the slot is new, or wasm_resume has taken the continuation
+// out to resume it. (On js, a synchronous callback leaves its continuation
+// in the slot of the g that called into JavaScript; see
+// wasm_export_resume.)
//
// When a goroutine exits, its frames are abandoned and its continuation
-// stays suspended in its g's slot. The next goroutine to run on that g
-// resumes it and unwinds the dead frames to wasm_goentry, which starts the
-// new goroutine on the same Wasm stack.
+// stays suspended. It goes to a pool of continuations (wasmContFree), and
+// the next goroutine that needs one, on any g, takes it from there and
+// unwinds the dead frames to wasm_goentry, which starts the new goroutine
+// on the same Wasm stack. So the number of continuations ever created stays
+// close to the peak number of goroutines that have begun executing and not
+// yet exited, not the number of g's, which can be far larger (a program may
+// start many goroutines before any of them runs). That matters because each
+// continuation holds an engine stack, which costs far more than a
+// goroutine's starting Go stack, and engines can hold only so many.
+// Continuations are never finished; like the g's, they live as long as the
+// program.
//
-// m0.g0 has no continuation: its code runs on the Wasm stack of the
-// goroutine that switched to it. m0.g0 is allocated statically rather than by
-// malg, so its index is 0 and slot 0 is unused. malg gives every other g a
-// slot of its own, starting at 1, which the g keeps permanently, including
-// while the g is on a free list. Like the g's themselves, slots are never
-// freed, so the table grows to the number of g's ever allocated.
+// Index 0 means no slot, and slot 0 is unused. m0.g0 never has one: it has
+// no continuation, and its code runs on the Wasm stack of the goroutine that
+// switched to it. Other g's get a slot lazily, when wasm_scheduler_loop first
+// resumes them (see wasmContStart): the slot of the most recently pooled
+// continuation, which comes with it, or a new one. A dead g pools its
+// continuation together with its slot and goes back to index 0. So the table
+// holds only unused slot 0, slots owned by live goroutines that have
+// started, and slots in wasmContFree, not one per g. Slots are never freed.
//
// WebAssembly runs a single thread, so the allocation state below needs no locking.
package runtime
+import "unsafe"
+
const (
// wasmContTable is the index of the continuation table among the
// module's wasm tables. It must match cmd/link/internal/wasm's
@@ -48,25 +61,90 @@ const (
// wasmContPerG is the per-g state of WebAssembly stack switching.
type wasmContPerG struct {
- // index is the g's slot in the continuation table, assigned by malg.
- // It is 0, an unused slot, for m0.g0.
+ // index is the g's slot in the continuation table, or 0 if it has
+ // none: m0.g0, a dead g that pooled its slot, or a g whose goroutine
+ // has not run yet (see wasmContStart). A g keeps its slot from its
+ // goroutine's first resume until it pools the slot on exit (see
+ // POOL_PUSH).
index int32
}
var (
- wasmContLast int32 // the highest slot assigned by wasmContAlloc so far
+ // wasmContFree holds the slots that no g owns. The first
+ // wasmContPooled hold the suspended continuations of dead goroutines
+ // (the pool); the others are null. A dead g pools its continuation
+ // with its own slot (POOL_PUSH inserts it at
+ // wasmContFree[wasmContPooled], moving any null slot there to the end),
+ // and a goroutine's first resume takes the most recently pooled slot
+ // (wasmContStart). When wasm_resume sees a null slot (a new slot, or on
+ // js a synchronous callback), it either decrements wasmContPooled and
+ // resumes the continuation from slot wasmContFree[wasmContPooled]
+ // (setting that pooled slot to null) if wasmContPooled > 0, or creates
+ // one with ContNew; wasm_scheduler_loop stores the yielded continuation
+ // in the goroutine's slot. cap(wasmContFree) is at least the number of
+ // assigned slots (wasmContLast; see wasmContNext), and each assigned
+ // slot is either a g's or in wasmContFree, so POOL_PUSH always has
+ // room. Its backing array is not in the GC heap, and assembly reads its
+ // pointer, length, and capacity (and updates its length).
+ wasmContFree []int32
+ wasmContPooled int32
+
+ // wasmContCreated counts the continuations wasm_resume has created.
+ wasmContCreated int32
+)
+
+var (
+ wasmContLast int32 // the highest slot assigned by wasmContNext so far
wasmContSize int32 // the continuation table's size, as last read or grown
)
-// wasmContAlloc gives gp, which malg just allocated, the next unused slot of
-// the continuation table, growing the table if the slot does not fit.
-func wasmContAlloc(gp *g) {
+// wasmContStart gives g a slot when wasm_scheduler_loop is about to resume
+// it with none (its goroutine has not run yet): the most recently pooled
+// continuation's slot, which wasm_resume then resumes, or else a new, null
+// slot, for which wasm_resume creates a continuation. It runs outside any
+// goroutine's continuation, so it must not switch goroutines or allocate
+// from the GC heap.
+//
+//go:nosplit
+func wasmContStart() {
+ gp := getg()
+ if p := wasmContPooled - 1; p >= 0 {
+ // Fill wasmContFree[p] with the last entry, so that the null
+ // slots stay after the pooled ones.
+ n := len(wasmContFree) - 1
+ gp.wasmCont.index = wasmContFree[p]
+ wasmContFree[p] = wasmContFree[n]
+ wasmContFree = wasmContFree[:n]
+ wasmContPooled = p
+ return
+ }
+ // systemstack overwrites gp.sched, which wasm_goentry reads.
+ pc, sp := gp.sched.pc, gp.sched.sp
+ var slot int32
+ systemstack(func() { slot = wasmContNext() })
+ gp.sched.pc, gp.sched.sp = pc, sp
+ gp.wasmCont.index = slot
+}
+
+// wasmContNext returns the next unused slot of the continuation table,
+// growing the table if the slot does not fit. It keeps cap(wasmContFree) at
+// least the number of assigned slots (wasmContLast), so that pooling never
+// allocates. wasmContFree is allocated with persistentalloc, so that
+// goroutine starts can grow it without triggering a garbage collection. Old
+// arrays are not freed.
+func wasmContNext() int32 {
slot := wasmContLast + 1
if slot >= wasmContSize {
wasmContGrow(slot)
}
+ if n := cap(wasmContFree); int(slot) > n {
+ c := max(2*n, 64)
+ p := persistentalloc(uintptr(c)*4, 4, &memstats.other_sys)
+ s := unsafe.Slice((*int32)(p), c)
+ wasmContFree = s[:copy(s, wasmContFree)]
+ }
wasmContLast = slot
- gp.wasmCont.index = slot
+ return slot
}
// wasmContGrow grows the continuation table so that it has slot n. It at