xref: /kvm-unit-tests/x86/vmx_tests.c (revision aa004fc06323d3796b0350c041bf13cd2f5b547c)
1 /*
2  * All test cases of nested virtualization should be in this file
3  *
4  * Author : Arthur Chunqi Li <yzt356@gmail.com>
5  */
6 
7 #include <asm/debugreg.h>
8 
9 #include "vmx.h"
10 #include "msr.h"
11 #include "processor.h"
12 #include "vm.h"
13 #include "pci.h"
14 #include "fwcfg.h"
15 #include "isr.h"
16 #include "desc.h"
17 #include "apic.h"
18 #include "types.h"
19 #include "vmalloc.h"
20 #include "alloc_page.h"
21 #include "smp.h"
22 #include "delay.h"
23 
24 #define NONCANONICAL            0xaaaaaaaaaaaaaaaaull
25 
26 #define VPID_CAP_INVVPID_TYPES_SHIFT 40
27 
28 u64 ia32_pat;
29 u64 ia32_efer;
30 void *io_bitmap_a, *io_bitmap_b;
31 u16 ioport;
32 
33 unsigned long *pml4;
34 u64 eptp;
35 void *data_page1, *data_page2;
36 
37 phys_addr_t pci_physaddr;
38 
39 void *pml_log;
40 #define PML_INDEX 512
41 
42 static inline unsigned ffs(unsigned x)
43 {
44 	int pos = -1;
45 
46 	__asm__ __volatile__("bsf %1, %%eax; cmovnz %%eax, %0"
47 			     : "+r"(pos) : "rm"(x) : "eax");
48 	return pos + 1;
49 }
50 
51 static inline void vmcall(void)
52 {
53 	asm volatile("vmcall");
54 }
55 
56 static void basic_guest_main(void)
57 {
58 	report(1, "Basic VMX test");
59 }
60 
61 static int basic_exit_handler(union exit_reason exit_reason)
62 {
63 	report(0, "Basic VMX test");
64 	print_vmexit_info(exit_reason);
65 	return VMX_TEST_EXIT;
66 }
67 
68 static void vmenter_main(void)
69 {
70 	u64 rax;
71 	u64 rsp, resume_rsp;
72 
73 	report(1, "test vmlaunch");
74 
75 	asm volatile(
76 		"mov %%rsp, %0\n\t"
77 		"mov %3, %%rax\n\t"
78 		"vmcall\n\t"
79 		"mov %%rax, %1\n\t"
80 		"mov %%rsp, %2\n\t"
81 		: "=r"(rsp), "=r"(rax), "=r"(resume_rsp)
82 		: "g"(0xABCD));
83 	report((rax == 0xFFFF) && (rsp == resume_rsp), "test vmresume");
84 }
85 
86 static int vmenter_exit_handler(union exit_reason exit_reason)
87 {
88 	u64 guest_rip = vmcs_read(GUEST_RIP);
89 
90 	switch (exit_reason.basic) {
91 	case VMX_VMCALL:
92 		if (regs.rax != 0xABCD) {
93 			report(0, "test vmresume");
94 			return VMX_TEST_VMEXIT;
95 		}
96 		regs.rax = 0xFFFF;
97 		vmcs_write(GUEST_RIP, guest_rip + 3);
98 		return VMX_TEST_RESUME;
99 	default:
100 		report(0, "test vmresume");
101 		print_vmexit_info(exit_reason);
102 	}
103 	return VMX_TEST_VMEXIT;
104 }
105 
106 u32 preempt_scale;
107 volatile unsigned long long tsc_val;
108 volatile u32 preempt_val;
109 u64 saved_rip;
110 
111 static int preemption_timer_init(struct vmcs *vmcs)
112 {
113 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
114 		printf("\tPreemption timer is not supported\n");
115 		return VMX_TEST_EXIT;
116 	}
117 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
118 	preempt_val = 10000000;
119 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
120 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
121 
122 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
123 		printf("\tSave preemption value is not supported\n");
124 
125 	return VMX_TEST_START;
126 }
127 
128 static void preemption_timer_main(void)
129 {
130 	tsc_val = rdtsc();
131 	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
132 		vmx_set_test_stage(0);
133 		vmcall();
134 		if (vmx_get_test_stage() == 1)
135 			vmcall();
136 	}
137 	vmx_set_test_stage(1);
138 	while (vmx_get_test_stage() == 1) {
139 		if (((rdtsc() - tsc_val) >> preempt_scale)
140 				> 10 * preempt_val) {
141 			vmx_set_test_stage(2);
142 			vmcall();
143 		}
144 	}
145 	tsc_val = rdtsc();
146 	asm volatile ("hlt");
147 	vmcall();
148 	vmx_set_test_stage(5);
149 	vmcall();
150 }
151 
152 static int preemption_timer_exit_handler(union exit_reason exit_reason)
153 {
154 	bool guest_halted;
155 	u64 guest_rip;
156 	u32 insn_len;
157 	u32 ctrl_exit;
158 
159 	guest_rip = vmcs_read(GUEST_RIP);
160 	insn_len = vmcs_read(EXI_INST_LEN);
161 	switch (exit_reason.basic) {
162 	case VMX_PREEMPT:
163 		switch (vmx_get_test_stage()) {
164 		case 1:
165 		case 2:
166 			report(((rdtsc() - tsc_val) >> preempt_scale) >= preempt_val,
167 			       "busy-wait for preemption timer");
168 			vmx_set_test_stage(3);
169 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
170 			return VMX_TEST_RESUME;
171 		case 3:
172 			guest_halted =
173 				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
174 			report(((rdtsc() - tsc_val) >> preempt_scale) >= preempt_val
175 			        && guest_halted,
176 			       "preemption timer during hlt");
177 			vmx_set_test_stage(4);
178 			vmcs_write(PIN_CONTROLS,
179 				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
180 			vmcs_write(EXI_CONTROLS,
181 				   vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_PREEMPT);
182 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
183 			return VMX_TEST_RESUME;
184 		case 4:
185 			report(saved_rip == guest_rip,
186 			       "preemption timer with 0 value");
187 			break;
188 		default:
189 			report(false, "Invalid stage.");
190 			print_vmexit_info(exit_reason);
191 			break;
192 		}
193 		break;
194 	case VMX_VMCALL:
195 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
196 		switch (vmx_get_test_stage()) {
197 		case 0:
198 			report(vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val,
199 			       "Keep preemption value");
200 			vmx_set_test_stage(1);
201 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
202 			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
203 				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
204 			vmcs_write(EXI_CONTROLS, ctrl_exit);
205 			return VMX_TEST_RESUME;
206 		case 1:
207 			report(vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val,
208 			       "Save preemption value");
209 			return VMX_TEST_RESUME;
210 		case 2:
211 			report(0, "busy-wait for preemption timer");
212 			vmx_set_test_stage(3);
213 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
214 			return VMX_TEST_RESUME;
215 		case 3:
216 			report(0, "preemption timer during hlt");
217 			vmx_set_test_stage(4);
218 			/* fall through */
219 		case 4:
220 			vmcs_write(PIN_CONTROLS,
221 				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
222 			vmcs_write(PREEMPT_TIMER_VALUE, 0);
223 			saved_rip = guest_rip + insn_len;
224 			return VMX_TEST_RESUME;
225 		case 5:
226 			report(0,
227 			       "preemption timer with 0 value (vmcall stage 5)");
228 			break;
229 		default:
230 			// Should not reach here
231 			report(false, "unexpected stage, %d",
232 			       vmx_get_test_stage());
233 			print_vmexit_info(exit_reason);
234 			return VMX_TEST_VMEXIT;
235 		}
236 		break;
237 	default:
238 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
239 		print_vmexit_info(exit_reason);
240 	}
241 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
242 	return VMX_TEST_VMEXIT;
243 }
244 
245 static void msr_bmp_init(void)
246 {
247 	void *msr_bitmap;
248 	u32 ctrl_cpu0;
249 
250 	msr_bitmap = alloc_page();
251 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
252 	ctrl_cpu0 |= CPU_MSR_BITMAP;
253 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
254 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
255 }
256 
257 static void *get_msr_bitmap(void)
258 {
259 	void *msr_bitmap;
260 
261 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_MSR_BITMAP) {
262 		msr_bitmap = (void *)vmcs_read(MSR_BITMAP);
263 	} else {
264 		msr_bitmap = alloc_page();
265 		memset(msr_bitmap, 0xff, PAGE_SIZE);
266 		vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
267 		vmcs_set_bits(CPU_EXEC_CTRL0, CPU_MSR_BITMAP);
268 	}
269 
270 	return msr_bitmap;
271 }
272 
273 static void disable_intercept_for_x2apic_msrs(void)
274 {
275 	unsigned long *msr_bitmap = (unsigned long *)get_msr_bitmap();
276 	u32 msr;
277 
278 	for (msr = APIC_BASE_MSR;
279 		 msr < (APIC_BASE_MSR+0xff);
280 		 msr += BITS_PER_LONG) {
281 		unsigned int word = msr / BITS_PER_LONG;
282 
283 		msr_bitmap[word] = 0;
284 		msr_bitmap[word + (0x800 / sizeof(long))] = 0;
285 	}
286 }
287 
288 static int test_ctrl_pat_init(struct vmcs *vmcs)
289 {
290 	u64 ctrl_ent;
291 	u64 ctrl_exi;
292 
293 	msr_bmp_init();
294 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
295 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
296 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
297 		printf("\tSave/load PAT is not supported\n");
298 		return 1;
299 	}
300 
301 	ctrl_ent = vmcs_read(ENT_CONTROLS);
302 	ctrl_exi = vmcs_read(EXI_CONTROLS);
303 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
304 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
305 	vmcs_write(ENT_CONTROLS, ctrl_ent);
306 	vmcs_write(EXI_CONTROLS, ctrl_exi);
307 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
308 	vmcs_write(GUEST_PAT, 0x0);
309 	vmcs_write(HOST_PAT, ia32_pat);
310 	return VMX_TEST_START;
311 }
312 
313 static void test_ctrl_pat_main(void)
314 {
315 	u64 guest_ia32_pat;
316 
317 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
318 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
319 		printf("\tENT_LOAD_PAT is not supported.\n");
320 	else {
321 		if (guest_ia32_pat != 0) {
322 			report(0, "Entry load PAT");
323 			return;
324 		}
325 	}
326 	wrmsr(MSR_IA32_CR_PAT, 0x6);
327 	vmcall();
328 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
329 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
330 		report(guest_ia32_pat == ia32_pat, "Entry load PAT");
331 }
332 
333 static int test_ctrl_pat_exit_handler(union exit_reason exit_reason)
334 {
335 	u64 guest_rip;
336 	u64 guest_pat;
337 
338 	guest_rip = vmcs_read(GUEST_RIP);
339 	switch (exit_reason.basic) {
340 	case VMX_VMCALL:
341 		guest_pat = vmcs_read(GUEST_PAT);
342 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
343 			printf("\tEXI_SAVE_PAT is not supported\n");
344 			vmcs_write(GUEST_PAT, 0x6);
345 		} else {
346 			report(guest_pat == 0x6, "Exit save PAT");
347 		}
348 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
349 			printf("\tEXI_LOAD_PAT is not supported\n");
350 		else
351 			report(rdmsr(MSR_IA32_CR_PAT) == ia32_pat,
352 			       "Exit load PAT");
353 		vmcs_write(GUEST_PAT, ia32_pat);
354 		vmcs_write(GUEST_RIP, guest_rip + 3);
355 		return VMX_TEST_RESUME;
356 	default:
357 		printf("ERROR : Unknown exit reason, 0x%x.\n", exit_reason.full);
358 		break;
359 	}
360 	return VMX_TEST_VMEXIT;
361 }
362 
363 static int test_ctrl_efer_init(struct vmcs *vmcs)
364 {
365 	u64 ctrl_ent;
366 	u64 ctrl_exi;
367 
368 	msr_bmp_init();
369 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
370 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
371 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
372 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
373 	ia32_efer = rdmsr(MSR_EFER);
374 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
375 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
376 	return VMX_TEST_START;
377 }
378 
379 static void test_ctrl_efer_main(void)
380 {
381 	u64 guest_ia32_efer;
382 
383 	guest_ia32_efer = rdmsr(MSR_EFER);
384 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
385 		printf("\tENT_LOAD_EFER is not supported.\n");
386 	else {
387 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
388 			report(0, "Entry load EFER");
389 			return;
390 		}
391 	}
392 	wrmsr(MSR_EFER, ia32_efer);
393 	vmcall();
394 	guest_ia32_efer = rdmsr(MSR_EFER);
395 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
396 		report(guest_ia32_efer == ia32_efer, "Entry load EFER");
397 }
398 
399 static int test_ctrl_efer_exit_handler(union exit_reason exit_reason)
400 {
401 	u64 guest_rip;
402 	u64 guest_efer;
403 
404 	guest_rip = vmcs_read(GUEST_RIP);
405 	switch (exit_reason.basic) {
406 	case VMX_VMCALL:
407 		guest_efer = vmcs_read(GUEST_EFER);
408 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
409 			printf("\tEXI_SAVE_EFER is not supported\n");
410 			vmcs_write(GUEST_EFER, ia32_efer);
411 		} else {
412 			report(guest_efer == ia32_efer, "Exit save EFER");
413 		}
414 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
415 			printf("\tEXI_LOAD_EFER is not supported\n");
416 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
417 		} else {
418 			report(rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX),
419 			       "Exit load EFER");
420 		}
421 		vmcs_write(GUEST_PAT, ia32_efer);
422 		vmcs_write(GUEST_RIP, guest_rip + 3);
423 		return VMX_TEST_RESUME;
424 	default:
425 		printf("ERROR : Unknown exit reason, 0x%x.\n", exit_reason.full);
426 		break;
427 	}
428 	return VMX_TEST_VMEXIT;
429 }
430 
431 u32 guest_cr0, guest_cr4;
432 
433 static void cr_shadowing_main(void)
434 {
435 	u32 cr0, cr4, tmp;
436 
437 	// Test read through
438 	vmx_set_test_stage(0);
439 	guest_cr0 = read_cr0();
440 	if (vmx_get_test_stage() == 1)
441 		report(0, "Read through CR0");
442 	else
443 		vmcall();
444 	vmx_set_test_stage(1);
445 	guest_cr4 = read_cr4();
446 	if (vmx_get_test_stage() == 2)
447 		report(0, "Read through CR4");
448 	else
449 		vmcall();
450 	// Test write through
451 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
452 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
453 	vmx_set_test_stage(2);
454 	write_cr0(guest_cr0);
455 	if (vmx_get_test_stage() == 3)
456 		report(0, "Write throuth CR0");
457 	else
458 		vmcall();
459 	vmx_set_test_stage(3);
460 	write_cr4(guest_cr4);
461 	if (vmx_get_test_stage() == 4)
462 		report(0, "Write through CR4");
463 	else
464 		vmcall();
465 	// Test read shadow
466 	vmx_set_test_stage(4);
467 	vmcall();
468 	cr0 = read_cr0();
469 	if (vmx_get_test_stage() != 5)
470 		report(cr0 == guest_cr0, "Read shadowing CR0");
471 	vmx_set_test_stage(5);
472 	cr4 = read_cr4();
473 	if (vmx_get_test_stage() != 6)
474 		report(cr4 == guest_cr4, "Read shadowing CR4");
475 	// Test write shadow (same value with shadow)
476 	vmx_set_test_stage(6);
477 	write_cr0(guest_cr0);
478 	if (vmx_get_test_stage() == 7)
479 		report(0, "Write shadowing CR0 (same value with shadow)");
480 	else
481 		vmcall();
482 	vmx_set_test_stage(7);
483 	write_cr4(guest_cr4);
484 	if (vmx_get_test_stage() == 8)
485 		report(0, "Write shadowing CR4 (same value with shadow)");
486 	else
487 		vmcall();
488 	// Test write shadow (different value)
489 	vmx_set_test_stage(8);
490 	tmp = guest_cr0 ^ X86_CR0_TS;
491 	asm volatile("mov %0, %%rsi\n\t"
492 		"mov %%rsi, %%cr0\n\t"
493 		::"m"(tmp)
494 		:"rsi", "memory", "cc");
495 	report(vmx_get_test_stage() == 9,
496 	       "Write shadowing different X86_CR0_TS");
497 	vmx_set_test_stage(9);
498 	tmp = guest_cr0 ^ X86_CR0_MP;
499 	asm volatile("mov %0, %%rsi\n\t"
500 		"mov %%rsi, %%cr0\n\t"
501 		::"m"(tmp)
502 		:"rsi", "memory", "cc");
503 	report(vmx_get_test_stage() == 10,
504 	       "Write shadowing different X86_CR0_MP");
505 	vmx_set_test_stage(10);
506 	tmp = guest_cr4 ^ X86_CR4_TSD;
507 	asm volatile("mov %0, %%rsi\n\t"
508 		"mov %%rsi, %%cr4\n\t"
509 		::"m"(tmp)
510 		:"rsi", "memory", "cc");
511 	report(vmx_get_test_stage() == 11,
512 	       "Write shadowing different X86_CR4_TSD");
513 	vmx_set_test_stage(11);
514 	tmp = guest_cr4 ^ X86_CR4_DE;
515 	asm volatile("mov %0, %%rsi\n\t"
516 		"mov %%rsi, %%cr4\n\t"
517 		::"m"(tmp)
518 		:"rsi", "memory", "cc");
519 	report(vmx_get_test_stage() == 12,
520 	       "Write shadowing different X86_CR4_DE");
521 }
522 
523 static int cr_shadowing_exit_handler(union exit_reason exit_reason)
524 {
525 	u64 guest_rip;
526 	u32 insn_len;
527 	u32 exit_qual;
528 
529 	guest_rip = vmcs_read(GUEST_RIP);
530 	insn_len = vmcs_read(EXI_INST_LEN);
531 	exit_qual = vmcs_read(EXI_QUALIFICATION);
532 	switch (exit_reason.basic) {
533 	case VMX_VMCALL:
534 		switch (vmx_get_test_stage()) {
535 		case 0:
536 			report(guest_cr0 == vmcs_read(GUEST_CR0),
537 			       "Read through CR0");
538 			break;
539 		case 1:
540 			report(guest_cr4 == vmcs_read(GUEST_CR4),
541 			       "Read through CR4");
542 			break;
543 		case 2:
544 			report(guest_cr0 == vmcs_read(GUEST_CR0),
545 			       "Write through CR0");
546 			break;
547 		case 3:
548 			report(guest_cr4 == vmcs_read(GUEST_CR4),
549 			       "Write through CR4");
550 			break;
551 		case 4:
552 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
553 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
554 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
555 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
556 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
557 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
558 			break;
559 		case 6:
560 			report(guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)),
561 			       "Write shadowing CR0 (same value)");
562 			break;
563 		case 7:
564 			report(guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)),
565 			       "Write shadowing CR4 (same value)");
566 			break;
567 		default:
568 			// Should not reach here
569 			report(false, "unexpected stage, %d",
570 			       vmx_get_test_stage());
571 			print_vmexit_info(exit_reason);
572 			return VMX_TEST_VMEXIT;
573 		}
574 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
575 		return VMX_TEST_RESUME;
576 	case VMX_CR:
577 		switch (vmx_get_test_stage()) {
578 		case 4:
579 			report(0, "Read shadowing CR0");
580 			vmx_inc_test_stage();
581 			break;
582 		case 5:
583 			report(0, "Read shadowing CR4");
584 			vmx_inc_test_stage();
585 			break;
586 		case 6:
587 			report(0, "Write shadowing CR0 (same value)");
588 			vmx_inc_test_stage();
589 			break;
590 		case 7:
591 			report(0, "Write shadowing CR4 (same value)");
592 			vmx_inc_test_stage();
593 			break;
594 		case 8:
595 		case 9:
596 			// 0x600 encodes "mov %esi, %cr0"
597 			if (exit_qual == 0x600)
598 				vmx_inc_test_stage();
599 			break;
600 		case 10:
601 		case 11:
602 			// 0x604 encodes "mov %esi, %cr4"
603 			if (exit_qual == 0x604)
604 				vmx_inc_test_stage();
605 			break;
606 		default:
607 			// Should not reach here
608 			report(false, "unexpected stage, %d",
609 			       vmx_get_test_stage());
610 			print_vmexit_info(exit_reason);
611 			return VMX_TEST_VMEXIT;
612 		}
613 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
614 		return VMX_TEST_RESUME;
615 	default:
616 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
617 		print_vmexit_info(exit_reason);
618 	}
619 	return VMX_TEST_VMEXIT;
620 }
621 
622 static int iobmp_init(struct vmcs *vmcs)
623 {
624 	u32 ctrl_cpu0;
625 
626 	io_bitmap_a = alloc_page();
627 	io_bitmap_b = alloc_page();
628 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
629 	ctrl_cpu0 |= CPU_IO_BITMAP;
630 	ctrl_cpu0 &= (~CPU_IO);
631 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
632 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
633 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
634 	return VMX_TEST_START;
635 }
636 
637 static void iobmp_main(void)
638 {
639 	// stage 0, test IO pass
640 	vmx_set_test_stage(0);
641 	inb(0x5000);
642 	outb(0x0, 0x5000);
643 	report(vmx_get_test_stage() == 0, "I/O bitmap - I/O pass");
644 	// test IO width, in/out
645 	((u8 *)io_bitmap_a)[0] = 0xFF;
646 	vmx_set_test_stage(2);
647 	inb(0x0);
648 	report(vmx_get_test_stage() == 3, "I/O bitmap - trap in");
649 	vmx_set_test_stage(3);
650 	outw(0x0, 0x0);
651 	report(vmx_get_test_stage() == 4, "I/O bitmap - trap out");
652 	vmx_set_test_stage(4);
653 	inl(0x0);
654 	report(vmx_get_test_stage() == 5, "I/O bitmap - I/O width, long");
655 	// test low/high IO port
656 	vmx_set_test_stage(5);
657 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
658 	inb(0x5000);
659 	report(vmx_get_test_stage() == 6, "I/O bitmap - I/O port, low part");
660 	vmx_set_test_stage(6);
661 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
662 	inb(0x9000);
663 	report(vmx_get_test_stage() == 7, "I/O bitmap - I/O port, high part");
664 	// test partial pass
665 	vmx_set_test_stage(7);
666 	inl(0x4FFF);
667 	report(vmx_get_test_stage() == 8, "I/O bitmap - partial pass");
668 	// test overrun
669 	vmx_set_test_stage(8);
670 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
671 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
672 	inl(0xFFFF);
673 	report(vmx_get_test_stage() == 9, "I/O bitmap - overrun");
674 	vmx_set_test_stage(9);
675 	vmcall();
676 	outb(0x0, 0x0);
677 	report(vmx_get_test_stage() == 9,
678 	       "I/O bitmap - ignore unconditional exiting");
679 	vmx_set_test_stage(10);
680 	vmcall();
681 	outb(0x0, 0x0);
682 	report(vmx_get_test_stage() == 11,
683 	       "I/O bitmap - unconditional exiting");
684 }
685 
686 static int iobmp_exit_handler(union exit_reason exit_reason)
687 {
688 	u64 guest_rip;
689 	ulong exit_qual;
690 	u32 insn_len, ctrl_cpu0;
691 
692 	guest_rip = vmcs_read(GUEST_RIP);
693 	exit_qual = vmcs_read(EXI_QUALIFICATION);
694 	insn_len = vmcs_read(EXI_INST_LEN);
695 	switch (exit_reason.basic) {
696 	case VMX_IO:
697 		switch (vmx_get_test_stage()) {
698 		case 0:
699 		case 1:
700 			vmx_inc_test_stage();
701 			break;
702 		case 2:
703 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE,
704 			       "I/O bitmap - I/O width, byte");
705 			report(exit_qual & VMX_IO_IN,
706 			       "I/O bitmap - I/O direction, in");
707 			vmx_inc_test_stage();
708 			break;
709 		case 3:
710 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD,
711 			       "I/O bitmap - I/O width, word");
712 			report(!(exit_qual & VMX_IO_IN),
713 			       "I/O bitmap - I/O direction, out");
714 			vmx_inc_test_stage();
715 			break;
716 		case 4:
717 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG,
718 			       "I/O bitmap - I/O width, long");
719 			vmx_inc_test_stage();
720 			break;
721 		case 5:
722 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
723 				vmx_inc_test_stage();
724 			break;
725 		case 6:
726 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
727 				vmx_inc_test_stage();
728 			break;
729 		case 7:
730 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
731 				vmx_inc_test_stage();
732 			break;
733 		case 8:
734 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
735 				vmx_inc_test_stage();
736 			break;
737 		case 9:
738 		case 10:
739 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
740 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
741 			vmx_inc_test_stage();
742 			break;
743 		default:
744 			// Should not reach here
745 			report(false, "unexpected stage, %d",
746 			       vmx_get_test_stage());
747 			print_vmexit_info(exit_reason);
748 			return VMX_TEST_VMEXIT;
749 		}
750 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
751 		return VMX_TEST_RESUME;
752 	case VMX_VMCALL:
753 		switch (vmx_get_test_stage()) {
754 		case 9:
755 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
756 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
757 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
758 			break;
759 		case 10:
760 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
761 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
762 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
763 			break;
764 		default:
765 			// Should not reach here
766 			report(false, "unexpected stage, %d",
767 			       vmx_get_test_stage());
768 			print_vmexit_info(exit_reason);
769 			return VMX_TEST_VMEXIT;
770 		}
771 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
772 		return VMX_TEST_RESUME;
773 	default:
774 		printf("guest_rip = %#lx\n", guest_rip);
775 		printf("\tERROR : Unknown exit reason, 0x%x\n", exit_reason.full);
776 		break;
777 	}
778 	return VMX_TEST_VMEXIT;
779 }
780 
781 #define INSN_CPU0		0
782 #define INSN_CPU1		1
783 #define INSN_ALWAYS_TRAP	2
784 
785 #define FIELD_EXIT_QUAL		(1 << 0)
786 #define FIELD_INSN_INFO		(1 << 1)
787 
788 asm(
789 	"insn_hlt: hlt;ret\n\t"
790 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
791 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
792 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
793 	"insn_rdtsc: rdtsc;ret\n\t"
794 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
795 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
796 #ifdef __x86_64__
797 	"insn_cr8_load: xor %eax, %eax; mov %rax,%cr8;ret\n\t"
798 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
799 #endif
800 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
801 	"insn_pause: pause;ret\n\t"
802 	"insn_wbinvd: wbinvd;ret\n\t"
803 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
804 	"insn_invd: invd;ret\n\t"
805 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
806 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
807 	"insn_sidt: sidt idt_descr;ret\n\t"
808 	"insn_lidt: lidt idt_descr;ret\n\t"
809 	"insn_sldt: sldt %ax;ret\n\t"
810 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
811 	"insn_str: str %ax;ret\n\t"
812 	"insn_rdrand: rdrand %rax;ret\n\t"
813 	"insn_rdseed: rdseed %rax;ret\n\t"
814 );
815 extern void insn_hlt(void);
816 extern void insn_invlpg(void);
817 extern void insn_mwait(void);
818 extern void insn_rdpmc(void);
819 extern void insn_rdtsc(void);
820 extern void insn_cr3_load(void);
821 extern void insn_cr3_store(void);
822 #ifdef __x86_64__
823 extern void insn_cr8_load(void);
824 extern void insn_cr8_store(void);
825 #endif
826 extern void insn_monitor(void);
827 extern void insn_pause(void);
828 extern void insn_wbinvd(void);
829 extern void insn_sgdt(void);
830 extern void insn_lgdt(void);
831 extern void insn_sidt(void);
832 extern void insn_lidt(void);
833 extern void insn_sldt(void);
834 extern void insn_lldt(void);
835 extern void insn_str(void);
836 extern void insn_cpuid(void);
837 extern void insn_invd(void);
838 extern void insn_rdrand(void);
839 extern void insn_rdseed(void);
840 
841 u32 cur_insn;
842 u64 cr3;
843 
844 #define X86_FEATURE_MONITOR	(1 << 3)
845 
846 typedef bool (*supported_fn)(void);
847 
848 static bool monitor_supported(void)
849 {
850 	return this_cpu_has(X86_FEATURE_MWAIT);
851 }
852 
853 struct insn_table {
854 	const char *name;
855 	u32 flag;
856 	void (*insn_func)(void);
857 	u32 type;
858 	u32 reason;
859 	ulong exit_qual;
860 	u32 insn_info;
861 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
862 	// which field need to be tested, reason is always tested
863 	u32 test_field;
864 	const supported_fn supported_fn;
865 	u8 disabled;
866 };
867 
868 /*
869  * Add more test cases of instruction intercept here. Elements in this
870  * table is:
871  *	name/control flag/insn function/type/exit reason/exit qulification/
872  *	instruction info/field to test
873  * The last field defines which fields (exit_qual and insn_info) need to be
874  * tested in exit handler. If set to 0, only "reason" is checked.
875  */
876 static struct insn_table insn_table[] = {
877 	// Flags for Primary Processor-Based VM-Execution Controls
878 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
879 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
880 		0x12345678, 0, FIELD_EXIT_QUAL},
881 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0, &monitor_supported},
882 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
883 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
884 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
885 		FIELD_EXIT_QUAL},
886 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
887 		FIELD_EXIT_QUAL},
888 #ifdef __x86_64__
889 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
890 		FIELD_EXIT_QUAL},
891 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
892 		FIELD_EXIT_QUAL},
893 #endif
894 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0, &monitor_supported},
895 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
896 	// Flags for Secondary Processor-Based VM-Execution Controls
897 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
898 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
899 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
900 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
901 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
902 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
903 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
904 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
905 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
906 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
907 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
908 	// Instructions always trap
909 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
910 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
911 	// Instructions never trap
912 	{NULL},
913 };
914 
915 static int insn_intercept_init(struct vmcs *vmcs)
916 {
917 	u32 ctrl_cpu, cur_insn;
918 
919 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
920 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
921 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
922 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
923 	cr3 = read_cr3();
924 
925 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
926 		if (insn_table[cur_insn].supported_fn == NULL)
927 			continue;
928 		insn_table[cur_insn].disabled = !insn_table[cur_insn].supported_fn();
929 	}
930 	return VMX_TEST_START;
931 }
932 
933 static void insn_intercept_main(void)
934 {
935 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
936 		vmx_set_test_stage(cur_insn * 2);
937 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
938 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
939 		    (insn_table[cur_insn].type == INSN_CPU1 &&
940 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
941 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
942 			       insn_table[cur_insn].type - INSN_CPU0,
943 			       insn_table[cur_insn].name);
944 			continue;
945 		}
946 
947 		if (insn_table[cur_insn].disabled) {
948 			printf("\tFeature required for %s is not supported.\n",
949 			       insn_table[cur_insn].name);
950 			continue;
951 		}
952 
953 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
954 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
955 		    (insn_table[cur_insn].type == INSN_CPU1 &&
956 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
957 			/* skip hlt, it stalls the guest and is tested below */
958 			if (insn_table[cur_insn].insn_func != insn_hlt)
959 				insn_table[cur_insn].insn_func();
960 			report(vmx_get_test_stage() == cur_insn * 2,
961 					"execute %s",
962 					insn_table[cur_insn].name);
963 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
964 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
965 			       insn_table[cur_insn].type - INSN_CPU0,
966 			       insn_table[cur_insn].name);
967 
968 		vmcall();
969 
970 		insn_table[cur_insn].insn_func();
971 		report(vmx_get_test_stage() == cur_insn * 2 + 1,
972 				"intercept %s",
973 				insn_table[cur_insn].name);
974 
975 		vmx_set_test_stage(cur_insn * 2 + 1);
976 		vmcall();
977 	}
978 }
979 
980 static int insn_intercept_exit_handler(union exit_reason exit_reason)
981 {
982 	u64 guest_rip;
983 	ulong exit_qual;
984 	u32 insn_len;
985 	u32 insn_info;
986 	bool pass;
987 
988 	guest_rip = vmcs_read(GUEST_RIP);
989 	exit_qual = vmcs_read(EXI_QUALIFICATION);
990 	insn_len = vmcs_read(EXI_INST_LEN);
991 	insn_info = vmcs_read(EXI_INST_INFO);
992 
993 	if (exit_reason.basic == VMX_VMCALL) {
994 		u32 val = 0;
995 
996 		if (insn_table[cur_insn].type == INSN_CPU0)
997 			val = vmcs_read(CPU_EXEC_CTRL0);
998 		else if (insn_table[cur_insn].type == INSN_CPU1)
999 			val = vmcs_read(CPU_EXEC_CTRL1);
1000 
1001 		if (vmx_get_test_stage() & 1)
1002 			val &= ~insn_table[cur_insn].flag;
1003 		else
1004 			val |= insn_table[cur_insn].flag;
1005 
1006 		if (insn_table[cur_insn].type == INSN_CPU0)
1007 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
1008 		else if (insn_table[cur_insn].type == INSN_CPU1)
1009 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
1010 	} else {
1011 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
1012 			insn_table[cur_insn].reason == exit_reason.full;
1013 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
1014 		    insn_table[cur_insn].exit_qual != exit_qual)
1015 			pass = false;
1016 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
1017 		    insn_table[cur_insn].insn_info != insn_info)
1018 			pass = false;
1019 		if (pass)
1020 			vmx_inc_test_stage();
1021 	}
1022 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
1023 	return VMX_TEST_RESUME;
1024 }
1025 
1026 /**
1027  * __setup_ept - Setup the VMCS fields to enable Extended Page Tables (EPT)
1028  * @hpa:	Host physical address of the top-level, a.k.a. root, EPT table
1029  * @enable_ad:	Whether or not to enable Access/Dirty bits for EPT entries
1030  *
1031  * Returns 0 on success, 1 on failure.
1032  *
1033  * Note that @hpa doesn't need to point at actual memory if VM-Launch is
1034  * expected to fail, e.g. setup_dummy_ept() arbitrarily passes '0' to satisfy
1035  * the various EPTP consistency checks, but doesn't ensure backing for HPA '0'.
1036  */
1037 static int __setup_ept(u64 hpa, bool enable_ad)
1038 {
1039 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1040 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
1041 		printf("\tEPT is not supported");
1042 		return 1;
1043 	}
1044 	if (!(ept_vpid.val & EPT_CAP_WB)) {
1045 		printf("WB memtype for EPT walks not supported\n");
1046 		return 1;
1047 	}
1048 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
1049 		printf("\tPWL4 is not supported\n");
1050 		return 1;
1051 	}
1052 
1053 	eptp = EPT_MEM_TYPE_WB;
1054 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1055 	eptp |= hpa;
1056 	if (enable_ad)
1057 		eptp |= EPTP_AD_FLAG;
1058 
1059 	vmcs_write(EPTP, eptp);
1060 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0)| CPU_SECONDARY);
1061 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1)| CPU_EPT);
1062 
1063 	return 0;
1064 }
1065 
1066 /**
1067  * setup_ept - Enable Extended Page Tables (EPT) and setup an identity map
1068  * @enable_ad:	Whether or not to enable Access/Dirty bits for EPT entries
1069  *
1070  * Returns 0 on success, 1 on failure.
1071  *
1072  * This is the "real" function for setting up EPT tables, i.e. use this for
1073  * tests that need to run code in the guest with EPT enabled.
1074  */
1075 static int setup_ept(bool enable_ad)
1076 {
1077 	unsigned long end_of_memory;
1078 
1079 	pml4 = alloc_page();
1080 
1081 	if (__setup_ept(virt_to_phys(pml4), enable_ad))
1082 		return 1;
1083 
1084 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1085 	if (end_of_memory < (1ul << 32))
1086 		end_of_memory = (1ul << 32);
1087 	/* Cannot use large EPT pages if we need to track EPT
1088 	 * accessed/dirty bits at 4K granularity.
1089 	 */
1090 	setup_ept_range(pml4, 0, end_of_memory, 0,
1091 			!enable_ad && ept_2m_supported(),
1092 			EPT_WA | EPT_RA | EPT_EA);
1093 	return 0;
1094 }
1095 
1096 /**
1097  * setup_dummy_ept - Enable Extended Page Tables (EPT) with a dummy root HPA
1098  *
1099  * Setup EPT using a semi-arbitrary dummy root HPA.  This function is intended
1100  * for use by tests that need EPT enabled to verify dependent VMCS controls
1101  * but never expect to fully enter the guest, i.e. don't need setup the actual
1102  * EPT tables.
1103  */
1104 static void setup_dummy_ept(void)
1105 {
1106 	if (__setup_ept(0, false))
1107 		report_abort("EPT setup unexpectedly failed");
1108 }
1109 
1110 static int enable_unrestricted_guest(void)
1111 {
1112 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1113 	    !(ctrl_cpu_rev[1].clr & CPU_URG) ||
1114 	    !(ctrl_cpu_rev[1].clr & CPU_EPT))
1115 		return 1;
1116 
1117 	setup_dummy_ept();
1118 
1119 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
1120 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | CPU_URG);
1121 
1122 	return 0;
1123 }
1124 
1125 static void ept_enable_ad_bits(void)
1126 {
1127 	eptp |= EPTP_AD_FLAG;
1128 	vmcs_write(EPTP, eptp);
1129 }
1130 
1131 static void ept_disable_ad_bits(void)
1132 {
1133 	eptp &= ~EPTP_AD_FLAG;
1134 	vmcs_write(EPTP, eptp);
1135 }
1136 
1137 static int ept_ad_enabled(void)
1138 {
1139 	return eptp & EPTP_AD_FLAG;
1140 }
1141 
1142 static void ept_enable_ad_bits_or_skip_test(void)
1143 {
1144 	if (!ept_ad_bits_supported())
1145 		test_skip("EPT AD bits not supported.");
1146 	ept_enable_ad_bits();
1147 }
1148 
1149 static int apic_version;
1150 
1151 static int ept_init_common(bool have_ad)
1152 {
1153 	int ret;
1154 	struct pci_dev pcidev;
1155 
1156 	if (setup_ept(have_ad))
1157 		return VMX_TEST_EXIT;
1158 	data_page1 = alloc_page();
1159 	data_page2 = alloc_page();
1160 	*((u32 *)data_page1) = MAGIC_VAL_1;
1161 	*((u32 *)data_page2) = MAGIC_VAL_2;
1162 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1163 			EPT_RA | EPT_WA | EPT_EA);
1164 
1165 	apic_version = apic_read(APIC_LVR);
1166 
1167 	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
1168 	if (ret != PCIDEVADDR_INVALID) {
1169 		pci_dev_init(&pcidev, ret);
1170 		pci_physaddr = pcidev.resource[PCI_TESTDEV_BAR_MEM];
1171 	}
1172 
1173 	return VMX_TEST_START;
1174 }
1175 
1176 static int ept_init(struct vmcs *vmcs)
1177 {
1178 	return ept_init_common(false);
1179 }
1180 
1181 static void ept_common(void)
1182 {
1183 	vmx_set_test_stage(0);
1184 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1185 			*((u32 *)data_page1) != MAGIC_VAL_1)
1186 		report(0, "EPT basic framework - read");
1187 	else {
1188 		*((u32 *)data_page2) = MAGIC_VAL_3;
1189 		vmcall();
1190 		if (vmx_get_test_stage() == 1) {
1191 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1192 					*((u32 *)data_page2) == MAGIC_VAL_2)
1193 				report(1, "EPT basic framework");
1194 			else
1195 				report(1, "EPT basic framework - remap");
1196 		}
1197 	}
1198 	// Test EPT Misconfigurations
1199 	vmx_set_test_stage(1);
1200 	vmcall();
1201 	*((u32 *)data_page1) = MAGIC_VAL_1;
1202 	if (vmx_get_test_stage() != 2) {
1203 		report(0, "EPT misconfigurations");
1204 		goto t1;
1205 	}
1206 	vmx_set_test_stage(2);
1207 	vmcall();
1208 	*((u32 *)data_page1) = MAGIC_VAL_1;
1209 	report(vmx_get_test_stage() == 3, "EPT misconfigurations");
1210 t1:
1211 	// Test EPT violation
1212 	vmx_set_test_stage(3);
1213 	vmcall();
1214 	*((u32 *)data_page1) = MAGIC_VAL_1;
1215 	report(vmx_get_test_stage() == 4, "EPT violation - page permission");
1216 	// Violation caused by EPT paging structure
1217 	vmx_set_test_stage(4);
1218 	vmcall();
1219 	*((u32 *)data_page1) = MAGIC_VAL_2;
1220 	report(vmx_get_test_stage() == 5, "EPT violation - paging structure");
1221 
1222 	// MMIO Read/Write
1223 	vmx_set_test_stage(5);
1224 	vmcall();
1225 
1226 	*(u32 volatile *)pci_physaddr;
1227 	report(vmx_get_test_stage() == 6, "MMIO EPT violation - read");
1228 
1229 	*(u32 volatile *)pci_physaddr = MAGIC_VAL_1;
1230 	report(vmx_get_test_stage() == 7, "MMIO EPT violation - write");
1231 }
1232 
1233 static void ept_main(void)
1234 {
1235 	ept_common();
1236 
1237 	// Test EPT access to L1 MMIO
1238 	vmx_set_test_stage(7);
1239 	report(*((u32 *)0xfee00030UL) == apic_version, "EPT - MMIO access");
1240 
1241 	// Test invalid operand for INVEPT
1242 	vmcall();
1243 	report(vmx_get_test_stage() == 8, "EPT - unsupported INVEPT");
1244 }
1245 
1246 static bool invept_test(int type, u64 eptp)
1247 {
1248 	bool ret, supported;
1249 
1250 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1251 	ret = invept(type, eptp);
1252 
1253 	if (ret == !supported)
1254 		return false;
1255 
1256 	if (!supported)
1257 		printf("WARNING: unsupported invept passed!\n");
1258 	else
1259 		printf("WARNING: invept failed!\n");
1260 
1261 	return true;
1262 }
1263 
1264 static int pml_exit_handler(union exit_reason exit_reason)
1265 {
1266 	u16 index, count;
1267 	u64 *pmlbuf = pml_log;
1268 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1269 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1270 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1271 
1272 	switch (exit_reason.basic) {
1273 	case VMX_VMCALL:
1274 		switch (vmx_get_test_stage()) {
1275 		case 0:
1276 			index = vmcs_read(GUEST_PML_INDEX);
1277 			for (count = index + 1; count < PML_INDEX; count++) {
1278 				if (pmlbuf[count] == (u64)data_page2) {
1279 					vmx_inc_test_stage();
1280 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1281 					break;
1282 				}
1283 			}
1284 			break;
1285 		case 1:
1286 			index = vmcs_read(GUEST_PML_INDEX);
1287 			/* Keep clearing the dirty bit till a overflow */
1288 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1289 			break;
1290 		default:
1291 			report(false, "unexpected stage, %d.",
1292 			       vmx_get_test_stage());
1293 			print_vmexit_info(exit_reason);
1294 			return VMX_TEST_VMEXIT;
1295 		}
1296 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1297 		return VMX_TEST_RESUME;
1298 	case VMX_PML_FULL:
1299 		vmx_inc_test_stage();
1300 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1301 		return VMX_TEST_RESUME;
1302 	default:
1303 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1304 		print_vmexit_info(exit_reason);
1305 	}
1306 	return VMX_TEST_VMEXIT;
1307 }
1308 
1309 static int ept_exit_handler_common(union exit_reason exit_reason, bool have_ad)
1310 {
1311 	u64 guest_rip;
1312 	u64 guest_cr3;
1313 	u32 insn_len;
1314 	u32 exit_qual;
1315 	static unsigned long data_page1_pte, data_page1_pte_pte, memaddr_pte,
1316 			     guest_pte_addr;
1317 
1318 	guest_rip = vmcs_read(GUEST_RIP);
1319 	guest_cr3 = vmcs_read(GUEST_CR3);
1320 	insn_len = vmcs_read(EXI_INST_LEN);
1321 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1322 	pteval_t *ptep;
1323 	switch (exit_reason.basic) {
1324 	case VMX_VMCALL:
1325 		switch (vmx_get_test_stage()) {
1326 		case 0:
1327 			check_ept_ad(pml4, guest_cr3,
1328 				     (unsigned long)data_page1,
1329 				     have_ad ? EPT_ACCESS_FLAG : 0,
1330 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1331 			check_ept_ad(pml4, guest_cr3,
1332 				     (unsigned long)data_page2,
1333 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1334 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1335 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1336 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1337 			if (have_ad)
1338 				ept_sync(INVEPT_SINGLE, eptp);;
1339 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1340 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1341 				vmx_inc_test_stage();
1342 				install_ept(pml4, (unsigned long)data_page2,
1343 						(unsigned long)data_page2,
1344 						EPT_RA | EPT_WA | EPT_EA);
1345 			} else
1346 				report(0, "EPT basic framework - write");
1347 			break;
1348 		case 1:
1349 			install_ept(pml4, (unsigned long)data_page1,
1350  				(unsigned long)data_page1, EPT_WA);
1351 			ept_sync(INVEPT_SINGLE, eptp);
1352 			break;
1353 		case 2:
1354 			install_ept(pml4, (unsigned long)data_page1,
1355  				(unsigned long)data_page1,
1356  				EPT_RA | EPT_WA | EPT_EA |
1357  				(2 << EPT_MEM_TYPE_SHIFT));
1358 			ept_sync(INVEPT_SINGLE, eptp);
1359 			break;
1360 		case 3:
1361 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1362 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1363 						1, &data_page1_pte));
1364 			set_ept_pte(pml4, (unsigned long)data_page1,
1365 				1, data_page1_pte & ~EPT_PRESENT);
1366 			ept_sync(INVEPT_SINGLE, eptp);
1367 			break;
1368 		case 4:
1369 			ptep = get_pte_level((pgd_t *)guest_cr3, data_page1, /*level=*/2);
1370 			guest_pte_addr = virt_to_phys(ptep) & PAGE_MASK;
1371 
1372 			TEST_ASSERT(get_ept_pte(pml4, guest_pte_addr, 2, &data_page1_pte_pte));
1373 			set_ept_pte(pml4, guest_pte_addr, 2,
1374 				data_page1_pte_pte & ~EPT_PRESENT);
1375 			ept_sync(INVEPT_SINGLE, eptp);
1376 			break;
1377 		case 5:
1378 			install_ept(pml4, (unsigned long)pci_physaddr,
1379 				(unsigned long)pci_physaddr, 0);
1380 			ept_sync(INVEPT_SINGLE, eptp);
1381 			break;
1382 		case 7:
1383 			if (!invept_test(0, eptp))
1384 				vmx_inc_test_stage();
1385 			break;
1386 		// Should not reach here
1387 		default:
1388 			report(false, "ERROR - unexpected stage, %d.",
1389 			       vmx_get_test_stage());
1390 			print_vmexit_info(exit_reason);
1391 			return VMX_TEST_VMEXIT;
1392 		}
1393 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1394 		return VMX_TEST_RESUME;
1395 	case VMX_EPT_MISCONFIG:
1396 		switch (vmx_get_test_stage()) {
1397 		case 1:
1398 		case 2:
1399 			vmx_inc_test_stage();
1400 			install_ept(pml4, (unsigned long)data_page1,
1401  				(unsigned long)data_page1,
1402  				EPT_RA | EPT_WA | EPT_EA);
1403 			ept_sync(INVEPT_SINGLE, eptp);
1404 			break;
1405 		// Should not reach here
1406 		default:
1407 			report(false, "ERROR - unexpected stage, %d.",
1408 			       vmx_get_test_stage());
1409 			print_vmexit_info(exit_reason);
1410 			return VMX_TEST_VMEXIT;
1411 		}
1412 		return VMX_TEST_RESUME;
1413 	case VMX_EPT_VIOLATION:
1414 		/*
1415 		 * Exit-qualifications are masked not to account for advanced
1416 		 * VM-exit information. Once KVM supports this feature, this
1417 		 * masking should be removed.
1418 		 */
1419 		exit_qual &= ~EPT_VLT_GUEST_MASK;
1420 
1421 		switch(vmx_get_test_stage()) {
1422 		case 3:
1423 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1424 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1425 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1426 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1427 					EPT_VLT_PADDR))
1428 				vmx_inc_test_stage();
1429 			set_ept_pte(pml4, (unsigned long)data_page1,
1430 				1, data_page1_pte | (EPT_PRESENT));
1431 			ept_sync(INVEPT_SINGLE, eptp);
1432 			break;
1433 		case 4:
1434 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1435 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1436 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1437 			if (exit_qual == (EPT_VLT_RD |
1438 					  (have_ad ? EPT_VLT_WR : 0) |
1439 					  EPT_VLT_LADDR_VLD))
1440 				vmx_inc_test_stage();
1441 			set_ept_pte(pml4, guest_pte_addr, 2,
1442 				data_page1_pte_pte | (EPT_PRESENT));
1443 			ept_sync(INVEPT_SINGLE, eptp);
1444 			break;
1445 		case 5:
1446 			if (exit_qual & EPT_VLT_RD)
1447 				vmx_inc_test_stage();
1448 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1449 						1, &memaddr_pte));
1450 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA);
1451 			ept_sync(INVEPT_SINGLE, eptp);
1452 			break;
1453 		case 6:
1454 			if (exit_qual & EPT_VLT_WR)
1455 				vmx_inc_test_stage();
1456 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1457 						1, &memaddr_pte));
1458 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA | EPT_WA);
1459 			ept_sync(INVEPT_SINGLE, eptp);
1460 			break;
1461 		default:
1462 			// Should not reach here
1463 			report(false, "ERROR : unexpected stage, %d",
1464 			       vmx_get_test_stage());
1465 			print_vmexit_info(exit_reason);
1466 			return VMX_TEST_VMEXIT;
1467 		}
1468 		return VMX_TEST_RESUME;
1469 	default:
1470 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1471 		print_vmexit_info(exit_reason);
1472 	}
1473 	return VMX_TEST_VMEXIT;
1474 }
1475 
1476 static int ept_exit_handler(union exit_reason exit_reason)
1477 {
1478 	return ept_exit_handler_common(exit_reason, false);
1479 }
1480 
1481 static int eptad_init(struct vmcs *vmcs)
1482 {
1483 	int r = ept_init_common(true);
1484 
1485 	if (r == VMX_TEST_EXIT)
1486 		return r;
1487 
1488 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1489 		printf("\tEPT A/D bits are not supported");
1490 		return VMX_TEST_EXIT;
1491 	}
1492 
1493 	return r;
1494 }
1495 
1496 static int pml_init(struct vmcs *vmcs)
1497 {
1498 	u32 ctrl_cpu;
1499 	int r = eptad_init(vmcs);
1500 
1501 	if (r == VMX_TEST_EXIT)
1502 		return r;
1503 
1504 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1505 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1506 		printf("\tPML is not supported");
1507 		return VMX_TEST_EXIT;
1508 	}
1509 
1510 	pml_log = alloc_page();
1511 	vmcs_write(PMLADDR, (u64)pml_log);
1512 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1513 
1514 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1515 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1516 
1517 	return VMX_TEST_START;
1518 }
1519 
1520 static void pml_main(void)
1521 {
1522 	int count = 0;
1523 
1524 	vmx_set_test_stage(0);
1525 	*((u32 *)data_page2) = 0x1;
1526 	vmcall();
1527 	report(vmx_get_test_stage() == 1, "PML - Dirty GPA Logging");
1528 
1529 	while (vmx_get_test_stage() == 1) {
1530 		vmcall();
1531 		*((u32 *)data_page2) = 0x1;
1532 		if (count++ > PML_INDEX)
1533 			break;
1534 	}
1535 	report(vmx_get_test_stage() == 2, "PML Full Event");
1536 }
1537 
1538 static void eptad_main(void)
1539 {
1540 	ept_common();
1541 }
1542 
1543 static int eptad_exit_handler(union exit_reason exit_reason)
1544 {
1545 	return ept_exit_handler_common(exit_reason, true);
1546 }
1547 
1548 static bool invvpid_test(int type, u16 vpid)
1549 {
1550 	bool ret, supported;
1551 
1552 	supported = ept_vpid.val &
1553 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1554 	ret = invvpid(type, vpid, 0);
1555 
1556 	if (ret == !supported)
1557 		return false;
1558 
1559 	if (!supported)
1560 		printf("WARNING: unsupported invvpid passed!\n");
1561 	else
1562 		printf("WARNING: invvpid failed!\n");
1563 
1564 	return true;
1565 }
1566 
1567 static int vpid_init(struct vmcs *vmcs)
1568 {
1569 	u32 ctrl_cpu1;
1570 
1571 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1572 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1573 		printf("\tVPID is not supported");
1574 		return VMX_TEST_EXIT;
1575 	}
1576 
1577 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1578 	ctrl_cpu1 |= CPU_VPID;
1579 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1580 	return VMX_TEST_START;
1581 }
1582 
1583 static void vpid_main(void)
1584 {
1585 	vmx_set_test_stage(0);
1586 	vmcall();
1587 	report(vmx_get_test_stage() == 1, "INVVPID SINGLE ADDRESS");
1588 	vmx_set_test_stage(2);
1589 	vmcall();
1590 	report(vmx_get_test_stage() == 3, "INVVPID SINGLE");
1591 	vmx_set_test_stage(4);
1592 	vmcall();
1593 	report(vmx_get_test_stage() == 5, "INVVPID ALL");
1594 }
1595 
1596 static int vpid_exit_handler(union exit_reason exit_reason)
1597 {
1598 	u64 guest_rip;
1599 	u32 insn_len;
1600 
1601 	guest_rip = vmcs_read(GUEST_RIP);
1602 	insn_len = vmcs_read(EXI_INST_LEN);
1603 
1604 	switch (exit_reason.basic) {
1605 	case VMX_VMCALL:
1606 		switch(vmx_get_test_stage()) {
1607 		case 0:
1608 			if (!invvpid_test(INVVPID_ADDR, 1))
1609 				vmx_inc_test_stage();
1610 			break;
1611 		case 2:
1612 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1613 				vmx_inc_test_stage();
1614 			break;
1615 		case 4:
1616 			if (!invvpid_test(INVVPID_ALL, 1))
1617 				vmx_inc_test_stage();
1618 			break;
1619 		default:
1620 			report(false, "ERROR: unexpected stage, %d",
1621 					vmx_get_test_stage());
1622 			print_vmexit_info(exit_reason);
1623 			return VMX_TEST_VMEXIT;
1624 		}
1625 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1626 		return VMX_TEST_RESUME;
1627 	default:
1628 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1629 		print_vmexit_info(exit_reason);
1630 	}
1631 	return VMX_TEST_VMEXIT;
1632 }
1633 
1634 #define TIMER_VECTOR	222
1635 
1636 static volatile bool timer_fired;
1637 
1638 static void timer_isr(isr_regs_t *regs)
1639 {
1640 	timer_fired = true;
1641 	apic_write(APIC_EOI, 0);
1642 }
1643 
1644 static int interrupt_init(struct vmcs *vmcs)
1645 {
1646 	msr_bmp_init();
1647 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1648 	handle_irq(TIMER_VECTOR, timer_isr);
1649 	return VMX_TEST_START;
1650 }
1651 
1652 static void interrupt_main(void)
1653 {
1654 	long long start, loops;
1655 
1656 	vmx_set_test_stage(0);
1657 
1658 	apic_write(APIC_LVTT, TIMER_VECTOR);
1659 	irq_enable();
1660 
1661 	apic_write(APIC_TMICT, 1);
1662 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1663 		asm volatile ("nop");
1664 	report(timer_fired, "direct interrupt while running guest");
1665 
1666 	apic_write(APIC_TMICT, 0);
1667 	irq_disable();
1668 	vmcall();
1669 	timer_fired = false;
1670 	apic_write(APIC_TMICT, 1);
1671 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1672 		asm volatile ("nop");
1673 	report(timer_fired, "intercepted interrupt while running guest");
1674 
1675 	irq_enable();
1676 	apic_write(APIC_TMICT, 0);
1677 	irq_disable();
1678 	vmcall();
1679 	timer_fired = false;
1680 	start = rdtsc();
1681 	apic_write(APIC_TMICT, 1000000);
1682 
1683 	asm volatile ("sti; hlt");
1684 
1685 	report(rdtsc() - start > 1000000 && timer_fired,
1686 	       "direct interrupt + hlt");
1687 
1688 	apic_write(APIC_TMICT, 0);
1689 	irq_disable();
1690 	vmcall();
1691 	timer_fired = false;
1692 	start = rdtsc();
1693 	apic_write(APIC_TMICT, 1000000);
1694 
1695 	asm volatile ("sti; hlt");
1696 
1697 	report(rdtsc() - start > 10000 && timer_fired,
1698 	       "intercepted interrupt + hlt");
1699 
1700 	apic_write(APIC_TMICT, 0);
1701 	irq_disable();
1702 	vmcall();
1703 	timer_fired = false;
1704 	start = rdtsc();
1705 	apic_write(APIC_TMICT, 1000000);
1706 
1707 	irq_enable();
1708 	asm volatile ("nop");
1709 	vmcall();
1710 
1711 	report(rdtsc() - start > 10000 && timer_fired,
1712 	       "direct interrupt + activity state hlt");
1713 
1714 	apic_write(APIC_TMICT, 0);
1715 	irq_disable();
1716 	vmcall();
1717 	timer_fired = false;
1718 	start = rdtsc();
1719 	apic_write(APIC_TMICT, 1000000);
1720 
1721 	irq_enable();
1722 	asm volatile ("nop");
1723 	vmcall();
1724 
1725 	report(rdtsc() - start > 10000 && timer_fired,
1726 	       "intercepted interrupt + activity state hlt");
1727 
1728 	apic_write(APIC_TMICT, 0);
1729 	irq_disable();
1730 	vmx_set_test_stage(7);
1731 	vmcall();
1732 	timer_fired = false;
1733 	apic_write(APIC_TMICT, 1);
1734 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1735 		asm volatile ("nop");
1736 	report(timer_fired,
1737 	       "running a guest with interrupt acknowledgement set");
1738 
1739 	apic_write(APIC_TMICT, 0);
1740 	irq_enable();
1741 	timer_fired = false;
1742 	vmcall();
1743 	report(timer_fired, "Inject an event to a halted guest");
1744 }
1745 
1746 static int interrupt_exit_handler(union exit_reason exit_reason)
1747 {
1748 	u64 guest_rip = vmcs_read(GUEST_RIP);
1749 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1750 
1751 	switch (exit_reason.basic) {
1752 	case VMX_VMCALL:
1753 		switch (vmx_get_test_stage()) {
1754 		case 0:
1755 		case 2:
1756 		case 5:
1757 			vmcs_write(PIN_CONTROLS,
1758 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1759 			break;
1760 		case 7:
1761 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1762 			vmcs_write(PIN_CONTROLS,
1763 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1764 			break;
1765 		case 1:
1766 		case 3:
1767 			vmcs_write(PIN_CONTROLS,
1768 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1769 			break;
1770 		case 4:
1771 		case 6:
1772 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1773 			break;
1774 
1775 		case 8:
1776 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1777 			vmcs_write(ENT_INTR_INFO,
1778 				   TIMER_VECTOR |
1779 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1780 				   INTR_INFO_VALID_MASK);
1781 			break;
1782 		}
1783 		vmx_inc_test_stage();
1784 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1785 		return VMX_TEST_RESUME;
1786 	case VMX_EXTINT:
1787 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1788 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1789 			handle_external_interrupt(vector);
1790 		} else {
1791 			irq_enable();
1792 			asm volatile ("nop");
1793 			irq_disable();
1794 		}
1795 		if (vmx_get_test_stage() >= 2)
1796 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1797 		return VMX_TEST_RESUME;
1798 	default:
1799 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1800 		print_vmexit_info(exit_reason);
1801 	}
1802 
1803 	return VMX_TEST_VMEXIT;
1804 }
1805 
1806 static int dbgctls_init(struct vmcs *vmcs)
1807 {
1808 	u64 dr7 = 0x402;
1809 	u64 zero = 0;
1810 
1811 	msr_bmp_init();
1812 	asm volatile(
1813 		"mov %0,%%dr0\n\t"
1814 		"mov %0,%%dr1\n\t"
1815 		"mov %0,%%dr2\n\t"
1816 		"mov %1,%%dr7\n\t"
1817 		: : "r" (zero), "r" (dr7));
1818 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1819 	vmcs_write(GUEST_DR7, 0x404);
1820 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1821 
1822 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1823 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1824 
1825 	return VMX_TEST_START;
1826 }
1827 
1828 static void dbgctls_main(void)
1829 {
1830 	u64 dr7, debugctl;
1831 
1832 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1833 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1834 	/* Commented out: KVM does not support DEBUGCTL so far */
1835 	(void)debugctl;
1836 	report(dr7 == 0x404, "Load debug controls" /* && debugctl == 0x2 */);
1837 
1838 	dr7 = 0x408;
1839 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1840 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1841 
1842 	vmx_set_test_stage(0);
1843 	vmcall();
1844 	report(vmx_get_test_stage() == 1, "Save debug controls");
1845 
1846 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1847 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1848 		printf("\tDebug controls are always loaded/saved\n");
1849 		return;
1850 	}
1851 	vmx_set_test_stage(2);
1852 	vmcall();
1853 
1854 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1855 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1856 	/* Commented out: KVM does not support DEBUGCTL so far */
1857 	(void)debugctl;
1858 	report(dr7 == 0x402,
1859 	       "Guest=host debug controls" /* && debugctl == 0x1 */);
1860 
1861 	dr7 = 0x408;
1862 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1863 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1864 
1865 	vmx_set_test_stage(3);
1866 	vmcall();
1867 	report(vmx_get_test_stage() == 4, "Don't save debug controls");
1868 }
1869 
1870 static int dbgctls_exit_handler(union exit_reason exit_reason)
1871 {
1872 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1873 	u64 guest_rip = vmcs_read(GUEST_RIP);
1874 	u64 dr7, debugctl;
1875 
1876 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1877 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1878 
1879 	switch (exit_reason.basic) {
1880 	case VMX_VMCALL:
1881 		switch (vmx_get_test_stage()) {
1882 		case 0:
1883 			if (dr7 == 0x400 && debugctl == 0 &&
1884 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1885 			    Commented out: KVM does not support DEBUGCTL so far
1886 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1887 				vmx_inc_test_stage();
1888 			break;
1889 		case 2:
1890 			dr7 = 0x402;
1891 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1892 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1893 			vmcs_write(GUEST_DR7, 0x404);
1894 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1895 
1896 			vmcs_write(ENT_CONTROLS,
1897 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1898 			vmcs_write(EXI_CONTROLS,
1899 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1900 			break;
1901 		case 3:
1902 			if (dr7 == 0x400 && debugctl == 0 &&
1903 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1904 			    Commented out: KVM does not support DEBUGCTL so far
1905 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1906 				vmx_inc_test_stage();
1907 			break;
1908 		}
1909 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1910 		return VMX_TEST_RESUME;
1911 	default:
1912 		report(false, "Unknown exit reason, %d", exit_reason.full);
1913 		print_vmexit_info(exit_reason);
1914 	}
1915 	return VMX_TEST_VMEXIT;
1916 }
1917 
1918 struct vmx_msr_entry {
1919 	u32 index;
1920 	u32 reserved;
1921 	u64 value;
1922 } __attribute__((packed));
1923 
1924 #define MSR_MAGIC 0x31415926
1925 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1926 
1927 static int msr_switch_init(struct vmcs *vmcs)
1928 {
1929 	msr_bmp_init();
1930 	exit_msr_store = alloc_page();
1931 	exit_msr_load = alloc_page();
1932 	entry_msr_load = alloc_page();
1933 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1934 	entry_msr_load[0].value = MSR_MAGIC;
1935 
1936 	vmx_set_test_stage(1);
1937 	vmcs_write(ENT_MSR_LD_CNT, 1);
1938 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1939 	vmcs_write(EXI_MSR_ST_CNT, 1);
1940 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1941 	vmcs_write(EXI_MSR_LD_CNT, 1);
1942 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1943 	return VMX_TEST_START;
1944 }
1945 
1946 static void msr_switch_main(void)
1947 {
1948 	if (vmx_get_test_stage() == 1) {
1949 		report(rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC,
1950 		       "VM entry MSR load");
1951 		vmx_set_test_stage(2);
1952 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1953 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1954 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1955 		exit_msr_load[0].value = MSR_MAGIC + 2;
1956 	}
1957 	vmcall();
1958 }
1959 
1960 static int msr_switch_exit_handler(union exit_reason exit_reason)
1961 {
1962 	if (exit_reason.basic == VMX_VMCALL && vmx_get_test_stage() == 2) {
1963 		report(exit_msr_store[0].value == MSR_MAGIC + 1,
1964 		       "VM exit MSR store");
1965 		report(rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2,
1966 		       "VM exit MSR load");
1967 		vmx_set_test_stage(3);
1968 		entry_msr_load[0].index = MSR_FS_BASE;
1969 		return VMX_TEST_RESUME;
1970 	}
1971 	printf("ERROR %s: unexpected stage=%u or reason=0x%x\n",
1972 		__func__, vmx_get_test_stage(), exit_reason.full);
1973 	return VMX_TEST_EXIT;
1974 }
1975 
1976 static int msr_switch_entry_failure(struct vmentry_result *result)
1977 {
1978 	if (result->vm_fail) {
1979 		printf("ERROR %s: VM-Fail on %s\n", __func__, result->instr);
1980 		return VMX_TEST_EXIT;
1981 	}
1982 
1983 	if (result->exit_reason.failed_vmentry &&
1984 	    result->exit_reason.basic == VMX_FAIL_MSR &&
1985 	    vmx_get_test_stage() == 3) {
1986 		report(vmcs_read(EXI_QUALIFICATION) == 1,
1987 		       "VM entry MSR load: try to load FS_BASE");
1988 		return VMX_TEST_VMEXIT;
1989 	}
1990 	printf("ERROR %s: unexpected stage=%u or reason=%x\n",
1991 		__func__, vmx_get_test_stage(), result->exit_reason.full);
1992 	return VMX_TEST_EXIT;
1993 }
1994 
1995 static int vmmcall_init(struct vmcs *vmcs)
1996 {
1997 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1998 	return VMX_TEST_START;
1999 }
2000 
2001 static void vmmcall_main(void)
2002 {
2003 	asm volatile(
2004 		"mov $0xABCD, %%rax\n\t"
2005 		"vmmcall\n\t"
2006 		::: "rax");
2007 
2008 	report(0, "VMMCALL");
2009 }
2010 
2011 static int vmmcall_exit_handler(union exit_reason exit_reason)
2012 {
2013 	switch (exit_reason.basic) {
2014 	case VMX_VMCALL:
2015 		printf("here\n");
2016 		report(0, "VMMCALL triggers #UD");
2017 		break;
2018 	case VMX_EXC_NMI:
2019 		report((vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR,
2020 		       "VMMCALL triggers #UD");
2021 		break;
2022 	default:
2023 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
2024 		print_vmexit_info(exit_reason);
2025 	}
2026 
2027 	return VMX_TEST_VMEXIT;
2028 }
2029 
2030 static int disable_rdtscp_init(struct vmcs *vmcs)
2031 {
2032 	u32 ctrl_cpu1;
2033 
2034 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
2035 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
2036 		ctrl_cpu1 &= ~CPU_RDTSCP;
2037 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
2038 	}
2039 
2040 	return VMX_TEST_START;
2041 }
2042 
2043 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
2044 {
2045 	switch (vmx_get_test_stage()) {
2046 	case 0:
2047 		report(true, "RDTSCP triggers #UD");
2048 		vmx_inc_test_stage();
2049 		regs->rip += 3;
2050 		break;
2051 	case 2:
2052 		report(true, "RDPID triggers #UD");
2053 		vmx_inc_test_stage();
2054 		regs->rip += 4;
2055 		break;
2056 	}
2057 	return;
2058 
2059 }
2060 
2061 static void disable_rdtscp_main(void)
2062 {
2063 	/* Test that #UD is properly injected in L2.  */
2064 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
2065 
2066 	vmx_set_test_stage(0);
2067 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
2068 	vmcall();
2069 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
2070 
2071 	handle_exception(UD_VECTOR, 0);
2072 	vmcall();
2073 }
2074 
2075 static int disable_rdtscp_exit_handler(union exit_reason exit_reason)
2076 {
2077 	switch (exit_reason.basic) {
2078 	case VMX_VMCALL:
2079 		switch (vmx_get_test_stage()) {
2080 		case 0:
2081 			report(false, "RDTSCP triggers #UD");
2082 			vmx_inc_test_stage();
2083 			/* fallthrough */
2084 		case 1:
2085 			vmx_inc_test_stage();
2086 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
2087 			return VMX_TEST_RESUME;
2088 		case 2:
2089 			report(false, "RDPID triggers #UD");
2090 			break;
2091 		}
2092 		break;
2093 
2094 	default:
2095 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
2096 		print_vmexit_info(exit_reason);
2097 	}
2098 	return VMX_TEST_VMEXIT;
2099 }
2100 
2101 static int int3_init(struct vmcs *vmcs)
2102 {
2103 	vmcs_write(EXC_BITMAP, ~0u);
2104 	return VMX_TEST_START;
2105 }
2106 
2107 static void int3_guest_main(void)
2108 {
2109 	asm volatile ("int3");
2110 }
2111 
2112 static int int3_exit_handler(union exit_reason exit_reason)
2113 {
2114 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2115 
2116 	report(exit_reason.basic == VMX_EXC_NMI &&
2117 	       (intr_info & INTR_INFO_VALID_MASK) &&
2118 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
2119 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2120 	        INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION,
2121 	       "L1 intercepts #BP");
2122 
2123 	return VMX_TEST_VMEXIT;
2124 }
2125 
2126 static int into_init(struct vmcs *vmcs)
2127 {
2128 	vmcs_write(EXC_BITMAP, ~0u);
2129 	return VMX_TEST_START;
2130 }
2131 
2132 static void into_guest_main(void)
2133 {
2134 	struct far_pointer32 fp = {
2135 		.offset = (uintptr_t)&&into,
2136 		.selector = KERNEL_CS32,
2137 	};
2138 	register uintptr_t rsp asm("rsp");
2139 
2140 	if (fp.offset != (uintptr_t)&&into) {
2141 		printf("Code address too high.\n");
2142 		return;
2143 	}
2144 	if ((u32)rsp != rsp) {
2145 		printf("Stack address too high.\n");
2146 		return;
2147 	}
2148 
2149 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2150 	return;
2151 into:
2152 	asm volatile (".code32;"
2153 		      "movl $0x7fffffff, %eax;"
2154 		      "addl %eax, %eax;"
2155 		      "into;"
2156 		      "lret;"
2157 		      ".code64");
2158 	__builtin_unreachable();
2159 }
2160 
2161 static int into_exit_handler(union exit_reason exit_reason)
2162 {
2163 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2164 
2165 	report(exit_reason.basic == VMX_EXC_NMI &&
2166 	       (intr_info & INTR_INFO_VALID_MASK) &&
2167 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2168 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2169 	        INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION,
2170 	       "L1 intercepts #OF");
2171 
2172 	return VMX_TEST_VMEXIT;
2173 }
2174 
2175 static void exit_monitor_from_l2_main(void)
2176 {
2177 	printf("Calling exit(0) from l2...\n");
2178 	exit(0);
2179 }
2180 
2181 static int exit_monitor_from_l2_handler(union exit_reason exit_reason)
2182 {
2183 	report(false, "The guest should have killed the VMM");
2184 	return VMX_TEST_EXIT;
2185 }
2186 
2187 static void assert_exit_reason(u64 expected)
2188 {
2189 	u64 actual = vmcs_read(EXI_REASON);
2190 
2191 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2192 			   exit_reason_description(expected),
2193 			   exit_reason_description(actual));
2194 }
2195 
2196 static void skip_exit_insn(void)
2197 {
2198 	u64 guest_rip = vmcs_read(GUEST_RIP);
2199 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2200 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2201 }
2202 
2203 static void skip_exit_vmcall(void)
2204 {
2205 	assert_exit_reason(VMX_VMCALL);
2206 	skip_exit_insn();
2207 }
2208 
2209 static void v2_null_test_guest(void)
2210 {
2211 }
2212 
2213 static void v2_null_test(void)
2214 {
2215 	test_set_guest(v2_null_test_guest);
2216 	enter_guest();
2217 	report(1, __func__);
2218 }
2219 
2220 static void v2_multiple_entries_test_guest(void)
2221 {
2222 	vmx_set_test_stage(1);
2223 	vmcall();
2224 	vmx_set_test_stage(2);
2225 }
2226 
2227 static void v2_multiple_entries_test(void)
2228 {
2229 	test_set_guest(v2_multiple_entries_test_guest);
2230 	enter_guest();
2231 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2232 	skip_exit_vmcall();
2233 	enter_guest();
2234 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2235 	report(1, __func__);
2236 }
2237 
2238 static int fixture_test_data = 1;
2239 
2240 static void fixture_test_teardown(void *data)
2241 {
2242 	*((int *) data) = 1;
2243 }
2244 
2245 static void fixture_test_guest(void)
2246 {
2247 	fixture_test_data++;
2248 }
2249 
2250 
2251 static void fixture_test_setup(void)
2252 {
2253 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2254 			   "fixture_test_teardown didn't run?!");
2255 	fixture_test_data = 2;
2256 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2257 	test_set_guest(fixture_test_guest);
2258 }
2259 
2260 static void fixture_test_case1(void)
2261 {
2262 	fixture_test_setup();
2263 	TEST_ASSERT_EQ(2, fixture_test_data);
2264 	enter_guest();
2265 	TEST_ASSERT_EQ(3, fixture_test_data);
2266 	report(1, __func__);
2267 }
2268 
2269 static void fixture_test_case2(void)
2270 {
2271 	fixture_test_setup();
2272 	TEST_ASSERT_EQ(2, fixture_test_data);
2273 	enter_guest();
2274 	TEST_ASSERT_EQ(3, fixture_test_data);
2275 	report(1, __func__);
2276 }
2277 
2278 enum ept_access_op {
2279 	OP_READ,
2280 	OP_WRITE,
2281 	OP_EXEC,
2282 	OP_FLUSH_TLB,
2283 	OP_EXIT,
2284 };
2285 
2286 static struct ept_access_test_data {
2287 	unsigned long gpa;
2288 	unsigned long *gva;
2289 	unsigned long hpa;
2290 	unsigned long *hva;
2291 	enum ept_access_op op;
2292 } ept_access_test_data;
2293 
2294 extern unsigned char ret42_start;
2295 extern unsigned char ret42_end;
2296 
2297 /* Returns 42. */
2298 asm(
2299 	".align 64\n"
2300 	"ret42_start:\n"
2301 	"mov $42, %eax\n"
2302 	"ret\n"
2303 	"ret42_end:\n"
2304 );
2305 
2306 static void
2307 diagnose_ept_violation_qual(u64 expected, u64 actual)
2308 {
2309 
2310 #define DIAGNOSE(flag)							\
2311 do {									\
2312 	if ((expected & flag) != (actual & flag))			\
2313 		printf(#flag " %sexpected\n",				\
2314 		       (expected & flag) ? "" : "un");			\
2315 } while (0)
2316 
2317 	DIAGNOSE(EPT_VLT_RD);
2318 	DIAGNOSE(EPT_VLT_WR);
2319 	DIAGNOSE(EPT_VLT_FETCH);
2320 	DIAGNOSE(EPT_VLT_PERM_RD);
2321 	DIAGNOSE(EPT_VLT_PERM_WR);
2322 	DIAGNOSE(EPT_VLT_PERM_EX);
2323 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2324 	DIAGNOSE(EPT_VLT_PADDR);
2325 
2326 #undef DIAGNOSE
2327 }
2328 
2329 static void do_ept_access_op(enum ept_access_op op)
2330 {
2331 	ept_access_test_data.op = op;
2332 	enter_guest();
2333 }
2334 
2335 /*
2336  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2337  * needed by tests that modify guest PTEs.
2338  */
2339 static void ept_access_test_guest_flush_tlb(void)
2340 {
2341 	do_ept_access_op(OP_FLUSH_TLB);
2342 	skip_exit_vmcall();
2343 }
2344 
2345 /*
2346  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2347  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2348  * a huge page.
2349  */
2350 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2351 				 unsigned long clear, unsigned long set)
2352 {
2353 	struct ept_access_test_data *data = &ept_access_test_data;
2354 	unsigned long orig_pte;
2355 	unsigned long pte;
2356 
2357 	/* Screw with the mapping at the requested level. */
2358 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2359 	pte = orig_pte;
2360 	if (mkhuge)
2361 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2362 	else
2363 		pte = orig_pte;
2364 	pte = (pte & ~clear) | set;
2365 	set_ept_pte(pml4, gpa, level, pte);
2366 	ept_sync(INVEPT_SINGLE, eptp);
2367 
2368 	return orig_pte;
2369 }
2370 
2371 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2372 {
2373 	set_ept_pte(pml4, gpa, level, orig_pte);
2374 	ept_sync(INVEPT_SINGLE, eptp);
2375 }
2376 
2377 static void do_ept_violation(bool leaf, enum ept_access_op op,
2378 			     u64 expected_qual, u64 expected_paddr)
2379 {
2380 	u64 qual;
2381 
2382 	/* Try the access and observe the violation. */
2383 	do_ept_access_op(op);
2384 
2385 	assert_exit_reason(VMX_EPT_VIOLATION);
2386 
2387 	qual = vmcs_read(EXI_QUALIFICATION);
2388 
2389 	/* Mask undefined bits (which may later be defined in certain cases). */
2390 	qual &= ~(EPT_VLT_GUEST_USER | EPT_VLT_GUEST_RW | EPT_VLT_GUEST_EX |
2391 		 EPT_VLT_PERM_USER_EX);
2392 
2393 	diagnose_ept_violation_qual(expected_qual, qual);
2394 	TEST_EXPECT_EQ(expected_qual, qual);
2395 
2396 	#if 0
2397 	/* Disable for now otherwise every test will fail */
2398 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2399 		       (unsigned long) (
2400 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2401 	#endif
2402 	/*
2403 	 * TODO: tests that probe expected_paddr in pages other than the one at
2404 	 * the beginning of the 1g region.
2405 	 */
2406 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2407 }
2408 
2409 static void
2410 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2411 			      unsigned long set, enum ept_access_op op,
2412 			      u64 expected_qual)
2413 {
2414 	struct ept_access_test_data *data = &ept_access_test_data;
2415 	unsigned long orig_pte;
2416 
2417 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2418 
2419 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2420 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2421 					 data->gpa);
2422 
2423 	/* Fix the violation and resume the op loop. */
2424 	ept_untwiddle(data->gpa, level, orig_pte);
2425 	enter_guest();
2426 	skip_exit_vmcall();
2427 }
2428 
2429 static void
2430 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2431 		       enum ept_access_op op, u64 expected_qual)
2432 {
2433 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2434 				      expected_qual);
2435 	if (ept_huge_pages_supported(level))
2436 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2437 					      expected_qual);
2438 }
2439 
2440 static void ept_violation(unsigned long clear, unsigned long set,
2441 			  enum ept_access_op op, u64 expected_qual)
2442 {
2443 	ept_violation_at_level(1, clear, set, op, expected_qual);
2444 	ept_violation_at_level(2, clear, set, op, expected_qual);
2445 	ept_violation_at_level(3, clear, set, op, expected_qual);
2446 	ept_violation_at_level(4, clear, set, op, expected_qual);
2447 }
2448 
2449 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2450 				       u64 expected_qual)
2451 {
2452 	ept_violation(EPT_PRESENT, access, op,
2453 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2454 }
2455 
2456 /*
2457  * For translations that don't involve a GVA, that is physical address (paddr)
2458  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2459  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2460  * translations don't involve GVAs, such as when the hardware does the guest
2461  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2462  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2463  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2464  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2465  *
2466  * Note that paddr violations can also be triggered by loading PAE page tables
2467  * with wonky addresses. We don't test that yet.
2468  *
2469  * This function modifies the EPT entry that maps the GPA that the guest page
2470  * table entry mapping ept_access_test_data.gva resides on.
2471  *
2472  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2473  *
2474  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2475  *
2476  *	@op		Guest operation to perform with
2477  *			ept_access_test_data.gva.
2478  *
2479  *	@expect_violation
2480  *			Is a violation expected during the paddr access?
2481  *
2482  *	@expected_qual	Expected qualification for the EPT violation.
2483  *			EPT_VLT_PADDR should be clear.
2484  */
2485 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2486 			     enum ept_access_op op, bool expect_violation,
2487 			     u64 expected_qual)
2488 {
2489 	struct ept_access_test_data *data = &ept_access_test_data;
2490 	unsigned long *ptep;
2491 	unsigned long gpa;
2492 	unsigned long orig_epte;
2493 	unsigned long epte;
2494 	int i;
2495 
2496 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2497 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2498 	TEST_ASSERT(ptep);
2499 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2500 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2501 	ept_access_test_guest_flush_tlb();
2502 
2503 	/*
2504 	 * Now modify the access bits on the EPT entry for the GPA that the
2505 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2506 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2507 	 * constructed our test such that those other 511 PTEs aren't used by
2508 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2509 	 * PTE we're modifying is at the beginning of a 4K page and the
2510 	 * following 511 entires are also under our control (and not touched by
2511 	 * the guest).
2512 	 */
2513 	gpa = virt_to_phys(ptep);
2514 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2515 	/*
2516 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2517 	 * otherwise our level=1 twiddling below will fail. We use the
2518 	 * identity map (gpa = gpa) since page tables are shared with the host.
2519 	 */
2520 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2521 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2522 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2523 
2524 	if (expect_violation) {
2525 		do_ept_violation(/*leaf=*/true, op,
2526 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2527 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2528 		do_ept_access_op(op);
2529 	} else {
2530 		do_ept_access_op(op);
2531 		if (ept_ad_enabled()) {
2532 			for (i = EPT_PAGE_LEVEL; i > 0; i--) {
2533 				TEST_ASSERT(get_ept_pte(pml4, gpa, i, &epte));
2534 				TEST_ASSERT(epte & EPT_ACCESS_FLAG);
2535 				if (i == 1)
2536 					TEST_ASSERT(epte & EPT_DIRTY_FLAG);
2537 				else
2538 					TEST_ASSERT_EQ(epte & EPT_DIRTY_FLAG, 0);
2539 			}
2540 		}
2541 
2542 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2543 	}
2544 
2545 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2546 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2547 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2548 
2549 	skip_exit_vmcall();
2550 }
2551 
2552 static void ept_access_allowed_paddr(unsigned long ept_access,
2553 				     unsigned long pte_ad,
2554 				     enum ept_access_op op)
2555 {
2556 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2557 			 /*expected_qual=*/-1);
2558 }
2559 
2560 static void ept_access_violation_paddr(unsigned long ept_access,
2561 				       unsigned long pte_ad,
2562 				       enum ept_access_op op,
2563 				       u64 expected_qual)
2564 {
2565 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2566 			 expected_qual);
2567 }
2568 
2569 
2570 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2571 					unsigned long clear,
2572 					unsigned long set,
2573 					enum ept_access_op op)
2574 {
2575 	struct ept_access_test_data *data = &ept_access_test_data;
2576 	unsigned long orig_pte;
2577 
2578 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2579 
2580 	/* No violation. Should proceed to vmcall. */
2581 	do_ept_access_op(op);
2582 	skip_exit_vmcall();
2583 
2584 	ept_untwiddle(data->gpa, level, orig_pte);
2585 }
2586 
2587 static void ept_allowed_at_level(int level, unsigned long clear,
2588 				 unsigned long set, enum ept_access_op op)
2589 {
2590 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2591 	if (ept_huge_pages_supported(level))
2592 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2593 }
2594 
2595 static void ept_allowed(unsigned long clear, unsigned long set,
2596 			enum ept_access_op op)
2597 {
2598 	ept_allowed_at_level(1, clear, set, op);
2599 	ept_allowed_at_level(2, clear, set, op);
2600 	ept_allowed_at_level(3, clear, set, op);
2601 	ept_allowed_at_level(4, clear, set, op);
2602 }
2603 
2604 static void ept_ignored_bit(int bit)
2605 {
2606 	/* Set the bit. */
2607 	ept_allowed(0, 1ul << bit, OP_READ);
2608 	ept_allowed(0, 1ul << bit, OP_WRITE);
2609 	ept_allowed(0, 1ul << bit, OP_EXEC);
2610 
2611 	/* Clear the bit. */
2612 	ept_allowed(1ul << bit, 0, OP_READ);
2613 	ept_allowed(1ul << bit, 0, OP_WRITE);
2614 	ept_allowed(1ul << bit, 0, OP_EXEC);
2615 }
2616 
2617 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2618 {
2619 	ept_allowed(EPT_PRESENT, access, op);
2620 }
2621 
2622 
2623 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2624 					     unsigned long clear,
2625 					     unsigned long set,
2626 					     enum ept_access_op op)
2627 {
2628 	struct ept_access_test_data *data = &ept_access_test_data;
2629 	unsigned long orig_pte;
2630 
2631 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2632 
2633 	do_ept_access_op(op);
2634 	assert_exit_reason(VMX_EPT_MISCONFIG);
2635 
2636 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2637 	#if 0
2638 	/* broken: */
2639 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2640 	#endif
2641 	#if 0
2642 	/*
2643 	 * broken:
2644 	 * According to description of exit qual for EPT violation,
2645 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2646 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2647 	 * to be set for msiconfig.
2648 	 */
2649 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2650 		       (unsigned long) (
2651 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2652 	#endif
2653 
2654 	/* Fix the violation and resume the op loop. */
2655 	ept_untwiddle(data->gpa, level, orig_pte);
2656 	enter_guest();
2657 	skip_exit_vmcall();
2658 }
2659 
2660 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2661 					  unsigned long clear,
2662 					  unsigned long set)
2663 {
2664 	/* The op shouldn't matter (read, write, exec), so try them all! */
2665 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2666 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2667 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2668 }
2669 
2670 static void ept_misconfig_at_level(int level, unsigned long clear,
2671 				   unsigned long set)
2672 {
2673 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2674 	if (ept_huge_pages_supported(level))
2675 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2676 }
2677 
2678 static void ept_misconfig(unsigned long clear, unsigned long set)
2679 {
2680 	ept_misconfig_at_level(1, clear, set);
2681 	ept_misconfig_at_level(2, clear, set);
2682 	ept_misconfig_at_level(3, clear, set);
2683 	ept_misconfig_at_level(4, clear, set);
2684 }
2685 
2686 static void ept_access_misconfig(unsigned long access)
2687 {
2688 	ept_misconfig(EPT_PRESENT, access);
2689 }
2690 
2691 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2692 {
2693 	/* Setting the bit causes a misconfig. */
2694 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2695 
2696 	/* Making the entry non-present turns reserved bits into ignored. */
2697 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2698 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2699 }
2700 
2701 static void ept_reserved_bit_at_level_huge(int level, int bit)
2702 {
2703 	/* Setting the bit causes a misconfig. */
2704 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2705 
2706 	/* Making the entry non-present turns reserved bits into ignored. */
2707 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2708 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2709 }
2710 
2711 static void ept_reserved_bit_at_level(int level, int bit)
2712 {
2713 	/* Setting the bit causes a misconfig. */
2714 	ept_misconfig_at_level(level, 0, 1ul << bit);
2715 
2716 	/* Making the entry non-present turns reserved bits into ignored. */
2717 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2718 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2719 }
2720 
2721 static void ept_reserved_bit(int bit)
2722 {
2723 	ept_reserved_bit_at_level(1, bit);
2724 	ept_reserved_bit_at_level(2, bit);
2725 	ept_reserved_bit_at_level(3, bit);
2726 	ept_reserved_bit_at_level(4, bit);
2727 }
2728 
2729 #define PAGE_2M_ORDER 9
2730 #define PAGE_1G_ORDER 18
2731 
2732 static void *get_1g_page(void)
2733 {
2734 	static void *alloc;
2735 
2736 	if (!alloc)
2737 		alloc = alloc_pages(PAGE_1G_ORDER);
2738 	return alloc;
2739 }
2740 
2741 static void ept_access_test_teardown(void *unused)
2742 {
2743 	/* Exit the guest cleanly. */
2744 	do_ept_access_op(OP_EXIT);
2745 }
2746 
2747 static void ept_access_test_guest(void)
2748 {
2749 	struct ept_access_test_data *data = &ept_access_test_data;
2750 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2751 
2752 	while (true) {
2753 		switch (data->op) {
2754 		case OP_READ:
2755 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2756 			break;
2757 		case OP_WRITE:
2758 			*data->gva = MAGIC_VAL_2;
2759 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2760 			*data->gva = MAGIC_VAL_1;
2761 			break;
2762 		case OP_EXEC:
2763 			TEST_ASSERT_EQ(42, code());
2764 			break;
2765 		case OP_FLUSH_TLB:
2766 			write_cr3(read_cr3());
2767 			break;
2768 		case OP_EXIT:
2769 			return;
2770 		default:
2771 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2772 		}
2773 		vmcall();
2774 	}
2775 }
2776 
2777 static void ept_access_test_setup(void)
2778 {
2779 	struct ept_access_test_data *data = &ept_access_test_data;
2780 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2781 	unsigned long size = npages * PAGE_SIZE;
2782 	unsigned long *page_table = current_page_table();
2783 	unsigned long pte;
2784 
2785 	if (setup_ept(false))
2786 		test_skip("EPT not supported");
2787 
2788 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2789 	if (cpuid_maxphyaddr() < 40)
2790 		test_skip("Test needs MAXPHYADDR >= 40");
2791 
2792 	test_set_guest(ept_access_test_guest);
2793 	test_add_teardown(ept_access_test_teardown, NULL);
2794 
2795 	data->hva = get_1g_page();
2796 	TEST_ASSERT(data->hva);
2797 	data->hpa = virt_to_phys(data->hva);
2798 
2799 	data->gpa = 1ul << 39;
2800 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2801 				   size);
2802 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2803 	install_pages(page_table, data->gpa, size, data->gva);
2804 
2805 	/*
2806 	 * Make sure nothing's mapped here so the tests that screw with the
2807 	 * pml4 entry don't inadvertently break something.
2808 	 */
2809 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2810 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2811 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2812 
2813 	data->hva[0] = MAGIC_VAL_1;
2814 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2815 }
2816 
2817 static void ept_access_test_not_present(void)
2818 {
2819 	ept_access_test_setup();
2820 	/* --- */
2821 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2822 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2823 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2824 }
2825 
2826 static void ept_access_test_read_only(void)
2827 {
2828 	ept_access_test_setup();
2829 
2830 	/* r-- */
2831 	ept_access_allowed(EPT_RA, OP_READ);
2832 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2833 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2834 }
2835 
2836 static void ept_access_test_write_only(void)
2837 {
2838 	ept_access_test_setup();
2839 	/* -w- */
2840 	ept_access_misconfig(EPT_WA);
2841 }
2842 
2843 static void ept_access_test_read_write(void)
2844 {
2845 	ept_access_test_setup();
2846 	/* rw- */
2847 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2848 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2849 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2850 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2851 }
2852 
2853 
2854 static void ept_access_test_execute_only(void)
2855 {
2856 	ept_access_test_setup();
2857 	/* --x */
2858 	if (ept_execute_only_supported()) {
2859 		ept_access_violation(EPT_EA, OP_READ,
2860 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2861 		ept_access_violation(EPT_EA, OP_WRITE,
2862 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2863 		ept_access_allowed(EPT_EA, OP_EXEC);
2864 	} else {
2865 		ept_access_misconfig(EPT_EA);
2866 	}
2867 }
2868 
2869 static void ept_access_test_read_execute(void)
2870 {
2871 	ept_access_test_setup();
2872 	/* r-x */
2873 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2874 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2875 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2876 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2877 }
2878 
2879 static void ept_access_test_write_execute(void)
2880 {
2881 	ept_access_test_setup();
2882 	/* -wx */
2883 	ept_access_misconfig(EPT_WA | EPT_EA);
2884 }
2885 
2886 static void ept_access_test_read_write_execute(void)
2887 {
2888 	ept_access_test_setup();
2889 	/* rwx */
2890 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2891 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2892 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2893 }
2894 
2895 static void ept_access_test_reserved_bits(void)
2896 {
2897 	int i;
2898 	int maxphyaddr;
2899 
2900 	ept_access_test_setup();
2901 
2902 	/* Reserved bits above maxphyaddr. */
2903 	maxphyaddr = cpuid_maxphyaddr();
2904 	for (i = maxphyaddr; i <= 51; i++) {
2905 		report_prefix_pushf("reserved_bit=%d", i);
2906 		ept_reserved_bit(i);
2907 		report_prefix_pop();
2908 	}
2909 
2910 	/* Level-specific reserved bits. */
2911 	ept_reserved_bit_at_level_nohuge(2, 3);
2912 	ept_reserved_bit_at_level_nohuge(2, 4);
2913 	ept_reserved_bit_at_level_nohuge(2, 5);
2914 	ept_reserved_bit_at_level_nohuge(2, 6);
2915 	/* 2M alignment. */
2916 	for (i = 12; i < 20; i++) {
2917 		report_prefix_pushf("reserved_bit=%d", i);
2918 		ept_reserved_bit_at_level_huge(2, i);
2919 		report_prefix_pop();
2920 	}
2921 	ept_reserved_bit_at_level_nohuge(3, 3);
2922 	ept_reserved_bit_at_level_nohuge(3, 4);
2923 	ept_reserved_bit_at_level_nohuge(3, 5);
2924 	ept_reserved_bit_at_level_nohuge(3, 6);
2925 	/* 1G alignment. */
2926 	for (i = 12; i < 29; i++) {
2927 		report_prefix_pushf("reserved_bit=%d", i);
2928 		ept_reserved_bit_at_level_huge(3, i);
2929 		report_prefix_pop();
2930 	}
2931 	ept_reserved_bit_at_level(4, 3);
2932 	ept_reserved_bit_at_level(4, 4);
2933 	ept_reserved_bit_at_level(4, 5);
2934 	ept_reserved_bit_at_level(4, 6);
2935 	ept_reserved_bit_at_level(4, 7);
2936 }
2937 
2938 static void ept_access_test_ignored_bits(void)
2939 {
2940 	ept_access_test_setup();
2941 	/*
2942 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2943 	 * far as translation is concerned even if AD bits are enabled in the
2944 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2945 	 * control is 0.
2946 	 */
2947 	ept_ignored_bit(8);
2948 	ept_ignored_bit(9);
2949 	ept_ignored_bit(10);
2950 	ept_ignored_bit(11);
2951 	ept_ignored_bit(52);
2952 	ept_ignored_bit(53);
2953 	ept_ignored_bit(54);
2954 	ept_ignored_bit(55);
2955 	ept_ignored_bit(56);
2956 	ept_ignored_bit(57);
2957 	ept_ignored_bit(58);
2958 	ept_ignored_bit(59);
2959 	ept_ignored_bit(60);
2960 	ept_ignored_bit(61);
2961 	ept_ignored_bit(62);
2962 	ept_ignored_bit(63);
2963 }
2964 
2965 static void ept_access_test_paddr_not_present_ad_disabled(void)
2966 {
2967 	ept_access_test_setup();
2968 	ept_disable_ad_bits();
2969 
2970 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2971 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2972 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2973 }
2974 
2975 static void ept_access_test_paddr_not_present_ad_enabled(void)
2976 {
2977 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2978 
2979 	ept_access_test_setup();
2980 	ept_enable_ad_bits_or_skip_test();
2981 
2982 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2983 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2984 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2985 }
2986 
2987 static void ept_access_test_paddr_read_only_ad_disabled(void)
2988 {
2989 	/*
2990 	 * When EPT AD bits are disabled, all accesses to guest paging
2991 	 * structures are reported separately as a read and (after
2992 	 * translation of the GPA to host physical address) a read+write
2993 	 * if the A/D bits have to be set.
2994 	 */
2995 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2996 
2997 	ept_access_test_setup();
2998 	ept_disable_ad_bits();
2999 
3000 	/* Can't update A bit, so all accesses fail. */
3001 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
3002 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
3003 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
3004 	/* AD bits disabled, so only writes try to update the D bit. */
3005 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
3006 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
3007 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
3008 	/* Both A and D already set, so read-only is OK. */
3009 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
3010 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
3011 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
3012 }
3013 
3014 static void ept_access_test_paddr_read_only_ad_enabled(void)
3015 {
3016 	/*
3017 	 * When EPT AD bits are enabled, all accesses to guest paging
3018 	 * structures are considered writes as far as EPT translation
3019 	 * is concerned.
3020 	 */
3021 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
3022 
3023 	ept_access_test_setup();
3024 	ept_enable_ad_bits_or_skip_test();
3025 
3026 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
3027 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
3028 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
3029 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
3030 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
3031 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
3032 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
3033 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
3034 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
3035 }
3036 
3037 static void ept_access_test_paddr_read_write(void)
3038 {
3039 	ept_access_test_setup();
3040 	/* Read-write access to paging structure. */
3041 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
3042 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
3043 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
3044 }
3045 
3046 static void ept_access_test_paddr_read_write_execute(void)
3047 {
3048 	ept_access_test_setup();
3049 	/* RWX access to paging structure. */
3050 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
3051 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
3052 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
3053 }
3054 
3055 static void ept_access_test_paddr_read_execute_ad_disabled(void)
3056 {
3057   	/*
3058 	 * When EPT AD bits are disabled, all accesses to guest paging
3059 	 * structures are reported separately as a read and (after
3060 	 * translation of the GPA to host physical address) a read+write
3061 	 * if the A/D bits have to be set.
3062 	 */
3063 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3064 
3065 	ept_access_test_setup();
3066 	ept_disable_ad_bits();
3067 
3068 	/* Can't update A bit, so all accesses fail. */
3069 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3070 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3071 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3072 	/* AD bits disabled, so only writes try to update the D bit. */
3073 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
3074 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3075 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
3076 	/* Both A and D already set, so read-only is OK. */
3077 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
3078 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
3079 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
3080 }
3081 
3082 static void ept_access_test_paddr_read_execute_ad_enabled(void)
3083 {
3084 	/*
3085 	 * When EPT AD bits are enabled, all accesses to guest paging
3086 	 * structures are considered writes as far as EPT translation
3087 	 * is concerned.
3088 	 */
3089 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3090 
3091 	ept_access_test_setup();
3092 	ept_enable_ad_bits_or_skip_test();
3093 
3094 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3095 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3096 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3097 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
3098 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3099 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
3100 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
3101 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
3102 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
3103 }
3104 
3105 static void ept_access_test_paddr_not_present_page_fault(void)
3106 {
3107 	ept_access_test_setup();
3108 	/*
3109 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
3110 	 * page is read-only in EPT but GVA is also mapped read only in PT.
3111 	 * Thus guest page fault before host takes EPT violation for trying to
3112 	 * update A bit.
3113 	 */
3114 }
3115 
3116 static void ept_access_test_force_2m_page(void)
3117 {
3118 	ept_access_test_setup();
3119 
3120 	TEST_ASSERT_EQ(ept_2m_supported(), true);
3121 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
3122 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
3123 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
3124 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
3125 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
3126 }
3127 
3128 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
3129 {
3130 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3131 
3132 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
3133 
3134 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
3135 		return false;
3136 
3137 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
3138 		return false;
3139 
3140 	if (vpid >> 16)
3141 		return false;
3142 
3143 	if (type != INVVPID_ALL && !vpid)
3144 		return false;
3145 
3146 	if (type == INVVPID_ADDR && !is_canonical(gla))
3147 		return false;
3148 
3149 	return true;
3150 }
3151 
3152 static void try_invvpid(u64 type, u64 vpid, u64 gla)
3153 {
3154 	int rc;
3155 	bool valid = invvpid_valid(type, vpid, gla);
3156 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
3157 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
3158 	/*
3159 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
3160 	 * that we can tell if it is updated by INVVPID.
3161 	 */
3162 	vmcs_read(~0);
3163 	rc = invvpid(type, vpid, gla);
3164 	report(!rc == valid, "INVVPID type %ld VPID %lx GLA %lx %s", type,
3165 	       vpid, gla,
3166 	       valid ? "passes" : "fails");
3167 	report(vmcs_read(VMX_INST_ERROR) == expected,
3168 	       "After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3169 	       rc ? "failed" : "successful",
3170 	       expected, vmcs_read(VMX_INST_ERROR));
3171 }
3172 
3173 static void ds_invvpid(void *data)
3174 {
3175 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3176 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3177 
3178 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3179 	asm volatile("invvpid %0, %1"
3180 		     :
3181 		     : "m"(*(struct invvpid_operand *)data),
3182 		       "r"(type));
3183 }
3184 
3185 /*
3186  * The SS override is ignored in 64-bit mode, so we use an addressing
3187  * mode with %rsp as the base register to generate an implicit SS
3188  * reference.
3189  */
3190 static void ss_invvpid(void *data)
3191 {
3192 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3193 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3194 
3195 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3196 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3197 		     : "+r"(data)
3198 		     : "r"(type));
3199 }
3200 
3201 static void invvpid_test_gp(void)
3202 {
3203 	bool fault;
3204 
3205 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3206 				   (void *)NONCANONICAL);
3207 	report(fault, "INVVPID with non-canonical DS operand raises #GP");
3208 }
3209 
3210 static void invvpid_test_ss(void)
3211 {
3212 	bool fault;
3213 
3214 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3215 				   (void *)NONCANONICAL);
3216 	report(fault, "INVVPID with non-canonical SS operand raises #SS");
3217 }
3218 
3219 static void invvpid_test_pf(void)
3220 {
3221 	void *vpage = alloc_vpage();
3222 	bool fault;
3223 
3224 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3225 	report(fault, "INVVPID with unmapped operand raises #PF");
3226 }
3227 
3228 static void try_compat_invvpid(void *unused)
3229 {
3230 	struct far_pointer32 fp = {
3231 		.offset = (uintptr_t)&&invvpid,
3232 		.selector = KERNEL_CS32,
3233 	};
3234 	register uintptr_t rsp asm("rsp");
3235 
3236 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3237 			"Code address too high.");
3238 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3239 
3240 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3241 	return;
3242 invvpid:
3243 	asm volatile (".code32;"
3244 		      "invvpid (%eax), %eax;"
3245 		      "lret;"
3246 		      ".code64");
3247 	__builtin_unreachable();
3248 }
3249 
3250 static void invvpid_test_compatibility_mode(void)
3251 {
3252 	bool fault;
3253 
3254 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3255 	report(fault, "Compatibility mode INVVPID raises #UD");
3256 }
3257 
3258 static void invvpid_test_not_in_vmx_operation(void)
3259 {
3260 	bool fault;
3261 
3262 	TEST_ASSERT(!vmx_off());
3263 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3264 	report(fault, "INVVPID outside of VMX operation raises #UD");
3265 	TEST_ASSERT(!vmx_on());
3266 }
3267 
3268 /*
3269  * This does not test real-address mode, virtual-8086 mode, protected mode,
3270  * or CPL > 0.
3271  */
3272 static void invvpid_test_v2(void)
3273 {
3274 	u64 msr;
3275 	int i;
3276 	unsigned types = 0;
3277 	unsigned type;
3278 
3279 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3280 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3281 		test_skip("VPID not supported");
3282 
3283 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3284 
3285 	if (!(msr & VPID_CAP_INVVPID))
3286 		test_skip("INVVPID not supported.\n");
3287 
3288 	if (msr & VPID_CAP_INVVPID_ADDR)
3289 		types |= 1u << INVVPID_ADDR;
3290 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3291 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3292 	if (msr & VPID_CAP_INVVPID_ALL)
3293 		types |= 1u << INVVPID_ALL;
3294 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3295 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3296 
3297 	if (!types)
3298 		test_skip("No INVVPID types supported.\n");
3299 
3300 	for (i = -127; i < 128; i++)
3301 		try_invvpid(i, 0xffff, 0);
3302 
3303 	/*
3304 	 * VPID must not be more than 16 bits.
3305 	 */
3306 	for (i = 0; i < 64; i++)
3307 		for (type = 0; type < 4; type++)
3308 			if (types & (1u << type))
3309 				try_invvpid(type, 1ul << i, 0);
3310 
3311 	/*
3312 	 * VPID must not be zero, except for "all contexts."
3313 	 */
3314 	for (type = 0; type < 4; type++)
3315 		if (types & (1u << type))
3316 			try_invvpid(type, 0, 0);
3317 
3318 	/*
3319 	 * The gla operand is only validated for single-address INVVPID.
3320 	 */
3321 	if (types & (1u << INVVPID_ADDR))
3322 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3323 
3324 	invvpid_test_gp();
3325 	invvpid_test_ss();
3326 	invvpid_test_pf();
3327 	invvpid_test_compatibility_mode();
3328 	invvpid_test_not_in_vmx_operation();
3329 }
3330 
3331 /*
3332  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3333  * at least as far as the guest-state checks. Returns false if the
3334  * VMLAUNCH fails early and execution falls through to the next
3335  * instruction.
3336  */
3337 static bool vmlaunch_succeeds(void)
3338 {
3339 	u32 exit_reason;
3340 
3341 	/*
3342 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3343 	 * unsupported VMCS component"). The caller can then check
3344 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3345 	 */
3346 	vmcs_write(~0u, 0);
3347 
3348 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3349 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3350 				   :
3351 				   : "r" ((u64)HOST_RSP)
3352 				   : "cc", "memory"
3353 				   : success);
3354 	return false;
3355 success:
3356 	exit_reason = vmcs_read(EXI_REASON);
3357 	TEST_ASSERT(exit_reason == (VMX_FAIL_STATE | VMX_ENTRY_FAILURE) ||
3358 		    exit_reason == (VMX_FAIL_MSR | VMX_ENTRY_FAILURE));
3359 	return true;
3360 }
3361 
3362 /*
3363  * Try to launch the current VMCS.
3364  */
3365 static void test_vmx_vmlaunch(u32 xerror)
3366 {
3367 	bool success = vmlaunch_succeeds();
3368 	u32 vmx_inst_err;
3369 
3370 	report(success == !xerror, "vmlaunch %s",
3371 	       !xerror ? "succeeds" : "fails");
3372 	if (!success && xerror) {
3373 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3374 		report(vmx_inst_err == xerror,
3375 		       "VMX inst error is %d (actual %d)", xerror,
3376 		       vmx_inst_err);
3377 	}
3378 }
3379 
3380 /*
3381  * Try to launch the current VMCS, and expect one of two possible
3382  * errors (or success) codes.
3383  */
3384 static void test_vmx_vmlaunch2(u32 xerror1, u32 xerror2)
3385 {
3386 	bool success = vmlaunch_succeeds();
3387 	u32 vmx_inst_err;
3388 
3389 	if (!xerror1 == !xerror2)
3390 		report(success == !xerror1, "vmlaunch %s",
3391 		       !xerror1 ? "succeeds" : "fails");
3392 
3393 	if (!success && (xerror1 || xerror2)) {
3394 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3395 		report(vmx_inst_err == xerror1 || vmx_inst_err == xerror2,
3396 		       "VMX inst error is %d or %d (actual %d)", xerror1,
3397 		       xerror2, vmx_inst_err);
3398 	}
3399 }
3400 
3401 static void test_vmx_invalid_controls(void)
3402 {
3403 	test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3404 }
3405 
3406 static void test_vmx_valid_controls(void)
3407 {
3408 	test_vmx_vmlaunch(0);
3409 }
3410 
3411 /*
3412  * Test a particular value of a VM-execution control bit, if the value
3413  * is required or if the value is zero.
3414  */
3415 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3416 				    enum Encoding encoding, unsigned bit,
3417 				    unsigned val)
3418 {
3419 	u32 mask = 1u << bit;
3420 	bool expected;
3421 	u32 controls;
3422 
3423 	if (msr.set & mask)
3424 		TEST_ASSERT(msr.clr & mask);
3425 
3426 	/*
3427 	 * We can't arbitrarily turn on a control bit, because it may
3428 	 * introduce dependencies on other VMCS fields. So, we only
3429 	 * test turning on bits that have a required setting.
3430 	 */
3431 	if (val && (msr.clr & mask) && !(msr.set & mask))
3432 		return;
3433 
3434 	report_prefix_pushf("%s %s bit %d",
3435 			    val ? "Set" : "Clear", name, bit);
3436 
3437 	controls = vmcs_read(encoding);
3438 	if (val) {
3439 		vmcs_write(encoding, msr.set | mask);
3440 		expected = (msr.clr & mask);
3441 	} else {
3442 		vmcs_write(encoding, msr.set & ~mask);
3443 		expected = !(msr.set & mask);
3444 	}
3445 	if (expected)
3446 		test_vmx_valid_controls();
3447 	else
3448 		test_vmx_invalid_controls();
3449 	vmcs_write(encoding, controls);
3450 	report_prefix_pop();
3451 }
3452 
3453 /*
3454  * Test reserved values of a VM-execution control bit, based on the
3455  * allowed bit settings from the corresponding VMX capability MSR.
3456  */
3457 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3458 			      enum Encoding encoding, unsigned bit)
3459 {
3460 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3461 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3462 }
3463 
3464 /*
3465  * Reserved bits in the pin-based VM-execution controls must be set
3466  * properly. Software may consult the VMX capability MSRs to determine
3467  * the proper settings.
3468  * [Intel SDM]
3469  */
3470 static void test_pin_based_ctls(void)
3471 {
3472 	unsigned bit;
3473 
3474 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3475 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3476 	for (bit = 0; bit < 32; bit++)
3477 		test_rsvd_ctl_bit("pin-based controls",
3478 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3479 }
3480 
3481 /*
3482  * Reserved bits in the primary processor-based VM-execution controls
3483  * must be set properly. Software may consult the VMX capability MSRs
3484  * to determine the proper settings.
3485  * [Intel SDM]
3486  */
3487 static void test_primary_processor_based_ctls(void)
3488 {
3489 	unsigned bit;
3490 
3491 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3492 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3493 	for (bit = 0; bit < 32; bit++)
3494 		test_rsvd_ctl_bit("primary processor-based controls",
3495 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3496 }
3497 
3498 /*
3499  * If the "activate secondary controls" primary processor-based
3500  * VM-execution control is 1, reserved bits in the secondary
3501  * processor-based VM-execution controls must be cleared. Software may
3502  * consult the VMX capability MSRs to determine which bits are
3503  * reserved.
3504  * If the "activate secondary controls" primary processor-based
3505  * VM-execution control is 0 (or if the processor does not support the
3506  * 1-setting of that control), no checks are performed on the
3507  * secondary processor-based VM-execution controls.
3508  * [Intel SDM]
3509  */
3510 static void test_secondary_processor_based_ctls(void)
3511 {
3512 	u32 primary;
3513 	u32 secondary;
3514 	unsigned bit;
3515 
3516 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3517 		return;
3518 
3519 	primary = vmcs_read(CPU_EXEC_CTRL0);
3520 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3521 
3522 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3523 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3524 	for (bit = 0; bit < 32; bit++)
3525 		test_rsvd_ctl_bit("secondary processor-based controls",
3526 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3527 
3528 	/*
3529 	 * When the "activate secondary controls" VM-execution control
3530 	 * is clear, there are no checks on the secondary controls.
3531 	 */
3532 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3533 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3534 	report(vmlaunch_succeeds(),
3535 	       "Secondary processor-based controls ignored");
3536 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3537 	vmcs_write(CPU_EXEC_CTRL0, primary);
3538 }
3539 
3540 static void try_cr3_target_count(unsigned i, unsigned max)
3541 {
3542 	report_prefix_pushf("CR3 target count 0x%x", i);
3543 	vmcs_write(CR3_TARGET_COUNT, i);
3544 	if (i <= max)
3545 		test_vmx_valid_controls();
3546 	else
3547 		test_vmx_invalid_controls();
3548 	report_prefix_pop();
3549 }
3550 
3551 /*
3552  * The CR3-target count must not be greater than 4. Future processors
3553  * may support a different number of CR3-target values. Software
3554  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3555  * number of values supported.
3556  * [Intel SDM]
3557  */
3558 static void test_cr3_targets(void)
3559 {
3560 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3561 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3562 	unsigned i;
3563 
3564 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3565 	TEST_ASSERT(supported_targets <= 256);
3566 
3567 	try_cr3_target_count(-1u, supported_targets);
3568 	try_cr3_target_count(0x80000000, supported_targets);
3569 	try_cr3_target_count(0x7fffffff, supported_targets);
3570 	for (i = 0; i <= supported_targets + 1; i++)
3571 		try_cr3_target_count(i, supported_targets);
3572 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3573 }
3574 
3575 /*
3576  * Test a particular address setting in the VMCS
3577  */
3578 static void test_vmcs_addr(const char *name,
3579 			   enum Encoding encoding,
3580 			   u64 align,
3581 			   bool ignored,
3582 			   bool skip_beyond_mapped_ram,
3583 			   u64 addr)
3584 {
3585 	report_prefix_pushf("%s = %lx", name, addr);
3586 	vmcs_write(encoding, addr);
3587 	if (skip_beyond_mapped_ram &&
3588 	    addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - align &&
3589 	    addr < (1ul << cpuid_maxphyaddr()))
3590 		printf("Skipping physical address beyond mapped RAM\n");
3591 	else if (ignored || (IS_ALIGNED(addr, align) &&
3592 	    addr < (1ul << cpuid_maxphyaddr())))
3593 		test_vmx_valid_controls();
3594 	else
3595 		test_vmx_invalid_controls();
3596 	report_prefix_pop();
3597 }
3598 
3599 /*
3600  * Test interesting values for a VMCS address
3601  */
3602 static void test_vmcs_addr_values(const char *name,
3603 				  enum Encoding encoding,
3604 				  u64 align,
3605 				  bool ignored,
3606 				  bool skip_beyond_mapped_ram,
3607 				  u32 bit_start, u32 bit_end)
3608 {
3609 	unsigned i;
3610 	u64 orig_val = vmcs_read(encoding);
3611 
3612 	for (i = bit_start; i <= bit_end; i++)
3613 		test_vmcs_addr(name, encoding, align, ignored,
3614 			       skip_beyond_mapped_ram, 1ul << i);
3615 
3616 	test_vmcs_addr(name, encoding, align, ignored,
3617 		       skip_beyond_mapped_ram, PAGE_SIZE - 1);
3618 	test_vmcs_addr(name, encoding, align, ignored,
3619 		       skip_beyond_mapped_ram, PAGE_SIZE);
3620 	test_vmcs_addr(name, encoding, align, ignored,
3621 		       skip_beyond_mapped_ram,
3622 		      (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3623 	test_vmcs_addr(name, encoding, align, ignored,
3624 		       skip_beyond_mapped_ram, -1ul);
3625 
3626 	vmcs_write(encoding, orig_val);
3627 }
3628 
3629 /*
3630  * Test a physical address reference in the VMCS, when the corresponding
3631  * feature is enabled and when the corresponding feature is disabled.
3632  */
3633 static void test_vmcs_addr_reference(u32 control_bit, enum Encoding field,
3634 				     const char *field_name,
3635 				     const char *control_name, u64 align,
3636 				     bool skip_beyond_mapped_ram,
3637 				     bool control_primary)
3638 {
3639 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3640 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3641 	u64 page_addr;
3642 
3643 	if (control_primary) {
3644 		if (!(ctrl_cpu_rev[0].clr & control_bit))
3645 			return;
3646 	} else {
3647 		if (!(ctrl_cpu_rev[1].clr & control_bit))
3648 			return;
3649 	}
3650 
3651 	page_addr = vmcs_read(field);
3652 
3653 	report_prefix_pushf("%s enabled", control_name);
3654 	if (control_primary) {
3655 		vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3656 	} else {
3657 		vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3658 		vmcs_write(CPU_EXEC_CTRL1, secondary | control_bit);
3659 	}
3660 
3661 	test_vmcs_addr_values(field_name, field, align, false,
3662 			      skip_beyond_mapped_ram, 0, 63);
3663 	report_prefix_pop();
3664 
3665 	report_prefix_pushf("%s disabled", control_name);
3666 	if (control_primary) {
3667 		vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3668 	} else {
3669 		vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3670 		vmcs_write(CPU_EXEC_CTRL1, secondary & ~control_bit);
3671 	}
3672 
3673 	test_vmcs_addr_values(field_name, field, align, true, false, 0, 63);
3674 	report_prefix_pop();
3675 
3676 	vmcs_write(field, page_addr);
3677 	vmcs_write(CPU_EXEC_CTRL0, primary);
3678 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3679 }
3680 
3681 /*
3682  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3683  * each I/O-bitmap address must be 0. Neither address should set any
3684  * bits beyond the processor's physical-address width.
3685  * [Intel SDM]
3686  */
3687 static void test_io_bitmaps(void)
3688 {
3689 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3690 				 "I/O bitmap A", "Use I/O bitmaps",
3691 				 PAGE_SIZE, false, true);
3692 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3693 				 "I/O bitmap B", "Use I/O bitmaps",
3694 				 PAGE_SIZE, false, true);
3695 }
3696 
3697 /*
3698  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3699  * the MSR-bitmap address must be 0. The address should not set any
3700  * bits beyond the processor's physical-address width.
3701  * [Intel SDM]
3702  */
3703 static void test_msr_bitmap(void)
3704 {
3705 	test_vmcs_addr_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3706 				 "MSR bitmap", "Use MSR bitmaps",
3707 				 PAGE_SIZE, false, true);
3708 }
3709 
3710 /*
3711  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3712  * address must satisfy the following checks:
3713  * - Bits 11:0 of the address must be 0.
3714  * - The address should not set any bits beyond the processor's
3715  *   physical-address width.
3716  * [Intel SDM]
3717  */
3718 static void test_apic_virt_addr(void)
3719 {
3720 	/*
3721 	 * Ensure the processor will never use the virtual-APIC page, since
3722 	 * we will point it to invalid RAM.  Otherwise KVM is puzzled about
3723 	 * what we're trying to achieve and fails vmentry.
3724 	 */
3725 	u32 cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
3726 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0 | CPU_CR8_LOAD | CPU_CR8_STORE);
3727 	test_vmcs_addr_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3728 				 "virtual-APIC address", "Use TPR shadow",
3729 				 PAGE_SIZE, false, true);
3730 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
3731 }
3732 
3733 /*
3734  * If the "virtualize APIC-accesses" VM-execution control is 1, the
3735  * APIC-access address must satisfy the following checks:
3736  *  - Bits 11:0 of the address must be 0.
3737  *  - The address should not set any bits beyond the processor's
3738  *    physical-address width.
3739  * [Intel SDM]
3740  */
3741 static void test_apic_access_addr(void)
3742 {
3743 	void *apic_access_page = alloc_page();
3744 
3745 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_page));
3746 
3747 	test_vmcs_addr_reference(CPU_VIRT_APIC_ACCESSES, APIC_ACCS_ADDR,
3748 				 "APIC-access address",
3749 				 "virtualize APIC-accesses", PAGE_SIZE,
3750 				 true, false);
3751 }
3752 
3753 static bool set_bit_pattern(u8 mask, u32 *secondary)
3754 {
3755 	u8 i;
3756 	bool flag = false;
3757 	u32 test_bits[3] = {
3758 		CPU_VIRT_X2APIC,
3759 		CPU_APIC_REG_VIRT,
3760 		CPU_VINTD
3761 	};
3762 
3763         for (i = 0; i < ARRAY_SIZE(test_bits); i++) {
3764 		if ((mask & (1u << i)) &&
3765 		    (ctrl_cpu_rev[1].clr & test_bits[i])) {
3766 			*secondary |= test_bits[i];
3767 			flag = true;
3768 		}
3769 	}
3770 
3771 	return (flag);
3772 }
3773 
3774 /*
3775  * If the "use TPR shadow" VM-execution control is 0, the following
3776  * VM-execution controls must also be 0:
3777  * 	- virtualize x2APIC mode
3778  *	- APIC-register virtualization
3779  *	- virtual-interrupt delivery
3780  *    [Intel SDM]
3781  *
3782  * 2. If the "virtualize x2APIC mode" VM-execution control is 1, the
3783  *    "virtualize APIC accesses" VM-execution control must be 0.
3784  *    [Intel SDM]
3785  */
3786 static void test_apic_virtual_ctls(void)
3787 {
3788 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3789 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3790 	u32 primary = saved_primary;
3791 	u32 secondary = saved_secondary;
3792 	bool ctrl = false;
3793 	char str[10] = "disabled";
3794 	u8 i = 0, j;
3795 
3796 	/*
3797 	 * First test
3798 	 */
3799 	if (!((ctrl_cpu_rev[0].clr & (CPU_SECONDARY | CPU_TPR_SHADOW)) ==
3800 	    (CPU_SECONDARY | CPU_TPR_SHADOW)))
3801 		return;
3802 
3803 	primary |= CPU_SECONDARY;
3804 	primary &= ~CPU_TPR_SHADOW;
3805 	vmcs_write(CPU_EXEC_CTRL0, primary);
3806 
3807 	while (1) {
3808 		for (j = 1; j < 8; j++) {
3809 			secondary &= ~(CPU_VIRT_X2APIC | CPU_APIC_REG_VIRT | CPU_VINTD);
3810 			if (primary & CPU_TPR_SHADOW) {
3811 				ctrl = true;
3812 			} else {
3813 				if (! set_bit_pattern(j, &secondary))
3814 					ctrl = true;
3815 				else
3816 					ctrl = false;
3817 			}
3818 
3819 			vmcs_write(CPU_EXEC_CTRL1, secondary);
3820 			report_prefix_pushf("Use TPR shadow %s, virtualize x2APIC mode %s, APIC-register virtualization %s, virtual-interrupt delivery %s",
3821 				str, (secondary & CPU_VIRT_X2APIC) ? "enabled" : "disabled", (secondary & CPU_APIC_REG_VIRT) ? "enabled" : "disabled", (secondary & CPU_VINTD) ? "enabled" : "disabled");
3822 			if (ctrl)
3823 				test_vmx_valid_controls();
3824 			else
3825 				test_vmx_invalid_controls();
3826 			report_prefix_pop();
3827 		}
3828 
3829 		if (i == 1)
3830 			break;
3831 		i++;
3832 
3833 		primary |= CPU_TPR_SHADOW;
3834 		vmcs_write(CPU_EXEC_CTRL0, primary);
3835 		strcpy(str, "enabled");
3836 	}
3837 
3838 	/*
3839 	 * Second test
3840 	 */
3841 	u32 apic_virt_ctls = (CPU_VIRT_X2APIC | CPU_VIRT_APIC_ACCESSES);
3842 
3843 	primary = saved_primary;
3844 	secondary = saved_secondary;
3845 	if (!((ctrl_cpu_rev[1].clr & apic_virt_ctls) == apic_virt_ctls))
3846 		return;
3847 
3848 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3849 	secondary &= ~CPU_VIRT_APIC_ACCESSES;
3850 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_X2APIC);
3851 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access disabled");
3852 	test_vmx_valid_controls();
3853 	report_prefix_pop();
3854 
3855 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_APIC_ACCESSES);
3856 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access enabled");
3857 	test_vmx_valid_controls();
3858 	report_prefix_pop();
3859 
3860 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_X2APIC);
3861 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access enabled");
3862 	test_vmx_invalid_controls();
3863 	report_prefix_pop();
3864 
3865 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_APIC_ACCESSES);
3866 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access disabled");
3867 	test_vmx_valid_controls();
3868 	report_prefix_pop();
3869 
3870 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3871 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3872 }
3873 
3874 /*
3875  * If the "virtual-interrupt delivery" VM-execution control is 1, the
3876  * "external-interrupt exiting" VM-execution control must be 1.
3877  * [Intel SDM]
3878  */
3879 static void test_virtual_intr_ctls(void)
3880 {
3881 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3882 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3883 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3884 	u32 primary = saved_primary;
3885 	u32 secondary = saved_secondary;
3886 	u32 pin = saved_pin;
3887 
3888 	if (!((ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3889 	    (ctrl_pin_rev.clr & PIN_EXTINT)))
3890 		return;
3891 
3892 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3893 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VINTD);
3894 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3895 	report_prefix_pushf("Virtualize interrupt-delivery disabled; external-interrupt exiting disabled");
3896 	test_vmx_valid_controls();
3897 	report_prefix_pop();
3898 
3899 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VINTD);
3900 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3901 	test_vmx_invalid_controls();
3902 	report_prefix_pop();
3903 
3904 	vmcs_write(PIN_CONTROLS, pin | PIN_EXTINT);
3905 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting enabled");
3906 	test_vmx_valid_controls();
3907 	report_prefix_pop();
3908 
3909 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3910 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3911 	test_vmx_invalid_controls();
3912 	report_prefix_pop();
3913 
3914 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3915 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3916 	vmcs_write(PIN_CONTROLS, saved_pin);
3917 }
3918 
3919 static void test_pi_desc_addr(u64 addr, bool ctrl)
3920 {
3921 	vmcs_write(POSTED_INTR_DESC_ADDR, addr);
3922 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-descriptor-address 0x%lx", addr);
3923 	if (ctrl)
3924 		test_vmx_valid_controls();
3925 	else
3926 		test_vmx_invalid_controls();
3927 	report_prefix_pop();
3928 }
3929 
3930 /*
3931  * If the “process posted interrupts†VM-execution control is 1, the
3932  * following must be true:
3933  *
3934  *	- The “virtual-interrupt delivery†VM-execution control is 1.
3935  *	- The “acknowledge interrupt on exit†VM-exit control is 1.
3936  *	- The posted-interrupt notification vector has a value in the
3937  *	- range 0–255 (bits 15:8 are all 0).
3938  *	- Bits 5:0 of the posted-interrupt descriptor address are all 0.
3939  *	- The posted-interrupt descriptor address does not set any bits
3940  *	  beyond the processor's physical-address width.
3941  * [Intel SDM]
3942  */
3943 static void test_posted_intr(void)
3944 {
3945 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3946 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3947 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3948 	u32 exit_ctl_saved = vmcs_read(EXI_CONTROLS);
3949 	u32 primary = saved_primary;
3950 	u32 secondary = saved_secondary;
3951 	u32 pin = saved_pin;
3952 	u32 exit_ctl = exit_ctl_saved;
3953 	u16 vec;
3954 	int i;
3955 
3956 	if (!((ctrl_pin_rev.clr & PIN_POST_INTR) &&
3957 	    (ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3958 	    (ctrl_exit_rev.clr & EXI_INTA)))
3959 		return;
3960 
3961 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3962 
3963 	/*
3964 	 * Test virtual-interrupt-delivery and acknowledge-interrupt-on-exit
3965 	 */
3966 	pin |= PIN_POST_INTR;
3967 	vmcs_write(PIN_CONTROLS, pin);
3968 	secondary &= ~CPU_VINTD;
3969 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3970 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled");
3971 	test_vmx_invalid_controls();
3972 	report_prefix_pop();
3973 
3974 	secondary |= CPU_VINTD;
3975 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3976 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled");
3977 	test_vmx_invalid_controls();
3978 	report_prefix_pop();
3979 
3980 	exit_ctl &= ~EXI_INTA;
3981 	vmcs_write(EXI_CONTROLS, exit_ctl);
3982 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit disabled");
3983 	test_vmx_invalid_controls();
3984 	report_prefix_pop();
3985 
3986 	exit_ctl |= EXI_INTA;
3987 	vmcs_write(EXI_CONTROLS, exit_ctl);
3988 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
3989 	test_vmx_valid_controls();
3990 	report_prefix_pop();
3991 
3992 	secondary &= ~CPU_VINTD;
3993 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3994 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled; acknowledge-interrupt-on-exit enabled");
3995 	test_vmx_invalid_controls();
3996 	report_prefix_pop();
3997 
3998 	secondary |= CPU_VINTD;
3999 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4000 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
4001 	test_vmx_valid_controls();
4002 	report_prefix_pop();
4003 
4004 	/*
4005 	 * Test posted-interrupt notification vector
4006 	 */
4007 	for (i = 0; i < 8; i++) {
4008 		vec = (1ul << i);
4009 		vmcs_write(PINV, vec);
4010 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4011 		test_vmx_valid_controls();
4012 		report_prefix_pop();
4013 	}
4014 	for (i = 8; i < 16; i++) {
4015 		vec = (1ul << i);
4016 		vmcs_write(PINV, vec);
4017 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4018 		test_vmx_invalid_controls();
4019 		report_prefix_pop();
4020 	}
4021 
4022 	vec &= ~(0xff << 8);
4023 	vmcs_write(PINV, vec);
4024 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4025 	test_vmx_valid_controls();
4026 	report_prefix_pop();
4027 
4028 	/*
4029 	 * Test posted-interrupt descriptor addresss
4030 	 */
4031 	for (i = 0; i < 6; i++) {
4032 		test_pi_desc_addr(1ul << i, false);
4033 	}
4034 
4035 	test_pi_desc_addr(0xf0, false);
4036 	test_pi_desc_addr(0xff, false);
4037 	test_pi_desc_addr(0x0f, false);
4038 	test_pi_desc_addr(0x8000, true);
4039 	test_pi_desc_addr(0x00, true);
4040 	test_pi_desc_addr(0xc000, true);
4041 
4042 	test_vmcs_addr_values("process-posted interrupts",
4043 			       POSTED_INTR_DESC_ADDR, 64,
4044 			       false, false, 0, 63);
4045 
4046 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
4047 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
4048 	vmcs_write(PIN_CONTROLS, saved_pin);
4049 }
4050 
4051 static void test_apic_ctls(void)
4052 {
4053 	test_apic_virt_addr();
4054 	test_apic_access_addr();
4055 	test_apic_virtual_ctls();
4056 	test_virtual_intr_ctls();
4057 	test_posted_intr();
4058 }
4059 
4060 /*
4061  * If the “enable VPID†VM-execution control is 1, the value of the
4062  * of the VPID VM-execution control field must not be 0000H.
4063  * [Intel SDM]
4064  */
4065 static void test_vpid(void)
4066 {
4067 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
4068 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
4069 	u16 vpid = 0x0000;
4070 	int i;
4071 
4072 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4073 	    (ctrl_cpu_rev[1].clr & CPU_VPID))) {
4074 		printf("Secondary controls and/or VPID not supported\n");
4075 		return;
4076 	}
4077 
4078 	vmcs_write(CPU_EXEC_CTRL0, saved_primary | CPU_SECONDARY);
4079 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary & ~CPU_VPID);
4080 	vmcs_write(VPID, vpid);
4081 	report_prefix_pushf("VPID disabled; VPID value %x", vpid);
4082 	test_vmx_valid_controls();
4083 	report_prefix_pop();
4084 
4085 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary | CPU_VPID);
4086 	report_prefix_pushf("VPID enabled; VPID value %x", vpid);
4087 	test_vmx_invalid_controls();
4088 	report_prefix_pop();
4089 
4090 	for (i = 0; i < 16; i++) {
4091 		vpid = (short)1 << i;;
4092 		vmcs_write(VPID, vpid);
4093 		report_prefix_pushf("VPID enabled; VPID value %x", vpid);
4094 		test_vmx_valid_controls();
4095 		report_prefix_pop();
4096 	}
4097 
4098 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
4099 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
4100 }
4101 
4102 static void set_vtpr(unsigned vtpr)
4103 {
4104 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
4105 }
4106 
4107 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
4108 {
4109 	bool valid = true;
4110 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4111 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4112 
4113 	if ((primary & CPU_TPR_SHADOW) &&
4114 	    (!(primary & CPU_SECONDARY) ||
4115 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
4116 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
4117 
4118 	set_vtpr(vtpr);
4119 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
4120 	    threshold, (vtpr >> 4) & 0xf);
4121 	if (valid)
4122 		test_vmx_valid_controls();
4123 	else
4124 		test_vmx_invalid_controls();
4125 	report_prefix_pop();
4126 }
4127 
4128 static void test_invalid_event_injection(void)
4129 {
4130 	u32 ent_intr_info_save = vmcs_read(ENT_INTR_INFO);
4131 	u32 ent_intr_error_save = vmcs_read(ENT_INTR_ERROR);
4132 	u32 ent_inst_len_save = vmcs_read(ENT_INST_LEN);
4133 	u32 primary_save = vmcs_read(CPU_EXEC_CTRL0);
4134 	u32 secondary_save = vmcs_read(CPU_EXEC_CTRL1);
4135 	u64 guest_cr0_save = vmcs_read(GUEST_CR0);
4136 	u32 ent_intr_info_base = INTR_INFO_VALID_MASK;
4137 	u32 ent_intr_info, ent_intr_err, ent_intr_len;
4138 	u32 cnt;
4139 
4140 	/* Setup */
4141 	report_prefix_push("invalid event injection");
4142 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4143 	vmcs_write(ENT_INST_LEN, 0x00000001);
4144 
4145 	/* The field’s interruption type is not set to a reserved value. */
4146 	ent_intr_info = ent_intr_info_base | INTR_TYPE_RESERVED | DE_VECTOR;
4147 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4148 			    "RESERVED interruption type invalid [-]",
4149 			    ent_intr_info);
4150 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4151 	test_vmx_invalid_controls();
4152 	report_prefix_pop();
4153 
4154 	ent_intr_info = ent_intr_info_base | INTR_TYPE_EXT_INTR |
4155 			DE_VECTOR;
4156 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4157 			    "RESERVED interruption type invalid [+]",
4158 			    ent_intr_info);
4159 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4160 	test_vmx_valid_controls();
4161 	report_prefix_pop();
4162 
4163 	/* If the interruption type is other event, the vector is 0. */
4164 	ent_intr_info = ent_intr_info_base | INTR_TYPE_OTHER_EVENT | DB_VECTOR;
4165 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4166 			    "(OTHER EVENT && vector != 0) invalid [-]",
4167 			    ent_intr_info);
4168 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4169 	test_vmx_invalid_controls();
4170 	report_prefix_pop();
4171 
4172 	/* If the interruption type is NMI, the vector is 2 (negative case). */
4173 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | DE_VECTOR;
4174 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4175 			    "(NMI && vector != 2) invalid [-]", ent_intr_info);
4176 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4177 	test_vmx_invalid_controls();
4178 	report_prefix_pop();
4179 
4180 	/* If the interruption type is NMI, the vector is 2 (positive case). */
4181 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | NMI_VECTOR;
4182 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4183 			    "(NMI && vector == 2) valid [+]", ent_intr_info);
4184 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4185 	test_vmx_valid_controls();
4186 	report_prefix_pop();
4187 
4188 	/*
4189 	 * If the interruption type
4190 	 * is HW exception, the vector is at most 31.
4191 	 */
4192 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION | 0x20;
4193 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4194 			    "(HW exception && vector > 31) invalid [-]",
4195 			    ent_intr_info);
4196 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4197 	test_vmx_invalid_controls();
4198 	report_prefix_pop();
4199 
4200 	/*
4201 	 * deliver-error-code is 1 iff either
4202 	 * (a) the "unrestricted guest" VM-execution control is 0
4203 	 * (b) CR0.PE is set.
4204 	 */
4205 
4206 	/* Assert that unrestricted guest is disabled or unsupported */
4207 	assert(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
4208 	       !(secondary_save & CPU_URG));
4209 
4210 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4211 			GP_VECTOR;
4212 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4213 			    "error code <-> (!URG || prot_mode) [-]",
4214 			    ent_intr_info);
4215 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4216 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4217 	test_vmx_invalid_controls();
4218 	report_prefix_pop();
4219 
4220 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4221 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4222 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4223 			    "error code <-> (!URG || prot_mode) [+]",
4224 			    ent_intr_info);
4225 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4226 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4227 	test_vmx_valid_controls();
4228 	report_prefix_pop();
4229 
4230 	if (enable_unrestricted_guest())
4231 		goto skip_unrestricted_guest;
4232 
4233 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4234 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4235 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4236 			    "error code <-> (!URG || prot_mode) [-]",
4237 			    ent_intr_info);
4238 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4239 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4240 	test_vmx_invalid_controls();
4241 	report_prefix_pop();
4242 
4243 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4244 			GP_VECTOR;
4245 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4246 			    "error code <-> (!URG || prot_mode) [-]",
4247 			    ent_intr_info);
4248 	vmcs_write(GUEST_CR0, guest_cr0_save | X86_CR0_PE);
4249 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4250 	test_vmx_invalid_controls();
4251 	report_prefix_pop();
4252 
4253 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4254 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4255 
4256 skip_unrestricted_guest:
4257 	vmcs_write(GUEST_CR0, guest_cr0_save);
4258 
4259 	/* deliver-error-code is 1 iff the interruption type is HW exception */
4260 	report_prefix_push("error code <-> HW exception");
4261 	for (cnt = 0; cnt < 8; cnt++) {
4262 		u32 exception_type_mask = cnt << 8;
4263 		u32 deliver_error_code_mask =
4264 			exception_type_mask != INTR_TYPE_HARD_EXCEPTION ?
4265 			INTR_INFO_DELIVER_CODE_MASK : 0;
4266 
4267 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4268 				exception_type_mask | GP_VECTOR;
4269 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4270 				    ent_intr_info);
4271 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4272 		test_vmx_invalid_controls();
4273 		report_prefix_pop();
4274 	}
4275 	report_prefix_pop();
4276 
4277 	/*
4278 	 * deliver-error-code is 1 iff the the vector
4279 	 * indicates an exception that would normally deliver an error code
4280 	 */
4281 	report_prefix_push("error code <-> vector delivers error code");
4282 	for (cnt = 0; cnt < 32; cnt++) {
4283 		bool has_error_code = false;
4284 		u32 deliver_error_code_mask;
4285 
4286 		switch (cnt) {
4287 		case DF_VECTOR:
4288 		case TS_VECTOR:
4289 		case NP_VECTOR:
4290 		case SS_VECTOR:
4291 		case GP_VECTOR:
4292 		case PF_VECTOR:
4293 		case AC_VECTOR:
4294 			has_error_code = true;
4295 		}
4296 
4297 		/* Negative case */
4298 		deliver_error_code_mask = has_error_code ?
4299 						0 :
4300 						INTR_INFO_DELIVER_CODE_MASK;
4301 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4302 				INTR_TYPE_HARD_EXCEPTION | cnt;
4303 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4304 				    ent_intr_info);
4305 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4306 		test_vmx_invalid_controls();
4307 		report_prefix_pop();
4308 
4309 		/* Positive case */
4310 		deliver_error_code_mask = has_error_code ?
4311 						INTR_INFO_DELIVER_CODE_MASK :
4312 						0;
4313 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4314 				INTR_TYPE_HARD_EXCEPTION | cnt;
4315 		report_prefix_pushf("VM-entry intr info=0x%x [+]",
4316 				    ent_intr_info);
4317 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4318 		test_vmx_valid_controls();
4319 		report_prefix_pop();
4320 	}
4321 	report_prefix_pop();
4322 
4323 	/* Reserved bits in the field (30:12) are 0. */
4324 	report_prefix_push("reserved bits clear");
4325 	for (cnt = 12; cnt <= 30; cnt++) {
4326 		ent_intr_info = ent_intr_info_base |
4327 				INTR_INFO_DELIVER_CODE_MASK |
4328 				INTR_TYPE_HARD_EXCEPTION | GP_VECTOR |
4329 				(1U << cnt);
4330 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4331 				    ent_intr_info);
4332 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4333 		test_vmx_invalid_controls();
4334 		report_prefix_pop();
4335 	}
4336 	report_prefix_pop();
4337 
4338 	/*
4339 	 * If deliver-error-code is 1
4340 	 * bits 31:16 of the VM-entry exception error-code field are 0.
4341 	 */
4342 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4343 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4344 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4345 			    "VM-entry exception error code[31:16] clear",
4346 			    ent_intr_info);
4347 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4348 	for (cnt = 16; cnt <= 31; cnt++) {
4349 		ent_intr_err = 1U << cnt;
4350 		report_prefix_pushf("VM-entry intr error=0x%x [-]",
4351 				    ent_intr_err);
4352 		vmcs_write(ENT_INTR_ERROR, ent_intr_err);
4353 		test_vmx_invalid_controls();
4354 		report_prefix_pop();
4355 	}
4356 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4357 	report_prefix_pop();
4358 
4359 	/*
4360 	 * If the interruption type is software interrupt, software exception,
4361 	 * or privileged software exception, the VM-entry instruction-length
4362 	 * field is in the range 0–15.
4363 	 */
4364 
4365 	for (cnt = 0; cnt < 3; cnt++) {
4366 		switch (cnt) {
4367 		case 0:
4368 			ent_intr_info = ent_intr_info_base |
4369 					INTR_TYPE_SOFT_INTR;
4370 			break;
4371 		case 1:
4372 			ent_intr_info = ent_intr_info_base |
4373 					INTR_TYPE_SOFT_EXCEPTION;
4374 			break;
4375 		case 2:
4376 			ent_intr_info = ent_intr_info_base |
4377 					INTR_TYPE_PRIV_SW_EXCEPTION;
4378 			break;
4379 		}
4380 		report_prefix_pushf("%s, VM-entry intr info=0x%x",
4381 				    "VM-entry instruction-length check",
4382 				    ent_intr_info);
4383 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4384 
4385 		/* Instruction length set to -1 (0xFFFFFFFF) should fail */
4386 		ent_intr_len = -1;
4387 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4388 				    ent_intr_len);
4389 		vmcs_write(ENT_INST_LEN, ent_intr_len);
4390 		test_vmx_invalid_controls();
4391 		report_prefix_pop();
4392 
4393 		/* Instruction length set to 16 should fail */
4394 		ent_intr_len = 0x00000010;
4395 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4396 				    ent_intr_len);
4397 		vmcs_write(ENT_INST_LEN, 0x00000010);
4398 		test_vmx_invalid_controls();
4399 		report_prefix_pop();
4400 
4401 		report_prefix_pop();
4402 	}
4403 
4404 	/* Cleanup */
4405 	vmcs_write(ENT_INTR_INFO, ent_intr_info_save);
4406 	vmcs_write(ENT_INTR_ERROR, ent_intr_error_save);
4407 	vmcs_write(ENT_INST_LEN, ent_inst_len_save);
4408 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4409 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4410 	vmcs_write(GUEST_CR0, guest_cr0_save);
4411 	report_prefix_pop();
4412 }
4413 
4414 /*
4415  * Test interesting vTPR values for a given TPR threshold.
4416  */
4417 static void test_vtpr_values(unsigned threshold)
4418 {
4419 	try_tpr_threshold_and_vtpr(threshold, (threshold - 1) << 4);
4420 	try_tpr_threshold_and_vtpr(threshold, threshold << 4);
4421 	try_tpr_threshold_and_vtpr(threshold, (threshold + 1) << 4);
4422 }
4423 
4424 static void try_tpr_threshold(unsigned threshold)
4425 {
4426 	bool valid = true;
4427 
4428 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4429 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4430 
4431 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
4432 	    (secondary & CPU_VINTD)))
4433 		valid = !(threshold >> 4);
4434 
4435 	set_vtpr(-1);
4436 	vmcs_write(TPR_THRESHOLD, threshold);
4437 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
4438 	if (valid)
4439 		test_vmx_valid_controls();
4440 	else
4441 		test_vmx_invalid_controls();
4442 	report_prefix_pop();
4443 
4444 	if (valid)
4445 		test_vtpr_values(threshold);
4446 }
4447 
4448 /*
4449  * Test interesting TPR threshold values.
4450  */
4451 static void test_tpr_threshold_values(void)
4452 {
4453 	unsigned i;
4454 
4455 	for (i = 0; i < 0x10; i++)
4456 		try_tpr_threshold(i);
4457 	for (i = 4; i < 32; i++)
4458 		try_tpr_threshold(1u << i);
4459 	try_tpr_threshold(-1u);
4460 	try_tpr_threshold(0x7fffffff);
4461 }
4462 
4463 /*
4464  * This test covers the following two VM entry checks:
4465  *
4466  *      i) If the "use TPR shadow" VM-execution control is 1 and the
4467  *         "virtual-interrupt delivery" VM-execution control is 0, bits
4468  *         31:4 of the TPR threshold VM-execution control field must
4469 	   be 0.
4470  *         [Intel SDM]
4471  *
4472  *      ii) If the "use TPR shadow" VM-execution control is 1, the
4473  *          "virtual-interrupt delivery" VM-execution control is 0
4474  *          and the "virtualize APIC accesses" VM-execution control
4475  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
4476  *          control field must not be greater than the value of bits
4477  *          7:4 of VTPR.
4478  *          [Intel SDM]
4479  */
4480 static void test_tpr_threshold(void)
4481 {
4482 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4483 	u64 apic_virt_addr = vmcs_read(APIC_VIRT_ADDR);
4484 	u64 threshold = vmcs_read(TPR_THRESHOLD);
4485 	void *virtual_apic_page;
4486 
4487 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
4488 		return;
4489 
4490 	virtual_apic_page = alloc_page();
4491 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
4492 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
4493 
4494 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
4495 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
4496 	test_tpr_threshold_values();
4497 	report_prefix_pop();
4498 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
4499 	report_prefix_pushf("Use TPR shadow enabled, secondary controls disabled");
4500 	test_tpr_threshold_values();
4501 	report_prefix_pop();
4502 
4503 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4504 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES))))
4505 		goto out;
4506 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4507 
4508 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
4509 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
4510 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4511 		test_tpr_threshold_values();
4512 		report_prefix_pop();
4513 
4514 		vmcs_write(CPU_EXEC_CTRL0,
4515 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4516 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4517 		test_tpr_threshold_values();
4518 		report_prefix_pop();
4519 	}
4520 
4521 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
4522 		vmcs_write(CPU_EXEC_CTRL0,
4523 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4524 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
4525 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4526 		test_tpr_threshold_values();
4527 		report_prefix_pop();
4528 
4529 		vmcs_write(CPU_EXEC_CTRL0,
4530 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4531 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4532 		test_tpr_threshold_values();
4533 		report_prefix_pop();
4534 	}
4535 
4536 	if ((ctrl_cpu_rev[1].clr &
4537 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
4538 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
4539 		vmcs_write(CPU_EXEC_CTRL0,
4540 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4541 		vmcs_write(CPU_EXEC_CTRL1,
4542 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
4543 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4544 		test_tpr_threshold_values();
4545 		report_prefix_pop();
4546 
4547 		vmcs_write(CPU_EXEC_CTRL0,
4548 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4549 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4550 		test_tpr_threshold_values();
4551 		report_prefix_pop();
4552 	}
4553 
4554 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4555 out:
4556 	vmcs_write(TPR_THRESHOLD, threshold);
4557 	vmcs_write(APIC_VIRT_ADDR, apic_virt_addr);
4558 	vmcs_write(CPU_EXEC_CTRL0, primary);
4559 }
4560 
4561 /*
4562  * This test verifies the following two vmentry checks:
4563  *
4564  *  If the "NMI exiting" VM-execution control is 0, "Virtual NMIs"
4565  *  VM-execution control must be 0.
4566  *  [Intel SDM]
4567  *
4568  *  If the “virtual NMIs” VM-execution control is 0, the “NMI-window
4569  *  exiting” VM-execution control must be 0.
4570  *  [Intel SDM]
4571  */
4572 static void test_nmi_ctrls(void)
4573 {
4574 	u32 pin_ctrls, cpu_ctrls0, test_pin_ctrls, test_cpu_ctrls0;
4575 
4576 	if ((ctrl_pin_rev.clr & (PIN_NMI | PIN_VIRT_NMI)) !=
4577 	    (PIN_NMI | PIN_VIRT_NMI)) {
4578 		printf("NMI exiting and Virtual NMIs are not supported !\n");
4579 		return;
4580 	}
4581 
4582 	/* Save the controls so that we can restore them after our tests */
4583 	pin_ctrls = vmcs_read(PIN_CONTROLS);
4584 	cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
4585 
4586 	test_pin_ctrls = pin_ctrls & ~(PIN_NMI | PIN_VIRT_NMI);
4587 	test_cpu_ctrls0 = cpu_ctrls0 & ~CPU_NMI_WINDOW;
4588 
4589 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4590 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs disabled");
4591 	test_vmx_valid_controls();
4592 	report_prefix_pop();
4593 
4594 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_VIRT_NMI);
4595 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs enabled");
4596 	test_vmx_invalid_controls();
4597 	report_prefix_pop();
4598 
4599 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4600 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs enabled");
4601 	test_vmx_valid_controls();
4602 	report_prefix_pop();
4603 
4604 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_NMI);
4605 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs disabled");
4606 	test_vmx_valid_controls();
4607 	report_prefix_pop();
4608 
4609 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
4610 		report_info("NMI-window exiting is not supported, skipping...");
4611 		goto done;
4612 	}
4613 
4614 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4615 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4616 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting enabled");
4617 	test_vmx_invalid_controls();
4618 	report_prefix_pop();
4619 
4620 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4621 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4622 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting disabled");
4623 	test_vmx_valid_controls();
4624 	report_prefix_pop();
4625 
4626 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4627 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4628 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting enabled");
4629 	test_vmx_valid_controls();
4630 	report_prefix_pop();
4631 
4632 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4633 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4634 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting disabled");
4635 	test_vmx_valid_controls();
4636 	report_prefix_pop();
4637 
4638 	/* Restore the controls to their original values */
4639 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
4640 done:
4641 	vmcs_write(PIN_CONTROLS, pin_ctrls);
4642 }
4643 
4644 static void test_eptp_ad_bit(u64 eptp, bool ctrl)
4645 {
4646 	vmcs_write(EPTP, eptp);
4647 	report_prefix_pushf("Enable-EPT enabled; EPT accessed and dirty flag %s",
4648 	    (eptp & EPTP_AD_FLAG) ? "1": "0");
4649 	if (ctrl)
4650 		test_vmx_valid_controls();
4651 	else
4652 		test_vmx_invalid_controls();
4653 	report_prefix_pop();
4654 
4655 }
4656 
4657 /*
4658  * 1. If the "enable EPT" VM-execution control is 1, the "EPTP VM-execution"
4659  *    control field must satisfy the following checks:
4660  *
4661  *     - The EPT memory type (bits 2:0) must be a value supported by the
4662  *	 processor as indicated in the IA32_VMX_EPT_VPID_CAP MSR.
4663  *     - Bits 5:3 (1 less than the EPT page-walk length) must be 3,
4664  *	 indicating an EPT page-walk length of 4.
4665  *     - Bit 6 (enable bit for accessed and dirty flags for EPT) must be
4666  *	 0 if bit 21 of the IA32_VMX_EPT_VPID_CAP MSR is read as 0,
4667  *	 indicating that the processor does not support accessed and dirty
4668  *	 dirty flags for EPT.
4669  *     - Reserved bits 11:7 and 63:N (where N is the processor's
4670  *	 physical-address width) must all be 0.
4671  *
4672  * 2. If the "unrestricted guest" VM-execution control is 1, the
4673  *    "enable EPT" VM-execution control must also be 1.
4674  */
4675 static void test_ept_eptp(void)
4676 {
4677 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4678 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4679 	u64 eptp_saved = vmcs_read(EPTP);
4680 	u32 primary = primary_saved;
4681 	u32 secondary = secondary_saved;
4682 	u64 msr, eptp = eptp_saved;
4683 	bool un_cache = false;
4684 	bool wr_bk = false;
4685 	bool ctrl;
4686 	u32 i, maxphysaddr;
4687 	u64 j, resv_bits_mask = 0;
4688 
4689 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4690 	    (ctrl_cpu_rev[1].clr & CPU_EPT))) {
4691 		printf("\"CPU secondary\" and/or \"enable EPT\" execution controls are not supported !\n");
4692 		return;
4693 	}
4694 
4695 	/*
4696 	 * Memory type (bits 2:0)
4697 	 */
4698 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
4699 	if (msr & EPT_CAP_UC)
4700 		un_cache = true;
4701 	if (msr & EPT_CAP_WB)
4702 		wr_bk = true;
4703 
4704 	primary |= CPU_SECONDARY;
4705 	vmcs_write(CPU_EXEC_CTRL0, primary);
4706 	secondary |= CPU_EPT;
4707 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4708 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4709 	    (3ul << EPTP_PG_WALK_LEN_SHIFT);
4710 	vmcs_write(EPTP, eptp);
4711 
4712 	for (i = 0; i < 8; i++) {
4713 		if (i == 0) {
4714 			if (un_cache) {
4715 				report_info("EPT paging structure memory-type is Un-cacheable\n");
4716 				ctrl = true;
4717 			} else {
4718 				ctrl = false;
4719 			}
4720 		} else if (i == 6) {
4721 			if (wr_bk) {
4722 				report_info("EPT paging structure memory-type is Write-back\n");
4723 				ctrl = true;
4724 			} else {
4725 				ctrl = false;
4726 			}
4727 		} else {
4728 			ctrl = false;
4729 		}
4730 
4731 		eptp = (eptp & ~EPT_MEM_TYPE_MASK) | i;
4732 		vmcs_write(EPTP, eptp);
4733 		report_prefix_pushf("Enable-EPT enabled; EPT memory type %lu",
4734 		    eptp & EPT_MEM_TYPE_MASK);
4735 		if (ctrl)
4736 			test_vmx_valid_controls();
4737 		else
4738 			test_vmx_invalid_controls();
4739 		report_prefix_pop();
4740 	}
4741 
4742 	eptp = (eptp & ~EPT_MEM_TYPE_MASK) | 6ul;
4743 
4744 	/*
4745 	 * Page walk length (bits 5:3)
4746 	 */
4747 	for (i = 0; i < 8; i++) {
4748 		eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4749 		    (i << EPTP_PG_WALK_LEN_SHIFT);
4750 		if (i == 3)
4751 			ctrl = true;
4752 		else
4753 			ctrl = false;
4754 
4755 		vmcs_write(EPTP, eptp);
4756 		report_prefix_pushf("Enable-EPT enabled; EPT page walk length %lu",
4757 		    eptp & EPTP_PG_WALK_LEN_MASK);
4758 		if (ctrl)
4759 			test_vmx_valid_controls();
4760 		else
4761 			test_vmx_invalid_controls();
4762 		report_prefix_pop();
4763 	}
4764 
4765 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4766 	    3ul << EPTP_PG_WALK_LEN_SHIFT;
4767 
4768 	/*
4769 	 * Accessed and dirty flag (bit 6)
4770 	 */
4771 	if (msr & EPT_CAP_AD_FLAG) {
4772 		report_info("Processor supports accessed and dirty flag");
4773 		eptp &= ~EPTP_AD_FLAG;
4774 		test_eptp_ad_bit(eptp, true);
4775 
4776 		eptp |= EPTP_AD_FLAG;
4777 		test_eptp_ad_bit(eptp, true);
4778 	} else {
4779 		report_info("Processor does not supports accessed and dirty flag");
4780 		eptp &= ~EPTP_AD_FLAG;
4781 		test_eptp_ad_bit(eptp, true);
4782 
4783 		eptp |= EPTP_AD_FLAG;
4784 		test_eptp_ad_bit(eptp, false);
4785 	}
4786 
4787 	/*
4788 	 * Reserved bits [11:7] and [63:N]
4789 	 */
4790 	for (i = 0; i < 32; i++) {
4791 		eptp = (eptp &
4792 		    ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT)) |
4793 		    (i << EPTP_RESERV_BITS_SHIFT);
4794 		vmcs_write(EPTP, eptp);
4795 		report_prefix_pushf("Enable-EPT enabled; reserved bits [11:7] %lu",
4796 		    (eptp >> EPTP_RESERV_BITS_SHIFT) &
4797 		    EPTP_RESERV_BITS_MASK);
4798 		if (i == 0)
4799 			test_vmx_valid_controls();
4800 		else
4801 			test_vmx_invalid_controls();
4802 		report_prefix_pop();
4803 	}
4804 
4805 	eptp = (eptp & ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT));
4806 
4807 	maxphysaddr = cpuid_maxphyaddr();
4808 	for (i = 0; i < (63 - maxphysaddr + 1); i++) {
4809 		resv_bits_mask |= 1ul << i;
4810 	}
4811 
4812 	for (j = maxphysaddr - 1; j <= 63; j++) {
4813 		eptp = (eptp & ~(resv_bits_mask << maxphysaddr)) |
4814 		    (j < maxphysaddr ? 0 : 1ul << j);
4815 		vmcs_write(EPTP, eptp);
4816 		report_prefix_pushf("Enable-EPT enabled; reserved bits [63:N] %lu",
4817 		    (eptp >> maxphysaddr) & resv_bits_mask);
4818 		if (j < maxphysaddr)
4819 			test_vmx_valid_controls();
4820 		else
4821 			test_vmx_invalid_controls();
4822 		report_prefix_pop();
4823 	}
4824 
4825 	secondary &= ~(CPU_EPT | CPU_URG);
4826 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4827 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest disabled");
4828 	test_vmx_valid_controls();
4829 	report_prefix_pop();
4830 
4831 	if (!(ctrl_cpu_rev[1].clr & CPU_URG))
4832 		goto skip_unrestricted_guest;
4833 
4834 	secondary |= CPU_URG;
4835 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4836 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest enabled");
4837 	test_vmx_invalid_controls();
4838 	report_prefix_pop();
4839 
4840 	secondary |= CPU_EPT;
4841 	setup_dummy_ept();
4842 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest enabled");
4843 	test_vmx_valid_controls();
4844 	report_prefix_pop();
4845 
4846 skip_unrestricted_guest:
4847 	secondary &= ~CPU_URG;
4848 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4849 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest disabled");
4850 	test_vmx_valid_controls();
4851 	report_prefix_pop();
4852 
4853 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4854 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4855 	vmcs_write(EPTP, eptp_saved);
4856 }
4857 
4858 /*
4859  * If the 'enable PML' VM-execution control is 1, the 'enable EPT'
4860  * VM-execution control must also be 1. In addition, the PML address
4861  * must satisfy the following checks:
4862  *
4863  *    * Bits 11:0 of the address must be 0.
4864  *    * The address should not set any bits beyond the processor's
4865  *	physical-address width.
4866  *
4867  *  [Intel SDM]
4868  */
4869 static void test_pml(void)
4870 {
4871 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4872 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4873 	u32 primary = primary_saved;
4874 	u32 secondary = secondary_saved;
4875 
4876 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4877 	    (ctrl_cpu_rev[1].clr & CPU_EPT) && (ctrl_cpu_rev[1].clr & CPU_PML))) {
4878 		printf("\"Secondary execution\" control or \"enable EPT\" control or \"enable PML\" control is not supported !\n");
4879 		return;
4880 	}
4881 
4882 	primary |= CPU_SECONDARY;
4883 	vmcs_write(CPU_EXEC_CTRL0, primary);
4884 	secondary &= ~(CPU_PML | CPU_EPT);
4885 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4886 	report_prefix_pushf("enable-PML disabled, enable-EPT disabled");
4887 	test_vmx_valid_controls();
4888 	report_prefix_pop();
4889 
4890 	secondary |= CPU_PML;
4891 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4892 	report_prefix_pushf("enable-PML enabled, enable-EPT disabled");
4893 	test_vmx_invalid_controls();
4894 	report_prefix_pop();
4895 
4896 	secondary |= CPU_EPT;
4897 	setup_dummy_ept();
4898 	report_prefix_pushf("enable-PML enabled, enable-EPT enabled");
4899 	test_vmx_valid_controls();
4900 	report_prefix_pop();
4901 
4902 	secondary &= ~CPU_PML;
4903 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4904 	report_prefix_pushf("enable-PML disabled, enable EPT enabled");
4905 	test_vmx_valid_controls();
4906 	report_prefix_pop();
4907 
4908 	test_vmcs_addr_reference(CPU_PML, PMLADDR, "PML address", "PML",
4909 				 PAGE_SIZE, false, false);
4910 
4911 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4912 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4913 }
4914 
4915  /*
4916  * If the "activate VMX-preemption timer" VM-execution control is 0, the
4917  * the "save VMX-preemption timer value" VM-exit control must also be 0.
4918  *
4919  *  [Intel SDM]
4920  */
4921 static void test_vmx_preemption_timer(void)
4922 {
4923 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4924 	u32 saved_exit = vmcs_read(EXI_CONTROLS);
4925 	u32 pin = saved_pin;
4926 	u32 exit = saved_exit;
4927 
4928 	if (!((ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) ||
4929 	    (ctrl_pin_rev.clr & PIN_PREEMPT))) {
4930 		printf("\"Save-VMX-preemption-timer\" control and/or \"Enable-VMX-preemption-timer\" control is not supported\n");
4931 		return;
4932 	}
4933 
4934 	pin |= PIN_PREEMPT;
4935 	vmcs_write(PIN_CONTROLS, pin);
4936 	exit &= ~EXI_SAVE_PREEMPT;
4937 	vmcs_write(EXI_CONTROLS, exit);
4938 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer disabled");
4939 	test_vmx_valid_controls();
4940 	report_prefix_pop();
4941 
4942 	exit |= EXI_SAVE_PREEMPT;
4943 	vmcs_write(EXI_CONTROLS, exit);
4944 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer enabled");
4945 	test_vmx_valid_controls();
4946 	report_prefix_pop();
4947 
4948 	pin &= ~PIN_PREEMPT;
4949 	vmcs_write(PIN_CONTROLS, pin);
4950 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer enabled");
4951 	test_vmx_invalid_controls();
4952 	report_prefix_pop();
4953 
4954 	exit &= ~EXI_SAVE_PREEMPT;
4955 	vmcs_write(EXI_CONTROLS, exit);
4956 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer disabled");
4957 	test_vmx_valid_controls();
4958 	report_prefix_pop();
4959 
4960 	vmcs_write(PIN_CONTROLS, saved_pin);
4961 	vmcs_write(EXI_CONTROLS, saved_exit);
4962 }
4963 
4964 extern unsigned char test_mtf1;
4965 extern unsigned char test_mtf2;
4966 extern unsigned char test_mtf3;
4967 extern unsigned char test_mtf4;
4968 
4969 static void test_mtf_guest(void)
4970 {
4971 	asm ("vmcall;\n\t"
4972 	     "out %al, $0x80;\n\t"
4973 	     "test_mtf1:\n\t"
4974 	     "vmcall;\n\t"
4975 	     "out %al, $0x80;\n\t"
4976 	     "test_mtf2:\n\t"
4977 	     /*
4978 	      * Prepare for the 'MOV CR3' test. Attempt to induce a
4979 	      * general-protection fault by moving a non-canonical address into
4980 	      * CR3. The 'MOV CR3' instruction does not take an imm64 operand,
4981 	      * so we must MOV the desired value into a register first.
4982 	      *
4983 	      * MOV RAX is done before the VMCALL such that MTF is only enabled
4984 	      * for the instruction under test.
4985 	      */
4986 	     "mov $0x8000000000000000, %rax;\n\t"
4987 	     "vmcall;\n\t"
4988 	     "mov %rax, %cr3;\n\t"
4989 	     "test_mtf3:\n\t"
4990 	     "vmcall;\n\t"
4991 	     /*
4992 	      * ICEBP/INT1 instruction. Though the instruction is now
4993 	      * documented, don't rely on assemblers enumerating the
4994 	      * instruction. Resort to hand assembly.
4995 	      */
4996 	     ".byte 0xf1;\n\t"
4997 	     "vmcall;\n\t"
4998 	     "test_mtf4:\n\t"
4999 	     "mov $0, %eax;\n\t");
5000 }
5001 
5002 static void test_mtf_gp_handler(struct ex_regs *regs)
5003 {
5004 	regs->rip = (unsigned long) &test_mtf3;
5005 }
5006 
5007 static void test_mtf_db_handler(struct ex_regs *regs)
5008 {
5009 }
5010 
5011 static void enable_mtf(void)
5012 {
5013 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5014 
5015 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 | CPU_MTF);
5016 }
5017 
5018 static void disable_mtf(void)
5019 {
5020 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5021 
5022 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 & ~CPU_MTF);
5023 }
5024 
5025 static void enable_tf(void)
5026 {
5027 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
5028 
5029 	vmcs_write(GUEST_RFLAGS, rflags | X86_EFLAGS_TF);
5030 }
5031 
5032 static void disable_tf(void)
5033 {
5034 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
5035 
5036 	vmcs_write(GUEST_RFLAGS, rflags & ~X86_EFLAGS_TF);
5037 }
5038 
5039 static void report_mtf(const char *insn_name, unsigned long exp_rip)
5040 {
5041 	unsigned long rip = vmcs_read(GUEST_RIP);
5042 
5043 	assert_exit_reason(VMX_MTF);
5044 	report(rip == exp_rip, "MTF VM-exit after %s. RIP: 0x%lx (expected 0x%lx)",
5045 	       insn_name, rip, exp_rip);
5046 }
5047 
5048 static void vmx_mtf_test(void)
5049 {
5050 	unsigned long pending_dbg;
5051 	handler old_gp, old_db;
5052 
5053 	if (!(ctrl_cpu_rev[0].clr & CPU_MTF)) {
5054 		printf("CPU does not support the 'monitor trap flag' processor-based VM-execution control.\n");
5055 		return;
5056 	}
5057 
5058 	test_set_guest(test_mtf_guest);
5059 
5060 	/* Expect an MTF VM-exit after OUT instruction */
5061 	enter_guest();
5062 	skip_exit_vmcall();
5063 
5064 	enable_mtf();
5065 	enter_guest();
5066 	report_mtf("OUT", (unsigned long) &test_mtf1);
5067 	disable_mtf();
5068 
5069 	/*
5070 	 * Concurrent #DB trap and MTF on instruction boundary. Expect MTF
5071 	 * VM-exit with populated 'pending debug exceptions' VMCS field.
5072 	 */
5073 	enter_guest();
5074 	skip_exit_vmcall();
5075 
5076 	enable_mtf();
5077 	enable_tf();
5078 
5079 	enter_guest();
5080 	report_mtf("OUT", (unsigned long) &test_mtf2);
5081 	pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
5082 	report(pending_dbg & DR_STEP,
5083 	       "'pending debug exceptions' field after MTF VM-exit: 0x%lx (expected 0x%lx)",
5084 	       pending_dbg, (unsigned long) DR_STEP);
5085 
5086 	disable_mtf();
5087 	disable_tf();
5088 	vmcs_write(GUEST_PENDING_DEBUG, 0);
5089 
5090 	/*
5091 	 * #GP exception takes priority over MTF. Expect MTF VM-exit with RIP
5092 	 * advanced to first instruction of #GP handler.
5093 	 */
5094 	enter_guest();
5095 	skip_exit_vmcall();
5096 
5097 	old_gp = handle_exception(GP_VECTOR, test_mtf_gp_handler);
5098 
5099 	enable_mtf();
5100 	enter_guest();
5101 	report_mtf("MOV CR3", (unsigned long) get_idt_addr(&boot_idt[GP_VECTOR]));
5102 	disable_mtf();
5103 
5104 	/*
5105 	 * Concurrent MTF and privileged software exception (i.e. ICEBP/INT1).
5106 	 * MTF should follow the delivery of #DB trap, though the SDM doesn't
5107 	 * provide clear indication of the relative priority.
5108 	 */
5109 	enter_guest();
5110 	skip_exit_vmcall();
5111 
5112 	handle_exception(GP_VECTOR, old_gp);
5113 	old_db = handle_exception(DB_VECTOR, test_mtf_db_handler);
5114 
5115 	enable_mtf();
5116 	enter_guest();
5117 	report_mtf("INT1", (unsigned long) get_idt_addr(&boot_idt[DB_VECTOR]));
5118 	disable_mtf();
5119 
5120 	enter_guest();
5121 	skip_exit_vmcall();
5122 	handle_exception(DB_VECTOR, old_db);
5123 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK | INTR_TYPE_OTHER_EVENT);
5124 	enter_guest();
5125 	report_mtf("injected MTF", (unsigned long) &test_mtf4);
5126 	enter_guest();
5127 }
5128 
5129 /*
5130  * Tests for VM-execution control fields
5131  */
5132 static void test_vm_execution_ctls(void)
5133 {
5134 	test_pin_based_ctls();
5135 	test_primary_processor_based_ctls();
5136 	test_secondary_processor_based_ctls();
5137 	test_cr3_targets();
5138 	test_io_bitmaps();
5139 	test_msr_bitmap();
5140 	test_apic_ctls();
5141 	test_tpr_threshold();
5142 	test_nmi_ctrls();
5143 	test_pml();
5144 	test_vpid();
5145 	test_ept_eptp();
5146 	test_vmx_preemption_timer();
5147 }
5148 
5149  /*
5150   * The following checks are performed for the VM-entry MSR-load address if
5151   * the VM-entry MSR-load count field is non-zero:
5152   *
5153   *    - The lower 4 bits of the VM-entry MSR-load address must be 0.
5154   *      The address should not set any bits beyond the processor’s
5155   *      physical-address width.
5156   *
5157   *    - The address of the last byte in the VM-entry MSR-load area
5158   *      should not set any bits beyond the processor’s physical-address
5159   *      width. The address of this last byte is VM-entry MSR-load address
5160   *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5161   *      uses more bits than the processor’s physical-address width.)
5162   *
5163   *
5164   *  [Intel SDM]
5165   */
5166 static void test_entry_msr_load(void)
5167 {
5168 	entry_msr_load = alloc_page();
5169 	u64 tmp;
5170 	u32 entry_msr_ld_cnt = 1;
5171 	int i;
5172 	u32 addr_len = 64;
5173 
5174 	vmcs_write(ENT_MSR_LD_CNT, entry_msr_ld_cnt);
5175 
5176 	/* Check first 4 bits of VM-entry MSR-load address */
5177 	for (i = 0; i < 4; i++) {
5178 		tmp = (u64)entry_msr_load | 1ull << i;
5179 		vmcs_write(ENTER_MSR_LD_ADDR, tmp);
5180 		report_prefix_pushf("VM-entry MSR-load addr [4:0] %lx",
5181 				    tmp & 0xf);
5182 		test_vmx_invalid_controls();
5183 		report_prefix_pop();
5184 	}
5185 
5186 	if (basic.val & (1ul << 48))
5187 		addr_len = 32;
5188 
5189 	test_vmcs_addr_values("VM-entry-MSR-load address",
5190 				ENTER_MSR_LD_ADDR, 16, false, false,
5191 				4, addr_len - 1);
5192 
5193 	/*
5194 	 * Check last byte of VM-entry MSR-load address
5195 	 */
5196 	entry_msr_load = (struct vmx_msr_entry *)((u64)entry_msr_load & ~0xf);
5197 
5198 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5199 							i < 64; i++) {
5200 		tmp = ((u64)entry_msr_load + entry_msr_ld_cnt * 16 - 1) |
5201 			1ul << i;
5202 		vmcs_write(ENTER_MSR_LD_ADDR,
5203 			   tmp - (entry_msr_ld_cnt * 16 - 1));
5204 		test_vmx_invalid_controls();
5205 	}
5206 
5207 	vmcs_write(ENT_MSR_LD_CNT, 2);
5208 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5209 	test_vmx_invalid_controls();
5210 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5211 	test_vmx_valid_controls();
5212 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5213 	test_vmx_valid_controls();
5214 }
5215 
5216 static struct vmx_state_area_test_data {
5217 	u32 msr;
5218 	u64 exp;
5219 	bool enabled;
5220 } vmx_state_area_test_data;
5221 
5222 static void guest_state_test_main(void)
5223 {
5224 	u64 obs;
5225 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
5226 
5227 	while (1) {
5228 		if (vmx_get_test_stage() == 2)
5229 			break;
5230 
5231 		if (data->enabled) {
5232 			obs = rdmsr(data->msr);
5233 			report(data->exp == obs,
5234 			       "Guest state is 0x%lx (expected 0x%lx)",
5235 			       obs, data->exp);
5236 		}
5237 
5238 		vmcall();
5239 	}
5240 
5241 	asm volatile("fnop");
5242 }
5243 
5244 static void test_guest_state(const char *test, bool xfail, u64 field,
5245 			     const char * field_name)
5246 {
5247 	struct vmentry_result result;
5248 	u8 abort_flags;
5249 
5250 	abort_flags = ABORT_ON_EARLY_VMENTRY_FAIL;
5251 	if (!xfail)
5252 		abort_flags = ABORT_ON_INVALID_GUEST_STATE;
5253 
5254 	__enter_guest(abort_flags, &result);
5255 
5256 	report(result.exit_reason.failed_vmentry == xfail &&
5257 	       ((xfail && result.exit_reason.basic == VMX_FAIL_STATE) ||
5258 	        (!xfail && result.exit_reason.basic == VMX_VMCALL)),
5259 	        "%s, %s %lx", test, field_name, field);
5260 
5261 	if (!result.exit_reason.failed_vmentry)
5262 		skip_exit_insn();
5263 }
5264 
5265 /*
5266  * Tests for VM-entry control fields
5267  */
5268 static void test_vm_entry_ctls(void)
5269 {
5270 	test_invalid_event_injection();
5271 	test_entry_msr_load();
5272 }
5273 
5274 /*
5275  * The following checks are performed for the VM-exit MSR-store address if
5276  * the VM-exit MSR-store count field is non-zero:
5277  *
5278  *    - The lower 4 bits of the VM-exit MSR-store address must be 0.
5279  *      The address should not set any bits beyond the processor’s
5280  *      physical-address width.
5281  *
5282  *    - The address of the last byte in the VM-exit MSR-store area
5283  *      should not set any bits beyond the processor’s physical-address
5284  *      width. The address of this last byte is VM-exit MSR-store address
5285  *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5286  *      uses more bits than the processor’s physical-address width.)
5287  *
5288  * If IA32_VMX_BASIC[48] is read as 1, neither address should set any bits
5289  * in the range 63:32.
5290  *
5291  *  [Intel SDM]
5292  */
5293 static void test_exit_msr_store(void)
5294 {
5295 	exit_msr_store = alloc_page();
5296 	u64 tmp;
5297 	u32 exit_msr_st_cnt = 1;
5298 	int i;
5299 	u32 addr_len = 64;
5300 
5301 	vmcs_write(EXI_MSR_ST_CNT, exit_msr_st_cnt);
5302 
5303 	/* Check first 4 bits of VM-exit MSR-store address */
5304 	for (i = 0; i < 4; i++) {
5305 		tmp = (u64)exit_msr_store | 1ull << i;
5306 		vmcs_write(EXIT_MSR_ST_ADDR, tmp);
5307 		report_prefix_pushf("VM-exit MSR-store addr [4:0] %lx",
5308 				    tmp & 0xf);
5309 		test_vmx_invalid_controls();
5310 		report_prefix_pop();
5311 	}
5312 
5313 	if (basic.val & (1ul << 48))
5314 		addr_len = 32;
5315 
5316 	test_vmcs_addr_values("VM-exit-MSR-store address",
5317 				EXIT_MSR_ST_ADDR, 16, false, false,
5318 				4, addr_len - 1);
5319 
5320 	/*
5321 	 * Check last byte of VM-exit MSR-store address
5322 	 */
5323 	exit_msr_store = (struct vmx_msr_entry *)((u64)exit_msr_store & ~0xf);
5324 
5325 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5326 							i < 64; i++) {
5327 		tmp = ((u64)exit_msr_store + exit_msr_st_cnt * 16 - 1) |
5328 			1ul << i;
5329 		vmcs_write(EXIT_MSR_ST_ADDR,
5330 			   tmp - (exit_msr_st_cnt * 16 - 1));
5331 		test_vmx_invalid_controls();
5332 	}
5333 
5334 	vmcs_write(EXI_MSR_ST_CNT, 2);
5335 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5336 	test_vmx_invalid_controls();
5337 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5338 	test_vmx_valid_controls();
5339 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5340 	test_vmx_valid_controls();
5341 }
5342 
5343 /*
5344  * Tests for VM-exit controls
5345  */
5346 static void test_vm_exit_ctls(void)
5347 {
5348 	test_exit_msr_store();
5349 }
5350 
5351 /*
5352  * Check that the virtual CPU checks all of the VMX controls as
5353  * documented in the Intel SDM.
5354  */
5355 static void vmx_controls_test(void)
5356 {
5357 	/*
5358 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
5359 	 * fail due to invalid guest state, should we make it that
5360 	 * far.
5361 	 */
5362 	vmcs_write(GUEST_RFLAGS, 0);
5363 
5364 	test_vm_execution_ctls();
5365 	test_vm_exit_ctls();
5366 	test_vm_entry_ctls();
5367 }
5368 
5369 struct apic_reg_virt_config {
5370 	bool apic_register_virtualization;
5371 	bool use_tpr_shadow;
5372 	bool virtualize_apic_accesses;
5373 	bool virtualize_x2apic_mode;
5374 	bool activate_secondary_controls;
5375 };
5376 
5377 struct apic_reg_test {
5378 	const char *name;
5379 	struct apic_reg_virt_config apic_reg_virt_config;
5380 };
5381 
5382 struct apic_reg_virt_expectation {
5383 	enum Reason rd_exit_reason;
5384 	enum Reason wr_exit_reason;
5385 	u32 val;
5386 	u32 (*virt_fn)(u32);
5387 
5388 	/*
5389 	 * If false, accessing the APIC access address from L2 is treated as a
5390 	 * normal memory operation, rather than triggering virtualization.
5391 	 */
5392 	bool virtualize_apic_accesses;
5393 };
5394 
5395 static u32 apic_virt_identity(u32 val)
5396 {
5397 	return val;
5398 }
5399 
5400 static u32 apic_virt_nibble1(u32 val)
5401 {
5402 	return val & 0xf0;
5403 }
5404 
5405 static u32 apic_virt_byte3(u32 val)
5406 {
5407 	return val & (0xff << 24);
5408 }
5409 
5410 static bool apic_reg_virt_exit_expectation(
5411 	u32 reg, struct apic_reg_virt_config *config,
5412 	struct apic_reg_virt_expectation *expectation)
5413 {
5414 	/* Good configs, where some L2 APIC accesses are virtualized. */
5415 	bool virtualize_apic_accesses_only =
5416 		config->virtualize_apic_accesses &&
5417 		!config->use_tpr_shadow &&
5418 		!config->apic_register_virtualization &&
5419 		!config->virtualize_x2apic_mode &&
5420 		config->activate_secondary_controls;
5421 	bool virtualize_apic_accesses_and_use_tpr_shadow =
5422 		config->virtualize_apic_accesses &&
5423 		config->use_tpr_shadow &&
5424 		!config->apic_register_virtualization &&
5425 		!config->virtualize_x2apic_mode &&
5426 		config->activate_secondary_controls;
5427 	bool apic_register_virtualization =
5428 		config->virtualize_apic_accesses &&
5429 		config->use_tpr_shadow &&
5430 		config->apic_register_virtualization &&
5431 		!config->virtualize_x2apic_mode &&
5432 		config->activate_secondary_controls;
5433 
5434 	expectation->val = MAGIC_VAL_1;
5435 	expectation->virt_fn = apic_virt_identity;
5436 	expectation->virtualize_apic_accesses =
5437 		config->virtualize_apic_accesses &&
5438 		config->activate_secondary_controls;
5439 	if (virtualize_apic_accesses_only) {
5440 		expectation->rd_exit_reason = VMX_APIC_ACCESS;
5441 		expectation->wr_exit_reason = VMX_APIC_ACCESS;
5442 	} else if (virtualize_apic_accesses_and_use_tpr_shadow) {
5443 		switch (reg) {
5444 		case APIC_TASKPRI:
5445 			expectation->rd_exit_reason = VMX_VMCALL;
5446 			expectation->wr_exit_reason = VMX_VMCALL;
5447 			expectation->virt_fn = apic_virt_nibble1;
5448 			break;
5449 		default:
5450 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5451 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5452 		}
5453 	} else if (apic_register_virtualization) {
5454 		expectation->rd_exit_reason = VMX_VMCALL;
5455 
5456 		switch (reg) {
5457 		case APIC_ID:
5458 		case APIC_EOI:
5459 		case APIC_LDR:
5460 		case APIC_DFR:
5461 		case APIC_SPIV:
5462 		case APIC_ESR:
5463 		case APIC_ICR:
5464 		case APIC_LVTT:
5465 		case APIC_LVTTHMR:
5466 		case APIC_LVTPC:
5467 		case APIC_LVT0:
5468 		case APIC_LVT1:
5469 		case APIC_LVTERR:
5470 		case APIC_TMICT:
5471 		case APIC_TDCR:
5472 			expectation->wr_exit_reason = VMX_APIC_WRITE;
5473 			break;
5474 		case APIC_LVR:
5475 		case APIC_ISR ... APIC_ISR + 0x70:
5476 		case APIC_TMR ... APIC_TMR + 0x70:
5477 		case APIC_IRR ... APIC_IRR + 0x70:
5478 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5479 			break;
5480 		case APIC_TASKPRI:
5481 			expectation->wr_exit_reason = VMX_VMCALL;
5482 			expectation->virt_fn = apic_virt_nibble1;
5483 			break;
5484 		case APIC_ICR2:
5485 			expectation->wr_exit_reason = VMX_VMCALL;
5486 			expectation->virt_fn = apic_virt_byte3;
5487 			break;
5488 		default:
5489 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5490 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5491 		}
5492 	} else if (!expectation->virtualize_apic_accesses) {
5493 		/*
5494 		 * No APIC registers are directly virtualized. This includes
5495 		 * VTPR, which can be virtualized through MOV to/from CR8 via
5496 		 * the use TPR shadow control, but not through directly
5497 		 * accessing VTPR.
5498 		 */
5499 		expectation->rd_exit_reason = VMX_VMCALL;
5500 		expectation->wr_exit_reason = VMX_VMCALL;
5501 	} else {
5502 		printf("Cannot parse APIC register virtualization config:\n"
5503 		       "\tvirtualize_apic_accesses: %d\n"
5504 		       "\tuse_tpr_shadow: %d\n"
5505 		       "\tapic_register_virtualization: %d\n"
5506 		       "\tvirtualize_x2apic_mode: %d\n"
5507 		       "\tactivate_secondary_controls: %d\n",
5508 		       config->virtualize_apic_accesses,
5509 		       config->use_tpr_shadow,
5510 		       config->apic_register_virtualization,
5511 		       config->virtualize_x2apic_mode,
5512 		       config->activate_secondary_controls);
5513 
5514 		return false;
5515 	}
5516 
5517 	return true;
5518 }
5519 
5520 struct apic_reg_test apic_reg_tests[] = {
5521 	/* Good configs, where some L2 APIC accesses are virtualized. */
5522 	{
5523 		.name = "Virtualize APIC accesses",
5524 		.apic_reg_virt_config = {
5525 			.virtualize_apic_accesses = true,
5526 			.use_tpr_shadow = false,
5527 			.apic_register_virtualization = false,
5528 			.virtualize_x2apic_mode = false,
5529 			.activate_secondary_controls = true,
5530 		},
5531 	},
5532 	{
5533 		.name = "Virtualize APIC accesses + Use TPR shadow",
5534 		.apic_reg_virt_config = {
5535 			.virtualize_apic_accesses = true,
5536 			.use_tpr_shadow = true,
5537 			.apic_register_virtualization = false,
5538 			.virtualize_x2apic_mode = false,
5539 			.activate_secondary_controls = true,
5540 		},
5541 	},
5542 	{
5543 		.name = "APIC-register virtualization",
5544 		.apic_reg_virt_config = {
5545 			.virtualize_apic_accesses = true,
5546 			.use_tpr_shadow = true,
5547 			.apic_register_virtualization = true,
5548 			.virtualize_x2apic_mode = false,
5549 			.activate_secondary_controls = true,
5550 		},
5551 	},
5552 
5553 	/*
5554 	 * Test that the secondary processor-based VM-execution controls are
5555 	 * correctly ignored when "activate secondary controls" is disabled.
5556 	 */
5557 	{
5558 		.name = "Activate secondary controls off",
5559 		.apic_reg_virt_config = {
5560 			.virtualize_apic_accesses = true,
5561 			.use_tpr_shadow = false,
5562 			.apic_register_virtualization = true,
5563 			.virtualize_x2apic_mode = true,
5564 			.activate_secondary_controls = false,
5565 		},
5566 	},
5567 	{
5568 		.name = "Activate secondary controls off + Use TPR shadow",
5569 		.apic_reg_virt_config = {
5570 			.virtualize_apic_accesses = true,
5571 			.use_tpr_shadow = true,
5572 			.apic_register_virtualization = true,
5573 			.virtualize_x2apic_mode = true,
5574 			.activate_secondary_controls = false,
5575 		},
5576 	},
5577 
5578 	/*
5579 	 * Test that the APIC access address is treated like an arbitrary memory
5580 	 * address when "virtualize APIC accesses" is disabled.
5581 	 */
5582 	{
5583 		.name = "Virtualize APIC accesses off + Use TPR shadow",
5584 		.apic_reg_virt_config = {
5585 			.virtualize_apic_accesses = false,
5586 			.use_tpr_shadow = true,
5587 			.apic_register_virtualization = true,
5588 			.virtualize_x2apic_mode = true,
5589 			.activate_secondary_controls = true,
5590 		},
5591 	},
5592 
5593 	/*
5594 	 * Test that VM entry fails due to invalid controls when
5595 	 * "APIC-register virtualization" is enabled while "use TPR shadow" is
5596 	 * disabled.
5597 	 */
5598 	{
5599 		.name = "APIC-register virtualization + Use TPR shadow off",
5600 		.apic_reg_virt_config = {
5601 			.virtualize_apic_accesses = true,
5602 			.use_tpr_shadow = false,
5603 			.apic_register_virtualization = true,
5604 			.virtualize_x2apic_mode = false,
5605 			.activate_secondary_controls = true,
5606 		},
5607 	},
5608 
5609 	/*
5610 	 * Test that VM entry fails due to invalid controls when
5611 	 * "Virtualize x2APIC mode" is enabled while "use TPR shadow" is
5612 	 * disabled.
5613 	 */
5614 	{
5615 		.name = "Virtualize x2APIC mode + Use TPR shadow off",
5616 		.apic_reg_virt_config = {
5617 			.virtualize_apic_accesses = false,
5618 			.use_tpr_shadow = false,
5619 			.apic_register_virtualization = false,
5620 			.virtualize_x2apic_mode = true,
5621 			.activate_secondary_controls = true,
5622 		},
5623 	},
5624 	{
5625 		.name = "Virtualize x2APIC mode + Use TPR shadow off v2",
5626 		.apic_reg_virt_config = {
5627 			.virtualize_apic_accesses = false,
5628 			.use_tpr_shadow = false,
5629 			.apic_register_virtualization = true,
5630 			.virtualize_x2apic_mode = true,
5631 			.activate_secondary_controls = true,
5632 		},
5633 	},
5634 
5635 	/*
5636 	 * Test that VM entry fails due to invalid controls when
5637 	 * "virtualize x2APIC mode" is enabled while "virtualize APIC accesses"
5638 	 * is enabled.
5639 	 */
5640 	{
5641 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses",
5642 		.apic_reg_virt_config = {
5643 			.virtualize_apic_accesses = true,
5644 			.use_tpr_shadow = true,
5645 			.apic_register_virtualization = false,
5646 			.virtualize_x2apic_mode = true,
5647 			.activate_secondary_controls = true,
5648 		},
5649 	},
5650 	{
5651 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses v2",
5652 		.apic_reg_virt_config = {
5653 			.virtualize_apic_accesses = true,
5654 			.use_tpr_shadow = true,
5655 			.apic_register_virtualization = true,
5656 			.virtualize_x2apic_mode = true,
5657 			.activate_secondary_controls = true,
5658 		},
5659 	},
5660 };
5661 
5662 enum Apic_op {
5663 	APIC_OP_XAPIC_RD,
5664 	APIC_OP_XAPIC_WR,
5665 	TERMINATE,
5666 };
5667 
5668 static u32 vmx_xapic_read(u32 *apic_access_address, u32 reg)
5669 {
5670 	return *(volatile u32 *)((uintptr_t)apic_access_address + reg);
5671 }
5672 
5673 static void vmx_xapic_write(u32 *apic_access_address, u32 reg, u32 val)
5674 {
5675 	*(volatile u32 *)((uintptr_t)apic_access_address + reg) = val;
5676 }
5677 
5678 struct apic_reg_virt_guest_args {
5679 	enum Apic_op op;
5680 	u32 *apic_access_address;
5681 	u32 reg;
5682 	u32 val;
5683 	bool check_rd;
5684 	u32 (*virt_fn)(u32);
5685 } apic_reg_virt_guest_args;
5686 
5687 static void apic_reg_virt_guest(void)
5688 {
5689 	volatile struct apic_reg_virt_guest_args *args =
5690 		&apic_reg_virt_guest_args;
5691 
5692 	for (;;) {
5693 		enum Apic_op op = args->op;
5694 		u32 *apic_access_address = args->apic_access_address;
5695 		u32 reg = args->reg;
5696 		u32 val = args->val;
5697 		bool check_rd = args->check_rd;
5698 		u32 (*virt_fn)(u32) = args->virt_fn;
5699 
5700 		if (op == TERMINATE)
5701 			break;
5702 
5703 		if (op == APIC_OP_XAPIC_RD) {
5704 			u32 ret = vmx_xapic_read(apic_access_address, reg);
5705 
5706 			if (check_rd) {
5707 				u32 want = virt_fn(val);
5708 				u32 got = virt_fn(ret);
5709 
5710 				report(got == want,
5711 				       "read 0x%x, expected 0x%x.", got, want);
5712 			}
5713 		} else if (op == APIC_OP_XAPIC_WR) {
5714 			vmx_xapic_write(apic_access_address, reg, val);
5715 		}
5716 
5717 		/*
5718 		 * The L1 should always execute a vmcall after it's done testing
5719 		 * an individual APIC operation. This helps to validate that the
5720 		 * L1 and L2 are in sync with each other, as expected.
5721 		 */
5722 		vmcall();
5723 	}
5724 }
5725 
5726 static void test_xapic_rd(
5727 	u32 reg, struct apic_reg_virt_expectation *expectation,
5728 	u32 *apic_access_address, u32 *virtual_apic_page)
5729 {
5730 	u32 val = expectation->val;
5731 	u32 exit_reason_want = expectation->rd_exit_reason;
5732 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5733 
5734 	report_prefix_pushf("xapic - reading 0x%03x", reg);
5735 
5736 	/* Configure guest to do an xapic read */
5737 	args->op = APIC_OP_XAPIC_RD;
5738 	args->apic_access_address = apic_access_address;
5739 	args->reg = reg;
5740 	args->val = val;
5741 	args->check_rd = exit_reason_want == VMX_VMCALL;
5742 	args->virt_fn = expectation->virt_fn;
5743 
5744 	/* Setup virtual APIC page */
5745 	if (!expectation->virtualize_apic_accesses) {
5746 		apic_access_address[apic_reg_index(reg)] = val;
5747 		virtual_apic_page[apic_reg_index(reg)] = 0;
5748 	} else if (exit_reason_want == VMX_VMCALL) {
5749 		apic_access_address[apic_reg_index(reg)] = 0;
5750 		virtual_apic_page[apic_reg_index(reg)] = val;
5751 	}
5752 
5753 	/* Enter guest */
5754 	enter_guest();
5755 
5756 	/*
5757 	 * Validate the behavior and
5758 	 * pass a magic value back to the guest.
5759 	 */
5760 	if (exit_reason_want == VMX_APIC_ACCESS) {
5761 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5762 
5763 		assert_exit_reason(exit_reason_want);
5764 		report(apic_page_offset == reg,
5765 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5766 		       apic_page_offset, reg);
5767 		skip_exit_insn();
5768 
5769 		/* Reenter guest so it can consume/check rcx and exit again. */
5770 		enter_guest();
5771 	} else if (exit_reason_want != VMX_VMCALL) {
5772 		report(false, "Oops, bad exit expectation: %u.",
5773 		       exit_reason_want);
5774 	}
5775 
5776 	skip_exit_vmcall();
5777 	report_prefix_pop();
5778 }
5779 
5780 static void test_xapic_wr(
5781 	u32 reg, struct apic_reg_virt_expectation *expectation,
5782 	u32 *apic_access_address, u32 *virtual_apic_page)
5783 {
5784 	u32 val = expectation->val;
5785 	u32 exit_reason_want = expectation->wr_exit_reason;
5786 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5787 	bool virtualized =
5788 		expectation->virtualize_apic_accesses &&
5789 		(exit_reason_want == VMX_APIC_WRITE ||
5790 		 exit_reason_want == VMX_VMCALL);
5791 	bool checked = false;
5792 
5793 	report_prefix_pushf("xapic - writing 0x%x to 0x%03x", val, reg);
5794 
5795 	/* Configure guest to do an xapic read */
5796 	args->op = APIC_OP_XAPIC_WR;
5797 	args->apic_access_address = apic_access_address;
5798 	args->reg = reg;
5799 	args->val = val;
5800 
5801 	/* Setup virtual APIC page */
5802 	if (virtualized || !expectation->virtualize_apic_accesses) {
5803 		apic_access_address[apic_reg_index(reg)] = 0;
5804 		virtual_apic_page[apic_reg_index(reg)] = 0;
5805 	}
5806 
5807 	/* Enter guest */
5808 	enter_guest();
5809 
5810 	/*
5811 	 * Validate the behavior and
5812 	 * pass a magic value back to the guest.
5813 	 */
5814 	if (exit_reason_want == VMX_APIC_ACCESS) {
5815 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5816 
5817 		assert_exit_reason(exit_reason_want);
5818 		report(apic_page_offset == reg,
5819 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5820 		       apic_page_offset, reg);
5821 		skip_exit_insn();
5822 
5823 		/* Reenter guest so it can consume/check rcx and exit again. */
5824 		enter_guest();
5825 	} else if (exit_reason_want == VMX_APIC_WRITE) {
5826 		assert_exit_reason(exit_reason_want);
5827 		report(virtual_apic_page[apic_reg_index(reg)] == val,
5828 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%x",
5829 		       apic_reg_index(reg),
5830 		       virtual_apic_page[apic_reg_index(reg)], val);
5831 		checked = true;
5832 
5833 		/* Reenter guest so it can consume/check rcx and exit again. */
5834 		enter_guest();
5835 	} else if (exit_reason_want != VMX_VMCALL) {
5836 		report(false, "Oops, bad exit expectation: %u.",
5837 		       exit_reason_want);
5838 	}
5839 
5840 	assert_exit_reason(VMX_VMCALL);
5841 	if (virtualized && !checked) {
5842 		u32 want = expectation->virt_fn(val);
5843 		u32 got = virtual_apic_page[apic_reg_index(reg)];
5844 		got = expectation->virt_fn(got);
5845 
5846 		report(got == want, "exitless write; val is 0x%x, want 0x%x",
5847 		       got, want);
5848 	} else if (!expectation->virtualize_apic_accesses && !checked) {
5849 		u32 got = apic_access_address[apic_reg_index(reg)];
5850 
5851 		report(got == val,
5852 		       "non-virtualized write; val is 0x%x, want 0x%x", got,
5853 		       val);
5854 	} else if (!expectation->virtualize_apic_accesses && checked) {
5855 		report(false,
5856 		       "Non-virtualized write was prematurely checked!");
5857 	}
5858 
5859 	skip_exit_vmcall();
5860 	report_prefix_pop();
5861 }
5862 
5863 enum Config_type {
5864 	CONFIG_TYPE_GOOD,
5865 	CONFIG_TYPE_UNSUPPORTED,
5866 	CONFIG_TYPE_VMENTRY_FAILS_EARLY,
5867 };
5868 
5869 static enum Config_type configure_apic_reg_virt_test(
5870 	struct apic_reg_virt_config *apic_reg_virt_config)
5871 {
5872 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5873 	u32 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
5874 	/* Configs where L2 entry fails early, due to invalid controls. */
5875 	bool use_tpr_shadow_incorrectly_off =
5876 		!apic_reg_virt_config->use_tpr_shadow &&
5877 		(apic_reg_virt_config->apic_register_virtualization ||
5878 		 apic_reg_virt_config->virtualize_x2apic_mode) &&
5879 		apic_reg_virt_config->activate_secondary_controls;
5880 	bool virtualize_apic_accesses_incorrectly_on =
5881 		apic_reg_virt_config->virtualize_apic_accesses &&
5882 		apic_reg_virt_config->virtualize_x2apic_mode &&
5883 		apic_reg_virt_config->activate_secondary_controls;
5884 	bool vmentry_fails_early =
5885 		use_tpr_shadow_incorrectly_off ||
5886 		virtualize_apic_accesses_incorrectly_on;
5887 
5888 	if (apic_reg_virt_config->activate_secondary_controls) {
5889 		if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
5890 			printf("VM-execution control \"activate secondary controls\" NOT supported.\n");
5891 			return CONFIG_TYPE_UNSUPPORTED;
5892 		}
5893 		cpu_exec_ctrl0 |= CPU_SECONDARY;
5894 	} else {
5895 		cpu_exec_ctrl0 &= ~CPU_SECONDARY;
5896 	}
5897 
5898 	if (apic_reg_virt_config->virtualize_apic_accesses) {
5899 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES)) {
5900 			printf("VM-execution control \"virtualize APIC accesses\" NOT supported.\n");
5901 			return CONFIG_TYPE_UNSUPPORTED;
5902 		}
5903 		cpu_exec_ctrl1 |= CPU_VIRT_APIC_ACCESSES;
5904 	} else {
5905 		cpu_exec_ctrl1 &= ~CPU_VIRT_APIC_ACCESSES;
5906 	}
5907 
5908 	if (apic_reg_virt_config->use_tpr_shadow) {
5909 		if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
5910 			printf("VM-execution control \"use TPR shadow\" NOT supported.\n");
5911 			return CONFIG_TYPE_UNSUPPORTED;
5912 		}
5913 		cpu_exec_ctrl0 |= CPU_TPR_SHADOW;
5914 	} else {
5915 		cpu_exec_ctrl0 &= ~CPU_TPR_SHADOW;
5916 	}
5917 
5918 	if (apic_reg_virt_config->apic_register_virtualization) {
5919 		if (!(ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT)) {
5920 			printf("VM-execution control \"APIC-register virtualization\" NOT supported.\n");
5921 			return CONFIG_TYPE_UNSUPPORTED;
5922 		}
5923 		cpu_exec_ctrl1 |= CPU_APIC_REG_VIRT;
5924 	} else {
5925 		cpu_exec_ctrl1 &= ~CPU_APIC_REG_VIRT;
5926 	}
5927 
5928 	if (apic_reg_virt_config->virtualize_x2apic_mode) {
5929 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_X2APIC)) {
5930 			printf("VM-execution control \"virtualize x2APIC mode\" NOT supported.\n");
5931 			return CONFIG_TYPE_UNSUPPORTED;
5932 		}
5933 		cpu_exec_ctrl1 |= CPU_VIRT_X2APIC;
5934 	} else {
5935 		cpu_exec_ctrl1 &= ~CPU_VIRT_X2APIC;
5936 	}
5937 
5938 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
5939 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
5940 
5941 	if (vmentry_fails_early)
5942 		return CONFIG_TYPE_VMENTRY_FAILS_EARLY;
5943 
5944 	return CONFIG_TYPE_GOOD;
5945 }
5946 
5947 static bool cpu_has_apicv(void)
5948 {
5949 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
5950 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
5951 		(ctrl_pin_rev.clr & PIN_POST_INTR));
5952 }
5953 
5954 /* Validates APIC register access across valid virtualization configurations. */
5955 static void apic_reg_virt_test(void)
5956 {
5957 	u32 *apic_access_address;
5958 	u32 *virtual_apic_page;
5959 	u64 control;
5960 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5961 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
5962 	int i;
5963 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5964 
5965 	if (!cpu_has_apicv()) {
5966 		report_skip(__func__);
5967 		return;
5968 	}
5969 
5970 	control = cpu_exec_ctrl1;
5971 	control &= ~CPU_VINTD;
5972 	vmcs_write(CPU_EXEC_CTRL1, control);
5973 
5974 	test_set_guest(apic_reg_virt_guest);
5975 
5976 	/*
5977 	 * From the SDM: The 1-setting of the "virtualize APIC accesses"
5978 	 * VM-execution is guaranteed to apply only if translations to the
5979 	 * APIC-access address use a 4-KByte page.
5980 	 */
5981 	apic_access_address = alloc_page();
5982 	force_4k_page(apic_access_address);
5983 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_address));
5984 
5985 	virtual_apic_page = alloc_page();
5986 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
5987 
5988 	for (i = 0; i < ARRAY_SIZE(apic_reg_tests); i++) {
5989 		struct apic_reg_test *apic_reg_test = &apic_reg_tests[i];
5990 		struct apic_reg_virt_config *apic_reg_virt_config =
5991 				&apic_reg_test->apic_reg_virt_config;
5992 		enum Config_type config_type;
5993 		u32 reg;
5994 
5995 		printf("--- %s test ---\n", apic_reg_test->name);
5996 		config_type =
5997 			configure_apic_reg_virt_test(apic_reg_virt_config);
5998 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
5999 			printf("Skip because of missing features.\n");
6000 			continue;
6001 		}
6002 
6003 		if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6004 			enter_guest_with_bad_controls();
6005 			continue;
6006 		}
6007 
6008 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6009 			struct apic_reg_virt_expectation expectation = {};
6010 			bool ok;
6011 
6012 			ok = apic_reg_virt_exit_expectation(
6013 				reg, apic_reg_virt_config, &expectation);
6014 			if (!ok) {
6015 				report(false, "Malformed test.");
6016 				break;
6017 			}
6018 
6019 			test_xapic_rd(reg, &expectation, apic_access_address,
6020 				      virtual_apic_page);
6021 			test_xapic_wr(reg, &expectation, apic_access_address,
6022 				      virtual_apic_page);
6023 		}
6024 	}
6025 
6026 	/* Terminate the guest */
6027 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6028 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6029 	args->op = TERMINATE;
6030 	enter_guest();
6031 	assert_exit_reason(VMX_VMCALL);
6032 }
6033 
6034 struct virt_x2apic_mode_config {
6035 	struct apic_reg_virt_config apic_reg_virt_config;
6036 	bool virtual_interrupt_delivery;
6037 	bool use_msr_bitmaps;
6038 	bool disable_x2apic_msr_intercepts;
6039 	bool disable_x2apic;
6040 };
6041 
6042 struct virt_x2apic_mode_test_case {
6043 	const char *name;
6044 	struct virt_x2apic_mode_config virt_x2apic_mode_config;
6045 };
6046 
6047 enum Virt_x2apic_mode_behavior_type {
6048 	X2APIC_ACCESS_VIRTUALIZED,
6049 	X2APIC_ACCESS_PASSED_THROUGH,
6050 	X2APIC_ACCESS_TRIGGERS_GP,
6051 };
6052 
6053 struct virt_x2apic_mode_expectation {
6054 	enum Reason rd_exit_reason;
6055 	enum Reason wr_exit_reason;
6056 
6057 	/*
6058 	 * RDMSR and WRMSR handle 64-bit values. However, except for ICR, all of
6059 	 * the x2APIC registers are 32 bits. Notice:
6060 	 *   1. vmx_x2apic_read() clears the upper 32 bits for 32-bit registers.
6061 	 *   2. vmx_x2apic_write() expects the val arg to be well-formed.
6062 	 */
6063 	u64 rd_val;
6064 	u64 wr_val;
6065 
6066 	/*
6067 	 * Compares input to virtualized output;
6068 	 * 1st arg is pointer to return expected virtualization output.
6069 	 */
6070 	u64 (*virt_fn)(u64);
6071 
6072 	enum Virt_x2apic_mode_behavior_type rd_behavior;
6073 	enum Virt_x2apic_mode_behavior_type wr_behavior;
6074 	bool wr_only;
6075 };
6076 
6077 static u64 virt_x2apic_mode_identity(u64 val)
6078 {
6079 	return val;
6080 }
6081 
6082 static u64 virt_x2apic_mode_nibble1(u64 val)
6083 {
6084 	return val & 0xf0;
6085 }
6086 
6087 static void virt_x2apic_mode_rd_expectation(
6088 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6089 	bool apic_register_virtualization, bool virtual_interrupt_delivery,
6090 	struct virt_x2apic_mode_expectation *expectation)
6091 {
6092 	bool readable =
6093 		!x2apic_reg_reserved(reg) &&
6094 		reg != APIC_EOI;
6095 
6096 	expectation->rd_exit_reason = VMX_VMCALL;
6097 	expectation->virt_fn = virt_x2apic_mode_identity;
6098 	if (virt_x2apic_mode_on && apic_register_virtualization) {
6099 		expectation->rd_val = MAGIC_VAL_1;
6100 		if (reg == APIC_PROCPRI && virtual_interrupt_delivery)
6101 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6102 		else if (reg == APIC_TASKPRI)
6103 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6104 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6105 	} else if (virt_x2apic_mode_on && !apic_register_virtualization &&
6106 		   reg == APIC_TASKPRI) {
6107 		expectation->rd_val = MAGIC_VAL_1;
6108 		expectation->virt_fn = virt_x2apic_mode_nibble1;
6109 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6110 	} else if (!disable_x2apic && readable) {
6111 		expectation->rd_val = apic_read(reg);
6112 		expectation->rd_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6113 	} else {
6114 		expectation->rd_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6115 	}
6116 }
6117 
6118 /*
6119  * get_x2apic_wr_val() creates an innocuous write value for an x2APIC register.
6120  *
6121  * For writable registers, get_x2apic_wr_val() deposits the write value into the
6122  * val pointer arg and returns true. For non-writable registers, val is not
6123  * modified and get_x2apic_wr_val() returns false.
6124  */
6125 static bool get_x2apic_wr_val(u32 reg, u64 *val)
6126 {
6127 	switch (reg) {
6128 	case APIC_TASKPRI:
6129 		/* Bits 31:8 are reserved. */
6130 		*val &= 0xff;
6131 		break;
6132 	case APIC_EOI:
6133 	case APIC_ESR:
6134 	case APIC_TMICT:
6135 		/*
6136 		 * EOI, ESR: WRMSR of a non-zero value causes #GP(0).
6137 		 * TMICT: A write of 0 to the initial-count register effectively
6138 		 *        stops the local APIC timer, in both one-shot and
6139 		 *        periodic mode.
6140 		 */
6141 		*val = 0;
6142 		break;
6143 	case APIC_SPIV:
6144 	case APIC_LVTT:
6145 	case APIC_LVTTHMR:
6146 	case APIC_LVTPC:
6147 	case APIC_LVT0:
6148 	case APIC_LVT1:
6149 	case APIC_LVTERR:
6150 	case APIC_TDCR:
6151 		/*
6152 		 * To avoid writing a 1 to a reserved bit or causing some other
6153 		 * unintended side effect, read the current value and use it as
6154 		 * the write value.
6155 		 */
6156 		*val = apic_read(reg);
6157 		break;
6158 	case APIC_CMCI:
6159 		if (!apic_lvt_entry_supported(6))
6160 			return false;
6161 		*val = apic_read(reg);
6162 		break;
6163 	case APIC_ICR:
6164 		*val = 0x40000 | 0xf1;
6165 		break;
6166 	case APIC_SELF_IPI:
6167 		/*
6168 		 * With special processing (i.e., virtualize x2APIC mode +
6169 		 * virtual interrupt delivery), writing zero causes an
6170 		 * APIC-write VM exit. We plan to add a test for enabling
6171 		 * "virtual-interrupt delivery" in VMCS12, and that's where we
6172 		 * will test a self IPI with special processing.
6173 		 */
6174 		*val = 0x0;
6175 		break;
6176 	default:
6177 		return false;
6178 	}
6179 
6180 	return true;
6181 }
6182 
6183 static bool special_processing_applies(u32 reg, u64 *val,
6184 				       bool virt_int_delivery)
6185 {
6186 	bool special_processing =
6187 		(reg == APIC_TASKPRI) ||
6188 		(virt_int_delivery &&
6189 		 (reg == APIC_EOI || reg == APIC_SELF_IPI));
6190 
6191 	if (special_processing) {
6192 		TEST_ASSERT(get_x2apic_wr_val(reg, val));
6193 		return true;
6194 	}
6195 
6196 	return false;
6197 }
6198 
6199 static void virt_x2apic_mode_wr_expectation(
6200 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6201 	bool virt_int_delivery,
6202 	struct virt_x2apic_mode_expectation *expectation)
6203 {
6204 	expectation->wr_exit_reason = VMX_VMCALL;
6205 	expectation->wr_val = MAGIC_VAL_1;
6206 	expectation->wr_only = false;
6207 
6208 	if (virt_x2apic_mode_on &&
6209 	    special_processing_applies(reg, &expectation->wr_val,
6210 				       virt_int_delivery)) {
6211 		expectation->wr_behavior = X2APIC_ACCESS_VIRTUALIZED;
6212 		if (reg == APIC_SELF_IPI)
6213 			expectation->wr_exit_reason = VMX_APIC_WRITE;
6214 	} else if (!disable_x2apic &&
6215 		   get_x2apic_wr_val(reg, &expectation->wr_val)) {
6216 		expectation->wr_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6217 		if (reg == APIC_EOI || reg == APIC_SELF_IPI)
6218 			expectation->wr_only = true;
6219 		if (reg == APIC_ICR)
6220 			expectation->wr_exit_reason = VMX_EXTINT;
6221 	} else {
6222 		expectation->wr_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6223 		/*
6224 		 * Writing 1 to a reserved bit triggers a #GP.
6225 		 * Thus, set the write value to 0, which seems
6226 		 * the most likely to detect a missed #GP.
6227 		 */
6228 		expectation->wr_val = 0;
6229 	}
6230 }
6231 
6232 static void virt_x2apic_mode_exit_expectation(
6233 	u32 reg, struct virt_x2apic_mode_config *config,
6234 	struct virt_x2apic_mode_expectation *expectation)
6235 {
6236 	struct apic_reg_virt_config *base_config =
6237 		&config->apic_reg_virt_config;
6238 	bool virt_x2apic_mode_on =
6239 		base_config->virtualize_x2apic_mode &&
6240 		config->use_msr_bitmaps &&
6241 		config->disable_x2apic_msr_intercepts &&
6242 		base_config->activate_secondary_controls;
6243 
6244 	virt_x2apic_mode_wr_expectation(
6245 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6246 		config->virtual_interrupt_delivery, expectation);
6247 	virt_x2apic_mode_rd_expectation(
6248 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6249 		base_config->apic_register_virtualization,
6250 		config->virtual_interrupt_delivery, expectation);
6251 }
6252 
6253 struct virt_x2apic_mode_test_case virt_x2apic_mode_tests[] = {
6254 	/*
6255 	 * Baseline "virtualize x2APIC mode" configuration:
6256 	 *   - virtualize x2APIC mode
6257 	 *   - virtual-interrupt delivery
6258 	 *   - APIC-register virtualization
6259 	 *   - x2APIC MSR intercepts disabled
6260 	 *
6261 	 * Reads come from virtual APIC page, special processing applies to
6262 	 * VTPR, EOI, and SELF IPI, and all other writes pass through to L1
6263 	 * APIC.
6264 	 */
6265 	{
6266 		.name = "Baseline",
6267 		.virt_x2apic_mode_config = {
6268 			.virtual_interrupt_delivery = true,
6269 			.use_msr_bitmaps = true,
6270 			.disable_x2apic_msr_intercepts = true,
6271 			.disable_x2apic = false,
6272 			.apic_reg_virt_config = {
6273 				.apic_register_virtualization = true,
6274 				.use_tpr_shadow = true,
6275 				.virtualize_apic_accesses = false,
6276 				.virtualize_x2apic_mode = true,
6277 				.activate_secondary_controls = true,
6278 			},
6279 		},
6280 	},
6281 	{
6282 		.name = "Baseline w/ x2apic disabled",
6283 		.virt_x2apic_mode_config = {
6284 			.virtual_interrupt_delivery = true,
6285 			.use_msr_bitmaps = true,
6286 			.disable_x2apic_msr_intercepts = true,
6287 			.disable_x2apic = true,
6288 			.apic_reg_virt_config = {
6289 				.apic_register_virtualization = true,
6290 				.use_tpr_shadow = true,
6291 				.virtualize_apic_accesses = false,
6292 				.virtualize_x2apic_mode = true,
6293 				.activate_secondary_controls = true,
6294 			},
6295 		},
6296 	},
6297 
6298 	/*
6299 	 * Baseline, minus virtual-interrupt delivery. Reads come from virtual
6300 	 * APIC page, special processing applies to VTPR, and all other writes
6301 	 * pass through to L1 APIC.
6302 	 */
6303 	{
6304 		.name = "Baseline - virtual interrupt delivery",
6305 		.virt_x2apic_mode_config = {
6306 			.virtual_interrupt_delivery = false,
6307 			.use_msr_bitmaps = true,
6308 			.disable_x2apic_msr_intercepts = true,
6309 			.disable_x2apic = false,
6310 			.apic_reg_virt_config = {
6311 				.apic_register_virtualization = true,
6312 				.use_tpr_shadow = true,
6313 				.virtualize_apic_accesses = false,
6314 				.virtualize_x2apic_mode = true,
6315 				.activate_secondary_controls = true,
6316 			},
6317 		},
6318 	},
6319 
6320 	/*
6321 	 * Baseline, minus APIC-register virtualization. x2APIC reads pass
6322 	 * through to L1's APIC, unless reading VTPR
6323 	 */
6324 	{
6325 		.name = "Virtualize x2APIC mode, no APIC reg virt",
6326 		.virt_x2apic_mode_config = {
6327 			.virtual_interrupt_delivery = true,
6328 			.use_msr_bitmaps = true,
6329 			.disable_x2apic_msr_intercepts = true,
6330 			.disable_x2apic = false,
6331 			.apic_reg_virt_config = {
6332 				.apic_register_virtualization = false,
6333 				.use_tpr_shadow = true,
6334 				.virtualize_apic_accesses = false,
6335 				.virtualize_x2apic_mode = true,
6336 				.activate_secondary_controls = true,
6337 			},
6338 		},
6339 	},
6340 	{
6341 		.name = "Virtualize x2APIC mode, no APIC reg virt, x2APIC off",
6342 		.virt_x2apic_mode_config = {
6343 			.virtual_interrupt_delivery = true,
6344 			.use_msr_bitmaps = true,
6345 			.disable_x2apic_msr_intercepts = true,
6346 			.disable_x2apic = true,
6347 			.apic_reg_virt_config = {
6348 				.apic_register_virtualization = false,
6349 				.use_tpr_shadow = true,
6350 				.virtualize_apic_accesses = false,
6351 				.virtualize_x2apic_mode = true,
6352 				.activate_secondary_controls = true,
6353 			},
6354 		},
6355 	},
6356 
6357 	/*
6358 	 * Enable "virtualize x2APIC mode" and "APIC-register virtualization",
6359 	 * and disable intercepts for the x2APIC MSRs, but fail to enable
6360 	 * "activate secondary controls" (i.e. L2 gets access to L1's x2APIC
6361 	 * MSRs).
6362 	 */
6363 	{
6364 		.name = "Fail to enable activate secondary controls",
6365 		.virt_x2apic_mode_config = {
6366 			.virtual_interrupt_delivery = true,
6367 			.use_msr_bitmaps = true,
6368 			.disable_x2apic_msr_intercepts = true,
6369 			.disable_x2apic = false,
6370 			.apic_reg_virt_config = {
6371 				.apic_register_virtualization = true,
6372 				.use_tpr_shadow = true,
6373 				.virtualize_apic_accesses = false,
6374 				.virtualize_x2apic_mode = true,
6375 				.activate_secondary_controls = false,
6376 			},
6377 		},
6378 	},
6379 
6380 	/*
6381 	 * Enable "APIC-register virtualization" and enable "activate secondary
6382 	 * controls" and disable intercepts for the x2APIC MSRs, but do not
6383 	 * enable the "virtualize x2APIC mode" VM-execution control (i.e. L2
6384 	 * gets access to L1's x2APIC MSRs).
6385 	 */
6386 	{
6387 		.name = "Fail to enable virtualize x2APIC mode",
6388 		.virt_x2apic_mode_config = {
6389 			.virtual_interrupt_delivery = true,
6390 			.use_msr_bitmaps = true,
6391 			.disable_x2apic_msr_intercepts = true,
6392 			.disable_x2apic = false,
6393 			.apic_reg_virt_config = {
6394 				.apic_register_virtualization = true,
6395 				.use_tpr_shadow = true,
6396 				.virtualize_apic_accesses = false,
6397 				.virtualize_x2apic_mode = false,
6398 				.activate_secondary_controls = true,
6399 			},
6400 		},
6401 	},
6402 
6403 	/*
6404 	 * Disable "Virtualize x2APIC mode", disable x2APIC MSR intercepts, and
6405 	 * enable "APIC-register virtualization" --> L2 gets L1's x2APIC MSRs.
6406 	 */
6407 	{
6408 		.name = "Baseline",
6409 		.virt_x2apic_mode_config = {
6410 			.virtual_interrupt_delivery = true,
6411 			.use_msr_bitmaps = true,
6412 			.disable_x2apic_msr_intercepts = true,
6413 			.disable_x2apic = false,
6414 			.apic_reg_virt_config = {
6415 				.apic_register_virtualization = true,
6416 				.use_tpr_shadow = true,
6417 				.virtualize_apic_accesses = false,
6418 				.virtualize_x2apic_mode = false,
6419 				.activate_secondary_controls = true,
6420 			},
6421 		},
6422 	},
6423 };
6424 
6425 enum X2apic_op {
6426 	X2APIC_OP_RD,
6427 	X2APIC_OP_WR,
6428 	X2APIC_TERMINATE,
6429 };
6430 
6431 static u64 vmx_x2apic_read(u32 reg)
6432 {
6433 	u32 msr_addr = x2apic_msr(reg);
6434 	u64 val;
6435 
6436 	val = rdmsr(msr_addr);
6437 
6438 	return val;
6439 }
6440 
6441 static void vmx_x2apic_write(u32 reg, u64 val)
6442 {
6443 	u32 msr_addr = x2apic_msr(reg);
6444 
6445 	wrmsr(msr_addr, val);
6446 }
6447 
6448 struct virt_x2apic_mode_guest_args {
6449 	enum X2apic_op op;
6450 	u32 reg;
6451 	u64 val;
6452 	bool should_gp;
6453 	u64 (*virt_fn)(u64);
6454 } virt_x2apic_mode_guest_args;
6455 
6456 static volatile bool handle_x2apic_gp_ran;
6457 static volatile u32 handle_x2apic_gp_insn_len;
6458 static void handle_x2apic_gp(struct ex_regs *regs)
6459 {
6460 	handle_x2apic_gp_ran = true;
6461 	regs->rip += handle_x2apic_gp_insn_len;
6462 }
6463 
6464 static handler setup_x2apic_gp_handler(void)
6465 {
6466 	handler old_handler;
6467 
6468 	old_handler = handle_exception(GP_VECTOR, handle_x2apic_gp);
6469 	/* RDMSR and WRMSR are both 2 bytes, assuming no prefixes. */
6470 	handle_x2apic_gp_insn_len = 2;
6471 
6472 	return old_handler;
6473 }
6474 
6475 static void teardown_x2apic_gp_handler(handler old_handler)
6476 {
6477 	handle_exception(GP_VECTOR, old_handler);
6478 
6479 	/*
6480 	 * Defensively reset instruction length, so that if the handler is
6481 	 * incorrectly used, it will loop infinitely, rather than run off into
6482 	 * la la land.
6483 	 */
6484 	handle_x2apic_gp_insn_len = 0;
6485 	handle_x2apic_gp_ran = false;
6486 }
6487 
6488 static void virt_x2apic_mode_guest(void)
6489 {
6490 	volatile struct virt_x2apic_mode_guest_args *args =
6491 		&virt_x2apic_mode_guest_args;
6492 
6493 	for (;;) {
6494 		enum X2apic_op op = args->op;
6495 		u32 reg = args->reg;
6496 		u64 val = args->val;
6497 		bool should_gp = args->should_gp;
6498 		u64 (*virt_fn)(u64) = args->virt_fn;
6499 		handler old_handler;
6500 
6501 		if (op == X2APIC_TERMINATE)
6502 			break;
6503 
6504 		if (should_gp) {
6505 			TEST_ASSERT(!handle_x2apic_gp_ran);
6506 			old_handler = setup_x2apic_gp_handler();
6507 		}
6508 
6509 		if (op == X2APIC_OP_RD) {
6510 			u64 ret = vmx_x2apic_read(reg);
6511 
6512 			if (!should_gp) {
6513 				u64 want = virt_fn(val);
6514 				u64 got = virt_fn(ret);
6515 
6516 				report(got == want,
6517 				       "APIC read; got 0x%lx, want 0x%lx.",
6518 				       got, want);
6519 			}
6520 		} else if (op == X2APIC_OP_WR) {
6521 			vmx_x2apic_write(reg, val);
6522 		}
6523 
6524 		if (should_gp) {
6525 			report(handle_x2apic_gp_ran,
6526 			       "x2APIC op triggered GP.");
6527 			teardown_x2apic_gp_handler(old_handler);
6528 		}
6529 
6530 		/*
6531 		 * The L1 should always execute a vmcall after it's done testing
6532 		 * an individual APIC operation. This helps to validate that the
6533 		 * L1 and L2 are in sync with each other, as expected.
6534 		 */
6535 		vmcall();
6536 	}
6537 }
6538 
6539 static void test_x2apic_rd(
6540 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6541 	u32 *virtual_apic_page)
6542 {
6543 	u64 val = expectation->rd_val;
6544 	u32 exit_reason_want = expectation->rd_exit_reason;
6545 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6546 
6547 	report_prefix_pushf("x2apic - reading 0x%03x", reg);
6548 
6549 	/* Configure guest to do an x2apic read */
6550 	args->op = X2APIC_OP_RD;
6551 	args->reg = reg;
6552 	args->val = val;
6553 	args->should_gp = expectation->rd_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6554 	args->virt_fn = expectation->virt_fn;
6555 
6556 	/* Setup virtual APIC page */
6557 	if (expectation->rd_behavior == X2APIC_ACCESS_VIRTUALIZED)
6558 		virtual_apic_page[apic_reg_index(reg)] = (u32)val;
6559 
6560 	/* Enter guest */
6561 	enter_guest();
6562 
6563 	if (exit_reason_want != VMX_VMCALL) {
6564 		report(false, "Oops, bad exit expectation: %u.",
6565 		       exit_reason_want);
6566 	}
6567 
6568 	skip_exit_vmcall();
6569 	report_prefix_pop();
6570 }
6571 
6572 static volatile bool handle_x2apic_ipi_ran;
6573 static void handle_x2apic_ipi(isr_regs_t *regs)
6574 {
6575 	handle_x2apic_ipi_ran = true;
6576 	eoi();
6577 }
6578 
6579 static void test_x2apic_wr(
6580 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6581 	u32 *virtual_apic_page)
6582 {
6583 	u64 val = expectation->wr_val;
6584 	u32 exit_reason_want = expectation->wr_exit_reason;
6585 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6586 	int ipi_vector = 0xf1;
6587 	u32 restore_val = 0;
6588 
6589 	report_prefix_pushf("x2apic - writing 0x%lx to 0x%03x", val, reg);
6590 
6591 	/* Configure guest to do an x2apic read */
6592 	args->op = X2APIC_OP_WR;
6593 	args->reg = reg;
6594 	args->val = val;
6595 	args->should_gp = expectation->wr_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6596 
6597 	/* Setup virtual APIC page */
6598 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED)
6599 		virtual_apic_page[apic_reg_index(reg)] = 0;
6600 	if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH && !expectation->wr_only)
6601 		restore_val = apic_read(reg);
6602 
6603 	/* Setup IPI handler */
6604 	handle_x2apic_ipi_ran = false;
6605 	handle_irq(ipi_vector, handle_x2apic_ipi);
6606 
6607 	/* Enter guest */
6608 	enter_guest();
6609 
6610 	/*
6611 	 * Validate the behavior and
6612 	 * pass a magic value back to the guest.
6613 	 */
6614 	if (exit_reason_want == VMX_EXTINT) {
6615 		assert_exit_reason(exit_reason_want);
6616 
6617 		/* Clear the external interrupt. */
6618 		irq_enable();
6619 		asm volatile ("nop");
6620 		irq_disable();
6621 		report(handle_x2apic_ipi_ran,
6622 		       "Got pending interrupt after IRQ enabled.");
6623 
6624 		enter_guest();
6625 	} else if (exit_reason_want == VMX_APIC_WRITE) {
6626 		assert_exit_reason(exit_reason_want);
6627 		report(virtual_apic_page[apic_reg_index(reg)] == val,
6628 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%lx",
6629 		       apic_reg_index(reg),
6630 		       virtual_apic_page[apic_reg_index(reg)], val);
6631 
6632 		/* Reenter guest so it can consume/check rcx and exit again. */
6633 		enter_guest();
6634 	} else if (exit_reason_want != VMX_VMCALL) {
6635 		report(false, "Oops, bad exit expectation: %u.",
6636 		       exit_reason_want);
6637 	}
6638 
6639 	assert_exit_reason(VMX_VMCALL);
6640 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED) {
6641 		u64 want = val;
6642 		u32 got = virtual_apic_page[apic_reg_index(reg)];
6643 
6644 		report(got == want, "x2APIC write; got 0x%x, want 0x%lx", got,
6645 		       want);
6646 	} else if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH) {
6647 		if (!expectation->wr_only) {
6648 			u32 got = apic_read(reg);
6649 			bool ok;
6650 
6651 			/*
6652 			 * When L1's TPR is passed through to L2, the lower
6653 			 * nibble can be lost. For example, if L2 executes
6654 			 * WRMSR(0x808, 0x78), then, L1 might read 0x70.
6655 			 *
6656 			 * Here's how the lower nibble can get lost:
6657 			 *   1. L2 executes WRMSR(0x808, 0x78).
6658 			 *   2. L2 exits to L0 with a WRMSR exit.
6659 			 *   3. L0 emulates WRMSR, by writing L1's TPR.
6660 			 *   4. L0 re-enters L2.
6661 			 *   5. L2 exits to L0 (reason doesn't matter).
6662 			 *   6. L0 reflects L2's exit to L1.
6663 			 *   7. Before entering L1, L0 exits to user-space
6664 			 *      (e.g., to satisfy TPR access reporting).
6665 			 *   8. User-space executes KVM_SET_REGS ioctl, which
6666 			 *      clears the lower nibble of L1's TPR.
6667 			 */
6668 			if (reg == APIC_TASKPRI) {
6669 				got = apic_virt_nibble1(got);
6670 				val = apic_virt_nibble1(val);
6671 			}
6672 
6673 			ok = got == val;
6674 			report(ok,
6675 			       "non-virtualized write; val is 0x%x, want 0x%lx",
6676 			       got, val);
6677 			apic_write(reg, restore_val);
6678 		} else {
6679 			report(true, "non-virtualized and write-only OK");
6680 		}
6681 	}
6682 	skip_exit_insn();
6683 
6684 	report_prefix_pop();
6685 }
6686 
6687 static enum Config_type configure_virt_x2apic_mode_test(
6688 	struct virt_x2apic_mode_config *virt_x2apic_mode_config,
6689 	u8 *msr_bitmap_page)
6690 {
6691 	int msr;
6692 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6693 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6694 
6695 	/* x2apic-specific VMCS config */
6696 	if (virt_x2apic_mode_config->use_msr_bitmaps) {
6697 		/* virt_x2apic_mode_test() checks for MSR bitmaps support */
6698 		cpu_exec_ctrl0 |= CPU_MSR_BITMAP;
6699 	} else {
6700 		cpu_exec_ctrl0 &= ~CPU_MSR_BITMAP;
6701 	}
6702 
6703 	if (virt_x2apic_mode_config->virtual_interrupt_delivery) {
6704 		if (!(ctrl_cpu_rev[1].clr & CPU_VINTD)) {
6705 			report_skip("VM-execution control \"virtual-interrupt delivery\" NOT supported.\n");
6706 			return CONFIG_TYPE_UNSUPPORTED;
6707 		}
6708 		cpu_exec_ctrl1 |= CPU_VINTD;
6709 	} else {
6710 		cpu_exec_ctrl1 &= ~CPU_VINTD;
6711 	}
6712 
6713 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6714 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6715 
6716 	/* x2APIC MSR intercepts are usually off for "Virtualize x2APIC mode" */
6717 	for (msr = 0x800; msr <= 0x8ff; msr++) {
6718 		if (virt_x2apic_mode_config->disable_x2apic_msr_intercepts) {
6719 			clear_bit(msr, msr_bitmap_page + 0x000);
6720 			clear_bit(msr, msr_bitmap_page + 0x800);
6721 		} else {
6722 			set_bit(msr, msr_bitmap_page + 0x000);
6723 			set_bit(msr, msr_bitmap_page + 0x800);
6724 		}
6725 	}
6726 
6727 	/* x2APIC mode can impact virtualization */
6728 	reset_apic();
6729 	if (!virt_x2apic_mode_config->disable_x2apic)
6730 		enable_x2apic();
6731 
6732 	return configure_apic_reg_virt_test(
6733 		&virt_x2apic_mode_config->apic_reg_virt_config);
6734 }
6735 
6736 static void virt_x2apic_mode_test(void)
6737 {
6738 	u32 *virtual_apic_page;
6739 	u8 *msr_bitmap_page;
6740 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6741 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6742 	int i;
6743 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6744 
6745 	if (!cpu_has_apicv()) {
6746 		report_skip(__func__);
6747 		return;
6748 	}
6749 
6750 	/*
6751 	 * This is to exercise an issue in KVM's logic to merge L0's and L1's
6752 	 * MSR bitmaps. Previously, an L1 could get at L0's x2APIC MSRs by
6753 	 * writing the IA32_SPEC_CTRL MSR or the IA32_PRED_CMD MSRs. KVM would
6754 	 * then proceed to manipulate the MSR bitmaps, as if VMCS12 had the
6755 	 * "Virtualize x2APIC mod" control set, even when it didn't.
6756 	 */
6757 	if (has_spec_ctrl())
6758 		wrmsr(MSR_IA32_SPEC_CTRL, 1);
6759 
6760 	/*
6761 	 * Check that VMCS12 supports:
6762 	 *   - "Virtual-APIC address", indicated by "use TPR shadow"
6763 	 *   - "MSR-bitmap address", indicated by "use MSR bitmaps"
6764 	 */
6765 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
6766 		report_skip("VM-execution control \"use TPR shadow\" NOT supported.\n");
6767 		return;
6768 	} else if (!(ctrl_cpu_rev[0].clr & CPU_MSR_BITMAP)) {
6769 		report_skip("VM-execution control \"use MSR bitmaps\" NOT supported.\n");
6770 		return;
6771 	}
6772 
6773 	test_set_guest(virt_x2apic_mode_guest);
6774 
6775 	virtual_apic_page = alloc_page();
6776 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
6777 
6778 	msr_bitmap_page = alloc_page();
6779 	memset(msr_bitmap_page, 0xff, PAGE_SIZE);
6780 	vmcs_write(MSR_BITMAP, virt_to_phys(msr_bitmap_page));
6781 
6782 	for (i = 0; i < ARRAY_SIZE(virt_x2apic_mode_tests); i++) {
6783 		struct virt_x2apic_mode_test_case *virt_x2apic_mode_test_case =
6784 			&virt_x2apic_mode_tests[i];
6785 		struct virt_x2apic_mode_config *virt_x2apic_mode_config =
6786 			&virt_x2apic_mode_test_case->virt_x2apic_mode_config;
6787 		enum Config_type config_type;
6788 		u32 reg;
6789 
6790 		printf("--- %s test ---\n", virt_x2apic_mode_test_case->name);
6791 		config_type =
6792 			configure_virt_x2apic_mode_test(virt_x2apic_mode_config,
6793 							msr_bitmap_page);
6794 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
6795 			report_skip("Skip because of missing features.\n");
6796 			continue;
6797 		} else if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6798 			enter_guest_with_bad_controls();
6799 			continue;
6800 		}
6801 
6802 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6803 			struct virt_x2apic_mode_expectation expectation;
6804 
6805 			virt_x2apic_mode_exit_expectation(
6806 				reg, virt_x2apic_mode_config, &expectation);
6807 
6808 			test_x2apic_rd(reg, &expectation, virtual_apic_page);
6809 			test_x2apic_wr(reg, &expectation, virtual_apic_page);
6810 		}
6811 	}
6812 
6813 
6814 	/* Terminate the guest */
6815 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6816 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6817 	args->op = X2APIC_TERMINATE;
6818 	enter_guest();
6819 	assert_exit_reason(VMX_VMCALL);
6820 }
6821 
6822 static void test_ctl_reg(const char *cr_name, u64 cr, u64 fixed0, u64 fixed1)
6823 {
6824 	u64 val;
6825 	u64 cr_saved = vmcs_read(cr);
6826 	int i;
6827 
6828 	val = fixed0 & fixed1;
6829 	if (cr == HOST_CR4)
6830 		vmcs_write(cr, val | X86_CR4_PAE);
6831 	else
6832 		vmcs_write(cr, val);
6833 	report_prefix_pushf("%s %lx", cr_name, val);
6834 	if (val == fixed0)
6835 		test_vmx_vmlaunch(0);
6836 	else
6837 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6838 	report_prefix_pop();
6839 
6840 	for (i = 0; i < 64; i++) {
6841 
6842 		/* Set a bit when the corresponding bit in fixed1 is 0 */
6843 		if ((fixed1 & (1ull << i)) == 0) {
6844 			if (cr == HOST_CR4 && ((1ull << i) & X86_CR4_SMEP ||
6845 					       (1ull << i) & X86_CR4_SMAP))
6846 				continue;
6847 
6848 			vmcs_write(cr, cr_saved | (1ull << i));
6849 			report_prefix_pushf("%s %llx", cr_name,
6850 						cr_saved | (1ull << i));
6851 			test_vmx_vmlaunch(
6852 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6853 			report_prefix_pop();
6854 		}
6855 
6856 		/* Unset a bit when the corresponding bit in fixed0 is 1 */
6857 		if (fixed0 & (1ull << i)) {
6858 			vmcs_write(cr, cr_saved & ~(1ull << i));
6859 			report_prefix_pushf("%s %llx", cr_name,
6860 						cr_saved & ~(1ull << i));
6861 			test_vmx_vmlaunch(
6862 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6863 			report_prefix_pop();
6864 		}
6865 	}
6866 
6867 	vmcs_write(cr, cr_saved);
6868 }
6869 
6870 /*
6871  * 1. The CR0 field must not set any bit to a value not supported in VMX
6872  *    operation.
6873  * 2. The CR4 field must not set any bit to a value not supported in VMX
6874  *    operation.
6875  * 3. On processors that support Intel 64 architecture, the CR3 field must
6876  *    be such that bits 63:52 and bits in the range 51:32 beyond the
6877  *    processor’s physical-address width must be 0.
6878  *
6879  *  [Intel SDM]
6880  */
6881 static void test_host_ctl_regs(void)
6882 {
6883 	u64 fixed0, fixed1, cr3, cr3_saved;
6884 	int i;
6885 
6886 	/* Test CR0 */
6887 	fixed0 = rdmsr(MSR_IA32_VMX_CR0_FIXED0);
6888 	fixed1 = rdmsr(MSR_IA32_VMX_CR0_FIXED1);
6889 	test_ctl_reg("HOST_CR0", HOST_CR0, fixed0, fixed1);
6890 
6891 	/* Test CR4 */
6892 	fixed0 = rdmsr(MSR_IA32_VMX_CR4_FIXED0);
6893 	fixed1 = rdmsr(MSR_IA32_VMX_CR4_FIXED1) &
6894 		 ~(X86_CR4_SMEP | X86_CR4_SMAP);
6895 	test_ctl_reg("HOST_CR4", HOST_CR4, fixed0, fixed1);
6896 
6897 	/* Test CR3 */
6898 	cr3_saved = vmcs_read(HOST_CR3);
6899 	for (i = cpuid_maxphyaddr(); i < 64; i++) {
6900 		cr3 = cr3_saved | (1ul << i);
6901 		vmcs_write(HOST_CR3, cr3);
6902 		report_prefix_pushf("HOST_CR3 %lx", cr3);
6903 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6904 		report_prefix_pop();
6905 	}
6906 
6907 	vmcs_write(HOST_CR3, cr3_saved);
6908 }
6909 
6910 static void test_efer_vmlaunch(u32 fld, bool ok)
6911 {
6912 	if (fld == HOST_EFER) {
6913 		if (ok)
6914 			test_vmx_vmlaunch(0);
6915 		else
6916 			test_vmx_vmlaunch2(VMXERR_ENTRY_INVALID_CONTROL_FIELD,
6917 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6918 	} else {
6919 		test_guest_state("EFER test", !ok, GUEST_EFER, "GUEST_EFER");
6920 	}
6921 }
6922 
6923 static void test_efer_one(u32 fld, const char * fld_name, u64 efer,
6924 			  u32 ctrl_fld, u64 ctrl,
6925 			  int i, const char *efer_bit_name)
6926 {
6927 	bool ok;
6928 
6929 	ok = true;
6930 	if (ctrl_fld == EXI_CONTROLS && (ctrl & EXI_LOAD_EFER)) {
6931 		if (!!(efer & EFER_LMA) != !!(ctrl & EXI_HOST_64))
6932 			ok = false;
6933 		if (!!(efer & EFER_LME) != !!(ctrl & EXI_HOST_64))
6934 			ok = false;
6935 	}
6936 	if (ctrl_fld == ENT_CONTROLS && (ctrl & ENT_LOAD_EFER)) {
6937 		/* Check LMA too since CR0.PG is set.  */
6938 		if (!!(efer & EFER_LMA) != !!(ctrl & ENT_GUEST_64))
6939 			ok = false;
6940 		if (!!(efer & EFER_LME) != !!(ctrl & ENT_GUEST_64))
6941 			ok = false;
6942 	}
6943 
6944 	/*
6945 	 * Skip the test if it would enter the guest in 32-bit mode.
6946 	 * Perhaps write the test in assembly and make sure it
6947 	 * can be run in either mode?
6948 	 */
6949 	if (fld == GUEST_EFER && ok && !(ctrl & ENT_GUEST_64))
6950 		return;
6951 
6952 	vmcs_write(ctrl_fld, ctrl);
6953 	vmcs_write(fld, efer);
6954 	report_prefix_pushf("%s %s bit turned %s, controls %s",
6955 			    fld_name, efer_bit_name,
6956 			    (i & 1) ? "on" : "off",
6957 			    (i & 2) ? "on" : "off");
6958 
6959 	test_efer_vmlaunch(fld, ok);
6960 	report_prefix_pop();
6961 }
6962 
6963 static void test_efer_bit(u32 fld, const char * fld_name,
6964 			  u32 ctrl_fld, u64 ctrl_bit, u64 efer_bit,
6965 			  const char *efer_bit_name)
6966 {
6967 	u64 efer_saved = vmcs_read(fld);
6968 	u32 ctrl_saved = vmcs_read(ctrl_fld);
6969 	int i;
6970 
6971 	for (i = 0; i < 4; i++) {
6972 		u64 efer = efer_saved & ~efer_bit;
6973 		u64 ctrl = ctrl_saved & ~ctrl_bit;
6974 
6975 		if (i & 1)
6976 			efer |= efer_bit;
6977 		if (i & 2)
6978 			ctrl |= ctrl_bit;
6979 
6980 		test_efer_one(fld, fld_name, efer, ctrl_fld, ctrl,
6981 			      i, efer_bit_name);
6982 	}
6983 
6984 	vmcs_write(ctrl_fld, ctrl_saved);
6985 	vmcs_write(fld, efer_saved);
6986 }
6987 
6988 static void test_efer(u32 fld, const char * fld_name, u32 ctrl_fld,
6989 		      u64 ctrl_bit1, u64 ctrl_bit2)
6990 {
6991 	u64 efer_saved = vmcs_read(fld);
6992 	u32 ctrl_saved = vmcs_read(ctrl_fld);
6993 	u64 efer_reserved_bits =  ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
6994 	u64 i;
6995 	u64 efer;
6996 
6997 	if (cpu_has_efer_nx())
6998 		efer_reserved_bits &= ~EFER_NX;
6999 
7000 	if (!ctrl_bit1) {
7001 		printf("\"Load-IA32-EFER\" exit control not supported\n");
7002 		goto test_entry_exit_mode;
7003 	}
7004 
7005 	report_prefix_pushf("%s %lx", fld_name, efer_saved);
7006 	test_efer_vmlaunch(fld, true);
7007 	report_prefix_pop();
7008 
7009 	/*
7010 	 * Check reserved bits
7011 	 */
7012 	vmcs_write(ctrl_fld, ctrl_saved & ~ctrl_bit1);
7013 	for (i = 0; i < 64; i++) {
7014 		if ((1ull << i) & efer_reserved_bits) {
7015 			efer = efer_saved | (1ull << i);
7016 			vmcs_write(fld, efer);
7017 			report_prefix_pushf("%s %lx", fld_name, efer);
7018 			test_efer_vmlaunch(fld, true);
7019 			report_prefix_pop();
7020 		}
7021 	}
7022 
7023 	vmcs_write(ctrl_fld, ctrl_saved | ctrl_bit1);
7024 	for (i = 0; i < 64; i++) {
7025 		if ((1ull << i) & efer_reserved_bits) {
7026 			efer = efer_saved | (1ull << i);
7027 			vmcs_write(fld, efer);
7028 			report_prefix_pushf("%s %lx", fld_name, efer);
7029 			test_efer_vmlaunch(fld, false);
7030 			report_prefix_pop();
7031 		}
7032 	}
7033 
7034 	vmcs_write(ctrl_fld, ctrl_saved);
7035 	vmcs_write(fld, efer_saved);
7036 
7037 	/*
7038 	 * Check LMA and LME bits
7039 	 */
7040 	test_efer_bit(fld, fld_name,
7041 		      ctrl_fld, ctrl_bit1,
7042 		      EFER_LMA,
7043 		      "EFER_LMA");
7044 	test_efer_bit(fld, fld_name,
7045 		      ctrl_fld, ctrl_bit1,
7046 		      EFER_LME,
7047 		      "EFER_LME");
7048 
7049 test_entry_exit_mode:
7050 	test_efer_bit(fld, fld_name,
7051 		      ctrl_fld, ctrl_bit2,
7052 		      EFER_LMA,
7053 		      "EFER_LMA");
7054 	test_efer_bit(fld, fld_name,
7055 		      ctrl_fld, ctrl_bit2,
7056 		      EFER_LME,
7057 		      "EFER_LME");
7058 }
7059 
7060 /*
7061  * If the 'load IA32_EFER' VM-exit control is 1, bits reserved in the
7062  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7063  * the values of the LMA and LME bits in the field must each be that of
7064  * the 'host address-space size' VM-exit control.
7065  *
7066  *  [Intel SDM]
7067  */
7068 static void test_host_efer(void)
7069 {
7070 	test_efer(HOST_EFER, "HOST_EFER", EXI_CONTROLS,
7071 		  ctrl_exit_rev.clr & EXI_LOAD_EFER,
7072 		  EXI_HOST_64);
7073 }
7074 
7075 /*
7076  * If the 'load IA32_EFER' VM-enter control is 1, bits reserved in the
7077  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7078  * the values of the LMA and LME bits in the field must each be that of
7079  * the 'IA32e-mode guest' VM-exit control.
7080  */
7081 static void test_guest_efer(void)
7082 {
7083 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER)) {
7084 		printf("\"Load-IA32-EFER\" entry control not supported\n");
7085 		return;
7086 	}
7087 
7088 	vmcs_write(GUEST_EFER, rdmsr(MSR_EFER));
7089 	test_efer(GUEST_EFER, "GUEST_EFER", ENT_CONTROLS,
7090 		  ctrl_enter_rev.clr & ENT_LOAD_EFER,
7091 		  ENT_GUEST_64);
7092 }
7093 
7094 /*
7095  * PAT values higher than 8 are uninteresting since they're likely lumped
7096  * in with "8". We only test values above 8 one bit at a time,
7097  * in order to reduce the number of VM-Entries and keep the runtime reasonable.
7098  */
7099 #define	PAT_VAL_LIMIT	8
7100 
7101 static void test_pat(u32 field, const char * field_name, u32 ctrl_field,
7102 		     u64 ctrl_bit)
7103 {
7104 	u32 ctrl_saved = vmcs_read(ctrl_field);
7105 	u64 pat_saved = vmcs_read(field);
7106 	u64 i, val;
7107 	u32 j;
7108 	int error;
7109 
7110 	vmcs_clear_bits(ctrl_field, ctrl_bit);
7111 
7112 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7113 		/* Test PAT0..PAT7 fields */
7114 		for (j = 0; j < (i ? 8 : 1); j++) {
7115 			val = i << j * 8;
7116 			vmcs_write(field, val);
7117 			if (field == HOST_PAT) {
7118 				report_prefix_pushf("%s %lx", field_name, val);
7119 				test_vmx_vmlaunch(0);
7120 				report_prefix_pop();
7121 
7122 			} else {	// GUEST_PAT
7123 				test_guest_state("ENT_LOAD_PAT enabled", false,
7124 						 val, "GUEST_PAT");
7125 			}
7126 		}
7127 	}
7128 
7129 	vmcs_set_bits(ctrl_field, ctrl_bit);
7130 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7131 		/* Test PAT0..PAT7 fields */
7132 		for (j = 0; j < (i ? 8 : 1); j++) {
7133 			val = i << j * 8;
7134 			vmcs_write(field, val);
7135 
7136 			if (field == HOST_PAT) {
7137 				report_prefix_pushf("%s %lx", field_name, val);
7138 				if (i == 0x2 || i == 0x3 || i >= 0x8)
7139 					error =
7140 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
7141 				else
7142 					error = 0;
7143 
7144 				test_vmx_vmlaunch(error);
7145 				report_prefix_pop();
7146 
7147 			} else {	// GUEST_PAT
7148 				error = (i == 0x2 || i == 0x3 || i >= 0x8);
7149 				test_guest_state("ENT_LOAD_PAT enabled", !!error,
7150 						 val, "GUEST_PAT");
7151 			}
7152 
7153 		}
7154 	}
7155 
7156 	vmcs_write(ctrl_field, ctrl_saved);
7157 	vmcs_write(field, pat_saved);
7158 }
7159 
7160 /*
7161  *  If the "load IA32_PAT" VM-exit control is 1, the value of the field
7162  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7163  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7164  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7165  *  6 (WB), or 7 (UC-).
7166  *
7167  *  [Intel SDM]
7168  */
7169 static void test_load_host_pat(void)
7170 {
7171 	/*
7172 	 * "load IA32_PAT" VM-exit control
7173 	 */
7174 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT)) {
7175 		printf("\"Load-IA32-PAT\" exit control not supported\n");
7176 		return;
7177 	}
7178 
7179 	test_pat(HOST_PAT, "HOST_PAT", EXI_CONTROLS, EXI_LOAD_PAT);
7180 }
7181 
7182 union cpuidA_eax {
7183 	struct {
7184 		unsigned int version_id:8;
7185 		unsigned int num_counters_gp:8;
7186 		unsigned int bit_width:8;
7187 		unsigned int mask_length:8;
7188 	} split;
7189 	unsigned int full;
7190 };
7191 
7192 union cpuidA_edx {
7193 	struct {
7194 		unsigned int num_counters_fixed:5;
7195 		unsigned int bit_width_fixed:8;
7196 		unsigned int reserved:9;
7197 	} split;
7198 	unsigned int full;
7199 };
7200 
7201 static bool valid_pgc(u64 val)
7202 {
7203 	struct cpuid id;
7204 	union cpuidA_eax eax;
7205 	union cpuidA_edx edx;
7206 	u64 mask;
7207 
7208 	id = cpuid(0xA);
7209 	eax.full = id.a;
7210 	edx.full = id.d;
7211 	mask = ~(((1ull << eax.split.num_counters_gp) - 1) |
7212 		 (((1ull << edx.split.num_counters_fixed) - 1) << 32));
7213 
7214 	return !(val & mask);
7215 }
7216 
7217 static void test_pgc_vmlaunch(u32 xerror, u32 xreason, bool xfail, bool host)
7218 {
7219 	u32 inst_err;
7220 	u64 obs;
7221 	bool success;
7222 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7223 
7224 	if (host) {
7225 		success = vmlaunch_succeeds();
7226 		obs = rdmsr(data->msr);
7227 		if (!success) {
7228 			inst_err = vmcs_read(VMX_INST_ERROR);
7229 			report(xerror == inst_err, "vmlaunch failed, "
7230 			       "VMX Inst Error is %d (expected %d)",
7231 			       inst_err, xerror);
7232 		} else {
7233 			report(!data->enabled || data->exp == obs,
7234 			       "Host state is 0x%lx (expected 0x%lx)",
7235 			       obs, data->exp);
7236 			report(success != xfail, "vmlaunch succeeded");
7237 		}
7238 	} else {
7239 		test_guest_state("load GUEST_PERF_GLOBAL_CTRL", xfail,
7240 				 GUEST_PERF_GLOBAL_CTRL,
7241 				 "GUEST_PERF_GLOBAL_CTRL");
7242 	}
7243 }
7244 
7245 /*
7246  * test_load_perf_global_ctrl is a generic function for testing the
7247  * "load IA32_PERF_GLOBAL_CTRL" VM-{Entry,Exit} controls. This test function
7248  * tests the provided ctrl_val when disabled and enabled.
7249  *
7250  * @nr: VMCS field number corresponding to the host/guest state field
7251  * @name: Name of the above VMCS field for printing in test report
7252  * @ctrl_nr: VMCS field number corresponding to the VM-{Entry,Exit} control
7253  * @ctrl_val: Bit to set on the ctrl_field
7254  */
7255 static void test_perf_global_ctrl(u32 nr, const char *name, u32 ctrl_nr,
7256 				  const char *ctrl_name, u64 ctrl_val)
7257 {
7258 	u64 ctrl_saved = vmcs_read(ctrl_nr);
7259 	u64 pgc_saved = vmcs_read(nr);
7260 	u64 i, val;
7261 	bool host = nr == HOST_PERF_GLOBAL_CTRL;
7262 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7263 
7264 	data->msr = MSR_CORE_PERF_GLOBAL_CTRL;
7265 	msr_bmp_init();
7266 	vmcs_write(ctrl_nr, ctrl_saved & ~ctrl_val);
7267 	data->enabled = false;
7268 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=0 on %s",
7269 			    ctrl_name);
7270 
7271 	for (i = 0; i < 64; i++) {
7272 		val = 1ull << i;
7273 		vmcs_write(nr, val);
7274 		report_prefix_pushf("%s = 0x%lx", name, val);
7275 		test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7276 		report_prefix_pop();
7277 	}
7278 	report_prefix_pop();
7279 
7280 	vmcs_write(ctrl_nr, ctrl_saved | ctrl_val);
7281 	data->enabled = true;
7282 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=1 on %s",
7283 			    ctrl_name);
7284 	for (i = 0; i < 64; i++) {
7285 		val = 1ull << i;
7286 		data->exp = val;
7287 		vmcs_write(nr, val);
7288 		report_prefix_pushf("%s = 0x%lx", name, val);
7289 		if (valid_pgc(val)) {
7290 			test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7291 		} else {
7292 			if (host)
7293 				test_pgc_vmlaunch(
7294 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD,
7295 					0,
7296 					true,
7297 					host);
7298 			else
7299 				test_pgc_vmlaunch(
7300 					0,
7301 					VMX_ENTRY_FAILURE | VMX_FAIL_STATE,
7302 					true,
7303 					host);
7304 		}
7305 		report_prefix_pop();
7306 	}
7307 
7308 	data->enabled = false;
7309 	report_prefix_pop();
7310 	vmcs_write(ctrl_nr, ctrl_saved);
7311 	vmcs_write(nr, pgc_saved);
7312 }
7313 
7314 static void test_load_host_perf_global_ctrl(void)
7315 {
7316 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PERF)) {
7317 		printf("\"load IA32_PERF_GLOBAL_CTRL\" exit control not supported\n");
7318 		return;
7319 	}
7320 
7321 	test_perf_global_ctrl(HOST_PERF_GLOBAL_CTRL, "HOST_PERF_GLOBAL_CTRL",
7322 				   EXI_CONTROLS, "EXI_CONTROLS", EXI_LOAD_PERF);
7323 }
7324 
7325 
7326 static void test_load_guest_perf_global_ctrl(void)
7327 {
7328 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PERF)) {
7329 		printf("\"load IA32_PERF_GLOBAL_CTRL\" entry control not supported\n");
7330 		return;
7331 	}
7332 
7333 	test_perf_global_ctrl(GUEST_PERF_GLOBAL_CTRL, "GUEST_PERF_GLOBAL_CTRL",
7334 				   ENT_CONTROLS, "ENT_CONTROLS", ENT_LOAD_PERF);
7335 }
7336 
7337 
7338 /*
7339  * test_vmcs_field - test a value for the given VMCS field
7340  * @field: VMCS field
7341  * @field_name: string name of VMCS field
7342  * @bit_start: starting bit
7343  * @bit_end: ending bit
7344  * @val: value that the bit range must or must not contain
7345  * @valid_val: whether value given in 'val' must be valid or not
7346  * @error: expected VMCS error when vmentry fails for an invalid value
7347  */
7348 static void test_vmcs_field(u64 field, const char *field_name, u32 bit_start,
7349 			    u32 bit_end, u64 val, bool valid_val, u32 error)
7350 {
7351 	u64 field_saved = vmcs_read(field);
7352 	u32 i;
7353 	u64 tmp;
7354 	u32 bit_on;
7355 	u64 mask = ~0ull;
7356 
7357 	mask = (mask >> bit_end) << bit_end;
7358 	mask = mask | ((1 << bit_start) - 1);
7359 	tmp = (field_saved & mask) | (val << bit_start);
7360 
7361 	vmcs_write(field, tmp);
7362 	report_prefix_pushf("%s %lx", field_name, tmp);
7363 	if (valid_val)
7364 		test_vmx_vmlaunch(0);
7365 	else
7366 		test_vmx_vmlaunch(error);
7367 	report_prefix_pop();
7368 
7369 	for (i = bit_start; i <= bit_end; i = i + 2) {
7370 		bit_on = ((1ull < i) & (val << bit_start)) ? 0 : 1;
7371 		if (bit_on)
7372 			tmp = field_saved | (1ull << i);
7373 		else
7374 			tmp = field_saved & ~(1ull << i);
7375 		vmcs_write(field, tmp);
7376 		report_prefix_pushf("%s %lx", field_name, tmp);
7377 		if (valid_val)
7378 			test_vmx_vmlaunch(error);
7379 		else
7380 			test_vmx_vmlaunch(0);
7381 		report_prefix_pop();
7382 	}
7383 
7384 	vmcs_write(field, field_saved);
7385 }
7386 
7387 static void test_canonical(u64 field, const char * field_name, bool host)
7388 {
7389 	u64 addr_saved = vmcs_read(field);
7390 
7391 	/*
7392 	 * Use the existing value if possible.  Writing a random canonical
7393 	 * value is not an option as doing so would corrupt the field being
7394 	 * tested and likely hose the test.
7395 	 */
7396 	if (is_canonical(addr_saved)) {
7397 		if (host) {
7398 			report_prefix_pushf("%s %lx", field_name, addr_saved);
7399 			test_vmx_vmlaunch(0);
7400 			report_prefix_pop();
7401 		} else {
7402 			test_guest_state("Test canonical address", false,
7403 					 addr_saved, field_name);
7404 		}
7405 	}
7406 
7407 	vmcs_write(field, NONCANONICAL);
7408 
7409 	if (host) {
7410 		report_prefix_pushf("%s %llx", field_name, NONCANONICAL);
7411 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7412 		report_prefix_pop();
7413 	} else {
7414 		test_guest_state("Test non-canonical address", true,
7415 				 NONCANONICAL, field_name);
7416 	}
7417 
7418 	vmcs_write(field, addr_saved);
7419 }
7420 
7421 #define TEST_RPL_TI_FLAGS(reg, name)				\
7422 	test_vmcs_field(reg, name, 0, 2, 0x0, true,		\
7423 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7424 
7425 #define TEST_CS_TR_FLAGS(reg, name)				\
7426 	test_vmcs_field(reg, name, 3, 15, 0x0000, false,	\
7427 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7428 
7429 /*
7430  * 1. In the selector field for each of CS, SS, DS, ES, FS, GS and TR, the
7431  *    RPL (bits 1:0) and the TI flag (bit 2) must be 0.
7432  * 2. The selector fields for CS and TR cannot be 0000H.
7433  * 3. The selector field for SS cannot be 0000H if the "host address-space
7434  *    size" VM-exit control is 0.
7435  * 4. On processors that support Intel 64 architecture, the base-address
7436  *    fields for FS, GS and TR must contain canonical addresses.
7437  */
7438 static void test_host_segment_regs(void)
7439 {
7440 	u16 selector_saved;
7441 
7442 	/*
7443 	 * Test RPL and TI flags
7444 	 */
7445 	TEST_RPL_TI_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7446 	TEST_RPL_TI_FLAGS(HOST_SEL_SS, "HOST_SEL_SS");
7447 	TEST_RPL_TI_FLAGS(HOST_SEL_DS, "HOST_SEL_DS");
7448 	TEST_RPL_TI_FLAGS(HOST_SEL_ES, "HOST_SEL_ES");
7449 	TEST_RPL_TI_FLAGS(HOST_SEL_FS, "HOST_SEL_FS");
7450 	TEST_RPL_TI_FLAGS(HOST_SEL_GS, "HOST_SEL_GS");
7451 	TEST_RPL_TI_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7452 
7453 	/*
7454 	 * Test that CS and TR fields can not be 0x0000
7455 	 */
7456 	TEST_CS_TR_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7457 	TEST_CS_TR_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7458 
7459 	/*
7460 	 * SS field can not be 0x0000 if "host address-space size" VM-exit
7461 	 * control is 0
7462 	 */
7463 	selector_saved = vmcs_read(HOST_SEL_SS);
7464 	vmcs_write(HOST_SEL_SS, 0);
7465 	report_prefix_pushf("HOST_SEL_SS 0");
7466 	if (vmcs_read(EXI_CONTROLS) & EXI_HOST_64) {
7467 		test_vmx_vmlaunch(0);
7468 	} else {
7469 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7470 	}
7471 	report_prefix_pop();
7472 
7473 	vmcs_write(HOST_SEL_SS, selector_saved);
7474 
7475 #ifdef __x86_64__
7476 	/*
7477 	 * Base address for FS, GS and TR must be canonical
7478 	 */
7479 	test_canonical(HOST_BASE_FS, "HOST_BASE_FS", true);
7480 	test_canonical(HOST_BASE_GS, "HOST_BASE_GS", true);
7481 	test_canonical(HOST_BASE_TR, "HOST_BASE_TR", true);
7482 #endif
7483 }
7484 
7485 /*
7486  *  On processors that support Intel 64 architecture, the base-address
7487  *  fields for GDTR and IDTR must contain canonical addresses.
7488  */
7489 static void test_host_desc_tables(void)
7490 {
7491 #ifdef __x86_64__
7492 	test_canonical(HOST_BASE_GDTR, "HOST_BASE_GDTR", true);
7493 	test_canonical(HOST_BASE_IDTR, "HOST_BASE_IDTR", true);
7494 #endif
7495 }
7496 
7497 /*
7498  * If the "host address-space size" VM-exit control is 0, the following must
7499  * hold:
7500  *    - The "IA-32e mode guest" VM-entry control is 0.
7501  *    - Bit 17 of the CR4 field (corresponding to CR4.PCIDE) is 0.
7502  *    - Bits 63:32 in the RIP field are 0.
7503  *
7504  * If the "host address-space size" VM-exit control is 1, the following must
7505  * hold:
7506  *    - Bit 5 of the CR4 field (corresponding to CR4.PAE) is 1.
7507  *    - The RIP field contains a canonical address.
7508  *
7509  */
7510 static void test_host_addr_size(void)
7511 {
7512 	u64 cr4_saved = vmcs_read(HOST_CR4);
7513 	u64 rip_saved = vmcs_read(HOST_RIP);
7514 	u64 entry_ctrl_saved = vmcs_read(ENT_CONTROLS);
7515 	int i;
7516 	u64 tmp;
7517 
7518 	if (vmcs_read(EXI_CONTROLS) & EXI_HOST_64) {
7519 		vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7520 		report_prefix_pushf("\"IA-32e mode guest\" enabled");
7521 		test_vmx_vmlaunch(0);
7522 		report_prefix_pop();
7523 
7524 		vmcs_write(HOST_CR4, cr4_saved | X86_CR4_PCIDE);
7525 		report_prefix_pushf("\"CR4.PCIDE\" set");
7526 		test_vmx_vmlaunch(0);
7527 		report_prefix_pop();
7528 
7529 		for (i = 32; i <= 63; i = i + 4) {
7530 			tmp = rip_saved | 1ull << i;
7531 			vmcs_write(HOST_RIP, tmp);
7532 			report_prefix_pushf("HOST_RIP %lx", tmp);
7533 			test_vmx_vmlaunch(0);
7534 			report_prefix_pop();
7535 		}
7536 
7537 		if (cr4_saved & X86_CR4_PAE) {
7538 			vmcs_write(HOST_CR4, cr4_saved  & ~X86_CR4_PAE);
7539 			report_prefix_pushf("\"CR4.PAE\" unset");
7540 			test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7541 		} else {
7542 			report_prefix_pushf("\"CR4.PAE\" set");
7543 			test_vmx_vmlaunch(0);
7544 		}
7545 		report_prefix_pop();
7546 
7547 		vmcs_write(HOST_RIP, NONCANONICAL);
7548 		report_prefix_pushf("HOST_RIP %llx", NONCANONICAL);
7549 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7550 		report_prefix_pop();
7551 
7552 		vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7553 		vmcs_write(HOST_RIP, rip_saved);
7554 		vmcs_write(HOST_CR4, cr4_saved);
7555 	}
7556 }
7557 
7558 /*
7559  * Check that the virtual CPU checks the VMX Host State Area as
7560  * documented in the Intel SDM.
7561  */
7562 static void vmx_host_state_area_test(void)
7563 {
7564 	/*
7565 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
7566 	 * fail due to invalid guest state, should we make it that
7567 	 * far.
7568 	 */
7569 	vmcs_write(GUEST_RFLAGS, 0);
7570 
7571 	test_host_ctl_regs();
7572 
7573 	test_canonical(HOST_SYSENTER_ESP, "HOST_SYSENTER_ESP", true);
7574 	test_canonical(HOST_SYSENTER_EIP, "HOST_SYSENTER_EIP", true);
7575 
7576 	test_host_efer();
7577 	test_load_host_pat();
7578 	test_host_segment_regs();
7579 	test_host_desc_tables();
7580 	test_host_addr_size();
7581 	test_load_host_perf_global_ctrl();
7582 }
7583 
7584 /*
7585  * If the "load debug controls" VM-entry control is 1, bits 63:32 in
7586  * the DR7 field must be 0.
7587  *
7588  * [Intel SDM]
7589  */
7590 static void test_guest_dr7(void)
7591 {
7592 	u32 ent_saved = vmcs_read(ENT_CONTROLS);
7593 	u64 dr7_saved = vmcs_read(GUEST_DR7);
7594 	u64 val;
7595 	int i;
7596 
7597 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS) {
7598 		vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7599 		for (i = 0; i < 64; i++) {
7600 			val = 1ull << i;
7601 			vmcs_write(GUEST_DR7, val);
7602 			test_guest_state("ENT_LOAD_DBGCTLS disabled", false,
7603 					 val, "GUEST_DR7");
7604 		}
7605 	}
7606 	if (ctrl_enter_rev.clr & ENT_LOAD_DBGCTLS) {
7607 		vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7608 		for (i = 0; i < 64; i++) {
7609 			val = 1ull << i;
7610 			vmcs_write(GUEST_DR7, val);
7611 			test_guest_state("ENT_LOAD_DBGCTLS enabled", i >= 32,
7612 					 val, "GUEST_DR7");
7613 		}
7614 	}
7615 	vmcs_write(GUEST_DR7, dr7_saved);
7616 	vmcs_write(ENT_CONTROLS, ent_saved);
7617 }
7618 
7619 /*
7620  *  If the "load IA32_PAT" VM-entry control is 1, the value of the field
7621  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7622  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7623  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7624  *  6 (WB), or 7 (UC-).
7625  *
7626  *  [Intel SDM]
7627  */
7628 static void test_load_guest_pat(void)
7629 {
7630 	/*
7631 	 * "load IA32_PAT" VM-entry control
7632 	 */
7633 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
7634 		printf("\"Load-IA32-PAT\" entry control not supported\n");
7635 		return;
7636 	}
7637 
7638 	test_pat(GUEST_PAT, "GUEST_PAT", ENT_CONTROLS, ENT_LOAD_PAT);
7639 }
7640 
7641 #define MSR_IA32_BNDCFGS_RSVD_MASK	0x00000ffc
7642 
7643 /*
7644  * If the “load IA32_BNDCFGS†VM-entry control is 1, the following
7645  * checks are performed on the field for the IA32_BNDCFGS MSR:
7646  *
7647  *   —  Bits reserved in the IA32_BNDCFGS MSR must be 0.
7648  *   —  The linear address in bits 63:12 must be canonical.
7649  *
7650  *  [Intel SDM]
7651  */
7652 static void test_load_guest_bndcfgs(void)
7653 {
7654 	u64 bndcfgs_saved = vmcs_read(GUEST_BNDCFGS);
7655 	u64 bndcfgs;
7656 
7657 	if (!(ctrl_enter_rev.clr & ENT_LOAD_BNDCFGS)) {
7658 		printf("\"Load-IA32-BNDCFGS\" entry control not supported\n");
7659 		return;
7660 	}
7661 
7662 	vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7663 
7664 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7665 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7666 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7667 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7668 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7669 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7670 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7671 
7672 	vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7673 
7674 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7675 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7676 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7677 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7678 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7679 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7680 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7681 
7682 	vmcs_write(GUEST_BNDCFGS, bndcfgs_saved);
7683 }
7684 
7685 /*
7686  * Check that the virtual CPU checks the VMX Guest State Area as
7687  * documented in the Intel SDM.
7688  */
7689 static void vmx_guest_state_area_test(void)
7690 {
7691 	vmx_set_test_stage(1);
7692 	test_set_guest(guest_state_test_main);
7693 
7694 	/*
7695 	 * The IA32_SYSENTER_ESP field and the IA32_SYSENTER_EIP field
7696 	 * must each contain a canonical address.
7697 	 */
7698 	test_canonical(GUEST_SYSENTER_ESP, "GUEST_SYSENTER_ESP", false);
7699 	test_canonical(GUEST_SYSENTER_EIP, "GUEST_SYSENTER_EIP", false);
7700 
7701 	test_guest_dr7();
7702 	test_load_guest_pat();
7703 	test_guest_efer();
7704 	test_load_guest_perf_global_ctrl();
7705 	test_load_guest_bndcfgs();
7706 
7707 	/*
7708 	 * Let the guest finish execution
7709 	 */
7710 	vmx_set_test_stage(2);
7711 	enter_guest();
7712 }
7713 
7714 static bool valid_vmcs_for_vmentry(void)
7715 {
7716 	struct vmcs *current_vmcs = NULL;
7717 
7718 	if (vmcs_save(&current_vmcs))
7719 		return false;
7720 
7721 	return current_vmcs && !current_vmcs->hdr.shadow_vmcs;
7722 }
7723 
7724 static void try_vmentry_in_movss_shadow(void)
7725 {
7726 	u32 vm_inst_err;
7727 	u32 flags;
7728 	bool early_failure = false;
7729 	u32 expected_flags = X86_EFLAGS_FIXED;
7730 	bool valid_vmcs = valid_vmcs_for_vmentry();
7731 
7732 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
7733 
7734 	/*
7735 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
7736 	 * unsupported VMCS component").
7737 	 */
7738 	vmcs_write(~0u, 0);
7739 
7740 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
7741 			      "vmwrite %%rsp, %%rdx;"
7742 			      "mov 0f, %%rax;"
7743 			      "mov %[host_rip], %%edx;"
7744 			      "vmwrite %%rax, %%rdx;"
7745 			      "mov $-1, %%ah;"
7746 			      "sahf;"
7747 			      "mov %%ss, %%ax;"
7748 			      "mov %%ax, %%ss;"
7749 			      "vmlaunch;"
7750 			      "mov $1, %[early_failure];"
7751 			      "0: lahf;"
7752 			      "movzbl %%ah, %[flags]"
7753 			      : [early_failure] "+r" (early_failure),
7754 				[flags] "=&a" (flags)
7755 			      : [host_rsp] "i" (HOST_RSP),
7756 				[host_rip] "i" (HOST_RIP)
7757 			      : "rdx", "cc", "memory");
7758 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
7759 
7760 	report(early_failure, "Early VM-entry failure");
7761 	report(flags == expected_flags, "RFLAGS[8:0] is %x (actual %x)",
7762 	       expected_flags, flags);
7763 	if (valid_vmcs)
7764 		report(vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
7765 		       "VM-instruction error is %d (actual %d)",
7766 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
7767 }
7768 
7769 static void vmentry_movss_shadow_test(void)
7770 {
7771 	struct vmcs *orig_vmcs;
7772 
7773 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
7774 
7775 	/*
7776 	 * Set the launched flag on the current VMCS to verify the correct
7777 	 * error priority, below.
7778 	 */
7779 	test_set_guest(v2_null_test_guest);
7780 	enter_guest();
7781 
7782 	/*
7783 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
7784 	 * fail due to invalid guest state (if we make it that far).
7785 	 */
7786 	vmcs_write(GUEST_RFLAGS, 0);
7787 
7788 	/*
7789 	 * "VM entry with events blocked by MOV SS" takes precedence over
7790 	 * "VMLAUNCH with non-clear VMCS."
7791 	 */
7792 	report_prefix_push("valid current-VMCS");
7793 	try_vmentry_in_movss_shadow();
7794 	report_prefix_pop();
7795 
7796 	/*
7797 	 * VMfailInvalid takes precedence over "VM entry with events
7798 	 * blocked by MOV SS."
7799 	 */
7800 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
7801 	report_prefix_push("no current-VMCS");
7802 	try_vmentry_in_movss_shadow();
7803 	report_prefix_pop();
7804 
7805 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
7806 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
7807 }
7808 
7809 static void vmx_cr_load_test(void)
7810 {
7811 	unsigned long cr3, cr4, orig_cr3, orig_cr4;
7812 
7813 	orig_cr4 = read_cr4();
7814 	orig_cr3 = read_cr3();
7815 
7816 	if (!this_cpu_has(X86_FEATURE_PCID)) {
7817 		report_skip("PCID not detected");
7818 		return;
7819 	}
7820 	if (!this_cpu_has(X86_FEATURE_MCE)) {
7821 		report_skip("MCE not detected");
7822 		return;
7823 	}
7824 
7825 	TEST_ASSERT(!(orig_cr3 & X86_CR3_PCID_MASK));
7826 
7827 	/* Enable PCID for L1. */
7828 	cr4 = orig_cr4 | X86_CR4_PCIDE;
7829 	cr3 = orig_cr3 | 0x1;
7830 	TEST_ASSERT(!write_cr4_checking(cr4));
7831 	write_cr3(cr3);
7832 
7833 	test_set_guest(v2_null_test_guest);
7834 	vmcs_write(HOST_CR4, cr4);
7835 	vmcs_write(HOST_CR3, cr3);
7836 	enter_guest();
7837 
7838 	/*
7839 	 * No exception is expected.
7840 	 *
7841 	 * NB. KVM loads the last guest write to CR4 into CR4 read
7842 	 *     shadow. In order to trigger an exit to KVM, we can toggle a
7843 	 *     bit that is owned by KVM. We use CR4.MCE, which shall
7844 	 *     have no side effect because normally no guest MCE (e.g., as the
7845 	 *     result of bad memory) would happen during this test.
7846 	 */
7847 	TEST_ASSERT(!write_cr4_checking(cr4 ^ X86_CR4_MCE));
7848 
7849 	/* Cleanup L1 state. */
7850 	write_cr3(orig_cr3);
7851 	TEST_ASSERT(!write_cr4_checking(orig_cr4));
7852 }
7853 
7854 static void vmx_nm_test_guest(void)
7855 {
7856 	write_cr0(read_cr0() | X86_CR0_TS);
7857 	asm volatile("fnop");
7858 }
7859 
7860 static void check_nm_exit(const char *test)
7861 {
7862 	u32 reason = vmcs_read(EXI_REASON);
7863 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
7864 	const u32 expected = INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
7865 		NM_VECTOR;
7866 
7867 	report(reason == VMX_EXC_NMI && intr_info == expected, "%s", test);
7868 }
7869 
7870 /*
7871  * This test checks that:
7872  *
7873  * (a) If L2 launches with CR0.TS clear, but later sets CR0.TS, then
7874  *     a subsequent #NM VM-exit is reflected to L1.
7875  *
7876  * (b) If L2 launches with CR0.TS clear and CR0.EM set, then a
7877  *     subsequent #NM VM-exit is reflected to L1.
7878  */
7879 static void vmx_nm_test(void)
7880 {
7881 	unsigned long cr0 = read_cr0();
7882 
7883 	test_set_guest(vmx_nm_test_guest);
7884 
7885 	/*
7886 	 * L1 wants to intercept #NM exceptions encountered in L2.
7887 	 */
7888 	vmcs_write(EXC_BITMAP, 1 << NM_VECTOR);
7889 
7890 	/*
7891 	 * Launch L2 with CR0.TS clear, but don't claim host ownership of
7892 	 * any CR0 bits. L2 will set CR0.TS and then try to execute fnop,
7893 	 * which will raise #NM. L0 should reflect the #NM VM-exit to L1.
7894 	 */
7895 	vmcs_write(CR0_MASK, 0);
7896 	vmcs_write(GUEST_CR0, cr0 & ~X86_CR0_TS);
7897 	enter_guest();
7898 	check_nm_exit("fnop with CR0.TS set in L2 triggers #NM VM-exit to L1");
7899 
7900 	/*
7901 	 * Re-enter L2 at the fnop instruction, with CR0.TS clear but
7902 	 * CR0.EM set. The fnop will still raise #NM, and L0 should
7903 	 * reflect the #NM VM-exit to L1.
7904 	 */
7905 	vmcs_write(GUEST_CR0, (cr0 & ~X86_CR0_TS) | X86_CR0_EM);
7906 	enter_guest();
7907 	check_nm_exit("fnop with CR0.EM set in L2 triggers #NM VM-exit to L1");
7908 
7909 	/*
7910 	 * Re-enter L2 at the fnop instruction, with both CR0.TS and
7911 	 * CR0.EM clear. There will be no #NM, and the L2 guest should
7912 	 * exit normally.
7913 	 */
7914 	vmcs_write(GUEST_CR0, cr0 & ~(X86_CR0_TS | X86_CR0_EM));
7915 	enter_guest();
7916 }
7917 
7918 bool vmx_pending_event_ipi_fired;
7919 static void vmx_pending_event_ipi_isr(isr_regs_t *regs)
7920 {
7921 	vmx_pending_event_ipi_fired = true;
7922 	eoi();
7923 }
7924 
7925 bool vmx_pending_event_guest_run;
7926 static void vmx_pending_event_guest(void)
7927 {
7928 	vmcall();
7929 	vmx_pending_event_guest_run = true;
7930 }
7931 
7932 static void vmx_pending_event_test_core(bool guest_hlt)
7933 {
7934 	int ipi_vector = 0xf1;
7935 
7936 	vmx_pending_event_ipi_fired = false;
7937 	handle_irq(ipi_vector, vmx_pending_event_ipi_isr);
7938 
7939 	vmx_pending_event_guest_run = false;
7940 	test_set_guest(vmx_pending_event_guest);
7941 
7942 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
7943 
7944 	enter_guest();
7945 	skip_exit_vmcall();
7946 
7947 	if (guest_hlt)
7948 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
7949 
7950 	irq_disable();
7951 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
7952 				   APIC_DM_FIXED | ipi_vector,
7953 				   0);
7954 
7955 	enter_guest();
7956 
7957 	assert_exit_reason(VMX_EXTINT);
7958 	report(!vmx_pending_event_guest_run,
7959 	       "Guest did not run before host received IPI");
7960 
7961 	irq_enable();
7962 	asm volatile ("nop");
7963 	irq_disable();
7964 	report(vmx_pending_event_ipi_fired,
7965 	       "Got pending interrupt after IRQ enabled");
7966 
7967 	if (guest_hlt)
7968 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
7969 
7970 	enter_guest();
7971 	report(vmx_pending_event_guest_run,
7972 	       "Guest finished running when no interrupt");
7973 }
7974 
7975 static void vmx_pending_event_test(void)
7976 {
7977 	vmx_pending_event_test_core(false);
7978 }
7979 
7980 static void vmx_pending_event_hlt_test(void)
7981 {
7982 	vmx_pending_event_test_core(true);
7983 }
7984 
7985 static int vmx_window_test_db_count;
7986 
7987 static void vmx_window_test_db_handler(struct ex_regs *regs)
7988 {
7989 	vmx_window_test_db_count++;
7990 }
7991 
7992 static void vmx_nmi_window_test_guest(void)
7993 {
7994 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
7995 
7996 	asm volatile("vmcall\n\t"
7997 		     "nop\n\t");
7998 
7999 	handle_exception(DB_VECTOR, NULL);
8000 }
8001 
8002 static void verify_nmi_window_exit(u64 rip)
8003 {
8004 	u32 exit_reason = vmcs_read(EXI_REASON);
8005 
8006 	report(exit_reason == VMX_NMI_WINDOW,
8007 	       "Exit reason (%d) is 'NMI window'", exit_reason);
8008 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8009 	       vmcs_read(GUEST_RIP), rip);
8010 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8011 }
8012 
8013 static void vmx_nmi_window_test(void)
8014 {
8015 	u64 nop_addr;
8016 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8017 
8018 	if (!(ctrl_pin_rev.clr & PIN_VIRT_NMI)) {
8019 		report_skip("CPU does not support the \"Virtual NMIs\" VM-execution control.");
8020 		return;
8021 	}
8022 
8023 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
8024 		report_skip("CPU does not support the \"NMI-window exiting\" VM-execution control.");
8025 		return;
8026 	}
8027 
8028 	vmx_window_test_db_count = 0;
8029 
8030 	report_prefix_push("NMI-window");
8031 	test_set_guest(vmx_nmi_window_test_guest);
8032 	vmcs_set_bits(PIN_CONTROLS, PIN_VIRT_NMI);
8033 	enter_guest();
8034 	skip_exit_vmcall();
8035 	nop_addr = vmcs_read(GUEST_RIP);
8036 
8037 	/*
8038 	 * Ask for "NMI-window exiting," and expect an immediate VM-exit.
8039 	 * RIP will not advance.
8040 	 */
8041 	report_prefix_push("active, no blocking");
8042 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8043 	enter_guest();
8044 	verify_nmi_window_exit(nop_addr);
8045 	report_prefix_pop();
8046 
8047 	/*
8048 	 * Ask for "NMI-window exiting" in a MOV-SS shadow, and expect
8049 	 * a VM-exit on the next instruction after the nop. (The nop
8050 	 * is one byte.)
8051 	 */
8052 	report_prefix_push("active, blocking by MOV-SS");
8053 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8054 	enter_guest();
8055 	verify_nmi_window_exit(nop_addr + 1);
8056 	report_prefix_pop();
8057 
8058 	/*
8059 	 * Ask for "NMI-window exiting" (with event injection), and
8060 	 * expect a VM-exit after the event is injected. (RIP should
8061 	 * be at the address specified in the IDT entry for #DB.)
8062 	 */
8063 	report_prefix_push("active, no blocking, injecting #DB");
8064 	vmcs_write(ENT_INTR_INFO,
8065 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8066 	enter_guest();
8067 	verify_nmi_window_exit((u64)db_fault_addr);
8068 	report_prefix_pop();
8069 
8070 	/*
8071 	 * Ask for "NMI-window exiting" with NMI blocking, and expect
8072 	 * a VM-exit after the next IRET (i.e. after the #DB handler
8073 	 * returns). So, RIP should be back at one byte past the nop.
8074 	 */
8075 	report_prefix_push("active, blocking by NMI");
8076 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_NMI);
8077 	enter_guest();
8078 	verify_nmi_window_exit(nop_addr + 1);
8079 	report(vmx_window_test_db_count == 1,
8080 	       "#DB handler executed once (actual %d times)",
8081 	       vmx_window_test_db_count);
8082 	report_prefix_pop();
8083 
8084 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8085 		report_skip("CPU does not support activity state HLT.");
8086 	} else {
8087 		/*
8088 		 * Ask for "NMI-window exiting" when entering activity
8089 		 * state HLT, and expect an immediate VM-exit. RIP is
8090 		 * still one byte past the nop.
8091 		 */
8092 		report_prefix_push("halted, no blocking");
8093 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8094 		enter_guest();
8095 		verify_nmi_window_exit(nop_addr + 1);
8096 		report_prefix_pop();
8097 
8098 		/*
8099 		 * Ask for "NMI-window exiting" when entering activity
8100 		 * state HLT (with event injection), and expect a
8101 		 * VM-exit after the event is injected. (RIP should be
8102 		 * at the address specified in the IDT entry for #DB.)
8103 		 */
8104 		report_prefix_push("halted, no blocking, injecting #DB");
8105 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8106 		vmcs_write(ENT_INTR_INFO,
8107 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8108 			   DB_VECTOR);
8109 		enter_guest();
8110 		verify_nmi_window_exit((u64)db_fault_addr);
8111 		report_prefix_pop();
8112 	}
8113 
8114 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8115 	enter_guest();
8116 	report_prefix_pop();
8117 }
8118 
8119 static void vmx_intr_window_test_guest(void)
8120 {
8121 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
8122 
8123 	/*
8124 	 * The two consecutive STIs are to ensure that only the first
8125 	 * one has a shadow. Note that NOP and STI are one byte
8126 	 * instructions.
8127 	 */
8128 	asm volatile("vmcall\n\t"
8129 		     "nop\n\t"
8130 		     "sti\n\t"
8131 		     "sti\n\t");
8132 
8133 	handle_exception(DB_VECTOR, NULL);
8134 }
8135 
8136 static void verify_intr_window_exit(u64 rip)
8137 {
8138 	u32 exit_reason = vmcs_read(EXI_REASON);
8139 
8140 	report(exit_reason == VMX_INTR_WINDOW,
8141 	       "Exit reason (%d) is 'interrupt window'", exit_reason);
8142 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8143 	       vmcs_read(GUEST_RIP), rip);
8144 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8145 }
8146 
8147 static void vmx_intr_window_test(void)
8148 {
8149 	u64 vmcall_addr;
8150 	u64 nop_addr;
8151 	unsigned int orig_db_gate_type;
8152 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8153 
8154 	if (!(ctrl_cpu_rev[0].clr & CPU_INTR_WINDOW)) {
8155 		report_skip("CPU does not support the \"interrupt-window exiting\" VM-execution control.");
8156 		return;
8157 	}
8158 
8159 	/*
8160 	 * Change the IDT entry for #DB from interrupt gate to trap gate,
8161 	 * so that it won't clear RFLAGS.IF. We don't want interrupts to
8162 	 * be disabled after vectoring a #DB.
8163 	 */
8164 	orig_db_gate_type = boot_idt[DB_VECTOR].type;
8165 	boot_idt[DB_VECTOR].type = 15;
8166 
8167 	report_prefix_push("interrupt-window");
8168 	test_set_guest(vmx_intr_window_test_guest);
8169 	enter_guest();
8170 	assert_exit_reason(VMX_VMCALL);
8171 	vmcall_addr = vmcs_read(GUEST_RIP);
8172 
8173 	/*
8174 	 * Ask for "interrupt-window exiting" with RFLAGS.IF set and
8175 	 * no blocking; expect an immediate VM-exit. Note that we have
8176 	 * not advanced past the vmcall instruction yet, so RIP should
8177 	 * point to the vmcall instruction.
8178 	 */
8179 	report_prefix_push("active, no blocking, RFLAGS.IF=1");
8180 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8181 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_IF);
8182 	enter_guest();
8183 	verify_intr_window_exit(vmcall_addr);
8184 	report_prefix_pop();
8185 
8186 	/*
8187 	 * Ask for "interrupt-window exiting" (with event injection)
8188 	 * with RFLAGS.IF set and no blocking; expect a VM-exit after
8189 	 * the event is injected. That is, RIP should should be at the
8190 	 * address specified in the IDT entry for #DB.
8191 	 */
8192 	report_prefix_push("active, no blocking, RFLAGS.IF=1, injecting #DB");
8193 	vmcs_write(ENT_INTR_INFO,
8194 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8195 	vmcall_addr = vmcs_read(GUEST_RIP);
8196 	enter_guest();
8197 	verify_intr_window_exit((u64)db_fault_addr);
8198 	report_prefix_pop();
8199 
8200 	/*
8201 	 * Let the L2 guest run through the IRET, back to the VMCALL.
8202 	 * We have to clear the "interrupt-window exiting"
8203 	 * VM-execution control, or it would just keep causing
8204 	 * VM-exits. Then, advance past the VMCALL and set the
8205 	 * "interrupt-window exiting" VM-execution control again.
8206 	 */
8207 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8208 	enter_guest();
8209 	skip_exit_vmcall();
8210 	nop_addr = vmcs_read(GUEST_RIP);
8211 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8212 
8213 	/*
8214 	 * Ask for "interrupt-window exiting" in a MOV-SS shadow with
8215 	 * RFLAGS.IF set, and expect a VM-exit on the next
8216 	 * instruction. (NOP is one byte.)
8217 	 */
8218 	report_prefix_push("active, blocking by MOV-SS, RFLAGS.IF=1");
8219 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8220 	enter_guest();
8221 	verify_intr_window_exit(nop_addr + 1);
8222 	report_prefix_pop();
8223 
8224 	/*
8225 	 * Back up to the NOP and ask for "interrupt-window exiting"
8226 	 * in an STI shadow with RFLAGS.IF set, and expect a VM-exit
8227 	 * on the next instruction. (NOP is one byte.)
8228 	 */
8229 	report_prefix_push("active, blocking by STI, RFLAGS.IF=1");
8230 	vmcs_write(GUEST_RIP, nop_addr);
8231 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_STI);
8232 	enter_guest();
8233 	verify_intr_window_exit(nop_addr + 1);
8234 	report_prefix_pop();
8235 
8236 	/*
8237 	 * Ask for "interrupt-window exiting" with RFLAGS.IF clear,
8238 	 * and expect a VM-exit on the instruction following the STI
8239 	 * shadow. Only the first STI (which is one byte past the NOP)
8240 	 * should have a shadow. The second STI (which is two bytes
8241 	 * past the NOP) has no shadow. Therefore, the interrupt
8242 	 * window opens at three bytes past the NOP.
8243 	 */
8244 	report_prefix_push("active, RFLAGS.IF = 0");
8245 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8246 	enter_guest();
8247 	verify_intr_window_exit(nop_addr + 3);
8248 	report_prefix_pop();
8249 
8250 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8251 		report_skip("CPU does not support activity state HLT.");
8252 	} else {
8253 		/*
8254 		 * Ask for "interrupt-window exiting" when entering
8255 		 * activity state HLT, and expect an immediate
8256 		 * VM-exit. RIP is still three bytes past the nop.
8257 		 */
8258 		report_prefix_push("halted, no blocking");
8259 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8260 		enter_guest();
8261 		verify_intr_window_exit(nop_addr + 3);
8262 		report_prefix_pop();
8263 
8264 		/*
8265 		 * Ask for "interrupt-window exiting" when entering
8266 		 * activity state HLT (with event injection), and
8267 		 * expect a VM-exit after the event is injected. That
8268 		 * is, RIP should should be at the address specified
8269 		 * in the IDT entry for #DB.
8270 		 */
8271 		report_prefix_push("halted, no blocking, injecting #DB");
8272 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8273 		vmcs_write(ENT_INTR_INFO,
8274 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8275 			   DB_VECTOR);
8276 		enter_guest();
8277 		verify_intr_window_exit((u64)db_fault_addr);
8278 		report_prefix_pop();
8279 	}
8280 
8281 	boot_idt[DB_VECTOR].type = orig_db_gate_type;
8282 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8283 	enter_guest();
8284 	report_prefix_pop();
8285 }
8286 
8287 #define GUEST_TSC_OFFSET (1u << 30)
8288 
8289 static u64 guest_tsc;
8290 
8291 static void vmx_store_tsc_test_guest(void)
8292 {
8293 	guest_tsc = rdtsc();
8294 }
8295 
8296 /*
8297  * This test ensures that when IA32_TSC is in the VM-exit MSR-store
8298  * list, the value saved is not subject to the TSC offset that is
8299  * applied to RDTSC/RDTSCP/RDMSR(IA32_TSC) in guest execution.
8300  */
8301 static void vmx_store_tsc_test(void)
8302 {
8303 	struct vmx_msr_entry msr_entry = { .index = MSR_IA32_TSC };
8304 	u64 low, high;
8305 
8306 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET)) {
8307 		report_skip("'Use TSC offsetting' not supported");
8308 		return;
8309 	}
8310 
8311 	test_set_guest(vmx_store_tsc_test_guest);
8312 
8313 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
8314 	vmcs_write(EXI_MSR_ST_CNT, 1);
8315 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(&msr_entry));
8316 	vmcs_write(TSC_OFFSET, GUEST_TSC_OFFSET);
8317 
8318 	low = rdtsc();
8319 	enter_guest();
8320 	high = rdtsc();
8321 
8322 	report(low + GUEST_TSC_OFFSET <= guest_tsc &&
8323 	       guest_tsc <= high + GUEST_TSC_OFFSET,
8324 	       "RDTSC value in the guest (%lu) is in range [%lu, %lu]",
8325 	       guest_tsc, low + GUEST_TSC_OFFSET, high + GUEST_TSC_OFFSET);
8326 	report(low <= msr_entry.value && msr_entry.value <= high,
8327 	       "IA32_TSC value saved in the VM-exit MSR-store list (%lu) is in range [%lu, %lu]",
8328 	       msr_entry.value, low, high);
8329 }
8330 
8331 static void vmx_preemption_timer_zero_test_db_handler(struct ex_regs *regs)
8332 {
8333 }
8334 
8335 static void vmx_preemption_timer_zero_test_guest(void)
8336 {
8337 	while (vmx_get_test_stage() < 3)
8338 		vmcall();
8339 }
8340 
8341 static void vmx_preemption_timer_zero_activate_preemption_timer(void)
8342 {
8343 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
8344 	vmcs_write(PREEMPT_TIMER_VALUE, 0);
8345 }
8346 
8347 static void vmx_preemption_timer_zero_advance_past_vmcall(void)
8348 {
8349 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8350 	enter_guest();
8351 	skip_exit_vmcall();
8352 }
8353 
8354 static void vmx_preemption_timer_zero_inject_db(bool intercept_db)
8355 {
8356 	vmx_preemption_timer_zero_activate_preemption_timer();
8357 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK |
8358 		   INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8359 	vmcs_write(EXC_BITMAP, intercept_db ? 1 << DB_VECTOR : 0);
8360 	enter_guest();
8361 }
8362 
8363 static void vmx_preemption_timer_zero_set_pending_dbg(u32 exception_bitmap)
8364 {
8365 	vmx_preemption_timer_zero_activate_preemption_timer();
8366 	vmcs_write(GUEST_PENDING_DEBUG, BIT(12) | DR_TRAP1);
8367 	vmcs_write(EXC_BITMAP, exception_bitmap);
8368 	enter_guest();
8369 }
8370 
8371 static void vmx_preemption_timer_zero_expect_preempt_at_rip(u64 expected_rip)
8372 {
8373 	u32 reason = (u32)vmcs_read(EXI_REASON);
8374 	u64 guest_rip = vmcs_read(GUEST_RIP);
8375 
8376 	report(reason == VMX_PREEMPT && guest_rip == expected_rip,
8377 	       "Exit reason is 0x%x (expected 0x%x) and guest RIP is %lx (0x%lx expected).",
8378 	       reason, VMX_PREEMPT, guest_rip, expected_rip);
8379 }
8380 
8381 /*
8382  * This test ensures that when the VMX preemption timer is zero at
8383  * VM-entry, a VM-exit occurs after any event injection and after any
8384  * pending debug exceptions are raised, but before execution of any
8385  * guest instructions.
8386  */
8387 static void vmx_preemption_timer_zero_test(void)
8388 {
8389 	u64 db_fault_address = (u64)get_idt_addr(&boot_idt[DB_VECTOR]);
8390 	handler old_db;
8391 	u32 reason;
8392 
8393 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
8394 		report_skip("'Activate VMX-preemption timer' not supported");
8395 		return;
8396 	}
8397 
8398 	/*
8399 	 * Install a custom #DB handler that doesn't abort.
8400 	 */
8401 	old_db = handle_exception(DB_VECTOR,
8402 				  vmx_preemption_timer_zero_test_db_handler);
8403 
8404 	test_set_guest(vmx_preemption_timer_zero_test_guest);
8405 
8406 	/*
8407 	 * VMX-preemption timer should fire after event injection.
8408 	 */
8409 	vmx_set_test_stage(0);
8410 	vmx_preemption_timer_zero_inject_db(0);
8411 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8412 	vmx_preemption_timer_zero_advance_past_vmcall();
8413 
8414 	/*
8415 	 * VMX-preemption timer should fire after event injection.
8416 	 * Exception bitmap is irrelevant, since you can't intercept
8417 	 * an event that you injected.
8418 	 */
8419 	vmx_set_test_stage(1);
8420 	vmx_preemption_timer_zero_inject_db(1 << DB_VECTOR);
8421 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8422 	vmx_preemption_timer_zero_advance_past_vmcall();
8423 
8424 	/*
8425 	 * VMX-preemption timer should fire after pending debug exceptions
8426 	 * have delivered a #DB trap.
8427 	 */
8428 	vmx_set_test_stage(2);
8429 	vmx_preemption_timer_zero_set_pending_dbg(0);
8430 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8431 	vmx_preemption_timer_zero_advance_past_vmcall();
8432 
8433 	/*
8434 	 * VMX-preemption timer would fire after pending debug exceptions
8435 	 * have delivered a #DB trap, but in this case, the #DB trap is
8436 	 * intercepted.
8437 	 */
8438 	vmx_set_test_stage(3);
8439 	vmx_preemption_timer_zero_set_pending_dbg(1 << DB_VECTOR);
8440 	reason = (u32)vmcs_read(EXI_REASON);
8441 	report(reason == VMX_EXC_NMI, "Exit reason is 0x%x (expected 0x%x)",
8442 	       reason, VMX_EXC_NMI);
8443 
8444 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8445 	enter_guest();
8446 
8447 	handle_exception(DB_VECTOR, old_db);
8448 }
8449 
8450 static void vmx_db_test_guest(void)
8451 {
8452 	/*
8453 	 * For a hardware generated single-step #DB.
8454 	 */
8455 	asm volatile("vmcall;"
8456 		     "nop;"
8457 		     ".Lpost_nop:");
8458 	/*
8459 	 * ...in a MOVSS shadow, with pending debug exceptions.
8460 	 */
8461 	asm volatile("vmcall;"
8462 		     "nop;"
8463 		     ".Lpost_movss_nop:");
8464 	/*
8465 	 * For an L0 synthesized single-step #DB. (L0 intercepts WBINVD and
8466 	 * emulates it in software.)
8467 	 */
8468 	asm volatile("vmcall;"
8469 		     "wbinvd;"
8470 		     ".Lpost_wbinvd:");
8471 	/*
8472 	 * ...in a MOVSS shadow, with pending debug exceptions.
8473 	 */
8474 	asm volatile("vmcall;"
8475 		     "wbinvd;"
8476 		     ".Lpost_movss_wbinvd:");
8477 	/*
8478 	 * For a hardware generated single-step #DB in a transactional region.
8479 	 */
8480 	asm volatile("vmcall;"
8481 		     ".Lxbegin: xbegin .Lskip_rtm;"
8482 		     "xend;"
8483 		     ".Lskip_rtm:");
8484 }
8485 
8486 /*
8487  * Clear the pending debug exceptions and RFLAGS.TF and re-enter
8488  * L2. No #DB is delivered and L2 continues to the next point of
8489  * interest.
8490  */
8491 static void dismiss_db(void)
8492 {
8493 	vmcs_write(GUEST_PENDING_DEBUG, 0);
8494 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8495 	enter_guest();
8496 }
8497 
8498 /*
8499  * Check a variety of VMCS fields relevant to an intercepted #DB exception.
8500  * Then throw away the #DB exception and resume L2.
8501  */
8502 static void check_db_exit(bool xfail_qual, bool xfail_dr6, bool xfail_pdbg,
8503 			  void *expected_rip, u64 expected_exit_qual,
8504 			  u64 expected_dr6)
8505 {
8506 	u32 reason = vmcs_read(EXI_REASON);
8507 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
8508 	u64 exit_qual = vmcs_read(EXI_QUALIFICATION);
8509 	u64 guest_rip = vmcs_read(GUEST_RIP);
8510 	u64 guest_pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
8511 	u64 dr6 = read_dr6();
8512 	const u32 expected_intr_info = INTR_INFO_VALID_MASK |
8513 		INTR_TYPE_HARD_EXCEPTION | DB_VECTOR;
8514 
8515 	report(reason == VMX_EXC_NMI && intr_info == expected_intr_info,
8516 	       "Expected #DB VM-exit");
8517 	report((u64)expected_rip == guest_rip, "Expected RIP %p (actual %lx)",
8518 	       expected_rip, guest_rip);
8519 	report_xfail(xfail_pdbg, 0 == guest_pending_dbg,
8520 		     "Expected pending debug exceptions 0 (actual %lx)",
8521 		     guest_pending_dbg);
8522 	report_xfail(xfail_qual, expected_exit_qual == exit_qual,
8523 		     "Expected exit qualification %lx (actual %lx)",
8524 		     expected_exit_qual, exit_qual);
8525 	report_xfail(xfail_dr6, expected_dr6 == dr6,
8526 		     "Expected DR6 %lx (actual %lx)", expected_dr6, dr6);
8527 	dismiss_db();
8528 }
8529 
8530 /*
8531  * Assuming the guest has just exited on a VMCALL instruction, skip
8532  * over the vmcall, and set the guest's RFLAGS.TF in the VMCS. If
8533  * pending debug exceptions are non-zero, set the VMCS up as if the
8534  * previous instruction was a MOVSS that generated the indicated
8535  * pending debug exceptions. Then enter L2.
8536  */
8537 static void single_step_guest(const char *test_name, u64 starting_dr6,
8538 			      u64 pending_debug_exceptions)
8539 {
8540 	printf("\n%s\n", test_name);
8541 	skip_exit_vmcall();
8542 	write_dr6(starting_dr6);
8543 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
8544 	if (pending_debug_exceptions) {
8545 		vmcs_write(GUEST_PENDING_DEBUG, pending_debug_exceptions);
8546 		vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8547 	}
8548 	enter_guest();
8549 }
8550 
8551 /*
8552  * When L1 intercepts #DB, verify that a single-step trap clears
8553  * pending debug exceptions, populates the exit qualification field
8554  * properly, and that DR6 is not prematurely clobbered. In a
8555  * (simulated) MOVSS shadow, make sure that the pending debug
8556  * exception bits are properly accumulated into the exit qualification
8557  * field.
8558  */
8559 static void vmx_db_test(void)
8560 {
8561 	/*
8562 	 * We are going to set a few arbitrary bits in DR6 to verify that
8563 	 * (a) DR6 is not modified by an intercepted #DB, and
8564 	 * (b) stale bits in DR6 (DR6.BD, in particular) don't leak into
8565          *     the exit qualification field for a subsequent #DB exception.
8566 	 */
8567 	const u64 starting_dr6 = DR6_RESERVED | BIT(13) | DR_TRAP3 | DR_TRAP1;
8568 	extern char post_nop asm(".Lpost_nop");
8569 	extern char post_movss_nop asm(".Lpost_movss_nop");
8570 	extern char post_wbinvd asm(".Lpost_wbinvd");
8571 	extern char post_movss_wbinvd asm(".Lpost_movss_wbinvd");
8572 	extern char xbegin asm(".Lxbegin");
8573 	extern char skip_rtm asm(".Lskip_rtm");
8574 
8575 	/*
8576 	 * L1 wants to intercept #DB exceptions encountered in L2.
8577 	 */
8578 	vmcs_write(EXC_BITMAP, BIT(DB_VECTOR));
8579 
8580 	/*
8581 	 * Start L2 and run it up to the first point of interest.
8582 	 */
8583 	test_set_guest(vmx_db_test_guest);
8584 	enter_guest();
8585 
8586 	/*
8587 	 * Hardware-delivered #DB trap for single-step sets the
8588 	 * standard that L0 has to follow for emulated instructions.
8589 	 */
8590 	single_step_guest("Hardware delivered single-step", starting_dr6, 0);
8591 	check_db_exit(false, false, false, &post_nop, DR_STEP, starting_dr6);
8592 
8593 	/*
8594 	 * Hardware-delivered #DB trap for single-step in MOVSS shadow
8595 	 * also sets the standard that L0 has to follow for emulated
8596 	 * instructions. Here, we establish the VMCS pending debug
8597 	 * exceptions to indicate that the simulated MOVSS triggered a
8598 	 * data breakpoint as well as the single-step trap.
8599 	 */
8600 	single_step_guest("Hardware delivered single-step in MOVSS shadow",
8601 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0 );
8602 	check_db_exit(false, false, false, &post_movss_nop, DR_STEP | DR_TRAP0,
8603 		      starting_dr6);
8604 
8605 	/*
8606 	 * L0 synthesized #DB trap for single-step is buggy, because
8607 	 * kvm (a) clobbers DR6 too early, and (b) tries its best to
8608 	 * reconstitute the exit qualification from the prematurely
8609 	 * modified DR6, but fails miserably.
8610 	 */
8611 	single_step_guest("Software synthesized single-step", starting_dr6, 0);
8612 	check_db_exit(false, false, false, &post_wbinvd, DR_STEP, starting_dr6);
8613 
8614 	/*
8615 	 * L0 synthesized #DB trap for single-step in MOVSS shadow is
8616 	 * even worse, because L0 also leaves the pending debug
8617 	 * exceptions in the VMCS instead of accumulating them into
8618 	 * the exit qualification field for the #DB exception.
8619 	 */
8620 	single_step_guest("Software synthesized single-step in MOVSS shadow",
8621 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0);
8622 	check_db_exit(true, false, true, &post_movss_wbinvd, DR_STEP | DR_TRAP0,
8623 		      starting_dr6);
8624 
8625 	/*
8626 	 * Optional RTM test for hardware that supports RTM, to
8627 	 * demonstrate that the current volume 3 of the SDM
8628 	 * (325384-067US), table 27-1 is incorrect. Bit 16 of the exit
8629 	 * qualification for debug exceptions is not reserved. It is
8630 	 * set to 1 if a debug exception (#DB) or a breakpoint
8631 	 * exception (#BP) occurs inside an RTM region while advanced
8632 	 * debugging of RTM transactional regions is enabled.
8633 	 */
8634 	if (this_cpu_has(X86_FEATURE_RTM)) {
8635 		vmcs_write(ENT_CONTROLS,
8636 			   vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
8637 		/*
8638 		 * Set DR7.RTM[bit 11] and IA32_DEBUGCTL.RTM[bit 15]
8639 		 * in the guest to enable advanced debugging of RTM
8640 		 * transactional regions.
8641 		 */
8642 		vmcs_write(GUEST_DR7, BIT(11));
8643 		vmcs_write(GUEST_DEBUGCTL, BIT(15));
8644 		single_step_guest("Hardware delivered single-step in "
8645 				  "transactional region", starting_dr6, 0);
8646 		check_db_exit(false, false, false, &xbegin, BIT(16),
8647 			      starting_dr6);
8648 	} else {
8649 		vmcs_write(GUEST_RIP, (u64)&skip_rtm);
8650 		enter_guest();
8651 	}
8652 }
8653 
8654 static void enable_vid(void)
8655 {
8656 	void *virtual_apic_page;
8657 
8658 	assert(cpu_has_apicv());
8659 
8660 	disable_intercept_for_x2apic_msrs();
8661 
8662 	virtual_apic_page = alloc_page();
8663 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
8664 
8665 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
8666 
8667 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
8668 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
8669 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
8670 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
8671 
8672 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY | CPU_TPR_SHADOW);
8673 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VINTD | CPU_VIRT_X2APIC);
8674 }
8675 
8676 static void trigger_ioapic_scan_thread(void *data)
8677 {
8678 	/* Wait until other CPU entered L2 */
8679 	while (vmx_get_test_stage() != 1)
8680 		;
8681 
8682 	/* Trigger ioapic scan */
8683 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
8684 	vmx_set_test_stage(2);
8685 }
8686 
8687 static void irq_79_handler_guest(isr_regs_t *regs)
8688 {
8689 	eoi();
8690 
8691 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
8692 	vmcall();
8693 }
8694 
8695 /*
8696  * Constant for num of busy-loop iterations after which
8697  * a timer interrupt should have happened in host
8698  */
8699 #define TIMER_INTERRUPT_DELAY 100000000
8700 
8701 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
8702 {
8703 	handle_irq(0x79, irq_79_handler_guest);
8704 	irq_enable();
8705 
8706 	/* Signal to L1 CPU to trigger ioapic scan */
8707 	vmx_set_test_stage(1);
8708 	/* Wait until L1 CPU to trigger ioapic scan */
8709 	while (vmx_get_test_stage() != 2)
8710 		;
8711 
8712 	/*
8713 	 * Wait for L0 timer interrupt to be raised while we run in L2
8714 	 * such that L0 will process the IOAPIC scan request before
8715 	 * resuming L2
8716 	 */
8717 	delay(TIMER_INTERRUPT_DELAY);
8718 
8719 	asm volatile ("int $0x79");
8720 }
8721 
8722 static void vmx_eoi_bitmap_ioapic_scan_test(void)
8723 {
8724 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
8725 		report_skip(__func__);
8726 		return;
8727 	}
8728 
8729 	enable_vid();
8730 
8731 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
8732 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
8733 
8734 	/*
8735 	 * Launch L2.
8736 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
8737 	 * In case the reason isn't VMX_VMCALL, the asserion inside
8738 	 * skip_exit_vmcall() will fail.
8739 	 */
8740 	enter_guest();
8741 	skip_exit_vmcall();
8742 
8743 	/* Let L2 finish */
8744 	enter_guest();
8745 	report(1, __func__);
8746 }
8747 
8748 #define HLT_WITH_RVI_VECTOR		(0xf1)
8749 
8750 bool vmx_hlt_with_rvi_guest_isr_fired;
8751 static void vmx_hlt_with_rvi_guest_isr(isr_regs_t *regs)
8752 {
8753 	vmx_hlt_with_rvi_guest_isr_fired = true;
8754 	eoi();
8755 }
8756 
8757 static void vmx_hlt_with_rvi_guest(void)
8758 {
8759 	handle_irq(HLT_WITH_RVI_VECTOR, vmx_hlt_with_rvi_guest_isr);
8760 
8761 	irq_enable();
8762 	asm volatile ("nop");
8763 
8764 	vmcall();
8765 }
8766 
8767 static void vmx_hlt_with_rvi_test(void)
8768 {
8769 	if (!cpu_has_apicv()) {
8770 		report_skip(__func__);
8771 		return;
8772 	}
8773 
8774 	enable_vid();
8775 
8776 	vmx_hlt_with_rvi_guest_isr_fired = false;
8777 	test_set_guest(vmx_hlt_with_rvi_guest);
8778 
8779 	enter_guest();
8780 	skip_exit_vmcall();
8781 
8782 	vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8783 	vmcs_write(GUEST_INT_STATUS, HLT_WITH_RVI_VECTOR);
8784 	enter_guest();
8785 
8786 	report(vmx_hlt_with_rvi_guest_isr_fired, "Interrupt raised in guest");
8787 }
8788 
8789 static void set_irq_line_thread(void *data)
8790 {
8791 	/* Wait until other CPU entered L2 */
8792 	while (vmx_get_test_stage() != 1)
8793 		;
8794 
8795 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
8796 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
8797 	vmx_set_test_stage(2);
8798 }
8799 
8800 static bool irq_78_handler_vmcall_before_eoi;
8801 static void irq_78_handler_guest(isr_regs_t *regs)
8802 {
8803 	set_irq_line(0xf, 0);
8804 	if (irq_78_handler_vmcall_before_eoi)
8805 		vmcall();
8806 	eoi();
8807 	vmcall();
8808 }
8809 
8810 static void vmx_apic_passthrough_guest(void)
8811 {
8812 	handle_irq(0x78, irq_78_handler_guest);
8813 	irq_enable();
8814 
8815 	/* If requested, wait for other CPU to trigger ioapic scan */
8816 	if (vmx_get_test_stage() < 1) {
8817 		vmx_set_test_stage(1);
8818 		while (vmx_get_test_stage() != 2)
8819 			;
8820 	}
8821 
8822 	set_irq_line(0xf, 1);
8823 }
8824 
8825 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
8826 {
8827 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
8828 		report_skip(__func__);
8829 		return;
8830 	}
8831 
8832 	/* Test device is required for generating IRQs */
8833 	if (!test_device_enabled()) {
8834 		report_skip(__func__);
8835 		return;
8836 	}
8837 	u64 cpu_ctrl_0 = CPU_SECONDARY;
8838 	u64 cpu_ctrl_1 = 0;
8839 
8840 	disable_intercept_for_x2apic_msrs();
8841 
8842 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
8843 
8844 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
8845 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
8846 
8847 	if (set_irq_line_from_thread) {
8848 		irq_78_handler_vmcall_before_eoi = false;
8849 		on_cpu_async(1, set_irq_line_thread, NULL);
8850 	} else {
8851 		irq_78_handler_vmcall_before_eoi = true;
8852 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
8853 		vmx_set_test_stage(2);
8854 	}
8855 	test_set_guest(vmx_apic_passthrough_guest);
8856 
8857 	if (irq_78_handler_vmcall_before_eoi) {
8858 		/* Before EOI remote_irr should still be set */
8859 		enter_guest();
8860 		skip_exit_vmcall();
8861 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
8862 			"IOAPIC pass-through: remote_irr=1 before EOI");
8863 	}
8864 
8865 	/* After EOI remote_irr should be cleared */
8866 	enter_guest();
8867 	skip_exit_vmcall();
8868 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
8869 		"IOAPIC pass-through: remote_irr=0 after EOI");
8870 
8871 	/* Let L2 finish */
8872 	enter_guest();
8873 	report(1, __func__);
8874 }
8875 
8876 static void vmx_apic_passthrough_test(void)
8877 {
8878 	vmx_apic_passthrough(false);
8879 }
8880 
8881 static void vmx_apic_passthrough_thread_test(void)
8882 {
8883 	vmx_apic_passthrough(true);
8884 }
8885 
8886 static void vmx_apic_passthrough_tpr_threshold_guest(void)
8887 {
8888 	cli();
8889 	apic_set_tpr(0);
8890 }
8891 
8892 static bool vmx_apic_passthrough_tpr_threshold_ipi_isr_fired;
8893 static void vmx_apic_passthrough_tpr_threshold_ipi_isr(isr_regs_t *regs)
8894 {
8895 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = true;
8896 	eoi();
8897 }
8898 
8899 static void vmx_apic_passthrough_tpr_threshold_test(void)
8900 {
8901 	int ipi_vector = 0xe1;
8902 
8903 	disable_intercept_for_x2apic_msrs();
8904 	vmcs_clear_bits(PIN_CONTROLS, PIN_EXTINT);
8905 
8906 	/* Raise L0 TPR-threshold by queueing vector in LAPIC IRR */
8907 	cli();
8908 	apic_set_tpr((ipi_vector >> 4) + 1);
8909 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
8910 			APIC_DM_FIXED | ipi_vector,
8911 			0);
8912 
8913 	test_set_guest(vmx_apic_passthrough_tpr_threshold_guest);
8914 	enter_guest();
8915 
8916 	report(apic_get_tpr() == 0, "TPR was zero by guest");
8917 
8918 	/* Clean pending self-IPI */
8919 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = false;
8920 	handle_irq(ipi_vector, vmx_apic_passthrough_tpr_threshold_ipi_isr);
8921 	sti();
8922 	asm volatile ("nop");
8923 	report(vmx_apic_passthrough_tpr_threshold_ipi_isr_fired, "self-IPI fired");
8924 
8925 	report(1, __func__);
8926 }
8927 
8928 static u64 init_signal_test_exit_reason;
8929 static bool init_signal_test_thread_continued;
8930 
8931 static void init_signal_test_thread(void *data)
8932 {
8933 	struct vmcs *test_vmcs = data;
8934 
8935 	/* Enter VMX operation (i.e. exec VMXON) */
8936 	u64 *ap_vmxon_region = alloc_page();
8937 	enable_vmx();
8938 	init_vmx(ap_vmxon_region);
8939 	_vmx_on(ap_vmxon_region);
8940 
8941 	/* Signal CPU have entered VMX operation */
8942 	vmx_set_test_stage(1);
8943 
8944 	/* Wait for BSP CPU to send INIT signal */
8945 	while (vmx_get_test_stage() != 2)
8946 		;
8947 
8948 	/*
8949 	 * Signal that we continue as usual as INIT signal
8950 	 * should be blocked while CPU is in VMX operation
8951 	 */
8952 	vmx_set_test_stage(3);
8953 
8954 	/* Wait for signal to enter VMX non-root mode */
8955 	while (vmx_get_test_stage() != 4)
8956 		;
8957 
8958 	/* Enter VMX non-root mode */
8959 	test_set_guest(v2_null_test_guest);
8960 	make_vmcs_current(test_vmcs);
8961 	enter_guest();
8962 	/* Save exit reason for BSP CPU to compare to expected result */
8963 	init_signal_test_exit_reason = vmcs_read(EXI_REASON);
8964 	/* VMCLEAR test-vmcs so it could be loaded by BSP CPU */
8965 	vmcs_clear(test_vmcs);
8966 	launched = false;
8967 	/* Signal that CPU exited to VMX root mode */
8968 	vmx_set_test_stage(5);
8969 
8970 	/* Wait for BSP CPU to signal to exit VMX operation */
8971 	while (vmx_get_test_stage() != 6)
8972 		;
8973 
8974 	/* Exit VMX operation (i.e. exec VMXOFF) */
8975 	vmx_off();
8976 
8977 	/*
8978 	 * Signal to BSP CPU that we continue as usual as INIT signal
8979 	 * should have been consumed by VMX_INIT exit from guest
8980 	 */
8981 	vmx_set_test_stage(7);
8982 
8983 	/* Wait for BSP CPU to signal to enter VMX operation */
8984 	while (vmx_get_test_stage() != 8)
8985 		;
8986 	/* Enter VMX operation (i.e. exec VMXON) */
8987 	_vmx_on(ap_vmxon_region);
8988 	/* Signal to BSP we are in VMX operation */
8989 	vmx_set_test_stage(9);
8990 
8991 	/* Wait for BSP CPU to send INIT signal */
8992 	while (vmx_get_test_stage() != 10)
8993 		;
8994 
8995 	/* Exit VMX operation (i.e. exec VMXOFF) */
8996 	vmx_off();
8997 
8998 	/*
8999 	 * Exiting VMX operation should result in latched
9000 	 * INIT signal being processed. Therefore, we should
9001 	 * never reach the below code. Thus, signal to BSP
9002 	 * CPU if we have reached here so it is able to
9003 	 * report an issue if it happens.
9004 	 */
9005 	init_signal_test_thread_continued = true;
9006 }
9007 
9008 #define INIT_SIGNAL_TEST_DELAY	100000000ULL
9009 
9010 static void vmx_init_signal_test(void)
9011 {
9012 	struct vmcs *test_vmcs;
9013 
9014 	if (cpu_count() < 2) {
9015 		report_skip(__func__);
9016 		return;
9017 	}
9018 
9019 	/* VMCLEAR test-vmcs so it could be loaded by other CPU */
9020 	vmcs_save(&test_vmcs);
9021 	vmcs_clear(test_vmcs);
9022 
9023 	vmx_set_test_stage(0);
9024 	on_cpu_async(1, init_signal_test_thread, test_vmcs);
9025 
9026 	/* Wait for other CPU to enter VMX operation */
9027 	while (vmx_get_test_stage() != 1)
9028 		;
9029 
9030 	/* Send INIT signal to other CPU */
9031 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9032 				   id_map[1]);
9033 	/* Signal other CPU we have sent INIT signal */
9034 	vmx_set_test_stage(2);
9035 
9036 	/*
9037 	 * Wait reasonable amount of time for INIT signal to
9038 	 * be received on other CPU and verify that other CPU
9039 	 * have proceed as usual to next test stage as INIT
9040 	 * signal should be blocked while other CPU in
9041 	 * VMX operation
9042 	 */
9043 	delay(INIT_SIGNAL_TEST_DELAY);
9044 	report(vmx_get_test_stage() == 3,
9045 	       "INIT signal blocked when CPU in VMX operation");
9046 	/* No point to continue if we failed at this point */
9047 	if (vmx_get_test_stage() != 3)
9048 		return;
9049 
9050 	/* Signal other CPU to enter VMX non-root mode */
9051 	init_signal_test_exit_reason = -1ull;
9052 	vmx_set_test_stage(4);
9053 	/*
9054 	 * Wait reasonable amont of time for other CPU
9055 	 * to exit to VMX root mode
9056 	 */
9057 	delay(INIT_SIGNAL_TEST_DELAY);
9058 	if (vmx_get_test_stage() != 5) {
9059 		report(false, "Pending INIT signal didn't result in VMX exit");
9060 		return;
9061 	}
9062 	report(init_signal_test_exit_reason == VMX_INIT,
9063 			"INIT signal during VMX non-root mode result in exit-reason %s (%lu)",
9064 			exit_reason_description(init_signal_test_exit_reason),
9065 			init_signal_test_exit_reason);
9066 
9067 	/* Run guest to completion */
9068 	make_vmcs_current(test_vmcs);
9069 	enter_guest();
9070 
9071 	/* Signal other CPU to exit VMX operation */
9072 	init_signal_test_thread_continued = false;
9073 	vmx_set_test_stage(6);
9074 
9075 	/* Wait reasonable amount of time for other CPU to exit VMX operation */
9076 	delay(INIT_SIGNAL_TEST_DELAY);
9077 	report(vmx_get_test_stage() == 7,
9078 	       "INIT signal consumed on VMX_INIT exit");
9079 	/* No point to continue if we failed at this point */
9080 	if (vmx_get_test_stage() != 7)
9081 		return;
9082 
9083 	/* Signal other CPU to enter VMX operation */
9084 	vmx_set_test_stage(8);
9085 	/* Wait for other CPU to enter VMX operation */
9086 	while (vmx_get_test_stage() != 9)
9087 		;
9088 
9089 	/* Send INIT signal to other CPU */
9090 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9091 				   id_map[1]);
9092 	/* Signal other CPU we have sent INIT signal */
9093 	vmx_set_test_stage(10);
9094 
9095 	/*
9096 	 * Wait reasonable amount of time for other CPU
9097 	 * to exit VMX operation and process INIT signal
9098 	 */
9099 	delay(INIT_SIGNAL_TEST_DELAY);
9100 	report(!init_signal_test_thread_continued,
9101 	       "INIT signal processed after exit VMX operation");
9102 
9103 	/*
9104 	 * TODO: Send SIPI to other CPU to sipi_entry (See x86/cstart64.S)
9105 	 * to re-init it to kvm-unit-tests standard environment.
9106 	 * Somehow (?) verify that SIPI was indeed received.
9107 	 */
9108 }
9109 
9110 enum vmcs_access {
9111 	ACCESS_VMREAD,
9112 	ACCESS_VMWRITE,
9113 	ACCESS_NONE,
9114 };
9115 
9116 struct vmcs_shadow_test_common {
9117 	enum vmcs_access op;
9118 	enum Reason reason;
9119 	u64 field;
9120 	u64 value;
9121 	u64 flags;
9122 	u64 time;
9123 } l1_l2_common;
9124 
9125 static inline u64 vmread_flags(u64 field, u64 *val)
9126 {
9127 	u64 flags;
9128 
9129 	asm volatile ("vmread %2, %1; pushf; pop %0"
9130 		      : "=r" (flags), "=rm" (*val) : "r" (field) : "cc");
9131 	return flags & X86_EFLAGS_ALU;
9132 }
9133 
9134 static inline u64 vmwrite_flags(u64 field, u64 val)
9135 {
9136 	u64 flags;
9137 
9138 	asm volatile ("vmwrite %1, %2; pushf; pop %0"
9139 		      : "=r"(flags) : "rm" (val), "r" (field) : "cc");
9140 	return flags & X86_EFLAGS_ALU;
9141 }
9142 
9143 static void vmx_vmcs_shadow_test_guest(void)
9144 {
9145 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9146 	u64 start;
9147 
9148 	while (c->op != ACCESS_NONE) {
9149 		start = rdtsc();
9150 		switch (c->op) {
9151 		default:
9152 			c->flags = -1ull;
9153 			break;
9154 		case ACCESS_VMREAD:
9155 			c->flags = vmread_flags(c->field, &c->value);
9156 			break;
9157 		case ACCESS_VMWRITE:
9158 			c->flags = vmwrite_flags(c->field, 0);
9159 			break;
9160 		}
9161 		c->time = rdtsc() - start;
9162 		vmcall();
9163 	}
9164 }
9165 
9166 static u64 vmread_from_shadow(u64 field)
9167 {
9168 	struct vmcs *primary;
9169 	struct vmcs *shadow;
9170 	u64 value;
9171 
9172 	TEST_ASSERT(!vmcs_save(&primary));
9173 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9174 	TEST_ASSERT(!make_vmcs_current(shadow));
9175 	value = vmcs_read(field);
9176 	TEST_ASSERT(!make_vmcs_current(primary));
9177 	return value;
9178 }
9179 
9180 static u64 vmwrite_to_shadow(u64 field, u64 value)
9181 {
9182 	struct vmcs *primary;
9183 	struct vmcs *shadow;
9184 
9185 	TEST_ASSERT(!vmcs_save(&primary));
9186 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9187 	TEST_ASSERT(!make_vmcs_current(shadow));
9188 	vmcs_write(field, value);
9189 	value = vmcs_read(field);
9190 	TEST_ASSERT(!make_vmcs_current(primary));
9191 	return value;
9192 }
9193 
9194 static void vmcs_shadow_test_access(u8 *bitmap[2], enum vmcs_access access)
9195 {
9196 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9197 
9198 	c->op = access;
9199 	vmcs_write(VMX_INST_ERROR, 0);
9200 	enter_guest();
9201 	c->reason = vmcs_read(EXI_REASON) & 0xffff;
9202 	if (c->reason != VMX_VMCALL) {
9203 		skip_exit_insn();
9204 		enter_guest();
9205 	}
9206 	skip_exit_vmcall();
9207 }
9208 
9209 static void vmcs_shadow_test_field(u8 *bitmap[2], u64 field)
9210 {
9211 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9212 	struct vmcs *shadow;
9213 	u64 value;
9214 	uintptr_t flags[2];
9215 	bool good_shadow;
9216 	u32 vmx_inst_error;
9217 
9218 	report_prefix_pushf("field %lx", field);
9219 	c->field = field;
9220 
9221 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9222 	if (shadow != (struct vmcs *)-1ull) {
9223 		flags[ACCESS_VMREAD] = vmread_flags(field, &value);
9224 		flags[ACCESS_VMWRITE] = vmwrite_flags(field, value);
9225 		good_shadow = !flags[ACCESS_VMREAD] && !flags[ACCESS_VMWRITE];
9226 	} else {
9227 		/*
9228 		 * When VMCS link pointer is -1ull, VMWRITE/VMREAD on
9229 		 * shadowed-fields should fail with setting RFLAGS.CF.
9230 		 */
9231 		flags[ACCESS_VMREAD] = X86_EFLAGS_CF;
9232 		flags[ACCESS_VMWRITE] = X86_EFLAGS_CF;
9233 		good_shadow = false;
9234 	}
9235 
9236 	/* Intercept both VMREAD and VMWRITE. */
9237 	report_prefix_push("no VMREAD/VMWRITE permission");
9238 	/* VMWRITE/VMREAD done on reserved-bit should always intercept */
9239 	if (!(field >> VMCS_FIELD_RESERVED_SHIFT)) {
9240 		set_bit(field, bitmap[ACCESS_VMREAD]);
9241 		set_bit(field, bitmap[ACCESS_VMWRITE]);
9242 	}
9243 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9244 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
9245 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9246 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
9247 	report_prefix_pop();
9248 
9249 	if (field >> VMCS_FIELD_RESERVED_SHIFT)
9250 		goto out;
9251 
9252 	/* Permit shadowed VMREAD. */
9253 	report_prefix_push("VMREAD permission only");
9254 	clear_bit(field, bitmap[ACCESS_VMREAD]);
9255 	set_bit(field, bitmap[ACCESS_VMWRITE]);
9256 	if (good_shadow)
9257 		value = vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9258 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9259 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
9260 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9261 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9262 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
9263 	       c->time);
9264 	report(c->flags == flags[ACCESS_VMREAD],
9265 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
9266 	       c->flags, flags[ACCESS_VMREAD]);
9267 	if (good_shadow)
9268 		report(c->value == value,
9269 		       "value read from shadow (%lx) is as expected (%lx)",
9270 		       c->value, value);
9271 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
9272 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9273 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9274 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9275 	report_prefix_pop();
9276 
9277 	/* Permit shadowed VMWRITE. */
9278 	report_prefix_push("VMWRITE permission only");
9279 	set_bit(field, bitmap[ACCESS_VMREAD]);
9280 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
9281 	if (good_shadow)
9282 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9283 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9284 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9285 	report(c->reason == VMX_VMCALL,
9286 		"shadowed for VMWRITE (in %ld cycles)",
9287 		c->time);
9288 	report(c->flags == flags[ACCESS_VMREAD],
9289 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
9290 	       c->flags, flags[ACCESS_VMREAD]);
9291 	if (good_shadow) {
9292 		value = vmread_from_shadow(field);
9293 		report(value == 0,
9294 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
9295 		       0ul);
9296 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
9297 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9298 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9299 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9300 	}
9301 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9302 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
9303 	report_prefix_pop();
9304 
9305 	/* Permit shadowed VMREAD and VMWRITE. */
9306 	report_prefix_push("VMREAD and VMWRITE permission");
9307 	clear_bit(field, bitmap[ACCESS_VMREAD]);
9308 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
9309 	if (good_shadow)
9310 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9311 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9312 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9313 	report(c->reason == VMX_VMCALL,
9314 		"shadowed for VMWRITE (in %ld cycles)",
9315 		c->time);
9316 	report(c->flags == flags[ACCESS_VMREAD],
9317 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
9318 	       c->flags, flags[ACCESS_VMREAD]);
9319 	if (good_shadow) {
9320 		value = vmread_from_shadow(field);
9321 		report(value == 0,
9322 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
9323 		       0ul);
9324 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
9325 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9326 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9327 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9328 	}
9329 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9330 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9331 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
9332 	       c->time);
9333 	report(c->flags == flags[ACCESS_VMREAD],
9334 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
9335 	       c->flags, flags[ACCESS_VMREAD]);
9336 	if (good_shadow)
9337 		report(c->value == 0,
9338 		       "value read from shadow (%lx) is as expected (%lx)",
9339 		       c->value, 0ul);
9340 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
9341 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9342 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9343 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9344 	report_prefix_pop();
9345 
9346 out:
9347 	report_prefix_pop();
9348 }
9349 
9350 static void vmx_vmcs_shadow_test_body(u8 *bitmap[2])
9351 {
9352 	unsigned base;
9353 	unsigned index;
9354 	unsigned bit;
9355 	unsigned highest_index = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
9356 
9357 	/* Run test on all possible valid VMCS fields */
9358 	for (base = 0;
9359 	     base < (1 << VMCS_FIELD_RESERVED_SHIFT);
9360 	     base += (1 << VMCS_FIELD_TYPE_SHIFT))
9361 		for (index = 0; index <= highest_index; index++)
9362 			vmcs_shadow_test_field(bitmap, base + index);
9363 
9364 	/*
9365 	 * Run tests on some invalid VMCS fields
9366 	 * (Have reserved bit set).
9367 	 */
9368 	for (bit = VMCS_FIELD_RESERVED_SHIFT; bit < VMCS_FIELD_BIT_SIZE; bit++)
9369 		vmcs_shadow_test_field(bitmap, (1ull << bit));
9370 }
9371 
9372 static void vmx_vmcs_shadow_test(void)
9373 {
9374 	u8 *bitmap[2];
9375 	struct vmcs *shadow;
9376 
9377 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
9378 		printf("\t'Activate secondary controls' not supported.\n");
9379 		return;
9380 	}
9381 
9382 	if (!(ctrl_cpu_rev[1].clr & CPU_SHADOW_VMCS)) {
9383 		printf("\t'VMCS shadowing' not supported.\n");
9384 		return;
9385 	}
9386 
9387 	if (!(rdmsr(MSR_IA32_VMX_MISC) &
9388 	      MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) {
9389 		printf("\tVMWRITE can't modify VM-exit information fields.\n");
9390 		return;
9391 	}
9392 
9393 	test_set_guest(vmx_vmcs_shadow_test_guest);
9394 
9395 	bitmap[ACCESS_VMREAD] = alloc_page();
9396 	bitmap[ACCESS_VMWRITE] = alloc_page();
9397 
9398 	vmcs_write(VMREAD_BITMAP, virt_to_phys(bitmap[ACCESS_VMREAD]));
9399 	vmcs_write(VMWRITE_BITMAP, virt_to_phys(bitmap[ACCESS_VMWRITE]));
9400 
9401 	shadow = alloc_page();
9402 	shadow->hdr.revision_id = basic.revision;
9403 	shadow->hdr.shadow_vmcs = 1;
9404 	TEST_ASSERT(!vmcs_clear(shadow));
9405 
9406 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_RDTSC);
9407 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
9408 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_SHADOW_VMCS);
9409 
9410 	vmcs_write(VMCS_LINK_PTR, virt_to_phys(shadow));
9411 	report_prefix_push("valid link pointer");
9412 	vmx_vmcs_shadow_test_body(bitmap);
9413 	report_prefix_pop();
9414 
9415 	vmcs_write(VMCS_LINK_PTR, -1ull);
9416 	report_prefix_push("invalid link pointer");
9417 	vmx_vmcs_shadow_test_body(bitmap);
9418 	report_prefix_pop();
9419 
9420 	l1_l2_common.op = ACCESS_NONE;
9421 	enter_guest();
9422 }
9423 
9424 /*
9425  * This test monitors the difference between a guest RDTSC instruction
9426  * and the IA32_TIME_STAMP_COUNTER MSR value stored in the VMCS12
9427  * VM-exit MSR-store list when taking a VM-exit on the instruction
9428  * following RDTSC.
9429  */
9430 #define RDTSC_DIFF_ITERS 100000
9431 #define RDTSC_DIFF_FAILS 100
9432 #define HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD 750
9433 
9434 /*
9435  * Set 'use TSC offsetting' and set the guest offset to the
9436  * inverse of the host's current TSC value, so that the guest starts running
9437  * with an effective TSC value of 0.
9438  */
9439 static void reset_guest_tsc_to_zero(void)
9440 {
9441 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
9442 	vmcs_write(TSC_OFFSET, -rdtsc());
9443 }
9444 
9445 static void rdtsc_vmexit_diff_test_guest(void)
9446 {
9447 	int i;
9448 
9449 	for (i = 0; i < RDTSC_DIFF_ITERS; i++)
9450 		/* Ensure rdtsc is the last instruction before the vmcall. */
9451 		asm volatile("rdtsc; vmcall" : : : "eax", "edx");
9452 }
9453 
9454 /*
9455  * This function only considers the "use TSC offsetting" VM-execution
9456  * control.  It does not handle "use TSC scaling" (because the latter
9457  * isn't available to the host today.)
9458  */
9459 static unsigned long long host_time_to_guest_time(unsigned long long t)
9460 {
9461 	TEST_ASSERT(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
9462 		    !(vmcs_read(CPU_EXEC_CTRL1) & CPU_USE_TSC_SCALING));
9463 
9464 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_USE_TSC_OFFSET)
9465 		t += vmcs_read(TSC_OFFSET);
9466 
9467 	return t;
9468 }
9469 
9470 static unsigned long long rdtsc_vmexit_diff_test_iteration(void)
9471 {
9472 	unsigned long long guest_tsc, host_to_guest_tsc;
9473 
9474 	enter_guest();
9475 	skip_exit_vmcall();
9476 	guest_tsc = (u32) regs.rax + (regs.rdx << 32);
9477 	host_to_guest_tsc = host_time_to_guest_time(exit_msr_store[0].value);
9478 
9479 	return host_to_guest_tsc - guest_tsc;
9480 }
9481 
9482 static void rdtsc_vmexit_diff_test(void)
9483 {
9484 	int fail = 0;
9485 	int i;
9486 
9487 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET))
9488 		test_skip("CPU doesn't support the 'use TSC offsetting' processor-based VM-execution control.\n");
9489 
9490 	test_set_guest(rdtsc_vmexit_diff_test_guest);
9491 
9492 	reset_guest_tsc_to_zero();
9493 
9494 	/*
9495 	 * Set up the VMCS12 VM-exit MSR-store list to store just one
9496 	 * MSR: IA32_TIME_STAMP_COUNTER. Note that the value stored is
9497 	 * in the host time domain (i.e., it is not adjusted according
9498 	 * to the TSC multiplier and TSC offset fields in the VMCS12,
9499 	 * as a guest RDTSC would be.)
9500 	 */
9501 	exit_msr_store = alloc_page();
9502 	exit_msr_store[0].index = MSR_IA32_TSC;
9503 	vmcs_write(EXI_MSR_ST_CNT, 1);
9504 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(exit_msr_store));
9505 
9506 	for (i = 0; i < RDTSC_DIFF_ITERS; i++) {
9507 		if (rdtsc_vmexit_diff_test_iteration() >=
9508 		    HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD)
9509 			fail++;
9510 	}
9511 
9512 	enter_guest();
9513 
9514 	report(fail < RDTSC_DIFF_FAILS,
9515 	       "RDTSC to VM-exit delta too high in %d of %d iterations",
9516 	       fail, RDTSC_DIFF_ITERS);
9517 }
9518 
9519 static int invalid_msr_init(struct vmcs *vmcs)
9520 {
9521 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
9522 		printf("\tPreemption timer is not supported\n");
9523 		return VMX_TEST_EXIT;
9524 	}
9525 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
9526 	preempt_val = 10000000;
9527 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
9528 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
9529 
9530 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
9531 		printf("\tSave preemption value is not supported\n");
9532 
9533 	vmcs_write(ENT_MSR_LD_CNT, 1);
9534 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)0x13370000);
9535 
9536 	return VMX_TEST_START;
9537 }
9538 
9539 
9540 static void invalid_msr_main(void)
9541 {
9542 	report(0, "Invalid MSR load");
9543 }
9544 
9545 static int invalid_msr_exit_handler(union exit_reason exit_reason)
9546 {
9547 	report(0, "Invalid MSR load");
9548 	print_vmexit_info(exit_reason);
9549 	return VMX_TEST_EXIT;
9550 }
9551 
9552 static int invalid_msr_entry_failure(struct vmentry_result *result)
9553 {
9554 	report(result->exit_reason.failed_vmentry &&
9555 	       result->exit_reason.basic == VMX_FAIL_MSR, "Invalid MSR load");
9556 	return VMX_TEST_VMEXIT;
9557 }
9558 
9559 /*
9560  * The max number of MSRs in an atomic switch MSR list is:
9561  * (111B + 1) * 512 = 4096
9562  *
9563  * Each list entry consumes:
9564  * 4-byte MSR index + 4 bytes reserved + 8-byte data = 16 bytes
9565  *
9566  * Allocate 128 kB to cover max_msr_list_size (i.e., 64 kB) and then some.
9567  */
9568 static const u32 msr_list_page_order = 5;
9569 
9570 static void atomic_switch_msr_limit_test_guest(void)
9571 {
9572 	vmcall();
9573 }
9574 
9575 static void populate_msr_list(struct vmx_msr_entry *msr_list,
9576 			      size_t byte_capacity, int count)
9577 {
9578 	int i;
9579 
9580 	for (i = 0; i < count; i++) {
9581 		msr_list[i].index = MSR_IA32_TSC;
9582 		msr_list[i].reserved = 0;
9583 		msr_list[i].value = 0x1234567890abcdef;
9584 	}
9585 
9586 	memset(msr_list + count, 0xff,
9587 	       byte_capacity - count * sizeof(*msr_list));
9588 }
9589 
9590 static int max_msr_list_size(void)
9591 {
9592 	u32 vmx_misc = rdmsr(MSR_IA32_VMX_MISC);
9593 	u32 factor = ((vmx_misc & GENMASK(27, 25)) >> 25) + 1;
9594 
9595 	return factor * 512;
9596 }
9597 
9598 static void atomic_switch_msrs_test(int count)
9599 {
9600 	struct vmx_msr_entry *vm_enter_load;
9601         struct vmx_msr_entry *vm_exit_load;
9602         struct vmx_msr_entry *vm_exit_store;
9603 	int max_allowed = max_msr_list_size();
9604 	int byte_capacity = 1ul << (msr_list_page_order + PAGE_SHIFT);
9605 	/* Exceeding the max MSR list size at exit trigers KVM to abort. */
9606 	int exit_count = count > max_allowed ? max_allowed : count;
9607 	int cleanup_count = count > max_allowed ? 2 : 1;
9608 	int i;
9609 
9610 	/*
9611 	 * Check for the IA32_TSC MSR,
9612 	 * available with the "TSC flag" and used to populate the MSR lists.
9613 	 */
9614 	if (!(cpuid(1).d & (1 << 4))) {
9615 		report_skip(__func__);
9616 		return;
9617 	}
9618 
9619 	/* Set L2 guest. */
9620 	test_set_guest(atomic_switch_msr_limit_test_guest);
9621 
9622 	/* Setup atomic MSR switch lists. */
9623 	vm_enter_load = alloc_pages(msr_list_page_order);
9624 	vm_exit_load = alloc_pages(msr_list_page_order);
9625 	vm_exit_store = alloc_pages(msr_list_page_order);
9626 
9627 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)vm_enter_load);
9628 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)vm_exit_load);
9629 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)vm_exit_store);
9630 
9631 	/*
9632 	 * VM-Enter should succeed up to the max number of MSRs per list, and
9633 	 * should not consume junk beyond the last entry.
9634 	 */
9635 	populate_msr_list(vm_enter_load, byte_capacity, count);
9636 	populate_msr_list(vm_exit_load, byte_capacity, exit_count);
9637 	populate_msr_list(vm_exit_store, byte_capacity, exit_count);
9638 
9639 	vmcs_write(ENT_MSR_LD_CNT, count);
9640 	vmcs_write(EXI_MSR_LD_CNT, exit_count);
9641 	vmcs_write(EXI_MSR_ST_CNT, exit_count);
9642 
9643 	if (count <= max_allowed) {
9644 		enter_guest();
9645 		assert_exit_reason(VMX_VMCALL);
9646 		skip_exit_vmcall();
9647 	} else {
9648 		u32 exit_qual;
9649 
9650 		test_guest_state("Invalid MSR Load Count", true, count,
9651 				 "ENT_MSR_LD_CNT");
9652 
9653 		exit_qual = vmcs_read(EXI_QUALIFICATION);
9654 		report(exit_qual == max_allowed + 1, "exit_qual, %u, is %u.",
9655 		       exit_qual, max_allowed + 1);
9656 	}
9657 
9658 	/* Cleanup. */
9659 	vmcs_write(ENT_MSR_LD_CNT, 0);
9660 	vmcs_write(EXI_MSR_LD_CNT, 0);
9661 	vmcs_write(EXI_MSR_ST_CNT, 0);
9662 	for (i = 0; i < cleanup_count; i++) {
9663 		enter_guest();
9664 		skip_exit_vmcall();
9665 	}
9666 	free_pages_by_order(vm_enter_load, msr_list_page_order);
9667 	free_pages_by_order(vm_exit_load, msr_list_page_order);
9668 	free_pages_by_order(vm_exit_store, msr_list_page_order);
9669 }
9670 
9671 static void atomic_switch_max_msrs_test(void)
9672 {
9673 	atomic_switch_msrs_test(max_msr_list_size());
9674 }
9675 
9676 static void atomic_switch_overflow_msrs_test(void)
9677 {
9678 	if (test_device_enabled())
9679 		atomic_switch_msrs_test(max_msr_list_size() + 1);
9680 	else
9681 		test_skip("Test is only supported on KVM");
9682 }
9683 
9684 #define TEST(name) { #name, .v2 = name }
9685 
9686 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
9687 struct vmx_test vmx_tests[] = {
9688 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
9689 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
9690 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
9691 		preemption_timer_exit_handler, NULL, {0} },
9692 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
9693 		test_ctrl_pat_exit_handler, NULL, {0} },
9694 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
9695 		test_ctrl_efer_exit_handler, NULL, {0} },
9696 	{ "CR shadowing", NULL, cr_shadowing_main,
9697 		cr_shadowing_exit_handler, NULL, {0} },
9698 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
9699 		NULL, {0} },
9700 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
9701 		insn_intercept_exit_handler, NULL, {0} },
9702 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
9703 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
9704 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
9705 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
9706 	{ "interrupt", interrupt_init, interrupt_main,
9707 		interrupt_exit_handler, NULL, {0} },
9708 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
9709 		NULL, {0} },
9710 	{ "MSR switch", msr_switch_init, msr_switch_main,
9711 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
9712 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
9713 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
9714 		disable_rdtscp_exit_handler, NULL, {0} },
9715 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
9716 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
9717 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
9718 		exit_monitor_from_l2_handler, NULL, {0} },
9719 	{ "invalid_msr", invalid_msr_init, invalid_msr_main,
9720 		invalid_msr_exit_handler, NULL, {0}, invalid_msr_entry_failure},
9721 	/* Basic V2 tests. */
9722 	TEST(v2_null_test),
9723 	TEST(v2_multiple_entries_test),
9724 	TEST(fixture_test_case1),
9725 	TEST(fixture_test_case2),
9726 	/* Opcode tests. */
9727 	TEST(invvpid_test_v2),
9728 	/* VM-entry tests */
9729 	TEST(vmx_controls_test),
9730 	TEST(vmx_host_state_area_test),
9731 	TEST(vmx_guest_state_area_test),
9732 	TEST(vmentry_movss_shadow_test),
9733 	/* APICv tests */
9734 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
9735 	TEST(vmx_hlt_with_rvi_test),
9736 	TEST(apic_reg_virt_test),
9737 	TEST(virt_x2apic_mode_test),
9738 	/* APIC pass-through tests */
9739 	TEST(vmx_apic_passthrough_test),
9740 	TEST(vmx_apic_passthrough_thread_test),
9741 	TEST(vmx_apic_passthrough_tpr_threshold_test),
9742 	TEST(vmx_init_signal_test),
9743 	/* VMCS Shadowing tests */
9744 	TEST(vmx_vmcs_shadow_test),
9745 	/* Regression tests */
9746 	TEST(vmx_cr_load_test),
9747 	TEST(vmx_nm_test),
9748 	TEST(vmx_db_test),
9749 	TEST(vmx_nmi_window_test),
9750 	TEST(vmx_intr_window_test),
9751 	TEST(vmx_pending_event_test),
9752 	TEST(vmx_pending_event_hlt_test),
9753 	TEST(vmx_store_tsc_test),
9754 	TEST(vmx_preemption_timer_zero_test),
9755 	/* EPT access tests. */
9756 	TEST(ept_access_test_not_present),
9757 	TEST(ept_access_test_read_only),
9758 	TEST(ept_access_test_write_only),
9759 	TEST(ept_access_test_read_write),
9760 	TEST(ept_access_test_execute_only),
9761 	TEST(ept_access_test_read_execute),
9762 	TEST(ept_access_test_write_execute),
9763 	TEST(ept_access_test_read_write_execute),
9764 	TEST(ept_access_test_reserved_bits),
9765 	TEST(ept_access_test_ignored_bits),
9766 	TEST(ept_access_test_paddr_not_present_ad_disabled),
9767 	TEST(ept_access_test_paddr_not_present_ad_enabled),
9768 	TEST(ept_access_test_paddr_read_only_ad_disabled),
9769 	TEST(ept_access_test_paddr_read_only_ad_enabled),
9770 	TEST(ept_access_test_paddr_read_write),
9771 	TEST(ept_access_test_paddr_read_write_execute),
9772 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
9773 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
9774 	TEST(ept_access_test_paddr_not_present_page_fault),
9775 	TEST(ept_access_test_force_2m_page),
9776 	/* Atomic MSR switch tests. */
9777 	TEST(atomic_switch_max_msrs_test),
9778 	TEST(atomic_switch_overflow_msrs_test),
9779 	TEST(rdtsc_vmexit_diff_test),
9780 	TEST(vmx_mtf_test),
9781 	{ NULL, NULL, NULL, NULL, NULL, {0} },
9782 };
9783