xref: /kvm-unit-tests/x86/tsc_adjust.c (revision 5c3582f05f30f30fee86b73efa2131540c7a2255)
15fecf5d8SWill Auld #include "libcflat.h"
25fecf5d8SWill Auld #include "processor.h"
35fecf5d8SWill Auld 
47db17e21SThomas Huth int main(void)
55fecf5d8SWill Auld {
65fecf5d8SWill Auld 	u64 t1, t2, t3, t4, t5;
75fecf5d8SWill Auld 	u64 est_delta_time;
85fecf5d8SWill Auld 
9badc98caSKrish Sadhukhan 	if (this_cpu_has(X86_FEATURE_TSC_ADJUST)) { // MSR_IA32_TSC_ADJUST Feature is enabled?
10a299895bSThomas Huth 		report(rdmsr(MSR_IA32_TSC_ADJUST) == 0x0,
11a299895bSThomas Huth 		       "MSR_IA32_TSC_ADJUST msr initialization");
125fecf5d8SWill Auld 		t3 = 100000000000ull;
135fecf5d8SWill Auld 		t1 = rdtsc();
142352e986SPaolo Bonzini 		wrmsr(MSR_IA32_TSC_ADJUST, t3);
155fecf5d8SWill Auld 		t2 = rdtsc();
16a299895bSThomas Huth 		report(rdmsr(MSR_IA32_TSC_ADJUST) == t3,
17a299895bSThomas Huth 		       "MSR_IA32_TSC_ADJUST msr read / write");
18a299895bSThomas Huth 		report((t2 - t1) >= t3,
19a299895bSThomas Huth 		       "TSC adjustment for MSR_IA32_TSC_ADJUST value");
205fecf5d8SWill Auld 		t3 = 0x0;
212352e986SPaolo Bonzini 		wrmsr(MSR_IA32_TSC_ADJUST, t3);
22a299895bSThomas Huth 		report(rdmsr(MSR_IA32_TSC_ADJUST) == t3,
23a299895bSThomas Huth 		       "MSR_IA32_TSC_ADJUST msr read / write");
245fecf5d8SWill Auld 		t4 = 100000000000ull;
255fecf5d8SWill Auld 		t1 = rdtsc();
265fecf5d8SWill Auld 		wrtsc(t4);
275fecf5d8SWill Auld 		t2 = rdtsc();
282352e986SPaolo Bonzini 		t5 = rdmsr(MSR_IA32_TSC_ADJUST);
295fecf5d8SWill Auld 		// est of time between reading tsc and writing tsc,
302352e986SPaolo Bonzini 		// (based on MSR_IA32_TSC_ADJUST msr value) should be small
315fecf5d8SWill Auld 		est_delta_time = t4 - t5 - t1;
325fecf5d8SWill Auld 		// arbitray 2x latency (wrtsc->rdtsc) threshold
33a299895bSThomas Huth 		report(est_delta_time <= (2 * (t2 - t4)),
34a299895bSThomas Huth 		       "MSR_IA32_TSC_ADJUST msr adjustment on tsc write");
355fecf5d8SWill Auld 	}
365fecf5d8SWill Auld 	else {
37*5c3582f0SJanis Schoetterl-Glausch 		report_pass("MSR_IA32_TSC_ADJUST feature not enabled");
385fecf5d8SWill Auld 	}
391ce2224dSAndrew Jones 	return report_summary();
405fecf5d8SWill Auld }
41