KVM: x86: Prevent 'hv_clock->system_time' from going negative in kvm_guest_time_update()
authorVitaly Kuznetsov <vkuznets@redhat.com>
Wed, 31 Mar 2021 12:41:29 +0000 (14:41 +0200)
committerPaolo Bonzini <pbonzini@redhat.com>
Thu, 1 Apr 2021 09:14:19 +0000 (05:14 -0400)
commit77fcbe823f002ad18426545351fa2fb94f8d5e61
tree23ce711101f3aab33c6fea0e336d947bf34ea49a
parenta83829f56c7ce17d5d05370820e185d9a23d3090
KVM: x86: Prevent 'hv_clock->system_time' from going negative in kvm_guest_time_update()

When guest time is reset with KVM_SET_CLOCK(0), it is possible for
'hv_clock->system_time' to become a small negative number. This happens
because in KVM_SET_CLOCK handling we set 'kvm->arch.kvmclock_offset' based
on get_kvmclock_ns(kvm) but when KVM_REQ_CLOCK_UPDATE is handled,
kvm_guest_time_update() does (masterclock in use case):

hv_clock.system_time = ka->master_kernel_ns + v->kvm->arch.kvmclock_offset;

And 'master_kernel_ns' represents the last time when masterclock
got updated, it can precede KVM_SET_CLOCK() call. Normally, this is not a
problem, the difference is very small, e.g. I'm observing
hv_clock.system_time = -70 ns. The issue comes from the fact that
'hv_clock.system_time' is stored as unsigned and 'system_time / 100' in
compute_tsc_page_parameters() becomes a very big number.

Use 'master_kernel_ns' instead of get_kvmclock_ns() when masterclock is in
use and get_kvmclock_base_ns() when it's not to prevent 'system_time' from
going negative.

Signed-off-by: Vitaly Kuznetsov <vkuznets@redhat.com>
Message-Id: <20210331124130.337992-2-vkuznets@redhat.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
arch/x86/kvm/x86.c