Re: [RFC] KVM: x86: Allow userspace exit on HLT and MWAIT, else yield on MWAIT
From: Paolo Bonzini
Date: Fri Sep 22 2023 - 08:01:08 EST
On Mon, Sep 18, 2023 at 11:30 AM David Woodhouse <dwmw2@xxxxxxxxxxxxx> wrote:
>
> From: David Woodhouse <dwmw@xxxxxxxxxxxx>
>
> The VMM may have work to do on behalf of the guest, and it's often
> desirable to use the cycles when the vCPUS are idle.
>
> When the vCPU uses HLT this works out OK because the VMM can run its
> tasks in a separate thread which gets scheduled when the in-kernel
> emulation of HLT schedules away. It isn't perfect, because it doesn't
> easily allow for handling both low-priority maintenance tasks when the
> VMM wants to wait until the vCPU is idle, and also for higher priority
> tasks where the VMM does want to preempt the vCPU. It can also lead to
> noisy neighbour effects, when a host has isn't necessarily sized to
> expect any given VMM to suddenly be contending for many *more* pCPUs
> than it has vCPUs.
>
> In addition, there are times when we need to expose MWAIT to a guest
> for compatibility with a previous environment. And MWAIT is much harder
> because it's very hard to emulate properly.
I don't dislike giving userspace more flexibility in deciding when to
exit on HLT and MWAIT (or even PAUSE), and kvm_run is a good place to
do this. It's an extension of request_interrupt_window and
immediate_exit. I'm not sure how it would interact with
KVM_CAP_X86_DISABLE_EXITS. Perhaps
KVM_ENABLE_CAP(KVM_X86_DISABLE_EXITS) could be changed to do nothing
except writing to a new kvm_run field? All the kvm->arch.*_in_guest
field would change into a kvm->arch.saved_request_userspace_exit, and
every vmentry would do something like
if (kvm->arch.saved_request_userspace_exit !=
kvm_run->request_userspace_exit) {
/* tweak intercepts */
}
To avoid races you need two flags though; there needs to be also a
kernel->userspace communication of whether the vCPU is currently in
HLT or MWAIT, using the "flags" field for example. If it was HLT only,
moving the mp_state in kvm_run would seem like a good idea; but not if
MWAIT or PAUSE are also included.
To set a kvm_run flag during MWAIT, you could reenter MWAIT with the
MWAIT-exiting bit cleared and the monitor trap flag bit (or just
EFLAGS.TF) set. On the subsequent singlestep exit, clear the flag in
kvm_run and set again the MWAIT-exiting bit. The MWAIT handler would
also check kvm_run->request_userspace_exit before reentering.
Paolo