public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH] ensure guest's kvmclock never goes backwards when TSC jumps backward
@ 2014-07-16  9:52 Igor Mammedov
  2014-07-16 10:18 ` Paolo Bonzini
  0 siblings, 1 reply; 8+ messages in thread
From: Igor Mammedov @ 2014-07-16  9:52 UTC (permalink / raw)
  To: linux-kernel; +Cc: kvm, pbonzini, x86, mtosatti

There are buggy hosts in the wild that advertise invariant
TSC and as result host uses TSC as clocksource, but TSC on
such host sometimes sporadically jumps backwards.

This causes kvmclock to go backwards if host advertises
PVCLOCK_TSC_STABLE_BIT, which turns off aggregated clock
accumulator and returns:
  pvclock_vcpu_time_info.system_timestamp + offset
where 'offset' is calculated using TSC.
Since TSC is not virtualized in KVM, it makes guest see
TSC jumped backwards and leads to kvmclock going backwards
as well.

This is defensive patch that keeps per CPU last clock value
and ensures that clock will never go backwards even with
using PVCLOCK_TSC_STABLE_BIT enabled path.

Signed-off-by: Igor Mammedov <imammedo@redhat.com>
---
RHBZ: 1115795

---
 arch/x86/kernel/pvclock.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/arch/x86/kernel/pvclock.c b/arch/x86/kernel/pvclock.c
index 2f355d2..dd9df0e 100644
--- a/arch/x86/kernel/pvclock.c
+++ b/arch/x86/kernel/pvclock.c
@@ -71,11 +71,14 @@ u8 pvclock_read_flags(struct pvclock_vcpu_time_info *src)
 	return flags & valid_flags;
 }
 
+static DEFINE_PER_CPU(cycle_t, last_clock);
+
 cycle_t pvclock_clocksource_read(struct pvclock_vcpu_time_info *src)
 {
 	unsigned version;
 	cycle_t ret;
-	u64 last;
+	u64 last, *this_cpu_last;
+	s64 clock_delta;
 	u8 flags;
 
 	do {
@@ -87,6 +90,16 @@ cycle_t pvclock_clocksource_read(struct pvclock_vcpu_time_info *src)
 		pvclock_touch_watchdogs();
 	}
 
+	this_cpu_last = &get_cpu_var(last_clock);
+	clock_delta = ret - *this_cpu_last;
+	if (likely(clock_delta > 0)) {
+		*this_cpu_last = ret;
+	} else {
+		ret = *this_cpu_last;
+		WARN_ONCE(1, "clock went backwards");
+	}
+	put_cpu_var(last_clock);
+
 	if ((valid_flags & PVCLOCK_TSC_STABLE_BIT) &&
 		(flags & PVCLOCK_TSC_STABLE_BIT))
 		return ret;
-- 
1.8.3.1


^ permalink raw reply related	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2014-07-16 15:19 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2014-07-16  9:52 [PATCH] ensure guest's kvmclock never goes backwards when TSC jumps backward Igor Mammedov
2014-07-16 10:18 ` Paolo Bonzini
2014-07-16 11:41   ` Marcelo Tosatti
2014-07-16 13:55     ` Igor Mammedov
2014-07-16 14:16       ` Paolo Bonzini
2014-07-16 14:51         ` Igor Mammedov
2014-07-16 14:55           ` Paolo Bonzini
2014-07-16 15:18             ` Igor Mammedov

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox