From 768c0364e446b6ee5a0ff9e48936f88c2a60a4fa Mon Sep 17 00:00:00 2001 From: Jamie Liu Date: Mon, 17 Mar 2025 14:21:28 -0700 Subject: [PATCH] kvm: unlock OS thread during machine.available.Wait() PiperOrigin-RevId: 737750303 --- pkg/sentry/platform/kvm/machine.go | 31 ++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/pkg/sentry/platform/kvm/machine.go b/pkg/sentry/platform/kvm/machine.go index 9bfb642b0..a89dea170 100644 --- a/pkg/sentry/platform/kvm/machine.go +++ b/pkg/sentry/platform/kvm/machine.go @@ -531,18 +531,19 @@ func (m *machine) Get() *vCPU { m.mu.RUnlock() runtime.UnlockOSThread() m.mu.Lock() - runtime.LockOSThread() - tid = hosttid.Current() - - // Recheck for an exact match. - if c := m.vCPUsByTID[tid]; c != nil { - c.lock() - m.mu.Unlock() - getVCPUCounter.Increment(&getVCPUAcquisitionReused) - return c - } for { + runtime.LockOSThread() + tid = hosttid.Current() + + // Recheck for an exact match. + if c := m.vCPUsByTID[tid]; c != nil { + c.lock() + m.mu.Unlock() + getVCPUCounter.Increment(&getVCPUAcquisitionReused) + return c + } + // Get vCPU from the m.vCPUsByID pool. if m.usedVCPUs < m.maxVCPUs { c := m.vCPUsByID[m.usedVCPUs] @@ -594,10 +595,12 @@ func (m *machine) Get() *vCPU { return c } - // Everything is executing in user mode. Wait until something - // is available. Note that signaling the condition variable - // will have the extra effect of kicking the vCPUs out of guest - // mode if that's where they were. + // Everything is executing in user mode. Wait until something is + // available. As with m.mu.Lock() above, unlock the OS thread while we + // do this to avoid spawning additional system threads. Note that + // signaling the condition variable will have the extra effect of + // kicking the vCPUs out of guest mode if that's where they were. + runtime.UnlockOSThread() m.available.Wait() } }