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