diff --git a/wgengine/wgcfg/mem_ios.go b/wgengine/wgcfg/mem_ios.go index 6a520e853..f68761c67 100644 --- a/wgengine/wgcfg/mem_ios.go +++ b/wgengine/wgcfg/mem_ios.go @@ -9,8 +9,14 @@ import ( func getDeviceOptions() []device.Option { // iOS has a very restrictive memory limit on network extensions. - // Reduce the maximum amount of memory that wireguard-go can allocate - // to avoid getting killed. + // Reduce the maximum amount of memory that wireguard-go can allocate to + // avoid getting killed. + // + // See _notios.go for a longer explanation of what the Queue{In,Out}boundSize + // knobs control and the tradeoffs involved. Eventually Queue{In,Out}boundSize + // should be CPU-scaled, and WithPreallocated... removed, but we keep them all + // static for now, until the [device.WaitPool] ceiling is eliminated. + // (See tailscale/corp#46396). return []device.Option{ device.WithQueueStagedSize(64), device.WithQueueOutboundSize(64), diff --git a/wgengine/wgcfg/mem_notios.go b/wgengine/wgcfg/mem_notios.go index a1c5b2a28..18fc1398c 100644 --- a/wgengine/wgcfg/mem_notios.go +++ b/wgengine/wgcfg/mem_notios.go @@ -5,9 +5,39 @@ package wgcfg -import "github.com/tailscale/wireguard-go/device" +import ( + "runtime" + + "github.com/tailscale/wireguard-go/device" +) func getDeviceOptions() []device.Option { - // Return nothing in order to use wireguard-go defaults, e.g. [device.DefaultQueueOutboundSize]. - return nil + // wireguard-go is a packet pipeline: + // + // TUN read -> encrypt -> ordered network write + // network read -> decrypt -> ordered TUN write + // + // The queues that we are sizing in this function sit between head I/O + // goroutines and downstream functions. They are buffered channels. + // + // The head I/O ops tend to "run ahead" the downstream functions, especially + // when head I/O ops utilize segmentation offloading, where a single head I/O + // op can contain about 45 packets at a typical MTU, which is equivalent to + // 45 crypto ops. + // + // Small queues park I/O goroutines and hurt throughput; large queues allow + // more packet batches and their associated memory to remain outstanding. We + // have to find a balance. Crypto goroutines are sized to [runtime.NumCPU] + // in wireguard-go, so we start there, and apply a benchmark-backed scaling + // factor to reduce head I/O goroutines parking around bursts. + const cpuScalingFactor = 4 + // maxQueueSize was the previous static default, prior to creation of the + // [device.Option]. + const maxQueueSize = 1024 + return []device.Option{ + // TODO: make cgroup-aware with runtime.GOMAXPROCS(0). + // See tailscale/corp#47966. + device.WithQueueInboundSize(min(maxQueueSize, runtime.NumCPU()*cpuScalingFactor)), + device.WithQueueOutboundSize(min(maxQueueSize, runtime.NumCPU()*cpuScalingFactor)), + } }