diff --git a/envknob/envknob.go b/envknob/envknob.go index b0e35f5b2..53c72fc3b 100644 --- a/envknob/envknob.go +++ b/envknob/envknob.go @@ -705,3 +705,22 @@ func IPCVersion() string { } return version.Long() } + +// MaxQueues limits the amount of tun and magicsock queues to open. The value +// is capped by GOMAXPROCS and can be overridden by TS_DEBUG_MAX_QUEUES. +// +// Each extra queue means allocating a goroutine and related buffers, and brings +// diminishing returns in performance (which also only apply to nodes speaking +// with multiple concurrent peers), so we stop scaling at a sane default max: +// 16. +// +// TODO(illotum): 16 is conservative. On a subnet router peering with 256 +// concurrent clients TX grows ~6x with 16 queues, and ~10x with 128. RX is +// capped by someting else and doesn't scale with more queues at all. This value +// may and should be reevaluated after other performance improvements. +func MaxQueues() int { + if n, ok := LookupInt("TS_DEBUG_MAX_QUEUES"); ok { + return max(1, n) + } + return min(16, runtime.GOMAXPROCS(0)) +} diff --git a/net/tstun/tun.go b/net/tstun/tun.go index aedd8750e..0945df476 100644 --- a/net/tstun/tun.go +++ b/net/tstun/tun.go @@ -17,6 +17,7 @@ import ( "time" "github.com/tailscale/wireguard-go/tun" + "tailscale.com/envknob" "tailscale.com/feature" "tailscale.com/feature/buildfeatures" "tailscale.com/types/logger" @@ -58,12 +59,20 @@ func New(logf logger.Logf, tunName string) (tun.Device, string, error) { if runtime.GOOS == "plan9" { cleanUpPlan9Interfaces() } + maxQueues := envknob.MaxQueues() // Try to create the TUN device up to two times. If it fails // the first time and we're on Linux, try a desperate // "modprobe tun" to load the tun module and try again. for try := range 2 { - dev, err = tun.CreateTUN(tunName, int(DefaultTUNMTU())) + dev, err = tun.CreateTUN( + tunName, + int(DefaultTUNMTU()), + tun.WithQueues(maxQueues), + ) if err == nil || !modprobeTunHook.IsSet() { + if err == nil { + logf("opened %d of %d TUN queues", len(tun.QueuesOf(dev)), maxQueues) + } if try > 0 { logf("created TUN device %q after doing `modprobe tun`", tunName) } diff --git a/wgengine/userspace.go b/wgengine/userspace.go index 88df6566f..d748da656 100644 --- a/wgengine/userspace.go +++ b/wgengine/userspace.go @@ -430,6 +430,7 @@ func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error) EventBus: e.eventBus, Logf: logf, Port: conf.ListenPort, + UDPSockets: envknob.MaxQueues(), // in sync with tun queues EndpointsFunc: endpointsFn, DERPActiveFunc: e.RequestStatus, IdleFunc: e.tundev.IdleDuration,