diff --git a/easytier-go/internal/engine/compile.go b/easytier-go/internal/engine/compile.go new file mode 100644 index 00000000..6b7a1086 --- /dev/null +++ b/easytier-go/internal/engine/compile.go @@ -0,0 +1,51 @@ +package engine + +import ( + "context" + "sync" + + "github.com/easytier/easytier/easytier-go/internal/artifact" + "github.com/easytier/easytier/easytier-go/internal/contextutil" + "github.com/metacubex/wazero" +) + +// Every Host runs the same embedded core. Compiling it takes a couple of +// seconds of CPU, briefly allocates ~100MB, and maps ~30MB of machine code. +// Hosts in one process share a compilation cache so the core is compiled +// once. The first compiled module stays open for the life of the process, +// which keeps the cache entry available to Hosts created after it closes. +var coreCompilation struct { + sync.Mutex + cache wazero.CompilationCache + pinned bool +} + +func newRuntime(ctx context.Context) wazero.Runtime { + coreCompilation.Lock() + if coreCompilation.cache == nil { + coreCompilation.cache = wazero.NewCompilationCache() + } + cache := coreCompilation.cache + coreCompilation.Unlock() + return wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(cache)) +} + +// compileCore returns the core compiled in runtime and a function that drops +// this Host's reference to it once the module has been instantiated. +func compileCore(ctx context.Context, runtime wazero.Runtime) (wazero.CompiledModule, func(), error) { + // Hold the lock across compilation so concurrent Hosts wait for the first + // compile and then reuse its result. + coreCompilation.Lock() + defer coreCompilation.Unlock() + compiled, err := runtime.CompileModule(ctx, artifact.Core()) + if err != nil { + return nil, nil, err + } + if !coreCompilation.pinned { + coreCompilation.pinned = true + return compiled, func() {}, nil + } + return compiled, func() { + _ = compiled.Close(contextutil.WithoutCancel(ctx)) + }, nil +} diff --git a/easytier-go/internal/engine/compile_test.go b/easytier-go/internal/engine/compile_test.go new file mode 100644 index 00000000..c2ece0b9 --- /dev/null +++ b/easytier-go/internal/engine/compile_test.go @@ -0,0 +1,62 @@ +package engine + +import ( + "context" + "testing" + "time" + + "github.com/easytier/easytier/easytier-go/platform/netstd" +) + +func TestHostsSharingCompiledCoreOutliveEachOther(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + startInstance := func(host *Host) *Instance { + t.Helper() + instance, err := host.CreateInstance(ctx, minimalConfig) + if err != nil { + t.Fatalf("create instance: %v", err) + } + if err := instance.Start(ctx); err != nil { + t.Fatalf("start instance: %v", err) + } + return instance + } + + first, err := NewHost(ctx, Options{Services: netstd.Services()}) + if err != nil { + t.Fatalf("create first host: %v", err) + } + second, err := NewHost(ctx, Options{Services: netstd.Services()}) + if err != nil { + t.Fatalf("create second host: %v", err) + } + startInstance(first) + running := startInstance(second) + + if err := first.Close(ctx); err != nil { + t.Fatalf("close first host: %v", err) + } + // The second host runs code compiled by the first one; it must keep + // working after the first runtime is gone. + if state := running.State(); state != 2 { + t.Fatalf("second instance state = %d, want 2", state) + } + if err := running.Stop(ctx); err != nil { + t.Fatalf("stop second instance: %v", err) + } + if err := running.Wait(ctx); err != nil { + t.Fatalf("wait for second instance: %v", err) + } + if err := second.Close(ctx); err != nil { + t.Fatalf("close second host: %v", err) + } + + third, err := NewHost(ctx, Options{Services: netstd.Services()}) + if err != nil { + t.Fatalf("create host after all hosts closed: %v", err) + } + defer third.Close(ctx) + startInstance(third) +} diff --git a/easytier-go/internal/engine/host.go b/easytier-go/internal/engine/host.go index db2c769d..82c0e5f4 100644 --- a/easytier-go/internal/engine/host.go +++ b/easytier-go/internal/engine/host.go @@ -10,7 +10,6 @@ import ( "sync" "time" - "github.com/easytier/easytier/easytier-go/internal/artifact" "github.com/easytier/easytier/easytier-go/internal/contextutil" "github.com/easytier/easytier/easytier-go/internal/coreabi" "github.com/easytier/easytier/easytier-go/internal/hostabi" @@ -68,7 +67,7 @@ func NewHost(ctx context.Context, options Options) (_ *Host, err error) { } lifetime, cancel := context.WithCancel(contextutil.WithoutCancel(ctx)) - runtime := wazero.NewRuntime(lifetime) + runtime := newRuntime(lifetime) var module api.Module var hostReactor *reactor.Reactor defer func() { @@ -99,16 +98,16 @@ func NewHost(ctx context.Context, options Options) (_ *Host, err error) { if err = adapter.Instantiate(ctx, runtime); err != nil { return nil, fmt.Errorf("instantiate EasyTier host ABI: %w", err) } - compiled, err := runtime.CompileModule(ctx, artifact.Core()) + compiled, release, err := compileCore(ctx, runtime) if err != nil { return nil, fmt.Errorf("compile embedded EasyTier core: %w", err) } - defer compiled.Close(contextutil.WithoutCancel(ctx)) + defer release() moduleConfig := newModuleConfig() if options.LogWriter != nil { moduleConfig = moduleConfig.WithStdout(options.LogWriter) } - module, err = runtime.InstantiateModule(ctx, compiled, moduleConfig) + module, err = runtime.InstantiateModule(withGuestMemoryAllocator(ctx), compiled, moduleConfig) if err != nil { return nil, fmt.Errorf("instantiate embedded EasyTier core: %w", err) } diff --git a/easytier-go/internal/engine/memory.go b/easytier-go/internal/engine/memory.go new file mode 100644 index 00000000..f147e8f7 --- /dev/null +++ b/easytier-go/internal/engine/memory.go @@ -0,0 +1,57 @@ +package engine + +import ( + "context" + + "github.com/metacubex/wazero/experimental" +) + +// is64Bit reports whether the address space is large enough to reserve a +// full 4 GiB wasm32 linear memory up front. +const is64Bit = ^uintptr(0)>>63 == 1 + +// withGuestMemoryAllocator places the core's linear memory outside the Go +// heap on 64-bit platforms. +// +// wazero's default linear memory is a Go []byte that grows with append, so +// each memory.grow copies the whole guest heap into a fresh slice and leaves +// the old one for the GC. The guest heap is also the largest live object in +// the process, so GOGC lets the Go heap grow to about twice its size. A +// reserved mapping grows in place, stays outside GC accounting, and costs +// RSS only for the pages the guest has touched. +func withGuestMemoryAllocator(ctx context.Context) context.Context { + if !is64Bit { + return ctx + } + return experimental.WithMemoryAllocator(ctx, experimental.MemoryAllocatorFunc(newGuestMemory)) +} + +func newGuestMemory(capacity, max uint64) experimental.LinearMemory { + if memory := reserveGuestMemory(max); memory != nil { + return memory + } + return &heapMemory{buffer: make([]byte, 0, capacity), max: max} +} + +// heapMemory grows the same way as wazero's built-in allocator. It backs the +// guest when the address space reservation fails. +type heapMemory struct { + buffer []byte + max uint64 +} + +func (memory *heapMemory) Reallocate(size uint64) []byte { + if size > memory.max { + return nil + } + if size <= uint64(cap(memory.buffer)) { + memory.buffer = memory.buffer[:size] + } else { + memory.buffer = append(memory.buffer[:cap(memory.buffer)], make([]byte, size-uint64(cap(memory.buffer)))...) + } + return memory.buffer +} + +func (memory *heapMemory) Free() { + memory.buffer = nil +} diff --git a/easytier-go/internal/engine/memory_other.go b/easytier-go/internal/engine/memory_other.go new file mode 100644 index 00000000..8c5b0c1a --- /dev/null +++ b/easytier-go/internal/engine/memory_other.go @@ -0,0 +1,9 @@ +//go:build !aix && !android && !darwin && !dragonfly && !freebsd && !illumos && !ios && !linux && !netbsd && !openbsd && !solaris && !windows + +package engine + +import "github.com/metacubex/wazero/experimental" + +func reserveGuestMemory(uint64) experimental.LinearMemory { + return nil +} diff --git a/easytier-go/internal/engine/memory_test.go b/easytier-go/internal/engine/memory_test.go new file mode 100644 index 00000000..d6703502 --- /dev/null +++ b/easytier-go/internal/engine/memory_test.go @@ -0,0 +1,37 @@ +package engine + +import ( + "testing" + "unsafe" +) + +func TestGuestMemoryGrowsInPlaceWithZeroedPages(t *testing.T) { + const page = 64 << 10 + memory := newGuestMemory(page, 1024*page) + defer memory.Free() + + buffer := memory.Reallocate(2 * page) + if len(buffer) != 2*page { + t.Fatalf("length = %d, want %d", len(buffer), 2*page) + } + buffer[0], buffer[len(buffer)-1] = 1, 2 + + grown := memory.Reallocate(8 * page) + if len(grown) != 8*page { + t.Fatalf("grown length = %d, want %d", len(grown), 8*page) + } + if grown[0] != 1 || grown[2*page-1] != 2 { + t.Fatal("growth lost existing contents") + } + for i, b := range grown[2*page:] { + if b != 0 { + t.Fatalf("new byte %d = %d, want 0", 2*page+i, b) + } + } + if _, onHeap := memory.(*heapMemory); !onHeap && unsafe.SliceData(grown) != unsafe.SliceData(buffer) { + t.Fatal("mapped memory moved while growing") + } + if memory.Reallocate(1025*page) != nil { + t.Fatal("growth past the maximum succeeded") + } +} diff --git a/easytier-go/internal/engine/memory_unix.go b/easytier-go/internal/engine/memory_unix.go new file mode 100644 index 00000000..554bc460 --- /dev/null +++ b/easytier-go/internal/engine/memory_unix.go @@ -0,0 +1,47 @@ +//go:build aix || android || darwin || dragonfly || freebsd || illumos || ios || linux || netbsd || openbsd || solaris + +package engine + +import ( + "golang.org/x/sys/unix" +) + +// mappedMemory reserves the whole linear memory as an inaccessible mapping +// and makes pages readable and writable as the guest grows into them. Fresh +// anonymous pages are zero-filled, as memory.grow requires. +type mappedMemory struct { + reserved []byte + committed uint64 +} + +func reserveGuestMemory(max uint64) *mappedMemory { + if max == 0 || max > uint64(^uint(0)>>1) { + return nil + } + reserved, err := unix.Mmap(-1, 0, int(max), unix.PROT_NONE, unix.MAP_PRIVATE|unix.MAP_ANON) + if err != nil { + return nil + } + return &mappedMemory{reserved: reserved} +} + +func (memory *mappedMemory) Reallocate(size uint64) []byte { + if size > uint64(len(memory.reserved)) { + return nil + } + if size > memory.committed { + if err := unix.Mprotect(memory.reserved[memory.committed:size], unix.PROT_READ|unix.PROT_WRITE); err != nil { + return nil + } + memory.committed = size + } + return memory.reserved[:size:size] +} + +func (memory *mappedMemory) Free() { + if memory.reserved != nil { + _ = unix.Munmap(memory.reserved) + memory.reserved = nil + memory.committed = 0 + } +} diff --git a/easytier-go/internal/engine/memory_windows.go b/easytier-go/internal/engine/memory_windows.go new file mode 100644 index 00000000..12c5e282 --- /dev/null +++ b/easytier-go/internal/engine/memory_windows.go @@ -0,0 +1,52 @@ +//go:build windows + +package engine + +import ( + "unsafe" + + "golang.org/x/sys/windows" +) + +// mappedMemory reserves the whole linear memory and commits pages as the +// guest grows into them. Newly committed pages are zero-filled, as +// memory.grow requires. +type mappedMemory struct { + reserved []byte + committed uint64 +} + +func reserveGuestMemory(max uint64) *mappedMemory { + if max == 0 || max > uint64(^uintptr(0)>>1) { + return nil + } + address, err := windows.VirtualAlloc(0, uintptr(max), windows.MEM_RESERVE, windows.PAGE_NOACCESS) + if err != nil { + return nil + } + // The reservation is outside the Go heap. + base := *(*unsafe.Pointer)(unsafe.Pointer(&address)) + return &mappedMemory{reserved: unsafe.Slice((*byte)(base), max)} +} + +func (memory *mappedMemory) Reallocate(size uint64) []byte { + if size > uint64(len(memory.reserved)) { + return nil + } + if size > memory.committed { + address := uintptr(unsafe.Pointer(unsafe.SliceData(memory.reserved))) + uintptr(memory.committed) + if _, err := windows.VirtualAlloc(address, uintptr(size-memory.committed), windows.MEM_COMMIT, windows.PAGE_READWRITE); err != nil { + return nil + } + memory.committed = size + } + return memory.reserved[:size:size] +} + +func (memory *mappedMemory) Free() { + if memory.reserved != nil { + _ = windows.VirtualFree(uintptr(unsafe.Pointer(unsafe.SliceData(memory.reserved))), 0, windows.MEM_RELEASE) + memory.reserved = nil + memory.committed = 0 + } +}