Skip to contentSkip to conversation

x86: kvm: Revert "remove sched notifier for cross-cpu migrations"

PATCH Marcelo Tosatti 4 participants 32 messages Mar 23, 2015 – Mar 26, 2015

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Add task migration notification back.

Problem noticed by Andy Lutomirski.

arch/x86/include/asm/pvclock.h +1 -0
index d6b078e..25b1cc0 100644
@@ -95,6 +95,7 @@ unsigned __pvclock_read_cycles(const struct pvclock_vcpu_time_info *src,
 
 struct pvclock_vsyscall_time_info {
 	struct pvclock_vcpu_time_info pvti;
+	u32 migrate_count;
 } __attribute__((__aligned__(SMP_CACHE_BYTES)));
 
 #define PVTI_SIZE sizeof(struct pvclock_vsyscall_time_info)
arch/x86/kernel/pvclock.c +44 -0

63 lines not on this page · raw message

arch/x86/vdso/vclock_gettime.c +8 -8
index 9793322..3093376 100644
@@ -82,18 +82,15 @@ static notrace cycle_t vread_pvclock(int *mode)
 	cycle_t ret;
 	u64 last;
 	u32 version;
+	u32 migrate_count;
 	u8 flags;
 	unsigned cpu, cpu1;
 
 
 	/*
-	 * Note: hypervisor must guarantee that:
-	 * 1. cpu ID number maps 1:1 to per-CPU pvclock time info.
-	 * 2. that per-CPU pvclock time info is updated if the
-	 *    underlying CPU changes.
-	 * 3. that version is increased whenever underlying CPU
-	 *    changes.
-	 *
+	 * When looping to get a consistent (time-info, tsc) pair, we
+	 * also need to deal with the possibility we can switch vcpus,
+	 * so make sure we always re-fetch time-info for the current vcpu.
 	 */
 	do {
 		cpu = __getcpu() & VGETCPU_CPU_MASK;
@@ -104,6 +101,8 @@ static notrace cycle_t vread_pvclock(int *mode)
 
 		pvti = get_pvti(cpu);
 
+		migrate_count = pvti->migrate_count;
+
 		version = __pvclock_read_cycles(&pvti->pvti, &ret, &flags);
 
 		/*
@@ -115,7 +114,8 @@ static notrace cycle_t vread_pvclock(int *mode)
 		cpu1 = __getcpu() & VGETCPU_CPU_MASK;
 	} while (unlikely(cpu != cpu1 ||
 			  (pvti->pvti.version & 1) ||
-			  pvti->pvti.version != version));
+			  pvti->pvti.version != version ||
+			  pvti->migrate_count != migrate_count));
 
 	if (unlikely(!(flags & PVCLOCK_TSC_STABLE_BIT)))
 		*mode = VCLOCK_NONE;
include/linux/sched.h +8 -0
index 6d77432..be98910 100644
@@ -176,6 +176,14 @@ extern void get_iowait_load(unsigned long *nr_waiters, unsigned long *load);
 extern void calc_global_load(unsigned long ticks);
 extern void update_cpu_load_nohz(void);
 
+/* Notifier for when a task gets migrated to a new CPU */
+struct task_migration_notifier {
+	struct task_struct *task;
+	int from_cpu;
+	int to_cpu;
+};
+extern void register_task_migration_notifier(struct notifier_block *n);
+
 extern unsigned long get_parent_ip(unsigned long addr);
 
 extern void dump_cpu_task(int cpu);
kernel/sched/core.c +15 -0
index f0f831e..d0c4209 100644
@@ -996,6 +996,13 @@ void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
 		rq_clock_skip_update(rq, true);
 }
 
+static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
+
+void register_task_migration_notifier(struct notifier_block *n)
+{
+	atomic_notifier_chain_register(&task_migration_notifier, n);
+}
+
 #ifdef CONFIG_SMP
 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
 {
@@ -1026,10 +1033,18 @@ void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
 	trace_sched_migrate_task(p, new_cpu);
 
 	if (task_cpu(p) != new_cpu) {
+		struct task_migration_notifier tmn;
+
 		if (p->sched_class->migrate_task_rq)
 			p->sched_class->migrate_task_rq(p, new_cpu);
 		p->se.nr_migrations++;
 		perf_sw_event_sched(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 0);
+
+		tmn.task = p;
+		tmn.from_cpu = task_cpu(p);
+		tmn.to_cpu = new_cpu;
+
+		atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
 	}
 
 	__set_task_cpu(p, new_cpu);
#1 lore raw
Quoted 10 lines · Marcelo Tosatti

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Add task migration notification back.

IMO this is a pretty big hammer to use to work around what appears to be a bug in the host, but I guess that's okay.

It's also unfortunate in another regard: it seems non-obvious to me how to use this without reading the cpu number twice in the vdso. On the other hand, unless we have a global pvti, or at least a global indication of TSC stability, I don't see how to do that even with the host bug fixed.

Grumble.

On a more useful note, could you rename migrate_count to migrate_from_count, since that's what it is?

--Andy

#2 lore raw
In reply to Marcelo Tosatti

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 7 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

I think that the revert doesn't fix point 2.: "KVM: x86: update pvclock [...]" changed the host to skip clock update on physical CPU change, but guest's task migration notifier isn't tied to it at all. (Guest can have all tasks pinned, so the revert changed nothing.)

Quoted 3 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

What is the problem?

Thanks.

#3 lore raw
Quoted 14 lines · Radim Krčmář

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 7 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

I think that the revert doesn't fix point 2.: "KVM: x86: update pvclock [...]" changed the host to skip clock update on physical CPU change, but guest's task migration notifier isn't tied to it at all. (Guest can have all tasks pinned, so the revert changed nothing.)

Quoted 5 lines
Quoted 3 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

What is the problem?

The kvmclock spec says that the host will increment a version field to an odd number, then update stuff, then increment it to an even number. The host is buggy and doesn't do this, and the result is observable when one vcpu reads another vcpu's kvmclock data.

Since there's no good way for a guest kernel to keep its vdso from reading a different vcpu's kvmclock data, this is a real corner-case bug. This patch allows the vdso to retry when this happens. I don't think it's a great solution, but it should mostly work.

--Andy

#25 lore raw
In reply to Radim Krčmář
Quoted 6 lines · Radim Krčmář

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 5 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Quoted 6 lines
Quoted 2 lines

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

I think that the revert doesn't fix point 2.: "KVM: x86: update pvclock [...]" changed the host to skip clock update on physical CPU change, but guest's task migration notifier isn't tied to it at all.

"per-CPU pvclock time info is updated if the underlying CPU changes" is the same as
"always perform clock update on physical CPU change".

That was a requirement for the original patch, to drop migration notifiers.

Quoted 9 lines

(Guest can have all tasks pinned, so the revert changed nothing.)

Quoted 3 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

What is the problem?

Thanks.

The problem is this:

T1) guest thread1 on vcpu1.
T2) guest thread1 on vcpu2.
T3) guest thread1 on vcpu1.

Inside a pvclock read loop.

Since the writes by hypervisor of pvclock area are not ordered, you cannot rely on version being updated _before_
the rest of pvclock data.

(in the case above, "has the physical cpu changed" check, inside the guests thread1, obviously fails).

#4 lore raw
In reply to Andy Lutomirski

2015-03-24 15:33-0700, Andy Lutomirski:

Quoted 8 lines · Radim Krčmář
Quoted 1 line

What is the problem?

The kvmclock spec says that the host will increment a version field to an odd number, then update stuff, then increment it to an even number. The host is buggy and doesn't do this, and the result is observable when one vcpu reads another vcpu's kvmclock data.

Quoted 4 lines

Since there's no good way for a guest kernel to keep its vdso from reading a different vcpu's kvmclock data, this is a real corner-case bug. This patch allows the vdso to retry when this happens. I don't think it's a great solution, but it should mostly work.

Great explanation, thank you.

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

arch/x86/kvm/x86.c +22 -5
index cc2c759f69a3..8658599e0024 100644
@@ -1658,12 +1658,24 @@ static int kvm_guest_time_update(struct kvm_vcpu *v)
 		&guest_hv_clock, sizeof(guest_hv_clock))))
 		return 0;
 
-	/*
-	 * The interface expects us to write an even number signaling that the
-	 * update is finished. Since the guest won't see the intermediate
-	 * state, we just increase by 2 at the end.
+	/* A guest can read other VCPU's kvmclock; specification says that
+	 * version is odd if data is being modified and even after it is
+	 * consistent.
+	 * We write three times to be sure.
+	 *  1) update version to odd number
+	 *  2) write modified data (version is still odd)
+	 *  3) update version to even number
+	 *
+	 * TODO: optimize
+	 *  - only two writes should be enough -- version is first
+	 *  - the second write could update just version
 	 */
-	vcpu->hv_clock.version = guest_hv_clock.version + 2;
+	guest_hv_clock.version += 1;
+	kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
+				&guest_hv_clock,
+				sizeof(guest_hv_clock));
+
+	vcpu->hv_clock.version = guest_hv_clock.version;
 
 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
 	pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
@@ -1684,6 +1696,11 @@ static int kvm_guest_time_update(struct kvm_vcpu *v)
 	kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
 				&vcpu->hv_clock,
 				sizeof(vcpu->hv_clock));
+
+	vcpu->hv_clock.version += 1;
+	kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
+				&vcpu->hv_clock,
+				sizeof(vcpu->hv_clock));
 	return 0;
 }
 
#26 lore raw
In reply to Marcelo Tosatti

2015-03-24 19:59-0300, Marcelo Tosatti:

Quoted 37 lines · Radim Krčmář
Quoted 6 lines

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 5 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Quoted 6 lines
Quoted 2 lines

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

I think that the revert doesn't fix point 2.: "KVM: x86: update pvclock [...]" changed the host to skip clock update on physical CPU change, but guest's task migration notifier isn't tied to it at all.

"per-CPU pvclock time info is updated if the underlying CPU changes" is the same as
"always perform clock update on physical CPU change".

That was a requirement for the original patch, to drop migration notifiers.

Quoted 9 lines

(Guest can have all tasks pinned, so the revert changed nothing.)

Quoted 3 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

What is the problem?

Thanks.

The problem is this:

T1) guest thread1 on vcpu1.
T2) guest thread1 on vcpu2.
T3) guest thread1 on vcpu1.

Quoted 8 lines

Inside a pvclock read loop.

Since the writes by hypervisor of pvclock area are not ordered, you cannot rely on version being updated _before_
the rest of pvclock data.

(in the case above, "has the physical cpu changed" check, inside the guests thread1, obviously fails).

Ah, thanks! so the "KVM: x86: update pvclock area conditionally [...]" has nothing to do with it -- that really confused me.

#5 lore raw
In reply to Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 7 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

Reviewed-by
#27 lore raw
In reply to Marcelo Tosatti

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 8 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Quoted 6 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

Please improve the commit message.
"KVM: x86: update pvclock area conditionally [...]" was merged half a year before the patch we are reverting and is completely unrelated to the bug we are fixing now, (reverted patch just was just wrong)

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 85

Quoted 13 lines
arch/x86/vdso/vclock_gettime.c +3 -7
@@ -82,18 +82,15 @@ static notrace cycle_t vread_pvclock(int *mode)
 	/*
-	 * Note: hypervisor must guarantee that:
-	 * 1. cpu ID number maps 1:1 to per-CPU pvclock time info.
-	 * 2. that per-CPU pvclock time info is updated if the
-	 *    underlying CPU changes.
-	 * 3. that version is increased whenever underlying CPU
-	 *    changes.
-	 *
+	 * When looping to get a consistent (time-info, tsc) pair, we
+	 * also need to deal with the possibility we can switch vcpus,
+	 * so make sure we always re-fetch time-info for the current vcpu.

(All points from the original comment need to hold -- it would be nicer
to keep both.)

#6 lore raw
In reply to Radim Krčmář
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

#7 lore raw
Quoted 11 lines · Marcelo Tosatti
Quoted 9 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 7 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

Quoted 9 lines
Quoted 3 lines

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

#8 lore raw
Quoted 22 lines · Andy Lutomirski
Quoted 11 lines · Marcelo Tosatti
Quoted 9 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 7 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

Quoted 9 lines
Quoted 3 lines

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

#9 lore raw
Quoted 23 lines · Marcelo Tosatti
Quoted 22 lines · Andy Lutomirski
Quoted 20 lines · Marcelo Tosatti
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 8 lines
Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

If you have a 512-vcpu system that switches between stable and unstable more than once per migration, then I expect that you have serious problems and this is the least of your worries.

Personally, I'd *much* rather we just made vcpu 0's pvti authoritative if we're stable. If nothing else, I'm not even remotely convinced that the current scheme gives monotonic timing due to skew between when the updates happen on different vcpus.

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#10 lore raw
Quoted 33 lines · Andy Lutomirski
Quoted 23 lines · Marcelo Tosatti
Quoted 22 lines · Andy Lutomirski
Quoted 20 lines · Marcelo Tosatti
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 8 lines
Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

Quoted 8 lines

If you have a 512-vcpu system that switches between stable and unstable more than once per migration, then I expect that you have serious problems and this is the least of your worries.

Personally, I'd *much* rather we just made vcpu 0's pvti authoritative if we're stable. If nothing else, I'm not even remotely convinced that the current scheme gives monotonic timing due to skew between when the updates happen on different vcpus.

Can you write down the problem ?

#11 lore raw
Quoted 38 lines · Marcelo Tosatti
Quoted 37 lines · Andy Lutomirski
Quoted 23 lines · Marcelo Tosatti
Quoted 22 lines · Andy Lutomirski
Quoted 20 lines · Marcelo Tosatti
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 8 lines
Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

If you have a 512-vcpu system that switches between stable and unstable more than once per migration, then I expect that you have serious problems and this is the least of your worries.

Quoted 7 lines
Quoted 4 lines

Personally, I'd *much* rather we just made vcpu 0's pvti authoritative if we're stable. If nothing else, I'm not even remotely convinced that the current scheme gives monotonic timing due to skew between when the updates happen on different vcpus.

Can you write down the problem ?

I can try.

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#12 lore raw
Quoted 47 lines · Andy Lutomirski
Quoted 38 lines · Marcelo Tosatti
Quoted 37 lines · Andy Lutomirski
Quoted 23 lines · Marcelo Tosatti
Quoted 22 lines · Andy Lutomirski
Quoted 20 lines · Marcelo Tosatti
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 8 lines
Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

If you have a 512-vcpu system that switches between stable and unstable more than once per migration, then I expect that you have serious problems and this is the least of your worries.

Quoted 7 lines
Quoted 4 lines

Personally, I'd *much* rather we just made vcpu 0's pvti authoritative if we're stable. If nothing else, I'm not even remotely convinced that the current scheme gives monotonic timing due to skew between when the updates happen on different vcpus.

Can you write down the problem ?

Quoted 8 lines

I can try.

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

#22 lore raw
In reply to Radim Krčmář
Quoted 60 lines · Radim Krčmář

2015-03-24 15:33-0700, Andy Lutomirski:

Quoted 8 lines · Radim Krčmář
Quoted 1 line

What is the problem?

The kvmclock spec says that the host will increment a version field to an odd number, then update stuff, then increment it to an even number. The host is buggy and doesn't do this, and the result is observable when one vcpu reads another vcpu's kvmclock data.

Quoted 4 lines

Since there's no good way for a guest kernel to keep its vdso from reading a different vcpu's kvmclock data, this is a real corner-case bug. This patch allows the vdso to retry when this happens. I don't think it's a great solution, but it should mostly work.

Great explanation, thank you.

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

arch/x86/kvm/x86.c +17 -5
index cc2c759f69a3..8658599e0024 100644
@@ -1658,12 +1658,24 @@ static int kvm_guest_time_update(struct kvm_vcpu *v)
                &guest_hv_clock, sizeof(guest_hv_clock))))
                return 0;
 
-       /*
-        * The interface expects us to write an even number signaling that the
-        * update is finished. Since the guest won't see the intermediate
-        * state, we just increase by 2 at the end.
+       /* A guest can read other VCPU's kvmclock; specification says that
+        * version is odd if data is being modified and even after it is
+        * consistent.
+        * We write three times to be sure.
+        *  1) update version to odd number
+        *  2) write modified data (version is still odd)
+        *  3) update version to even number
+        *
+        * TODO: optimize
+        *  - only two writes should be enough -- version is first
+        *  - the second write could update just version
         */
-       vcpu->hv_clock.version = guest_hv_clock.version + 2;
+       guest_hv_clock.version += 1;
+       kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
+                               &guest_hv_clock,
+                               sizeof(guest_hv_clock));
+
+       vcpu->hv_clock.version = guest_hv_clock.version;
 
        /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
        pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
@@ -1684,6 +1696,11 @@ static int kvm_guest_time_update(struct kvm_vcpu *v)
        kvm_write_guest_cached(v->kvm, &vcpu->pv_time,

arch/x86/kvm/x86.c static int kvm_guest_time_update(struct kvm_vcpu *v) · line 1706

Quoted 10 lines
arch/x86/kvm/x86.c +5 -0
                                &vcpu->hv_clock,
                                sizeof(vcpu->hv_clock));
+
+       vcpu->hv_clock.version += 1;
+       kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
+                               &vcpu->hv_clock,
+                               sizeof(vcpu->hv_clock));
        return 0;
 }
 

The trouble with this is that kvm_write_guest_cached seems to correspond roughly to a "rep movs" variant, and those are weakly ordered. As a result, I don't really know whether they have well-defined semantics wrt concurrent reads. What we really want is just "mov".

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#13 lore raw
In reply to Marcelo Tosatti
Quoted 61 lines · Marcelo Tosatti
Quoted 47 lines · Andy Lutomirski
Quoted 38 lines · Marcelo Tosatti
Quoted 37 lines · Andy Lutomirski
Quoted 23 lines · Marcelo Tosatti
Quoted 22 lines · Andy Lutomirski
Quoted 20 lines · Marcelo Tosatti
Quoted 6 lines · Radim Krčmář

2015-03-25 12:08+0100, Radim Krčmář:

Quoted 5 lines

Reverting the patch protects us from any migration, but I don't think we need to care about changing VCPUs as long as we read a consistent data from kvmclock. (VCPU can change outside of this loop too, so it doesn't matter if we return a value not fit for this VCPU.)

Quoted 6 lines
Quoted 2 lines

I think we could drop the second __getcpu if our kvmclock was being handled better; maybe with a patch like the one below:

The second __getcpu is not neccessary, but I forgot about rdtsc. We need to either use rtdscp, know the host has synchronized tsc, or monitor VCPU migrations. Only the last one works everywhere.

The vdso code is only used if host has synchronized tsc.

But you have to handle the case where host goes from synchronized tsc to unsynchronized tsc (see the clocksource notifier in the host side).

Quoted 8 lines
Quoted 5 lines

Can't we change the host to freeze all vcpus and clear the stable bit on all of them if this happens? This would simplify and speed up vclock_gettime.

--Andy

Seems interesting to do on 512-vcpus, but sure, could be done.

If you have a 512-vcpu system that switches between stable and unstable more than once per migration, then I expect that you have serious problems and this is the least of your worries.

Quoted 7 lines
Quoted 4 lines

Personally, I'd *much* rather we just made vcpu 0's pvti authoritative if we're stable. If nothing else, I'm not even remotely convinced that the current scheme gives monotonic timing due to skew between when the updates happen on different vcpus.

Can you write down the problem ?

Quoted 8 lines

I can try.

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 12 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

[resend without HTML]

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at, and we need another to make sure that we were actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.). The migration hook has the same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

--Andy

#23 lore raw
In reply to Andy Lutomirski

2015-03-26 11:47-0700, Andy Lutomirski:

Quoted 12 lines · Radim Krčmář
Quoted 11 lines
arch/x86/kvm/x86.c +10 -0
+       /* A guest can read other VCPU's kvmclock; specification says that
+        * version is odd if data is being modified and even after it is
+        * consistent.
+        * We write three times to be sure.
+        *  1) update version to odd number
+        *  2) write modified data (version is still odd)
+        *  3) update version to even number
+        *
+        * TODO: optimize
+        *  - only two writes should be enough -- version is first
Quoted 8 lines
Quoted 2 lines

+ * - the second write could update just version

         */

The trouble with this is that kvm_write_guest_cached seems to correspond roughly to a "rep movs" variant, and those are weakly ordered. As a result, I don't really know whether they have well-defined semantics wrt concurrent reads. What we really want is just "mov".

Ah, so the first optimization TODO is not possible, but stores are
weakly ordered only within one rep movs. We're safe if compiler
outputs three mov-like instructions.

(Btw. does current hardware reorder string stores?)

#14 lore raw
In reply to Andy Lutomirski

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

Quoted 3 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

maintainer
#24 lore raw
In reply to Radim Krčmář
Quoted 22 lines · Radim Krčmář

2015-03-26 11:47-0700, Andy Lutomirski:

Quoted 12 lines · Radim Krčmář
Quoted 11 lines
arch/x86/kvm/x86.c +10 -0
+       /* A guest can read other VCPU's kvmclock; specification says that
+        * version is odd if data is being modified and even after it is
+        * consistent.
+        * We write three times to be sure.
+        *  1) update version to odd number
+        *  2) write modified data (version is still odd)
+        *  3) update version to even number
+        *
+        * TODO: optimize
+        *  - only two writes should be enough -- version is first
Quoted 8 lines
Quoted 2 lines

+ * - the second write could update just version

         */

The trouble with this is that kvm_write_guest_cached seems to correspond roughly to a "rep movs" variant, and those are weakly ordered. As a result, I don't really know whether they have well-defined semantics wrt concurrent reads. What we really want is just "mov".

Quoted 5 lines

Ah, so the first optimization TODO is not possible, but stores are
weakly ordered only within one rep movs. We're safe if compiler
outputs three mov-like instructions.

(Btw. does current hardware reorder string stores?)

It probably does so if they hit multiple cache lines. Within a cache line, probably not.

We can add kvm_map/unmap_guest_cached and then use __put_user.

Paolo

#15 lore raw
In reply to Radim Krcmar
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

b) If version remains buggy but we use this migrations_from hack:

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

Why doesn't KVM just update all of the kvmclock data at once? (For that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

--Andy

#28 lore raw
In reply to Marcelo Tosatti

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 9 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Quoted 6 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

Revert contains a bug that got pointed out in the discussion:

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode)

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +0 -0
 	do {
 		cpu = __getcpu() & VGETCPU_CPU_MASK;
 
 		pvti = get_pvti(cpu);

We can migrate to 'other cpu' here.

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 106

Quoted 3 lines
arch/x86/vdso/vclock_gettime.c +2 -0
+		migrate_count = pvti->migrate_count;
+
 		version = __pvclock_read_cycles(&pvti->pvti, &ret, &flags);

And migrate back to 'cpu' here.

rdtsc was executed on different cpu, so pvti and tsc might not be in sync, but migrate_count hasn't changed.

Quoted 1 line

cpu1 = __getcpu() & VGETCPU_CPU_MASK;

(Reading cpuid here is useless.)

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 118

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +2 -1
 	} while (unlikely(cpu != cpu1 ||
 			  (pvti->pvti.version & 1) ||
-			  pvti->pvti.version != version));
+			  pvti->pvti.version != version ||
+			  pvti->migrate_count != migrate_count));

We can workaround the bug with,

  	cpu = __getcpu() & VGETCPU_CPU_MASK;
  	pvti = get_pvti(cpu);
  	migrate_count = pvti->migrate_count;
  	if (cpu != (__getcpu() & VGETCPU_CPU_MASK))
  		continue;
#16 lore raw
In reply to Andy Lutomirski

[much snippage]

Quoted 10 lines · Andy Lutomirski

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

Rik pointed out that this could actually be okay. Apparently vcpu 0 is somewhat special, and it may actually be impossible to switch from stable to unstable which a vcpu other than 0 is running and vcpu0 hasn't updated its kvmclock data.

--Andy

Quoted 7 lines

Why doesn't KVM just update all of the kvmclock data at once? (For that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#29 lore raw
In reply to Radim Krčmář
Quoted 27 lines · Radim Krčmář

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 9 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Quoted 6 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

Revert contains a bug that got pointed out in the discussion:

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode)

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +0 -0
 	do {
 		cpu = __getcpu() & VGETCPU_CPU_MASK;
 
 		pvti = get_pvti(cpu);

We can migrate to 'other cpu' here.

Quoted 5 lines

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 106

Quoted 3 lines
arch/x86/vdso/vclock_gettime.c +2 -0
+		migrate_count = pvti->migrate_count;
+
 		version = __pvclock_read_cycles(&pvti->pvti, &ret, &flags);

And migrate back to 'cpu' here.

Migrating back will increase pvti->migrate_count, right ?

Quoted 20 lines

rdtsc was executed on different cpu, so pvti and tsc might not be in sync, but migrate_count hasn't changed.

Quoted 1 line

cpu1 = __getcpu() & VGETCPU_CPU_MASK;

(Reading cpuid here is useless.)

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 118

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +2 -1
 	} while (unlikely(cpu != cpu1 ||
 			  (pvti->pvti.version & 1) ||
-			  pvti->pvti.version != version));
+			  pvti->pvti.version != version ||
+			  pvti->migrate_count != migrate_count));

We can workaround the bug with,

  	cpu = __getcpu() & VGETCPU_CPU_MASK;
  	pvti = get_pvti(cpu);
  	migrate_count = pvti->migrate_count;
  	if (cpu != (__getcpu() & VGETCPU_CPU_MASK))
  		continue;
#30 lore raw
Quoted 28 lines · Marcelo Tosatti
Quoted 27 lines · Radim Krčmář

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 9 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Quoted 6 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

Revert contains a bug that got pointed out in the discussion:

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode)

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +0 -0
    do {
            cpu = __getcpu() & VGETCPU_CPU_MASK;
 
            pvti = get_pvti(cpu);

We can migrate to 'other cpu' here.

Quoted 7 lines
Quoted 5 lines

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 106

Quoted 3 lines
arch/x86/vdso/vclock_gettime.c +2 -0
+           migrate_count = pvti->migrate_count;
+
            version = __pvclock_read_cycles(&pvti->pvti, &ret, &flags);

And migrate back to 'cpu' here.

Migrating back will increase pvti->migrate_count, right ?

I thought it only increased the count when we migrated away.

--Andy

Quoted 21 lines
Quoted 21 lines

rdtsc was executed on different cpu, so pvti and tsc might not be in sync, but migrate_count hasn't changed.

Quoted 1 line
            cpu1 = __getcpu() & VGETCPU_CPU_MASK;

(Reading cpuid here is useless.)

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 118

Quoted 5 lines
    } while (unlikely(cpu != cpu1 ||
                      (pvti->pvti.version & 1) ||
arch/x86/vdso/vclock_gettime.c +2 -1
-                     pvti->pvti.version != version));
+                     pvti->pvti.version != version ||
+                     pvti->migrate_count != migrate_count));

We can workaround the bug with,

      cpu = __getcpu() & VGETCPU_CPU_MASK;
      pvti = get_pvti(cpu);
      migrate_count = pvti->migrate_count;
      if (cpu != (__getcpu() & VGETCPU_CPU_MASK))
              continue;
Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#31 lore raw
Quoted 33 lines · Andy Lutomirski
Quoted 32 lines · Marcelo Tosatti
Quoted 31 lines · Radim Krčmář

2015-03-23 20:21-0300, Marcelo Tosatti:

Quoted 9 lines

The following point:

2. per-CPU pvclock time info is updated if the underlying CPU changes.

Is not true anymore since "KVM: x86: update pvclock area conditionally, on cpu migration".

Quoted 6 lines

Add task migration notification back.

Problem noticed by Andy Lutomirski.

Revert contains a bug that got pointed out in the discussion:

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode)

Quoted 5 lines
arch/x86/vdso/vclock_gettime.c +0 -0
    do {
            cpu = __getcpu() & VGETCPU_CPU_MASK;
 
            pvti = get_pvti(cpu);

We can migrate to 'other cpu' here.

Quoted 3 lines
arch/x86/vdso/vclock_gettime.c +2 -0
+           migrate_count = pvti->migrate_count;
+
            version = __pvclock_read_cycles(&pvti->pvti, &ret, &flags);
Quoted 5 lines
Quoted 3 lines
Quoted 1 line

And migrate back to 'cpu' here.

Migrating back will increase pvti->migrate_count, right ?

I thought it only increased the count when we migrated away.

Right.

Quoted 23 lines

--Andy

Quoted 21 lines
Quoted 21 lines

rdtsc was executed on different cpu, so pvti and tsc might not be in sync, but migrate_count hasn't changed.

Quoted 1 line
            cpu1 = __getcpu() & VGETCPU_CPU_MASK;

(Reading cpuid here is useless.)

arch/x86/vdso/vclock_gettime.c static notrace cycle_t vread_pvclock(int *mode) · line 118

Quoted 5 lines
    } while (unlikely(cpu != cpu1 ||
                      (pvti->pvti.version & 1) ||
arch/x86/vdso/vclock_gettime.c +2 -1
-                     pvti->pvti.version != version));
+                     pvti->pvti.version != version ||
+                     pvti->migrate_count != migrate_count));

We can workaround the bug with,

      cpu = __getcpu() & VGETCPU_CPU_MASK;
      pvti = get_pvti(cpu);
      migrate_count = pvti->migrate_count;
      if (cpu != (__getcpu() & VGETCPU_CPU_MASK))
              continue;

Looks good, please submit a fix.

#17 lore raw
In reply to Andy Lutomirski
Quoted 62 lines · Andy Lutomirski
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

Quoted 7 lines

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

All for it.

Quoted 9 lines

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

Quoted 7 lines

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

Yes, can't see a problem with that.

Quoted 1 line

b) If version remains buggy but we use this migrations_from hack:

There is no reason for version to remain buggy.

Quoted 37 lines

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

What is that window again ? Have no objections against using vcpu0's pvti (cacheline should be read-only 99.9% of time).

Quoted 1 line

Why doesn't KVM just update all of the kvmclock data at once?

Because it has not been necessary -- updating kvmclock data on vcpu entry was the previous method, so that was reused.

Quoted 4 lines

(For
that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

And use a 4K TLB entry for that kvmclock area rather than sharing one of kernel's 2MB (or 1GB) TLB entry?

Quoted 2 lines

--Andy

#18 lore raw
Quoted 133 lines · Marcelo Tosatti
Quoted 62 lines · Andy Lutomirski
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

Quoted 7 lines

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

All for it.

Quoted 9 lines

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

Quoted 7 lines

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

Yes, can't see a problem with that.

Quoted 1 line

b) If version remains buggy but we use this migrations_from hack:

There is no reason for version to remain buggy.

Quoted 37 lines

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 7 lines
Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

What is that window again ? Have no objections against using vcpu0's pvti (cacheline should be read-only 99.9% of time).

This is based on my (mis?)understanding of the code. Here goes.

Suppose we transition from stable to unstable. The host freezes all vcpus and set a flag for each vcpu that the kvmclock data needs updating. There could then be a window in which vcpu 1 runs vdso code and vcpu 0 hasn't updated its kvmclock data yet.

I don't know whether this is actually possible. Rik suspects it isn't.

Quoted 6 lines
Quoted 2 lines

Why doesn't KVM just update all of the kvmclock data at once?

Because it has not been necessary -- updating kvmclock data on vcpu entry was the previous method, so that was reused.

Quoted 7 lines
Quoted 4 lines

(For
that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

And use a 4K TLB entry for that kvmclock area rather than sharing one of kernel's 2MB (or 1GB) TLB entry?

Exactly. I'd also move it into the vvar area instead of using the fixmap so 32-bit userspace could use it.

I'm more than happy to handle the vdso side of all of this, but I'd like the host code to settle down first. I'm also not quite sure whether it's okay to cause the vdso timing code to regress on old hosts with new gusts.

--Andy

#19 lore raw
Quoted 142 lines · Andy Lutomirski
Quoted 133 lines · Marcelo Tosatti
Quoted 62 lines · Andy Lutomirski
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

Quoted 7 lines

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

All for it.

Quoted 9 lines

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

Quoted 7 lines

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

Yes, can't see a problem with that.

Quoted 1 line

b) If version remains buggy but we use this migrations_from hack:

There is no reason for version to remain buggy.

Quoted 37 lines

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 7 lines
Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

What is that window again ? Have no objections against using vcpu0's pvti (cacheline should be read-only 99.9% of time).

Quoted 8 lines

This is based on my (mis?)understanding of the code. Here goes.

Suppose we transition from stable to unstable. The host freezes all vcpus and set a flag for each vcpu that the kvmclock data needs updating. There could then be a window in which vcpu 1 runs vdso code and vcpu 0 hasn't updated its kvmclock data yet.

I don't know whether this is actually possible. Rik suspects it isn't.

I don't see why its not possible. We can force vcpu0's kvmclock to be updated.

Do you have an estimation of the performance gain of using vcpu0 pvti?

Quoted 10 lines
Quoted 10 lines
Quoted 1 line

Why doesn't KVM just update all of the kvmclock data at once?

Because it has not been necessary -- updating kvmclock data on vcpu entry was the previous method, so that was reused.

Quoted 4 lines

(For
that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

Quoted 5 lines
Quoted 2 lines

And use a 4K TLB entry for that kvmclock area rather than sharing one of kernel's 2MB (or 1GB) TLB entry?

Exactly. I'd also move it into the vvar area instead of using the fixmap so 32-bit userspace could use it.

Thats an obvious downside (an additional entry in the TLB occupied just for the kvmclock area?).

Quoted 4 lines

I'm more than happy to handle the vdso side of all of this, but I'd like the host code to settle down first.
I'm also not quite sure whether it's okay to cause the vdso timing code to regress on old hosts with new gusts.

Must be backwards compatible.

#20 lore raw
Quoted 150 lines · Marcelo Tosatti
Quoted 149 lines · Andy Lutomirski
Quoted 133 lines · Marcelo Tosatti
Quoted 62 lines · Andy Lutomirski
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

Quoted 7 lines

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

All for it.

Quoted 9 lines

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

Quoted 7 lines

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

Yes, can't see a problem with that.

Quoted 1 line

b) If version remains buggy but we use this migrations_from hack:

There is no reason for version to remain buggy.

Quoted 37 lines

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 7 lines
Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

What is that window again ? Have no objections against using vcpu0's pvti (cacheline should be read-only 99.9% of time).

This is based on my (mis?)understanding of the code. Here goes.

Suppose we transition from stable to unstable. The host freezes all vcpus and set a flag for each vcpu that the kvmclock data needs updating. There could then be a window in which vcpu 1 runs vdso code and vcpu 0 hasn't updated its kvmclock data yet.

Quoted 6 lines
Quoted 1 line

I don't know whether this is actually possible. Rik suspects it isn't.

I don't see why its not possible. We can force vcpu0's kvmclock to be updated.

Do you have an estimation of the performance gain of using vcpu0 pvti?

rdtscp is approximately 3 cycles worse than rdtsc_barrier(); rdtsc() on my machine, but that doesn't help much, since the current scheme requires that we get the cpu number before reading the time. The fastest way I know of to get the cpu number is 25-ish cycles, so this ends up being a large fraction of the overall cost.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 2 lines

Why doesn't KVM just update all of the kvmclock data at once?

Because it has not been necessary -- updating kvmclock data on vcpu entry was the previous method, so that was reused.

Quoted 4 lines

(For
that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

And use a 4K TLB entry for that kvmclock area rather than sharing one of kernel's 2MB (or 1GB) TLB entry?

Exactly. I'd also move it into the vvar area instead of using the fixmap so 32-bit userspace could use it.

Thats an obvious downside (an additional entry in the TLB occupied just for the kvmclock area?).

True. But TLB misses are actually pretty cheap on new hardware, and it's still only one TLB entry per process.

Quoted 8 lines
Quoted 5 lines

I'm more than happy to handle the vdso side of all of this, but I'd like the host code to settle down first.
I'm also not quite sure whether it's okay to cause the vdso timing code to regress on old hosts with new gusts.

Must be backwards compatible.

Could we add a new feature bit that indicates that the host is updated? Then we could use the new code on new hosts and the old code on old hosts and eventually deprecate accelerated vdso timing on old hosts.

--Andy

Signature · 2 lines
Andy Lutomirski
AMA Capital Management, LLC
#21 lore raw
Quoted 156 lines · Andy Lutomirski
Quoted 155 lines · Marcelo Tosatti
Quoted 142 lines · Andy Lutomirski
Quoted 133 lines · Marcelo Tosatti
Quoted 62 lines · Andy Lutomirski
Quoted 49 lines · Radim Krcmar

2015-03-26 11:51-0700, Andy Lutomirski:

Quoted 28 lines · Marcelo Tosatti
Quoted 12 lines · Andy Lutomirski
Quoted 6 lines

Suppose we start out with all vcpus agreeing on their pvti and perfect invariant TSCs. Now the host updates its frequency (due to NTP or whatever). KVM updates vcpu 0's pvti. Before KVM updates vcpu 1's pvti, guest code on vcpus 0 and 1 see synced TSCs but different pvti. They'll disagree on the time, and one of them will be ahead until vcpu 1's pvti gets updated.

The masterclock scheme enforces the same system_timestamp/tsc_timestamp pairs to be visible at one time, for all vcpus.

Quoted 10 lines

* That is, when timespec0 != timespec1, M < N. Unfortunately that is
* not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.

Yuck. So we have per cpu timing data, but the protocol is only usable for monotonic timing because we forcibly freeze all vcpus when we update the nominally per cpu data.

Quoted 7 lines

The obvious guest implementations are still unnecessarily slow, though. It would be nice if the guest could get away without using any getcpu operation at all.

Even if we fixed the host to increment version as advertised, I think we can't avoid two getcpu ops. We need one before rdtsc to figure out which pvti to look at,

Yes.

Quoted 4 lines

and we need another to make sure that we were
actually on that cpu at the time we did rdtsc. (Rdtscp doesn't help -- we need to check version before rdtsc, and we don't know what version to check until we do a getcpu.).

Exactly, reading cpuid after rdtsc doesn't do that though, we could have migrated back between those reads.
rtdscp would allow us to check that we read tsc of pvti's cpu. (It doesn't get rid of that first read.)

Quoted 8 lines
Quoted 4 lines

The migration hook has the
same issue -- we need to check the migration count, then confirm we're on that cpu, then check the migration count again, and we can't do that until we know what cpu we're on.

True; the revert has a bug -- we need to check cpuid for the second time before rdtsc. (Migration hook is there just because we don't know which cpu executed rdtsc.)

One way or another, I'm planning on completely rewriting the vdso code. An early draft is here:

Quoted 7 lines

https://git.kernel.org/cgit/linux/kernel/git/luto/linux.git/commit/?h=x86/vdso&id=57ace6e6e032afc4faf7b9ec52f78a8e6642c980

but I can't finish it until the KVM side shakes out.

I think there are at least two ways that would work:

a) If KVM incremented version as advertised:

All for it.

Quoted 9 lines

cpu = getcpu();
pvti = pvti for cpu;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry;

Quoted 7 lines

I think this is safe because, we're guaranteed that there was an interval (between the two version reads) in which the vcpu we think we're on was running and the kvmclock data was valid and marked stable, and we know that the tsc we read came from that interval.

Note: rdtscp isn't needed. If we're stable, is makes no difference which cpu's tsc we actually read.

Yes, can't see a problem with that.

Quoted 1 line

b) If version remains buggy but we use this migrations_from hack:

There is no reason for version to remain buggy.

Quoted 37 lines

cpu = getcpu();
pvti = pvti for cpu;
m1 = pvti->migrations_from;
barrier();

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (getcpu() != cpu) retry;
if (pvti->version != ver1) retry; /* probably not really needed */

barrier();
if (pvti->migrations_from != m1) retry;

This is just like (a), except that we're using a guest kernel hack to ensure that no one migrated off the vcpu during the version-protected critical section and that we were, in fact, on that vcpu at some point during that critical section. Once we've ensured that we were on pvti's associated vcpu for the entire time we were reading it, then we are protected by the existing versioning in the host.

Quoted 6 lines
Quoted 4 lines

If, on the other hand, we could rely on having all of these things in sync, then this complication goes away, and we go down from two getcpu ops to zero.

(Yeah, we should look what are the drawbacks of doing it differently.)

If the versioning were fixed, I think we could almost get away with:

pvti = pvti for vcpu 0;

ver1 = pvti->version;
check stable bit;
rdtsc_barrier, rdtsc, read scale, shift, etc.
if (pvti->version != ver1) retry;

Quoted 7 lines
Quoted 4 lines

This guarantees that the tsc came from an interval in which vcpu0's kvmclock was *marked* stable. If vcpu0's kvmclock were genuinely stable in that interval, then we'd be fine, but there's a race window in which the kvmclock is *not* stable and vcpu 0 wasn't running.

What is that window again ? Have no objections against using vcpu0's pvti (cacheline should be read-only 99.9% of time).

Quoted 8 lines

This is based on my (mis?)understanding of the code. Here goes.

Suppose we transition from stable to unstable. The host freezes all vcpus and set a flag for each vcpu that the kvmclock data needs updating. There could then be a window in which vcpu 1 runs vdso code and vcpu 0 hasn't updated its kvmclock data yet.

I don't know whether this is actually possible. Rik suspects it isn't.

I don't see why its not possible. We can force vcpu0's kvmclock to be updated.

Quoted 7 lines
Quoted 1 line

Do you have an estimation of the performance gain of using vcpu0 pvti?

rdtscp is approximately 3 cycles worse than rdtsc_barrier(); rdtsc() on my machine, but that doesn't help much, since the current scheme requires that we get the cpu number before reading the time. The fastest way I know of to get the cpu number is 25-ish cycles, so this ends up being a large fraction of the overall cost.

It should be possible to force vcpu0 kvmclock area to be updated before vm-entry, on the update of any other vcpuN kvmclock area.

        kvm_make_mclock_inprogress_request(kvm);
        /* no guest entries from this point */
        pvclock_update_vm_gtod_copy(kvm);

	<---- HERE ------->

        kvm_for_each_vcpu(i, vcpu, kvm)
                kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);

        /* guest entries allowed */
        kvm_for_each_vcpu(i, vcpu, kvm)
                clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
Quoted 26 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
Quoted 1 line

Why doesn't KVM just update all of the kvmclock data at once?

Because it has not been necessary -- updating kvmclock data on vcpu entry was the previous method, so that was reused.

Quoted 4 lines

(For
that matter, why is the pvti in guest memory at all? Wouldn't this all be simpler if the kvmclock data were host-allocated so the host could write it directly and maybe even share it between guests?)

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

And use a 4K TLB entry for that kvmclock area rather than sharing one of kernel's 2MB (or 1GB) TLB entry?

Exactly. I'd also move it into the vvar area instead of using the fixmap so 32-bit userspace could use it.

Thats an obvious downside (an additional entry in the TLB occupied just for the kvmclock area?).

True. But TLB misses are actually pretty cheap on new hardware, and it's still only one TLB entry per process.

Quoted 5 lines
Quoted 4 lines

I'm more than happy to handle the vdso side of all of this, but I'd like the host code to settle down first.
I'm also not quite sure whether it's okay to cause the vdso timing code to regress on old hosts with new gusts.

Quoted 7 lines
Quoted 2 lines

Must be backwards compatible.

Could we add a new feature bit that indicates that the host is updated? Then we could use the new code on new hosts and the old code on old hosts and eventually deprecate accelerated vdso timing on old hosts.

Makes sense.