xref: /kvm-unit-tests/x86/vmx_tests.c (revision d065566f60288636c23753bad77f14c23d03b544)
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 	memset(msr_bitmap, 0x0, PAGE_SIZE);
257 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
258 	ctrl_cpu0 |= CPU_MSR_BITMAP;
259 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
260 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
261 }
262 
263 static void *get_msr_bitmap(void)
264 {
265 	void *msr_bitmap;
266 
267 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_MSR_BITMAP) {
268 		msr_bitmap = (void *)vmcs_read(MSR_BITMAP);
269 	} else {
270 		msr_bitmap = alloc_page();
271 		memset(msr_bitmap, 0xff, PAGE_SIZE);
272 		vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
273 		vmcs_set_bits(CPU_EXEC_CTRL0, CPU_MSR_BITMAP);
274 	}
275 
276 	return msr_bitmap;
277 }
278 
279 static void disable_intercept_for_x2apic_msrs(void)
280 {
281 	unsigned long *msr_bitmap = (unsigned long *)get_msr_bitmap();
282 	u32 msr;
283 
284 	for (msr = APIC_BASE_MSR;
285 		 msr < (APIC_BASE_MSR+0xff);
286 		 msr += BITS_PER_LONG) {
287 		unsigned int word = msr / BITS_PER_LONG;
288 
289 		msr_bitmap[word] = 0;
290 		msr_bitmap[word + (0x800 / sizeof(long))] = 0;
291 	}
292 }
293 
294 static int test_ctrl_pat_init(struct vmcs *vmcs)
295 {
296 	u64 ctrl_ent;
297 	u64 ctrl_exi;
298 
299 	msr_bmp_init();
300 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
301 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
302 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
303 		printf("\tSave/load PAT is not supported\n");
304 		return 1;
305 	}
306 
307 	ctrl_ent = vmcs_read(ENT_CONTROLS);
308 	ctrl_exi = vmcs_read(EXI_CONTROLS);
309 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
310 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
311 	vmcs_write(ENT_CONTROLS, ctrl_ent);
312 	vmcs_write(EXI_CONTROLS, ctrl_exi);
313 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
314 	vmcs_write(GUEST_PAT, 0x0);
315 	vmcs_write(HOST_PAT, ia32_pat);
316 	return VMX_TEST_START;
317 }
318 
319 static void test_ctrl_pat_main(void)
320 {
321 	u64 guest_ia32_pat;
322 
323 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
324 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
325 		printf("\tENT_LOAD_PAT is not supported.\n");
326 	else {
327 		if (guest_ia32_pat != 0) {
328 			report("Entry load PAT", 0);
329 			return;
330 		}
331 	}
332 	wrmsr(MSR_IA32_CR_PAT, 0x6);
333 	vmcall();
334 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
335 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
336 		report("Entry load PAT", guest_ia32_pat == ia32_pat);
337 }
338 
339 static int test_ctrl_pat_exit_handler(void)
340 {
341 	u64 guest_rip;
342 	ulong reason;
343 	u64 guest_pat;
344 
345 	guest_rip = vmcs_read(GUEST_RIP);
346 	reason = vmcs_read(EXI_REASON) & 0xff;
347 	switch (reason) {
348 	case VMX_VMCALL:
349 		guest_pat = vmcs_read(GUEST_PAT);
350 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
351 			printf("\tEXI_SAVE_PAT is not supported\n");
352 			vmcs_write(GUEST_PAT, 0x6);
353 		} else {
354 			report("Exit save PAT", guest_pat == 0x6);
355 		}
356 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
357 			printf("\tEXI_LOAD_PAT is not supported\n");
358 		else
359 			report("Exit load PAT", rdmsr(MSR_IA32_CR_PAT) == ia32_pat);
360 		vmcs_write(GUEST_PAT, ia32_pat);
361 		vmcs_write(GUEST_RIP, guest_rip + 3);
362 		return VMX_TEST_RESUME;
363 	default:
364 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
365 		break;
366 	}
367 	return VMX_TEST_VMEXIT;
368 }
369 
370 static int test_ctrl_efer_init(struct vmcs *vmcs)
371 {
372 	u64 ctrl_ent;
373 	u64 ctrl_exi;
374 
375 	msr_bmp_init();
376 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
377 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
378 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
379 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
380 	ia32_efer = rdmsr(MSR_EFER);
381 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
382 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
383 	return VMX_TEST_START;
384 }
385 
386 static void test_ctrl_efer_main(void)
387 {
388 	u64 guest_ia32_efer;
389 
390 	guest_ia32_efer = rdmsr(MSR_EFER);
391 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
392 		printf("\tENT_LOAD_EFER is not supported.\n");
393 	else {
394 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
395 			report("Entry load EFER", 0);
396 			return;
397 		}
398 	}
399 	wrmsr(MSR_EFER, ia32_efer);
400 	vmcall();
401 	guest_ia32_efer = rdmsr(MSR_EFER);
402 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
403 		report("Entry load EFER", guest_ia32_efer == ia32_efer);
404 }
405 
406 static int test_ctrl_efer_exit_handler(void)
407 {
408 	u64 guest_rip;
409 	ulong reason;
410 	u64 guest_efer;
411 
412 	guest_rip = vmcs_read(GUEST_RIP);
413 	reason = vmcs_read(EXI_REASON) & 0xff;
414 	switch (reason) {
415 	case VMX_VMCALL:
416 		guest_efer = vmcs_read(GUEST_EFER);
417 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
418 			printf("\tEXI_SAVE_EFER is not supported\n");
419 			vmcs_write(GUEST_EFER, ia32_efer);
420 		} else {
421 			report("Exit save EFER", guest_efer == ia32_efer);
422 		}
423 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
424 			printf("\tEXI_LOAD_EFER is not supported\n");
425 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
426 		} else {
427 			report("Exit load EFER", rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX));
428 		}
429 		vmcs_write(GUEST_PAT, ia32_efer);
430 		vmcs_write(GUEST_RIP, guest_rip + 3);
431 		return VMX_TEST_RESUME;
432 	default:
433 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
434 		break;
435 	}
436 	return VMX_TEST_VMEXIT;
437 }
438 
439 u32 guest_cr0, guest_cr4;
440 
441 static void cr_shadowing_main(void)
442 {
443 	u32 cr0, cr4, tmp;
444 
445 	// Test read through
446 	vmx_set_test_stage(0);
447 	guest_cr0 = read_cr0();
448 	if (vmx_get_test_stage() == 1)
449 		report("Read through CR0", 0);
450 	else
451 		vmcall();
452 	vmx_set_test_stage(1);
453 	guest_cr4 = read_cr4();
454 	if (vmx_get_test_stage() == 2)
455 		report("Read through CR4", 0);
456 	else
457 		vmcall();
458 	// Test write through
459 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
460 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
461 	vmx_set_test_stage(2);
462 	write_cr0(guest_cr0);
463 	if (vmx_get_test_stage() == 3)
464 		report("Write throuth CR0", 0);
465 	else
466 		vmcall();
467 	vmx_set_test_stage(3);
468 	write_cr4(guest_cr4);
469 	if (vmx_get_test_stage() == 4)
470 		report("Write through CR4", 0);
471 	else
472 		vmcall();
473 	// Test read shadow
474 	vmx_set_test_stage(4);
475 	vmcall();
476 	cr0 = read_cr0();
477 	if (vmx_get_test_stage() != 5)
478 		report("Read shadowing CR0", cr0 == guest_cr0);
479 	vmx_set_test_stage(5);
480 	cr4 = read_cr4();
481 	if (vmx_get_test_stage() != 6)
482 		report("Read shadowing CR4", cr4 == guest_cr4);
483 	// Test write shadow (same value with shadow)
484 	vmx_set_test_stage(6);
485 	write_cr0(guest_cr0);
486 	if (vmx_get_test_stage() == 7)
487 		report("Write shadowing CR0 (same value with shadow)", 0);
488 	else
489 		vmcall();
490 	vmx_set_test_stage(7);
491 	write_cr4(guest_cr4);
492 	if (vmx_get_test_stage() == 8)
493 		report("Write shadowing CR4 (same value with shadow)", 0);
494 	else
495 		vmcall();
496 	// Test write shadow (different value)
497 	vmx_set_test_stage(8);
498 	tmp = guest_cr0 ^ X86_CR0_TS;
499 	asm volatile("mov %0, %%rsi\n\t"
500 		"mov %%rsi, %%cr0\n\t"
501 		::"m"(tmp)
502 		:"rsi", "memory", "cc");
503 	report("Write shadowing different X86_CR0_TS", vmx_get_test_stage() == 9);
504 	vmx_set_test_stage(9);
505 	tmp = guest_cr0 ^ X86_CR0_MP;
506 	asm volatile("mov %0, %%rsi\n\t"
507 		"mov %%rsi, %%cr0\n\t"
508 		::"m"(tmp)
509 		:"rsi", "memory", "cc");
510 	report("Write shadowing different X86_CR0_MP", vmx_get_test_stage() == 10);
511 	vmx_set_test_stage(10);
512 	tmp = guest_cr4 ^ X86_CR4_TSD;
513 	asm volatile("mov %0, %%rsi\n\t"
514 		"mov %%rsi, %%cr4\n\t"
515 		::"m"(tmp)
516 		:"rsi", "memory", "cc");
517 	report("Write shadowing different X86_CR4_TSD", vmx_get_test_stage() == 11);
518 	vmx_set_test_stage(11);
519 	tmp = guest_cr4 ^ X86_CR4_DE;
520 	asm volatile("mov %0, %%rsi\n\t"
521 		"mov %%rsi, %%cr4\n\t"
522 		::"m"(tmp)
523 		:"rsi", "memory", "cc");
524 	report("Write shadowing different X86_CR4_DE", vmx_get_test_stage() == 12);
525 }
526 
527 static int cr_shadowing_exit_handler(void)
528 {
529 	u64 guest_rip;
530 	ulong reason;
531 	u32 insn_len;
532 	u32 exit_qual;
533 
534 	guest_rip = vmcs_read(GUEST_RIP);
535 	reason = vmcs_read(EXI_REASON) & 0xff;
536 	insn_len = vmcs_read(EXI_INST_LEN);
537 	exit_qual = vmcs_read(EXI_QUALIFICATION);
538 	switch (reason) {
539 	case VMX_VMCALL:
540 		switch (vmx_get_test_stage()) {
541 		case 0:
542 			report("Read through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
543 			break;
544 		case 1:
545 			report("Read through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
546 			break;
547 		case 2:
548 			report("Write through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
549 			break;
550 		case 3:
551 			report("Write through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
552 			break;
553 		case 4:
554 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
555 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
556 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
557 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
558 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
559 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
560 			break;
561 		case 6:
562 			report("Write shadowing CR0 (same value)",
563 					guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)));
564 			break;
565 		case 7:
566 			report("Write shadowing CR4 (same value)",
567 					guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)));
568 			break;
569 		default:
570 			// Should not reach here
571 			report("unexpected stage, %d", false,
572 			       vmx_get_test_stage());
573 			print_vmexit_info();
574 			return VMX_TEST_VMEXIT;
575 		}
576 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
577 		return VMX_TEST_RESUME;
578 	case VMX_CR:
579 		switch (vmx_get_test_stage()) {
580 		case 4:
581 			report("Read shadowing CR0", 0);
582 			vmx_inc_test_stage();
583 			break;
584 		case 5:
585 			report("Read shadowing CR4", 0);
586 			vmx_inc_test_stage();
587 			break;
588 		case 6:
589 			report("Write shadowing CR0 (same value)", 0);
590 			vmx_inc_test_stage();
591 			break;
592 		case 7:
593 			report("Write shadowing CR4 (same value)", 0);
594 			vmx_inc_test_stage();
595 			break;
596 		case 8:
597 		case 9:
598 			// 0x600 encodes "mov %esi, %cr0"
599 			if (exit_qual == 0x600)
600 				vmx_inc_test_stage();
601 			break;
602 		case 10:
603 		case 11:
604 			// 0x604 encodes "mov %esi, %cr4"
605 			if (exit_qual == 0x604)
606 				vmx_inc_test_stage();
607 			break;
608 		default:
609 			// Should not reach here
610 			report("unexpected stage, %d", false,
611 			       vmx_get_test_stage());
612 			print_vmexit_info();
613 			return VMX_TEST_VMEXIT;
614 		}
615 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
616 		return VMX_TEST_RESUME;
617 	default:
618 		report("Unknown exit reason, %ld", false, reason);
619 		print_vmexit_info();
620 	}
621 	return VMX_TEST_VMEXIT;
622 }
623 
624 static int iobmp_init(struct vmcs *vmcs)
625 {
626 	u32 ctrl_cpu0;
627 
628 	io_bitmap_a = alloc_page();
629 	io_bitmap_b = alloc_page();
630 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
631 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
632 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
633 	ctrl_cpu0 |= CPU_IO_BITMAP;
634 	ctrl_cpu0 &= (~CPU_IO);
635 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
636 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
637 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
638 	return VMX_TEST_START;
639 }
640 
641 static void iobmp_main(void)
642 {
643 	// stage 0, test IO pass
644 	vmx_set_test_stage(0);
645 	inb(0x5000);
646 	outb(0x0, 0x5000);
647 	report("I/O bitmap - I/O pass", vmx_get_test_stage() == 0);
648 	// test IO width, in/out
649 	((u8 *)io_bitmap_a)[0] = 0xFF;
650 	vmx_set_test_stage(2);
651 	inb(0x0);
652 	report("I/O bitmap - trap in", vmx_get_test_stage() == 3);
653 	vmx_set_test_stage(3);
654 	outw(0x0, 0x0);
655 	report("I/O bitmap - trap out", vmx_get_test_stage() == 4);
656 	vmx_set_test_stage(4);
657 	inl(0x0);
658 	report("I/O bitmap - I/O width, long", vmx_get_test_stage() == 5);
659 	// test low/high IO port
660 	vmx_set_test_stage(5);
661 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
662 	inb(0x5000);
663 	report("I/O bitmap - I/O port, low part", vmx_get_test_stage() == 6);
664 	vmx_set_test_stage(6);
665 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
666 	inb(0x9000);
667 	report("I/O bitmap - I/O port, high part", vmx_get_test_stage() == 7);
668 	// test partial pass
669 	vmx_set_test_stage(7);
670 	inl(0x4FFF);
671 	report("I/O bitmap - partial pass", vmx_get_test_stage() == 8);
672 	// test overrun
673 	vmx_set_test_stage(8);
674 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
675 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
676 	inl(0xFFFF);
677 	report("I/O bitmap - overrun", vmx_get_test_stage() == 9);
678 	vmx_set_test_stage(9);
679 	vmcall();
680 	outb(0x0, 0x0);
681 	report("I/O bitmap - ignore unconditional exiting",
682 	       vmx_get_test_stage() == 9);
683 	vmx_set_test_stage(10);
684 	vmcall();
685 	outb(0x0, 0x0);
686 	report("I/O bitmap - unconditional exiting",
687 	       vmx_get_test_stage() == 11);
688 }
689 
690 static int iobmp_exit_handler(void)
691 {
692 	u64 guest_rip;
693 	ulong reason, exit_qual;
694 	u32 insn_len, ctrl_cpu0;
695 
696 	guest_rip = vmcs_read(GUEST_RIP);
697 	reason = vmcs_read(EXI_REASON) & 0xff;
698 	exit_qual = vmcs_read(EXI_QUALIFICATION);
699 	insn_len = vmcs_read(EXI_INST_LEN);
700 	switch (reason) {
701 	case VMX_IO:
702 		switch (vmx_get_test_stage()) {
703 		case 0:
704 		case 1:
705 			vmx_inc_test_stage();
706 			break;
707 		case 2:
708 			report("I/O bitmap - I/O width, byte",
709 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE);
710 			report("I/O bitmap - I/O direction, in", exit_qual & VMX_IO_IN);
711 			vmx_inc_test_stage();
712 			break;
713 		case 3:
714 			report("I/O bitmap - I/O width, word",
715 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD);
716 			report("I/O bitmap - I/O direction, out",
717 					!(exit_qual & VMX_IO_IN));
718 			vmx_inc_test_stage();
719 			break;
720 		case 4:
721 			report("I/O bitmap - I/O width, long",
722 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG);
723 			vmx_inc_test_stage();
724 			break;
725 		case 5:
726 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
727 				vmx_inc_test_stage();
728 			break;
729 		case 6:
730 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
731 				vmx_inc_test_stage();
732 			break;
733 		case 7:
734 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
735 				vmx_inc_test_stage();
736 			break;
737 		case 8:
738 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
739 				vmx_inc_test_stage();
740 			break;
741 		case 9:
742 		case 10:
743 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
744 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
745 			vmx_inc_test_stage();
746 			break;
747 		default:
748 			// Should not reach here
749 			report("unexpected stage, %d", false,
750 			       vmx_get_test_stage());
751 			print_vmexit_info();
752 			return VMX_TEST_VMEXIT;
753 		}
754 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
755 		return VMX_TEST_RESUME;
756 	case VMX_VMCALL:
757 		switch (vmx_get_test_stage()) {
758 		case 9:
759 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
760 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
761 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
762 			break;
763 		case 10:
764 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
765 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
766 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
767 			break;
768 		default:
769 			// Should not reach here
770 			report("unexpected stage, %d", false,
771 			       vmx_get_test_stage());
772 			print_vmexit_info();
773 			return VMX_TEST_VMEXIT;
774 		}
775 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
776 		return VMX_TEST_RESUME;
777 	default:
778 		printf("guest_rip = %#lx\n", guest_rip);
779 		printf("\tERROR : Undefined exit reason, reason = %ld.\n", reason);
780 		break;
781 	}
782 	return VMX_TEST_VMEXIT;
783 }
784 
785 #define INSN_CPU0		0
786 #define INSN_CPU1		1
787 #define INSN_ALWAYS_TRAP	2
788 
789 #define FIELD_EXIT_QUAL		(1 << 0)
790 #define FIELD_INSN_INFO		(1 << 1)
791 
792 asm(
793 	"insn_hlt: hlt;ret\n\t"
794 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
795 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
796 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
797 	"insn_rdtsc: rdtsc;ret\n\t"
798 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
799 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
800 #ifdef __x86_64__
801 	"insn_cr8_load: xor %eax, %eax; mov %rax,%cr8;ret\n\t"
802 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
803 #endif
804 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
805 	"insn_pause: pause;ret\n\t"
806 	"insn_wbinvd: wbinvd;ret\n\t"
807 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
808 	"insn_invd: invd;ret\n\t"
809 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
810 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
811 	"insn_sidt: sidt idt_descr;ret\n\t"
812 	"insn_lidt: lidt idt_descr;ret\n\t"
813 	"insn_sldt: sldt %ax;ret\n\t"
814 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
815 	"insn_str: str %ax;ret\n\t"
816 	"insn_rdrand: rdrand %rax;ret\n\t"
817 	"insn_rdseed: rdseed %rax;ret\n\t"
818 );
819 extern void insn_hlt(void);
820 extern void insn_invlpg(void);
821 extern void insn_mwait(void);
822 extern void insn_rdpmc(void);
823 extern void insn_rdtsc(void);
824 extern void insn_cr3_load(void);
825 extern void insn_cr3_store(void);
826 #ifdef __x86_64__
827 extern void insn_cr8_load(void);
828 extern void insn_cr8_store(void);
829 #endif
830 extern void insn_monitor(void);
831 extern void insn_pause(void);
832 extern void insn_wbinvd(void);
833 extern void insn_sgdt(void);
834 extern void insn_lgdt(void);
835 extern void insn_sidt(void);
836 extern void insn_lidt(void);
837 extern void insn_sldt(void);
838 extern void insn_lldt(void);
839 extern void insn_str(void);
840 extern void insn_cpuid(void);
841 extern void insn_invd(void);
842 extern void insn_rdrand(void);
843 extern void insn_rdseed(void);
844 
845 u32 cur_insn;
846 u64 cr3;
847 
848 struct insn_table {
849 	const char *name;
850 	u32 flag;
851 	void (*insn_func)(void);
852 	u32 type;
853 	u32 reason;
854 	ulong exit_qual;
855 	u32 insn_info;
856 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
857 	// which field need to be tested, reason is always tested
858 	u32 test_field;
859 };
860 
861 /*
862  * Add more test cases of instruction intercept here. Elements in this
863  * table is:
864  *	name/control flag/insn function/type/exit reason/exit qulification/
865  *	instruction info/field to test
866  * The last field defines which fields (exit_qual and insn_info) need to be
867  * tested in exit handler. If set to 0, only "reason" is checked.
868  */
869 static struct insn_table insn_table[] = {
870 	// Flags for Primary Processor-Based VM-Execution Controls
871 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
872 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
873 		0x12345678, 0, FIELD_EXIT_QUAL},
874 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0},
875 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
876 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
877 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
878 		FIELD_EXIT_QUAL},
879 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
880 		FIELD_EXIT_QUAL},
881 #ifdef __x86_64__
882 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
883 		FIELD_EXIT_QUAL},
884 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
885 		FIELD_EXIT_QUAL},
886 #endif
887 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0},
888 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
889 	// Flags for Secondary Processor-Based VM-Execution Controls
890 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
891 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
892 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
893 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
894 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
895 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
896 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
897 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
898 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
899 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
900 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
901 	// Instructions always trap
902 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
903 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
904 	// Instructions never trap
905 	{NULL},
906 };
907 
908 static int insn_intercept_init(struct vmcs *vmcs)
909 {
910 	u32 ctrl_cpu;
911 
912 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
913 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
914 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
915 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
916 	cr3 = read_cr3();
917 	return VMX_TEST_START;
918 }
919 
920 static void insn_intercept_main(void)
921 {
922 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
923 		vmx_set_test_stage(cur_insn * 2);
924 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
925 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
926 		    (insn_table[cur_insn].type == INSN_CPU1 &&
927 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
928 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
929 			       insn_table[cur_insn].type - INSN_CPU0,
930 			       insn_table[cur_insn].name);
931 			continue;
932 		}
933 
934 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
935 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
936 		    (insn_table[cur_insn].type == INSN_CPU1 &&
937 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
938 			/* skip hlt, it stalls the guest and is tested below */
939 			if (insn_table[cur_insn].insn_func != insn_hlt)
940 				insn_table[cur_insn].insn_func();
941 			report("execute %s", vmx_get_test_stage() == cur_insn * 2,
942 					insn_table[cur_insn].name);
943 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
944 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
945 			       insn_table[cur_insn].type - INSN_CPU0,
946 			       insn_table[cur_insn].name);
947 
948 		vmcall();
949 
950 		insn_table[cur_insn].insn_func();
951 		report("intercept %s", vmx_get_test_stage() == cur_insn * 2 + 1,
952 				insn_table[cur_insn].name);
953 
954 		vmx_set_test_stage(cur_insn * 2 + 1);
955 		vmcall();
956 	}
957 }
958 
959 static int insn_intercept_exit_handler(void)
960 {
961 	u64 guest_rip;
962 	u32 reason;
963 	ulong exit_qual;
964 	u32 insn_len;
965 	u32 insn_info;
966 	bool pass;
967 
968 	guest_rip = vmcs_read(GUEST_RIP);
969 	reason = vmcs_read(EXI_REASON) & 0xff;
970 	exit_qual = vmcs_read(EXI_QUALIFICATION);
971 	insn_len = vmcs_read(EXI_INST_LEN);
972 	insn_info = vmcs_read(EXI_INST_INFO);
973 
974 	if (reason == VMX_VMCALL) {
975 		u32 val = 0;
976 
977 		if (insn_table[cur_insn].type == INSN_CPU0)
978 			val = vmcs_read(CPU_EXEC_CTRL0);
979 		else if (insn_table[cur_insn].type == INSN_CPU1)
980 			val = vmcs_read(CPU_EXEC_CTRL1);
981 
982 		if (vmx_get_test_stage() & 1)
983 			val &= ~insn_table[cur_insn].flag;
984 		else
985 			val |= insn_table[cur_insn].flag;
986 
987 		if (insn_table[cur_insn].type == INSN_CPU0)
988 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
989 		else if (insn_table[cur_insn].type == INSN_CPU1)
990 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
991 	} else {
992 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
993 			insn_table[cur_insn].reason == reason;
994 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
995 		    insn_table[cur_insn].exit_qual != exit_qual)
996 			pass = false;
997 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
998 		    insn_table[cur_insn].insn_info != insn_info)
999 			pass = false;
1000 		if (pass)
1001 			vmx_inc_test_stage();
1002 	}
1003 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
1004 	return VMX_TEST_RESUME;
1005 }
1006 
1007 static int setup_eptp(u64 hpa, bool enable_ad)
1008 {
1009 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1010 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
1011 		printf("\tEPT is not supported");
1012 		return 1;
1013 	}
1014 
1015 	if (!(ept_vpid.val & EPT_CAP_UC) &&
1016 			!(ept_vpid.val & EPT_CAP_WB)) {
1017 		printf("\tEPT paging-structure memory type "
1018 				"UC&WB are not supported\n");
1019 		return 1;
1020 	}
1021 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
1022 		printf("\tPWL4 is not supported\n");
1023 		return 1;
1024 	}
1025 
1026 	if (ept_vpid.val & EPT_CAP_UC)
1027 		eptp = EPT_MEM_TYPE_UC;
1028 	else
1029 		eptp = EPT_MEM_TYPE_WB;
1030 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1031 	eptp |= hpa;
1032 	if (enable_ad)
1033 		eptp |= EPTP_AD_FLAG;
1034 
1035 	vmcs_write(EPTP, eptp);
1036 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0)| CPU_SECONDARY);
1037 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1)| CPU_EPT);
1038 
1039 	return 0;
1040 }
1041 
1042 /* Enables EPT and sets up the identity map. */
1043 static int setup_ept(bool enable_ad)
1044 {
1045 	unsigned long end_of_memory;
1046 
1047 	pml4 = alloc_page();
1048 
1049 	setup_eptp(virt_to_phys(pml4), enable_ad);
1050 
1051 	memset(pml4, 0, PAGE_SIZE);
1052 
1053 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1054 	if (end_of_memory < (1ul << 32))
1055 		end_of_memory = (1ul << 32);
1056 	/* Cannot use large EPT pages if we need to track EPT
1057 	 * accessed/dirty bits at 4K granularity.
1058 	 */
1059 	setup_ept_range(pml4, 0, end_of_memory, 0,
1060 			!enable_ad && ept_2m_supported(),
1061 			EPT_WA | EPT_RA | EPT_EA);
1062 	return 0;
1063 }
1064 
1065 static int enable_ept(void)
1066 {
1067 	return setup_eptp(0, false);
1068 }
1069 
1070 static void ept_enable_ad_bits(void)
1071 {
1072 	eptp |= EPTP_AD_FLAG;
1073 	vmcs_write(EPTP, eptp);
1074 }
1075 
1076 static void ept_disable_ad_bits(void)
1077 {
1078 	eptp &= ~EPTP_AD_FLAG;
1079 	vmcs_write(EPTP, eptp);
1080 }
1081 
1082 static void ept_enable_ad_bits_or_skip_test(void)
1083 {
1084 	if (!ept_ad_bits_supported())
1085 		test_skip("EPT AD bits not supported.");
1086 	ept_enable_ad_bits();
1087 }
1088 
1089 static int apic_version;
1090 
1091 static int ept_init_common(bool have_ad)
1092 {
1093 	int ret;
1094 	struct pci_dev pcidev;
1095 
1096 	if (setup_ept(have_ad))
1097 		return VMX_TEST_EXIT;
1098 	data_page1 = alloc_page();
1099 	data_page2 = alloc_page();
1100 	memset(data_page1, 0x0, PAGE_SIZE);
1101 	memset(data_page2, 0x0, PAGE_SIZE);
1102 	*((u32 *)data_page1) = MAGIC_VAL_1;
1103 	*((u32 *)data_page2) = MAGIC_VAL_2;
1104 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1105 			EPT_RA | EPT_WA | EPT_EA);
1106 
1107 	apic_version = apic_read(APIC_LVR);
1108 
1109 	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
1110 	if (ret != PCIDEVADDR_INVALID) {
1111 		pci_dev_init(&pcidev, ret);
1112 		pci_physaddr = pcidev.resource[PCI_TESTDEV_BAR_MEM];
1113 	}
1114 
1115 	return VMX_TEST_START;
1116 }
1117 
1118 static int ept_init(struct vmcs *vmcs)
1119 {
1120 	return ept_init_common(false);
1121 }
1122 
1123 static void ept_common(void)
1124 {
1125 	vmx_set_test_stage(0);
1126 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1127 			*((u32 *)data_page1) != MAGIC_VAL_1)
1128 		report("EPT basic framework - read", 0);
1129 	else {
1130 		*((u32 *)data_page2) = MAGIC_VAL_3;
1131 		vmcall();
1132 		if (vmx_get_test_stage() == 1) {
1133 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1134 					*((u32 *)data_page2) == MAGIC_VAL_2)
1135 				report("EPT basic framework", 1);
1136 			else
1137 				report("EPT basic framework - remap", 1);
1138 		}
1139 	}
1140 	// Test EPT Misconfigurations
1141 	vmx_set_test_stage(1);
1142 	vmcall();
1143 	*((u32 *)data_page1) = MAGIC_VAL_1;
1144 	if (vmx_get_test_stage() != 2) {
1145 		report("EPT misconfigurations", 0);
1146 		goto t1;
1147 	}
1148 	vmx_set_test_stage(2);
1149 	vmcall();
1150 	*((u32 *)data_page1) = MAGIC_VAL_1;
1151 	report("EPT misconfigurations", vmx_get_test_stage() == 3);
1152 t1:
1153 	// Test EPT violation
1154 	vmx_set_test_stage(3);
1155 	vmcall();
1156 	*((u32 *)data_page1) = MAGIC_VAL_1;
1157 	report("EPT violation - page permission", vmx_get_test_stage() == 4);
1158 	// Violation caused by EPT paging structure
1159 	vmx_set_test_stage(4);
1160 	vmcall();
1161 	*((u32 *)data_page1) = MAGIC_VAL_2;
1162 	report("EPT violation - paging structure", vmx_get_test_stage() == 5);
1163 
1164 	// MMIO Read/Write
1165 	vmx_set_test_stage(5);
1166 	vmcall();
1167 
1168 	*(u32 volatile *)pci_physaddr;
1169 	report("MMIO EPT violation - read", vmx_get_test_stage() == 6);
1170 
1171 	*(u32 volatile *)pci_physaddr = MAGIC_VAL_1;
1172 	report("MMIO EPT violation - write", vmx_get_test_stage() == 7);
1173 }
1174 
1175 static void ept_main(void)
1176 {
1177 	ept_common();
1178 
1179 	// Test EPT access to L1 MMIO
1180 	vmx_set_test_stage(7);
1181 	report("EPT - MMIO access", *((u32 *)0xfee00030UL) == apic_version);
1182 
1183 	// Test invalid operand for INVEPT
1184 	vmcall();
1185 	report("EPT - unsupported INVEPT", vmx_get_test_stage() == 8);
1186 }
1187 
1188 static bool invept_test(int type, u64 eptp)
1189 {
1190 	bool ret, supported;
1191 
1192 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1193 	ret = invept(type, eptp);
1194 
1195 	if (ret == !supported)
1196 		return false;
1197 
1198 	if (!supported)
1199 		printf("WARNING: unsupported invept passed!\n");
1200 	else
1201 		printf("WARNING: invept failed!\n");
1202 
1203 	return true;
1204 }
1205 
1206 static int pml_exit_handler(void)
1207 {
1208 	u16 index, count;
1209 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1210 	u64 *pmlbuf = pml_log;
1211 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1212 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1213 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1214 
1215 	switch (reason) {
1216 	case VMX_VMCALL:
1217 		switch (vmx_get_test_stage()) {
1218 		case 0:
1219 			index = vmcs_read(GUEST_PML_INDEX);
1220 			for (count = index + 1; count < PML_INDEX; count++) {
1221 				if (pmlbuf[count] == (u64)data_page2) {
1222 					vmx_inc_test_stage();
1223 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1224 					break;
1225 				}
1226 			}
1227 			break;
1228 		case 1:
1229 			index = vmcs_read(GUEST_PML_INDEX);
1230 			/* Keep clearing the dirty bit till a overflow */
1231 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1232 			break;
1233 		default:
1234 			report("unexpected stage, %d.", false,
1235 			       vmx_get_test_stage());
1236 			print_vmexit_info();
1237 			return VMX_TEST_VMEXIT;
1238 		}
1239 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1240 		return VMX_TEST_RESUME;
1241 	case VMX_PML_FULL:
1242 		vmx_inc_test_stage();
1243 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1244 		return VMX_TEST_RESUME;
1245 	default:
1246 		report("Unknown exit reason, %ld", false, reason);
1247 		print_vmexit_info();
1248 	}
1249 	return VMX_TEST_VMEXIT;
1250 }
1251 
1252 static int ept_exit_handler_common(bool have_ad)
1253 {
1254 	u64 guest_rip;
1255 	u64 guest_cr3;
1256 	ulong reason;
1257 	u32 insn_len;
1258 	u32 exit_qual;
1259 	static unsigned long data_page1_pte, data_page1_pte_pte, memaddr_pte;
1260 
1261 	guest_rip = vmcs_read(GUEST_RIP);
1262 	guest_cr3 = vmcs_read(GUEST_CR3);
1263 	reason = vmcs_read(EXI_REASON) & 0xff;
1264 	insn_len = vmcs_read(EXI_INST_LEN);
1265 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1266 	switch (reason) {
1267 	case VMX_VMCALL:
1268 		switch (vmx_get_test_stage()) {
1269 		case 0:
1270 			check_ept_ad(pml4, guest_cr3,
1271 				     (unsigned long)data_page1,
1272 				     have_ad ? EPT_ACCESS_FLAG : 0,
1273 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1274 			check_ept_ad(pml4, guest_cr3,
1275 				     (unsigned long)data_page2,
1276 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1277 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1278 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1279 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1280 			if (have_ad)
1281 				ept_sync(INVEPT_SINGLE, eptp);;
1282 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1283 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1284 				vmx_inc_test_stage();
1285 				install_ept(pml4, (unsigned long)data_page2,
1286 						(unsigned long)data_page2,
1287 						EPT_RA | EPT_WA | EPT_EA);
1288 			} else
1289 				report("EPT basic framework - write", 0);
1290 			break;
1291 		case 1:
1292 			install_ept(pml4, (unsigned long)data_page1,
1293  				(unsigned long)data_page1, EPT_WA);
1294 			ept_sync(INVEPT_SINGLE, eptp);
1295 			break;
1296 		case 2:
1297 			install_ept(pml4, (unsigned long)data_page1,
1298  				(unsigned long)data_page1,
1299  				EPT_RA | EPT_WA | EPT_EA |
1300  				(2 << EPT_MEM_TYPE_SHIFT));
1301 			ept_sync(INVEPT_SINGLE, eptp);
1302 			break;
1303 		case 3:
1304 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1305 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1306 						1, &data_page1_pte));
1307 			set_ept_pte(pml4, (unsigned long)data_page1,
1308 				1, data_page1_pte & ~EPT_PRESENT);
1309 			ept_sync(INVEPT_SINGLE, eptp);
1310 			break;
1311 		case 4:
1312 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1313 						2, &data_page1_pte));
1314 			data_page1_pte &= PAGE_MASK;
1315 			TEST_ASSERT(get_ept_pte(pml4, data_page1_pte,
1316 						2, &data_page1_pte_pte));
1317 			set_ept_pte(pml4, data_page1_pte, 2,
1318 				data_page1_pte_pte & ~EPT_PRESENT);
1319 			ept_sync(INVEPT_SINGLE, eptp);
1320 			break;
1321 		case 5:
1322 			install_ept(pml4, (unsigned long)pci_physaddr,
1323 				(unsigned long)pci_physaddr, 0);
1324 			ept_sync(INVEPT_SINGLE, eptp);
1325 			break;
1326 		case 7:
1327 			if (!invept_test(0, eptp))
1328 				vmx_inc_test_stage();
1329 			break;
1330 		// Should not reach here
1331 		default:
1332 			report("ERROR - unexpected stage, %d.", false,
1333 			       vmx_get_test_stage());
1334 			print_vmexit_info();
1335 			return VMX_TEST_VMEXIT;
1336 		}
1337 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1338 		return VMX_TEST_RESUME;
1339 	case VMX_EPT_MISCONFIG:
1340 		switch (vmx_get_test_stage()) {
1341 		case 1:
1342 		case 2:
1343 			vmx_inc_test_stage();
1344 			install_ept(pml4, (unsigned long)data_page1,
1345  				(unsigned long)data_page1,
1346  				EPT_RA | EPT_WA | EPT_EA);
1347 			ept_sync(INVEPT_SINGLE, eptp);
1348 			break;
1349 		// Should not reach here
1350 		default:
1351 			report("ERROR - unexpected stage, %d.", false,
1352 			       vmx_get_test_stage());
1353 			print_vmexit_info();
1354 			return VMX_TEST_VMEXIT;
1355 		}
1356 		return VMX_TEST_RESUME;
1357 	case VMX_EPT_VIOLATION:
1358 		switch(vmx_get_test_stage()) {
1359 		case 3:
1360 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1361 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1362 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1363 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1364 					EPT_VLT_PADDR))
1365 				vmx_inc_test_stage();
1366 			set_ept_pte(pml4, (unsigned long)data_page1,
1367 				1, data_page1_pte | (EPT_PRESENT));
1368 			ept_sync(INVEPT_SINGLE, eptp);
1369 			break;
1370 		case 4:
1371 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1372 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1373 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1374 			if (exit_qual == (EPT_VLT_RD |
1375 					  (have_ad ? EPT_VLT_WR : 0) |
1376 					  EPT_VLT_LADDR_VLD))
1377 				vmx_inc_test_stage();
1378 			set_ept_pte(pml4, data_page1_pte, 2,
1379 				data_page1_pte_pte | (EPT_PRESENT));
1380 			ept_sync(INVEPT_SINGLE, eptp);
1381 			break;
1382 		case 5:
1383 			if (exit_qual & EPT_VLT_RD)
1384 				vmx_inc_test_stage();
1385 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1386 						1, &memaddr_pte));
1387 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA);
1388 			ept_sync(INVEPT_SINGLE, eptp);
1389 			break;
1390 		case 6:
1391 			if (exit_qual & EPT_VLT_WR)
1392 				vmx_inc_test_stage();
1393 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1394 						1, &memaddr_pte));
1395 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA | EPT_WA);
1396 			ept_sync(INVEPT_SINGLE, eptp);
1397 			break;
1398 		default:
1399 			// Should not reach here
1400 			report("ERROR : unexpected stage, %d", false,
1401 			       vmx_get_test_stage());
1402 			print_vmexit_info();
1403 			return VMX_TEST_VMEXIT;
1404 		}
1405 		return VMX_TEST_RESUME;
1406 	default:
1407 		report("Unknown exit reason, %ld", false, reason);
1408 		print_vmexit_info();
1409 	}
1410 	return VMX_TEST_VMEXIT;
1411 }
1412 
1413 static int ept_exit_handler(void)
1414 {
1415 	return ept_exit_handler_common(false);
1416 }
1417 
1418 static int eptad_init(struct vmcs *vmcs)
1419 {
1420 	int r = ept_init_common(true);
1421 
1422 	if (r == VMX_TEST_EXIT)
1423 		return r;
1424 
1425 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1426 		printf("\tEPT A/D bits are not supported");
1427 		return VMX_TEST_EXIT;
1428 	}
1429 
1430 	return r;
1431 }
1432 
1433 static int pml_init(struct vmcs *vmcs)
1434 {
1435 	u32 ctrl_cpu;
1436 	int r = eptad_init(vmcs);
1437 
1438 	if (r == VMX_TEST_EXIT)
1439 		return r;
1440 
1441 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1442 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1443 		printf("\tPML is not supported");
1444 		return VMX_TEST_EXIT;
1445 	}
1446 
1447 	pml_log = alloc_page();
1448 	memset(pml_log, 0x0, PAGE_SIZE);
1449 	vmcs_write(PMLADDR, (u64)pml_log);
1450 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1451 
1452 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1453 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1454 
1455 	return VMX_TEST_START;
1456 }
1457 
1458 static void pml_main(void)
1459 {
1460 	int count = 0;
1461 
1462 	vmx_set_test_stage(0);
1463 	*((u32 *)data_page2) = 0x1;
1464 	vmcall();
1465 	report("PML - Dirty GPA Logging", vmx_get_test_stage() == 1);
1466 
1467 	while (vmx_get_test_stage() == 1) {
1468 		vmcall();
1469 		*((u32 *)data_page2) = 0x1;
1470 		if (count++ > PML_INDEX)
1471 			break;
1472 	}
1473 	report("PML Full Event", vmx_get_test_stage() == 2);
1474 }
1475 
1476 static void eptad_main(void)
1477 {
1478 	ept_common();
1479 }
1480 
1481 static int eptad_exit_handler(void)
1482 {
1483 	return ept_exit_handler_common(true);
1484 }
1485 
1486 static bool invvpid_test(int type, u16 vpid)
1487 {
1488 	bool ret, supported;
1489 
1490 	supported = ept_vpid.val &
1491 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1492 	ret = invvpid(type, vpid, 0);
1493 
1494 	if (ret == !supported)
1495 		return false;
1496 
1497 	if (!supported)
1498 		printf("WARNING: unsupported invvpid passed!\n");
1499 	else
1500 		printf("WARNING: invvpid failed!\n");
1501 
1502 	return true;
1503 }
1504 
1505 static int vpid_init(struct vmcs *vmcs)
1506 {
1507 	u32 ctrl_cpu1;
1508 
1509 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1510 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1511 		printf("\tVPID is not supported");
1512 		return VMX_TEST_EXIT;
1513 	}
1514 
1515 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1516 	ctrl_cpu1 |= CPU_VPID;
1517 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1518 	return VMX_TEST_START;
1519 }
1520 
1521 static void vpid_main(void)
1522 {
1523 	vmx_set_test_stage(0);
1524 	vmcall();
1525 	report("INVVPID SINGLE ADDRESS", vmx_get_test_stage() == 1);
1526 	vmx_set_test_stage(2);
1527 	vmcall();
1528 	report("INVVPID SINGLE", vmx_get_test_stage() == 3);
1529 	vmx_set_test_stage(4);
1530 	vmcall();
1531 	report("INVVPID ALL", vmx_get_test_stage() == 5);
1532 }
1533 
1534 static int vpid_exit_handler(void)
1535 {
1536 	u64 guest_rip;
1537 	ulong reason;
1538 	u32 insn_len;
1539 
1540 	guest_rip = vmcs_read(GUEST_RIP);
1541 	reason = vmcs_read(EXI_REASON) & 0xff;
1542 	insn_len = vmcs_read(EXI_INST_LEN);
1543 
1544 	switch (reason) {
1545 	case VMX_VMCALL:
1546 		switch(vmx_get_test_stage()) {
1547 		case 0:
1548 			if (!invvpid_test(INVVPID_ADDR, 1))
1549 				vmx_inc_test_stage();
1550 			break;
1551 		case 2:
1552 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1553 				vmx_inc_test_stage();
1554 			break;
1555 		case 4:
1556 			if (!invvpid_test(INVVPID_ALL, 1))
1557 				vmx_inc_test_stage();
1558 			break;
1559 		default:
1560 			report("ERROR: unexpected stage, %d", false,
1561 					vmx_get_test_stage());
1562 			print_vmexit_info();
1563 			return VMX_TEST_VMEXIT;
1564 		}
1565 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1566 		return VMX_TEST_RESUME;
1567 	default:
1568 		report("Unknown exit reason, %ld", false, reason);
1569 		print_vmexit_info();
1570 	}
1571 	return VMX_TEST_VMEXIT;
1572 }
1573 
1574 #define TIMER_VECTOR	222
1575 
1576 static volatile bool timer_fired;
1577 
1578 static void timer_isr(isr_regs_t *regs)
1579 {
1580 	timer_fired = true;
1581 	apic_write(APIC_EOI, 0);
1582 }
1583 
1584 static int interrupt_init(struct vmcs *vmcs)
1585 {
1586 	msr_bmp_init();
1587 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1588 	handle_irq(TIMER_VECTOR, timer_isr);
1589 	return VMX_TEST_START;
1590 }
1591 
1592 static void interrupt_main(void)
1593 {
1594 	long long start, loops;
1595 
1596 	vmx_set_test_stage(0);
1597 
1598 	apic_write(APIC_LVTT, TIMER_VECTOR);
1599 	irq_enable();
1600 
1601 	apic_write(APIC_TMICT, 1);
1602 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1603 		asm volatile ("nop");
1604 	report("direct interrupt while running guest", timer_fired);
1605 
1606 	apic_write(APIC_TMICT, 0);
1607 	irq_disable();
1608 	vmcall();
1609 	timer_fired = false;
1610 	apic_write(APIC_TMICT, 1);
1611 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1612 		asm volatile ("nop");
1613 	report("intercepted interrupt while running guest", timer_fired);
1614 
1615 	irq_enable();
1616 	apic_write(APIC_TMICT, 0);
1617 	irq_disable();
1618 	vmcall();
1619 	timer_fired = false;
1620 	start = rdtsc();
1621 	apic_write(APIC_TMICT, 1000000);
1622 
1623 	asm volatile ("sti; hlt");
1624 
1625 	report("direct interrupt + hlt",
1626 	       rdtsc() - start > 1000000 && timer_fired);
1627 
1628 	apic_write(APIC_TMICT, 0);
1629 	irq_disable();
1630 	vmcall();
1631 	timer_fired = false;
1632 	start = rdtsc();
1633 	apic_write(APIC_TMICT, 1000000);
1634 
1635 	asm volatile ("sti; hlt");
1636 
1637 	report("intercepted interrupt + hlt",
1638 	       rdtsc() - start > 10000 && timer_fired);
1639 
1640 	apic_write(APIC_TMICT, 0);
1641 	irq_disable();
1642 	vmcall();
1643 	timer_fired = false;
1644 	start = rdtsc();
1645 	apic_write(APIC_TMICT, 1000000);
1646 
1647 	irq_enable();
1648 	asm volatile ("nop");
1649 	vmcall();
1650 
1651 	report("direct interrupt + activity state hlt",
1652 	       rdtsc() - start > 10000 && timer_fired);
1653 
1654 	apic_write(APIC_TMICT, 0);
1655 	irq_disable();
1656 	vmcall();
1657 	timer_fired = false;
1658 	start = rdtsc();
1659 	apic_write(APIC_TMICT, 1000000);
1660 
1661 	irq_enable();
1662 	asm volatile ("nop");
1663 	vmcall();
1664 
1665 	report("intercepted interrupt + activity state hlt",
1666 	       rdtsc() - start > 10000 && timer_fired);
1667 
1668 	apic_write(APIC_TMICT, 0);
1669 	irq_disable();
1670 	vmx_set_test_stage(7);
1671 	vmcall();
1672 	timer_fired = false;
1673 	apic_write(APIC_TMICT, 1);
1674 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1675 		asm volatile ("nop");
1676 	report("running a guest with interrupt acknowledgement set", timer_fired);
1677 
1678 	apic_write(APIC_TMICT, 0);
1679 	irq_enable();
1680 	timer_fired = false;
1681 	vmcall();
1682 	report("Inject an event to a halted guest", timer_fired);
1683 }
1684 
1685 static int interrupt_exit_handler(void)
1686 {
1687 	u64 guest_rip = vmcs_read(GUEST_RIP);
1688 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1689 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1690 
1691 	switch (reason) {
1692 	case VMX_VMCALL:
1693 		switch (vmx_get_test_stage()) {
1694 		case 0:
1695 		case 2:
1696 		case 5:
1697 			vmcs_write(PIN_CONTROLS,
1698 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1699 			break;
1700 		case 7:
1701 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1702 			vmcs_write(PIN_CONTROLS,
1703 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1704 			break;
1705 		case 1:
1706 		case 3:
1707 			vmcs_write(PIN_CONTROLS,
1708 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1709 			break;
1710 		case 4:
1711 		case 6:
1712 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1713 			break;
1714 
1715 		case 8:
1716 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1717 			vmcs_write(ENT_INTR_INFO,
1718 				   TIMER_VECTOR |
1719 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1720 				   INTR_INFO_VALID_MASK);
1721 			break;
1722 		}
1723 		vmx_inc_test_stage();
1724 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1725 		return VMX_TEST_RESUME;
1726 	case VMX_EXTINT:
1727 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1728 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1729 			handle_external_interrupt(vector);
1730 		} else {
1731 			irq_enable();
1732 			asm volatile ("nop");
1733 			irq_disable();
1734 		}
1735 		if (vmx_get_test_stage() >= 2)
1736 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1737 		return VMX_TEST_RESUME;
1738 	default:
1739 		report("Unknown exit reason, %ld", false, reason);
1740 		print_vmexit_info();
1741 	}
1742 
1743 	return VMX_TEST_VMEXIT;
1744 }
1745 
1746 static int dbgctls_init(struct vmcs *vmcs)
1747 {
1748 	u64 dr7 = 0x402;
1749 	u64 zero = 0;
1750 
1751 	msr_bmp_init();
1752 	asm volatile(
1753 		"mov %0,%%dr0\n\t"
1754 		"mov %0,%%dr1\n\t"
1755 		"mov %0,%%dr2\n\t"
1756 		"mov %1,%%dr7\n\t"
1757 		: : "r" (zero), "r" (dr7));
1758 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1759 	vmcs_write(GUEST_DR7, 0x404);
1760 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1761 
1762 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1763 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1764 
1765 	return VMX_TEST_START;
1766 }
1767 
1768 static void dbgctls_main(void)
1769 {
1770 	u64 dr7, debugctl;
1771 
1772 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1773 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1774 	/* Commented out: KVM does not support DEBUGCTL so far */
1775 	(void)debugctl;
1776 	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);
1777 
1778 	dr7 = 0x408;
1779 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1780 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1781 
1782 	vmx_set_test_stage(0);
1783 	vmcall();
1784 	report("Save debug controls", vmx_get_test_stage() == 1);
1785 
1786 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1787 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1788 		printf("\tDebug controls are always loaded/saved\n");
1789 		return;
1790 	}
1791 	vmx_set_test_stage(2);
1792 	vmcall();
1793 
1794 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1795 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1796 	/* Commented out: KVM does not support DEBUGCTL so far */
1797 	(void)debugctl;
1798 	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);
1799 
1800 	dr7 = 0x408;
1801 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1802 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1803 
1804 	vmx_set_test_stage(3);
1805 	vmcall();
1806 	report("Don't save debug controls", vmx_get_test_stage() == 4);
1807 }
1808 
1809 static int dbgctls_exit_handler(void)
1810 {
1811 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1812 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1813 	u64 guest_rip = vmcs_read(GUEST_RIP);
1814 	u64 dr7, debugctl;
1815 
1816 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1817 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1818 
1819 	switch (reason) {
1820 	case VMX_VMCALL:
1821 		switch (vmx_get_test_stage()) {
1822 		case 0:
1823 			if (dr7 == 0x400 && debugctl == 0 &&
1824 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1825 			    Commented out: KVM does not support DEBUGCTL so far
1826 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1827 				vmx_inc_test_stage();
1828 			break;
1829 		case 2:
1830 			dr7 = 0x402;
1831 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1832 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1833 			vmcs_write(GUEST_DR7, 0x404);
1834 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1835 
1836 			vmcs_write(ENT_CONTROLS,
1837 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1838 			vmcs_write(EXI_CONTROLS,
1839 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1840 			break;
1841 		case 3:
1842 			if (dr7 == 0x400 && debugctl == 0 &&
1843 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1844 			    Commented out: KVM does not support DEBUGCTL so far
1845 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1846 				vmx_inc_test_stage();
1847 			break;
1848 		}
1849 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1850 		return VMX_TEST_RESUME;
1851 	default:
1852 		report("Unknown exit reason, %d", false, reason);
1853 		print_vmexit_info();
1854 	}
1855 	return VMX_TEST_VMEXIT;
1856 }
1857 
1858 struct vmx_msr_entry {
1859 	u32 index;
1860 	u32 reserved;
1861 	u64 value;
1862 } __attribute__((packed));
1863 
1864 #define MSR_MAGIC 0x31415926
1865 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1866 
1867 static int msr_switch_init(struct vmcs *vmcs)
1868 {
1869 	msr_bmp_init();
1870 	exit_msr_store = alloc_page();
1871 	exit_msr_load = alloc_page();
1872 	entry_msr_load = alloc_page();
1873 	memset(exit_msr_store, 0, PAGE_SIZE);
1874 	memset(exit_msr_load, 0, PAGE_SIZE);
1875 	memset(entry_msr_load, 0, PAGE_SIZE);
1876 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1877 	entry_msr_load[0].value = MSR_MAGIC;
1878 
1879 	vmx_set_test_stage(1);
1880 	vmcs_write(ENT_MSR_LD_CNT, 1);
1881 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1882 	vmcs_write(EXI_MSR_ST_CNT, 1);
1883 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1884 	vmcs_write(EXI_MSR_LD_CNT, 1);
1885 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1886 	return VMX_TEST_START;
1887 }
1888 
1889 static void msr_switch_main(void)
1890 {
1891 	if (vmx_get_test_stage() == 1) {
1892 		report("VM entry MSR load",
1893 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
1894 		vmx_set_test_stage(2);
1895 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1896 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1897 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1898 		exit_msr_load[0].value = MSR_MAGIC + 2;
1899 	}
1900 	vmcall();
1901 }
1902 
1903 static int msr_switch_exit_handler(void)
1904 {
1905 	ulong reason;
1906 
1907 	reason = vmcs_read(EXI_REASON);
1908 	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
1909 		report("VM exit MSR store",
1910 			exit_msr_store[0].value == MSR_MAGIC + 1);
1911 		report("VM exit MSR load",
1912 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
1913 		vmx_set_test_stage(3);
1914 		entry_msr_load[0].index = MSR_FS_BASE;
1915 		return VMX_TEST_RESUME;
1916 	}
1917 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1918 		__func__, vmx_get_test_stage(), reason);
1919 	return VMX_TEST_EXIT;
1920 }
1921 
1922 static int msr_switch_entry_failure(struct vmentry_failure *failure)
1923 {
1924 	ulong reason;
1925 
1926 	if (failure->early) {
1927 		printf("ERROR %s: early exit\n", __func__);
1928 		return VMX_TEST_EXIT;
1929 	}
1930 
1931 	reason = vmcs_read(EXI_REASON);
1932 	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
1933 	    vmx_get_test_stage() == 3) {
1934 		report("VM entry MSR load: try to load FS_BASE",
1935 			vmcs_read(EXI_QUALIFICATION) == 1);
1936 		return VMX_TEST_VMEXIT;
1937 	}
1938 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1939 		__func__, vmx_get_test_stage(), reason);
1940 	return VMX_TEST_EXIT;
1941 }
1942 
1943 static int vmmcall_init(struct vmcs *vmcs)
1944 {
1945 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1946 	return VMX_TEST_START;
1947 }
1948 
1949 static void vmmcall_main(void)
1950 {
1951 	asm volatile(
1952 		"mov $0xABCD, %%rax\n\t"
1953 		"vmmcall\n\t"
1954 		::: "rax");
1955 
1956 	report("VMMCALL", 0);
1957 }
1958 
1959 static int vmmcall_exit_handler(void)
1960 {
1961 	ulong reason;
1962 
1963 	reason = vmcs_read(EXI_REASON);
1964 	switch (reason) {
1965 	case VMX_VMCALL:
1966 		printf("here\n");
1967 		report("VMMCALL triggers #UD", 0);
1968 		break;
1969 	case VMX_EXC_NMI:
1970 		report("VMMCALL triggers #UD",
1971 		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
1972 		break;
1973 	default:
1974 		report("Unknown exit reason, %ld", false, reason);
1975 		print_vmexit_info();
1976 	}
1977 
1978 	return VMX_TEST_VMEXIT;
1979 }
1980 
1981 static int disable_rdtscp_init(struct vmcs *vmcs)
1982 {
1983 	u32 ctrl_cpu1;
1984 
1985 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
1986 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1987 		ctrl_cpu1 &= ~CPU_RDTSCP;
1988 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1989 	}
1990 
1991 	return VMX_TEST_START;
1992 }
1993 
1994 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
1995 {
1996 	switch (vmx_get_test_stage()) {
1997 	case 0:
1998 		report("RDTSCP triggers #UD", true);
1999 		vmx_inc_test_stage();
2000 		regs->rip += 3;
2001 		break;
2002 	case 2:
2003 		report("RDPID triggers #UD", true);
2004 		vmx_inc_test_stage();
2005 		regs->rip += 4;
2006 		break;
2007 	}
2008 	return;
2009 
2010 }
2011 
2012 static void disable_rdtscp_main(void)
2013 {
2014 	/* Test that #UD is properly injected in L2.  */
2015 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
2016 
2017 	vmx_set_test_stage(0);
2018 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
2019 	vmcall();
2020 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
2021 
2022 	handle_exception(UD_VECTOR, 0);
2023 	vmcall();
2024 }
2025 
2026 static int disable_rdtscp_exit_handler(void)
2027 {
2028 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
2029 
2030 	switch (reason) {
2031 	case VMX_VMCALL:
2032 		switch (vmx_get_test_stage()) {
2033 		case 0:
2034 			report("RDTSCP triggers #UD", false);
2035 			vmx_inc_test_stage();
2036 			/* fallthrough */
2037 		case 1:
2038 			vmx_inc_test_stage();
2039 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
2040 			return VMX_TEST_RESUME;
2041 		case 2:
2042 			report("RDPID triggers #UD", false);
2043 			break;
2044 		}
2045 		break;
2046 
2047 	default:
2048 		report("Unknown exit reason, %d", false, reason);
2049 		print_vmexit_info();
2050 	}
2051 	return VMX_TEST_VMEXIT;
2052 }
2053 
2054 static int int3_init(struct vmcs *vmcs)
2055 {
2056 	vmcs_write(EXC_BITMAP, ~0u);
2057 	return VMX_TEST_START;
2058 }
2059 
2060 static void int3_guest_main(void)
2061 {
2062 	asm volatile ("int3");
2063 }
2064 
2065 static int int3_exit_handler(void)
2066 {
2067 	u32 reason = vmcs_read(EXI_REASON);
2068 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2069 
2070 	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
2071 	       (intr_info & INTR_INFO_VALID_MASK) &&
2072 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
2073 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2074 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2075 
2076 	return VMX_TEST_VMEXIT;
2077 }
2078 
2079 static int into_init(struct vmcs *vmcs)
2080 {
2081 	vmcs_write(EXC_BITMAP, ~0u);
2082 	return VMX_TEST_START;
2083 }
2084 
2085 static void into_guest_main(void)
2086 {
2087 	struct far_pointer32 fp = {
2088 		.offset = (uintptr_t)&&into,
2089 		.selector = KERNEL_CS32,
2090 	};
2091 	register uintptr_t rsp asm("rsp");
2092 
2093 	if (fp.offset != (uintptr_t)&&into) {
2094 		printf("Code address too high.\n");
2095 		return;
2096 	}
2097 	if ((u32)rsp != rsp) {
2098 		printf("Stack address too high.\n");
2099 		return;
2100 	}
2101 
2102 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2103 	return;
2104 into:
2105 	asm volatile (".code32;"
2106 		      "movl $0x7fffffff, %eax;"
2107 		      "addl %eax, %eax;"
2108 		      "into;"
2109 		      "lret;"
2110 		      ".code64");
2111 	__builtin_unreachable();
2112 }
2113 
2114 static int into_exit_handler(void)
2115 {
2116 	u32 reason = vmcs_read(EXI_REASON);
2117 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2118 
2119 	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
2120 	       (intr_info & INTR_INFO_VALID_MASK) &&
2121 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2122 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2123 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2124 
2125 	return VMX_TEST_VMEXIT;
2126 }
2127 
2128 static void exit_monitor_from_l2_main(void)
2129 {
2130 	printf("Calling exit(0) from l2...\n");
2131 	exit(0);
2132 }
2133 
2134 static int exit_monitor_from_l2_handler(void)
2135 {
2136 	report("The guest should have killed the VMM", false);
2137 	return VMX_TEST_EXIT;
2138 }
2139 
2140 static void assert_exit_reason(u64 expected)
2141 {
2142 	u64 actual = vmcs_read(EXI_REASON);
2143 
2144 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2145 			   exit_reason_description(expected),
2146 			   exit_reason_description(actual));
2147 }
2148 
2149 static void skip_exit_insn(void)
2150 {
2151 	u64 guest_rip = vmcs_read(GUEST_RIP);
2152 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2153 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2154 }
2155 
2156 static void skip_exit_vmcall(void)
2157 {
2158 	assert_exit_reason(VMX_VMCALL);
2159 	skip_exit_insn();
2160 }
2161 
2162 static void v2_null_test_guest(void)
2163 {
2164 }
2165 
2166 static void v2_null_test(void)
2167 {
2168 	test_set_guest(v2_null_test_guest);
2169 	enter_guest();
2170 	report(__func__, 1);
2171 }
2172 
2173 static void v2_multiple_entries_test_guest(void)
2174 {
2175 	vmx_set_test_stage(1);
2176 	vmcall();
2177 	vmx_set_test_stage(2);
2178 }
2179 
2180 static void v2_multiple_entries_test(void)
2181 {
2182 	test_set_guest(v2_multiple_entries_test_guest);
2183 	enter_guest();
2184 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2185 	skip_exit_vmcall();
2186 	enter_guest();
2187 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2188 	report(__func__, 1);
2189 }
2190 
2191 static int fixture_test_data = 1;
2192 
2193 static void fixture_test_teardown(void *data)
2194 {
2195 	*((int *) data) = 1;
2196 }
2197 
2198 static void fixture_test_guest(void)
2199 {
2200 	fixture_test_data++;
2201 }
2202 
2203 
2204 static void fixture_test_setup(void)
2205 {
2206 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2207 			   "fixture_test_teardown didn't run?!");
2208 	fixture_test_data = 2;
2209 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2210 	test_set_guest(fixture_test_guest);
2211 }
2212 
2213 static void fixture_test_case1(void)
2214 {
2215 	fixture_test_setup();
2216 	TEST_ASSERT_EQ(2, fixture_test_data);
2217 	enter_guest();
2218 	TEST_ASSERT_EQ(3, fixture_test_data);
2219 	report(__func__, 1);
2220 }
2221 
2222 static void fixture_test_case2(void)
2223 {
2224 	fixture_test_setup();
2225 	TEST_ASSERT_EQ(2, fixture_test_data);
2226 	enter_guest();
2227 	TEST_ASSERT_EQ(3, fixture_test_data);
2228 	report(__func__, 1);
2229 }
2230 
2231 enum ept_access_op {
2232 	OP_READ,
2233 	OP_WRITE,
2234 	OP_EXEC,
2235 	OP_FLUSH_TLB,
2236 	OP_EXIT,
2237 };
2238 
2239 static struct ept_access_test_data {
2240 	unsigned long gpa;
2241 	unsigned long *gva;
2242 	unsigned long hpa;
2243 	unsigned long *hva;
2244 	enum ept_access_op op;
2245 } ept_access_test_data;
2246 
2247 extern unsigned char ret42_start;
2248 extern unsigned char ret42_end;
2249 
2250 /* Returns 42. */
2251 asm(
2252 	".align 64\n"
2253 	"ret42_start:\n"
2254 	"mov $42, %eax\n"
2255 	"ret\n"
2256 	"ret42_end:\n"
2257 );
2258 
2259 static void
2260 diagnose_ept_violation_qual(u64 expected, u64 actual)
2261 {
2262 
2263 #define DIAGNOSE(flag)							\
2264 do {									\
2265 	if ((expected & flag) != (actual & flag))			\
2266 		printf(#flag " %sexpected\n",				\
2267 		       (expected & flag) ? "" : "un");			\
2268 } while (0)
2269 
2270 	DIAGNOSE(EPT_VLT_RD);
2271 	DIAGNOSE(EPT_VLT_WR);
2272 	DIAGNOSE(EPT_VLT_FETCH);
2273 	DIAGNOSE(EPT_VLT_PERM_RD);
2274 	DIAGNOSE(EPT_VLT_PERM_WR);
2275 	DIAGNOSE(EPT_VLT_PERM_EX);
2276 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2277 	DIAGNOSE(EPT_VLT_PADDR);
2278 
2279 #undef DIAGNOSE
2280 }
2281 
2282 static void do_ept_access_op(enum ept_access_op op)
2283 {
2284 	ept_access_test_data.op = op;
2285 	enter_guest();
2286 }
2287 
2288 /*
2289  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2290  * needed by tests that modify guest PTEs.
2291  */
2292 static void ept_access_test_guest_flush_tlb(void)
2293 {
2294 	do_ept_access_op(OP_FLUSH_TLB);
2295 	skip_exit_vmcall();
2296 }
2297 
2298 /*
2299  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2300  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2301  * a huge page.
2302  */
2303 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2304 				 unsigned long clear, unsigned long set)
2305 {
2306 	struct ept_access_test_data *data = &ept_access_test_data;
2307 	unsigned long orig_pte;
2308 	unsigned long pte;
2309 
2310 	/* Screw with the mapping at the requested level. */
2311 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2312 	pte = orig_pte;
2313 	if (mkhuge)
2314 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2315 	else
2316 		pte = orig_pte;
2317 	pte = (pte & ~clear) | set;
2318 	set_ept_pte(pml4, gpa, level, pte);
2319 	ept_sync(INVEPT_SINGLE, eptp);
2320 
2321 	return orig_pte;
2322 }
2323 
2324 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2325 {
2326 	set_ept_pte(pml4, gpa, level, orig_pte);
2327 }
2328 
2329 static void do_ept_violation(bool leaf, enum ept_access_op op,
2330 			     u64 expected_qual, u64 expected_paddr)
2331 {
2332 	u64 qual;
2333 
2334 	/* Try the access and observe the violation. */
2335 	do_ept_access_op(op);
2336 
2337 	assert_exit_reason(VMX_EPT_VIOLATION);
2338 
2339 	qual = vmcs_read(EXI_QUALIFICATION);
2340 
2341 	diagnose_ept_violation_qual(expected_qual, qual);
2342 	TEST_EXPECT_EQ(expected_qual, qual);
2343 
2344 	#if 0
2345 	/* Disable for now otherwise every test will fail */
2346 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2347 		       (unsigned long) (
2348 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2349 	#endif
2350 	/*
2351 	 * TODO: tests that probe expected_paddr in pages other than the one at
2352 	 * the beginning of the 1g region.
2353 	 */
2354 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2355 }
2356 
2357 static void
2358 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2359 			      unsigned long set, enum ept_access_op op,
2360 			      u64 expected_qual)
2361 {
2362 	struct ept_access_test_data *data = &ept_access_test_data;
2363 	unsigned long orig_pte;
2364 
2365 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2366 
2367 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2368 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2369 					 data->gpa);
2370 
2371 	/* Fix the violation and resume the op loop. */
2372 	ept_untwiddle(data->gpa, level, orig_pte);
2373 	enter_guest();
2374 	skip_exit_vmcall();
2375 }
2376 
2377 static void
2378 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2379 		       enum ept_access_op op, u64 expected_qual)
2380 {
2381 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2382 				      expected_qual);
2383 	if (ept_huge_pages_supported(level))
2384 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2385 					      expected_qual);
2386 }
2387 
2388 static void ept_violation(unsigned long clear, unsigned long set,
2389 			  enum ept_access_op op, u64 expected_qual)
2390 {
2391 	ept_violation_at_level(1, clear, set, op, expected_qual);
2392 	ept_violation_at_level(2, clear, set, op, expected_qual);
2393 	ept_violation_at_level(3, clear, set, op, expected_qual);
2394 	ept_violation_at_level(4, clear, set, op, expected_qual);
2395 }
2396 
2397 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2398 				       u64 expected_qual)
2399 {
2400 	ept_violation(EPT_PRESENT, access, op,
2401 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2402 }
2403 
2404 /*
2405  * For translations that don't involve a GVA, that is physical address (paddr)
2406  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2407  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2408  * translations don't involve GVAs, such as when the hardware does the guest
2409  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2410  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2411  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2412  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2413  *
2414  * Note that paddr violations can also be triggered by loading PAE page tables
2415  * with wonky addresses. We don't test that yet.
2416  *
2417  * This function modifies the EPT entry that maps the GPA that the guest page
2418  * table entry mapping ept_access_data.gva resides on.
2419  *
2420  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2421  *
2422  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2423  *
2424  *	@op		Guest operation to perform with ept_access_data.gva.
2425  *
2426  *	@expect_violation
2427  *			Is a violation expected during the paddr access?
2428  *
2429  *	@expected_qual	Expected qualification for the EPT violation.
2430  *			EPT_VLT_PADDR should be clear.
2431  */
2432 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2433 			     enum ept_access_op op, bool expect_violation,
2434 			     u64 expected_qual)
2435 {
2436 	struct ept_access_test_data *data = &ept_access_test_data;
2437 	unsigned long *ptep;
2438 	unsigned long gpa;
2439 	unsigned long orig_epte;
2440 
2441 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2442 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2443 	TEST_ASSERT(ptep);
2444 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2445 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2446 	ept_access_test_guest_flush_tlb();
2447 
2448 	/*
2449 	 * Now modify the access bits on the EPT entry for the GPA that the
2450 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2451 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2452 	 * constructed our test such that those other 511 PTEs aren't used by
2453 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2454 	 * PTE we're modifying is at the beginning of a 4K page and the
2455 	 * following 511 entires are also under our control (and not touched by
2456 	 * the guest).
2457 	 */
2458 	gpa = virt_to_phys(ptep);
2459 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2460 	/*
2461 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2462 	 * otherwise our level=1 twiddling below will fail. We use the
2463 	 * identity map (gpa = gpa) since page tables are shared with the host.
2464 	 */
2465 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2466 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2467 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2468 
2469 	if (expect_violation) {
2470 		do_ept_violation(/*leaf=*/true, op,
2471 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2472 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2473 		do_ept_access_op(op);
2474 	} else {
2475 		do_ept_access_op(op);
2476 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2477 	}
2478 
2479 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2480 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2481 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2482 
2483 	skip_exit_vmcall();
2484 }
2485 
2486 static void ept_access_allowed_paddr(unsigned long ept_access,
2487 				     unsigned long pte_ad,
2488 				     enum ept_access_op op)
2489 {
2490 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2491 			 /*expected_qual=*/-1);
2492 }
2493 
2494 static void ept_access_violation_paddr(unsigned long ept_access,
2495 				       unsigned long pte_ad,
2496 				       enum ept_access_op op,
2497 				       u64 expected_qual)
2498 {
2499 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2500 			 expected_qual);
2501 }
2502 
2503 
2504 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2505 					unsigned long clear,
2506 					unsigned long set,
2507 					enum ept_access_op op)
2508 {
2509 	struct ept_access_test_data *data = &ept_access_test_data;
2510 	unsigned long orig_pte;
2511 
2512 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2513 
2514 	/* No violation. Should proceed to vmcall. */
2515 	do_ept_access_op(op);
2516 	skip_exit_vmcall();
2517 
2518 	ept_untwiddle(data->gpa, level, orig_pte);
2519 }
2520 
2521 static void ept_allowed_at_level(int level, unsigned long clear,
2522 				 unsigned long set, enum ept_access_op op)
2523 {
2524 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2525 	if (ept_huge_pages_supported(level))
2526 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2527 }
2528 
2529 static void ept_allowed(unsigned long clear, unsigned long set,
2530 			enum ept_access_op op)
2531 {
2532 	ept_allowed_at_level(1, clear, set, op);
2533 	ept_allowed_at_level(2, clear, set, op);
2534 	ept_allowed_at_level(3, clear, set, op);
2535 	ept_allowed_at_level(4, clear, set, op);
2536 }
2537 
2538 static void ept_ignored_bit(int bit)
2539 {
2540 	/* Set the bit. */
2541 	ept_allowed(0, 1ul << bit, OP_READ);
2542 	ept_allowed(0, 1ul << bit, OP_WRITE);
2543 	ept_allowed(0, 1ul << bit, OP_EXEC);
2544 
2545 	/* Clear the bit. */
2546 	ept_allowed(1ul << bit, 0, OP_READ);
2547 	ept_allowed(1ul << bit, 0, OP_WRITE);
2548 	ept_allowed(1ul << bit, 0, OP_EXEC);
2549 }
2550 
2551 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2552 {
2553 	ept_allowed(EPT_PRESENT, access, op);
2554 }
2555 
2556 
2557 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2558 					     unsigned long clear,
2559 					     unsigned long set,
2560 					     enum ept_access_op op)
2561 {
2562 	struct ept_access_test_data *data = &ept_access_test_data;
2563 	unsigned long orig_pte;
2564 
2565 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2566 
2567 	do_ept_access_op(op);
2568 	assert_exit_reason(VMX_EPT_MISCONFIG);
2569 
2570 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2571 	#if 0
2572 	/* broken: */
2573 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2574 	#endif
2575 	#if 0
2576 	/*
2577 	 * broken:
2578 	 * According to description of exit qual for EPT violation,
2579 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2580 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2581 	 * to be set for msiconfig.
2582 	 */
2583 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2584 		       (unsigned long) (
2585 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2586 	#endif
2587 
2588 	/* Fix the violation and resume the op loop. */
2589 	ept_untwiddle(data->gpa, level, orig_pte);
2590 	enter_guest();
2591 	skip_exit_vmcall();
2592 }
2593 
2594 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2595 					  unsigned long clear,
2596 					  unsigned long set)
2597 {
2598 	/* The op shouldn't matter (read, write, exec), so try them all! */
2599 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2600 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2601 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2602 }
2603 
2604 static void ept_misconfig_at_level(int level, unsigned long clear,
2605 				   unsigned long set)
2606 {
2607 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2608 	if (ept_huge_pages_supported(level))
2609 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2610 }
2611 
2612 static void ept_misconfig(unsigned long clear, unsigned long set)
2613 {
2614 	ept_misconfig_at_level(1, clear, set);
2615 	ept_misconfig_at_level(2, clear, set);
2616 	ept_misconfig_at_level(3, clear, set);
2617 	ept_misconfig_at_level(4, clear, set);
2618 }
2619 
2620 static void ept_access_misconfig(unsigned long access)
2621 {
2622 	ept_misconfig(EPT_PRESENT, access);
2623 }
2624 
2625 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2626 {
2627 	/* Setting the bit causes a misconfig. */
2628 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2629 
2630 	/* Making the entry non-present turns reserved bits into ignored. */
2631 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2632 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2633 }
2634 
2635 static void ept_reserved_bit_at_level_huge(int level, int bit)
2636 {
2637 	/* Setting the bit causes a misconfig. */
2638 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2639 
2640 	/* Making the entry non-present turns reserved bits into ignored. */
2641 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2642 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2643 }
2644 
2645 static void ept_reserved_bit_at_level(int level, int bit)
2646 {
2647 	/* Setting the bit causes a misconfig. */
2648 	ept_misconfig_at_level(level, 0, 1ul << bit);
2649 
2650 	/* Making the entry non-present turns reserved bits into ignored. */
2651 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2652 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2653 }
2654 
2655 static void ept_reserved_bit(int bit)
2656 {
2657 	ept_reserved_bit_at_level(1, bit);
2658 	ept_reserved_bit_at_level(2, bit);
2659 	ept_reserved_bit_at_level(3, bit);
2660 	ept_reserved_bit_at_level(4, bit);
2661 }
2662 
2663 #define PAGE_2M_ORDER 9
2664 #define PAGE_1G_ORDER 18
2665 
2666 static void *get_1g_page(void)
2667 {
2668 	static void *alloc;
2669 
2670 	if (!alloc)
2671 		alloc = alloc_pages(PAGE_1G_ORDER);
2672 	return alloc;
2673 }
2674 
2675 static void ept_access_test_teardown(void *unused)
2676 {
2677 	/* Exit the guest cleanly. */
2678 	do_ept_access_op(OP_EXIT);
2679 }
2680 
2681 static void ept_access_test_guest(void)
2682 {
2683 	struct ept_access_test_data *data = &ept_access_test_data;
2684 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2685 
2686 	while (true) {
2687 		switch (data->op) {
2688 		case OP_READ:
2689 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2690 			break;
2691 		case OP_WRITE:
2692 			*data->gva = MAGIC_VAL_2;
2693 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2694 			*data->gva = MAGIC_VAL_1;
2695 			break;
2696 		case OP_EXEC:
2697 			TEST_ASSERT_EQ(42, code());
2698 			break;
2699 		case OP_FLUSH_TLB:
2700 			write_cr3(read_cr3());
2701 			break;
2702 		case OP_EXIT:
2703 			return;
2704 		default:
2705 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2706 		}
2707 		vmcall();
2708 	}
2709 }
2710 
2711 static void ept_access_test_setup(void)
2712 {
2713 	struct ept_access_test_data *data = &ept_access_test_data;
2714 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2715 	unsigned long size = npages * PAGE_SIZE;
2716 	unsigned long *page_table = current_page_table();
2717 	unsigned long pte;
2718 
2719 	if (setup_ept(false))
2720 		test_skip("EPT not supported");
2721 
2722 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2723 	if (cpuid_maxphyaddr() < 40)
2724 		test_skip("Test needs MAXPHYADDR >= 40");
2725 
2726 	test_set_guest(ept_access_test_guest);
2727 	test_add_teardown(ept_access_test_teardown, NULL);
2728 
2729 	data->hva = get_1g_page();
2730 	TEST_ASSERT(data->hva);
2731 	data->hpa = virt_to_phys(data->hva);
2732 
2733 	data->gpa = 1ul << 39;
2734 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2735 				   size);
2736 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2737 	install_pages(page_table, data->gpa, size, data->gva);
2738 
2739 	/*
2740 	 * Make sure nothing's mapped here so the tests that screw with the
2741 	 * pml4 entry don't inadvertently break something.
2742 	 */
2743 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2744 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2745 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2746 
2747 	data->hva[0] = MAGIC_VAL_1;
2748 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2749 }
2750 
2751 static void ept_access_test_not_present(void)
2752 {
2753 	ept_access_test_setup();
2754 	/* --- */
2755 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2756 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2757 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2758 }
2759 
2760 static void ept_access_test_read_only(void)
2761 {
2762 	ept_access_test_setup();
2763 
2764 	/* r-- */
2765 	ept_access_allowed(EPT_RA, OP_READ);
2766 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2767 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2768 }
2769 
2770 static void ept_access_test_write_only(void)
2771 {
2772 	ept_access_test_setup();
2773 	/* -w- */
2774 	ept_access_misconfig(EPT_WA);
2775 }
2776 
2777 static void ept_access_test_read_write(void)
2778 {
2779 	ept_access_test_setup();
2780 	/* rw- */
2781 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2782 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2783 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2784 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2785 }
2786 
2787 
2788 static void ept_access_test_execute_only(void)
2789 {
2790 	ept_access_test_setup();
2791 	/* --x */
2792 	if (ept_execute_only_supported()) {
2793 		ept_access_violation(EPT_EA, OP_READ,
2794 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2795 		ept_access_violation(EPT_EA, OP_WRITE,
2796 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2797 		ept_access_allowed(EPT_EA, OP_EXEC);
2798 	} else {
2799 		ept_access_misconfig(EPT_EA);
2800 	}
2801 }
2802 
2803 static void ept_access_test_read_execute(void)
2804 {
2805 	ept_access_test_setup();
2806 	/* r-x */
2807 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2808 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2809 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2810 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2811 }
2812 
2813 static void ept_access_test_write_execute(void)
2814 {
2815 	ept_access_test_setup();
2816 	/* -wx */
2817 	ept_access_misconfig(EPT_WA | EPT_EA);
2818 }
2819 
2820 static void ept_access_test_read_write_execute(void)
2821 {
2822 	ept_access_test_setup();
2823 	/* rwx */
2824 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2825 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2826 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2827 }
2828 
2829 static void ept_access_test_reserved_bits(void)
2830 {
2831 	int i;
2832 	int maxphyaddr;
2833 
2834 	ept_access_test_setup();
2835 
2836 	/* Reserved bits above maxphyaddr. */
2837 	maxphyaddr = cpuid_maxphyaddr();
2838 	for (i = maxphyaddr; i <= 51; i++) {
2839 		report_prefix_pushf("reserved_bit=%d", i);
2840 		ept_reserved_bit(i);
2841 		report_prefix_pop();
2842 	}
2843 
2844 	/* Level-specific reserved bits. */
2845 	ept_reserved_bit_at_level_nohuge(2, 3);
2846 	ept_reserved_bit_at_level_nohuge(2, 4);
2847 	ept_reserved_bit_at_level_nohuge(2, 5);
2848 	ept_reserved_bit_at_level_nohuge(2, 6);
2849 	/* 2M alignment. */
2850 	for (i = 12; i < 20; i++) {
2851 		report_prefix_pushf("reserved_bit=%d", i);
2852 		ept_reserved_bit_at_level_huge(2, i);
2853 		report_prefix_pop();
2854 	}
2855 	ept_reserved_bit_at_level_nohuge(3, 3);
2856 	ept_reserved_bit_at_level_nohuge(3, 4);
2857 	ept_reserved_bit_at_level_nohuge(3, 5);
2858 	ept_reserved_bit_at_level_nohuge(3, 6);
2859 	/* 1G alignment. */
2860 	for (i = 12; i < 29; i++) {
2861 		report_prefix_pushf("reserved_bit=%d", i);
2862 		ept_reserved_bit_at_level_huge(3, i);
2863 		report_prefix_pop();
2864 	}
2865 	ept_reserved_bit_at_level(4, 3);
2866 	ept_reserved_bit_at_level(4, 4);
2867 	ept_reserved_bit_at_level(4, 5);
2868 	ept_reserved_bit_at_level(4, 6);
2869 	ept_reserved_bit_at_level(4, 7);
2870 }
2871 
2872 static void ept_access_test_ignored_bits(void)
2873 {
2874 	ept_access_test_setup();
2875 	/*
2876 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2877 	 * far as translation is concerned even if AD bits are enabled in the
2878 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2879 	 * control is 0.
2880 	 */
2881 	ept_ignored_bit(8);
2882 	ept_ignored_bit(9);
2883 	ept_ignored_bit(10);
2884 	ept_ignored_bit(11);
2885 	ept_ignored_bit(52);
2886 	ept_ignored_bit(53);
2887 	ept_ignored_bit(54);
2888 	ept_ignored_bit(55);
2889 	ept_ignored_bit(56);
2890 	ept_ignored_bit(57);
2891 	ept_ignored_bit(58);
2892 	ept_ignored_bit(59);
2893 	ept_ignored_bit(60);
2894 	ept_ignored_bit(61);
2895 	ept_ignored_bit(62);
2896 	ept_ignored_bit(63);
2897 }
2898 
2899 static void ept_access_test_paddr_not_present_ad_disabled(void)
2900 {
2901 	ept_access_test_setup();
2902 	ept_disable_ad_bits();
2903 
2904 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2905 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2906 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2907 }
2908 
2909 static void ept_access_test_paddr_not_present_ad_enabled(void)
2910 {
2911 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2912 
2913 	ept_access_test_setup();
2914 	ept_enable_ad_bits_or_skip_test();
2915 
2916 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2917 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2918 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2919 }
2920 
2921 static void ept_access_test_paddr_read_only_ad_disabled(void)
2922 {
2923 	/*
2924 	 * When EPT AD bits are disabled, all accesses to guest paging
2925 	 * structures are reported separately as a read and (after
2926 	 * translation of the GPA to host physical address) a read+write
2927 	 * if the A/D bits have to be set.
2928 	 */
2929 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2930 
2931 	ept_access_test_setup();
2932 	ept_disable_ad_bits();
2933 
2934 	/* Can't update A bit, so all accesses fail. */
2935 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2936 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2937 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2938 	/* AD bits disabled, so only writes try to update the D bit. */
2939 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
2940 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2941 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
2942 	/* Both A and D already set, so read-only is OK. */
2943 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
2944 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
2945 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
2946 }
2947 
2948 static void ept_access_test_paddr_read_only_ad_enabled(void)
2949 {
2950 	/*
2951 	 * When EPT AD bits are enabled, all accesses to guest paging
2952 	 * structures are considered writes as far as EPT translation
2953 	 * is concerned.
2954 	 */
2955 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2956 
2957 	ept_access_test_setup();
2958 	ept_enable_ad_bits_or_skip_test();
2959 
2960 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2961 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2962 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2963 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
2964 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2965 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
2966 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
2967 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
2968 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
2969 }
2970 
2971 static void ept_access_test_paddr_read_write(void)
2972 {
2973 	ept_access_test_setup();
2974 	/* Read-write access to paging structure. */
2975 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
2976 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
2977 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
2978 }
2979 
2980 static void ept_access_test_paddr_read_write_execute(void)
2981 {
2982 	ept_access_test_setup();
2983 	/* RWX access to paging structure. */
2984 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
2985 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
2986 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
2987 }
2988 
2989 static void ept_access_test_paddr_read_execute_ad_disabled(void)
2990 {
2991   	/*
2992 	 * When EPT AD bits are disabled, all accesses to guest paging
2993 	 * structures are reported separately as a read and (after
2994 	 * translation of the GPA to host physical address) a read+write
2995 	 * if the A/D bits have to be set.
2996 	 */
2997 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2998 
2999 	ept_access_test_setup();
3000 	ept_disable_ad_bits();
3001 
3002 	/* Can't update A bit, so all accesses fail. */
3003 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3004 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3005 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3006 	/* AD bits disabled, so only writes try to update the D bit. */
3007 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
3008 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3009 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
3010 	/* Both A and D already set, so read-only is OK. */
3011 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
3012 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
3013 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
3014 }
3015 
3016 static void ept_access_test_paddr_read_execute_ad_enabled(void)
3017 {
3018 	/*
3019 	 * When EPT AD bits are enabled, all accesses to guest paging
3020 	 * structures are considered writes as far as EPT translation
3021 	 * is concerned.
3022 	 */
3023 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3024 
3025 	ept_access_test_setup();
3026 	ept_enable_ad_bits_or_skip_test();
3027 
3028 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3029 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3030 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3031 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
3032 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3033 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
3034 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
3035 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
3036 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
3037 }
3038 
3039 static void ept_access_test_paddr_not_present_page_fault(void)
3040 {
3041 	ept_access_test_setup();
3042 	/*
3043 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
3044 	 * page is read-only in EPT but GVA is also mapped read only in PT.
3045 	 * Thus guest page fault before host takes EPT violation for trying to
3046 	 * update A bit.
3047 	 */
3048 }
3049 
3050 static void ept_access_test_force_2m_page(void)
3051 {
3052 	ept_access_test_setup();
3053 
3054 	TEST_ASSERT_EQ(ept_2m_supported(), true);
3055 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
3056 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
3057 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
3058 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
3059 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
3060 }
3061 
3062 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
3063 {
3064 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3065 
3066 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
3067 
3068 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
3069 		return false;
3070 
3071 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
3072 		return false;
3073 
3074 	if (vpid >> 16)
3075 		return false;
3076 
3077 	if (type != INVVPID_ALL && !vpid)
3078 		return false;
3079 
3080 	if (type == INVVPID_ADDR && !is_canonical(gla))
3081 		return false;
3082 
3083 	return true;
3084 }
3085 
3086 static void try_invvpid(u64 type, u64 vpid, u64 gla)
3087 {
3088 	int rc;
3089 	bool valid = invvpid_valid(type, vpid, gla);
3090 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
3091 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
3092 	/*
3093 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
3094 	 * that we can tell if it is updated by INVVPID.
3095 	 */
3096 	vmcs_read(~0);
3097 	rc = invvpid(type, vpid, gla);
3098 	report("INVVPID type %ld VPID %lx GLA %lx %s",
3099 	       !rc == valid, type, vpid, gla,
3100 	       valid ? "passes" : "fails");
3101 	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3102 	       vmcs_read(VMX_INST_ERROR) == expected,
3103 	       rc ? "failed" : "successful",
3104 	       expected, vmcs_read(VMX_INST_ERROR));
3105 }
3106 
3107 static void ds_invvpid(void *data)
3108 {
3109 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3110 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3111 
3112 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3113 	asm volatile("invvpid %0, %1"
3114 		     :
3115 		     : "m"(*(struct invvpid_operand *)data),
3116 		       "r"(type));
3117 }
3118 
3119 /*
3120  * The SS override is ignored in 64-bit mode, so we use an addressing
3121  * mode with %rsp as the base register to generate an implicit SS
3122  * reference.
3123  */
3124 static void ss_invvpid(void *data)
3125 {
3126 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3127 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3128 
3129 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3130 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3131 		     : "+r"(data)
3132 		     : "r"(type));
3133 }
3134 
3135 static void invvpid_test_gp(void)
3136 {
3137 	bool fault;
3138 
3139 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3140 				   (void *)NONCANONICAL);
3141 	report("INVVPID with non-canonical DS operand raises #GP", fault);
3142 }
3143 
3144 static void invvpid_test_ss(void)
3145 {
3146 	bool fault;
3147 
3148 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3149 				   (void *)NONCANONICAL);
3150 	report("INVVPID with non-canonical SS operand raises #SS", fault);
3151 }
3152 
3153 static void invvpid_test_pf(void)
3154 {
3155 	void *vpage = alloc_vpage();
3156 	bool fault;
3157 
3158 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3159 	report("INVVPID with unmapped operand raises #PF", fault);
3160 }
3161 
3162 static void try_compat_invvpid(void *unused)
3163 {
3164 	struct far_pointer32 fp = {
3165 		.offset = (uintptr_t)&&invvpid,
3166 		.selector = KERNEL_CS32,
3167 	};
3168 	register uintptr_t rsp asm("rsp");
3169 
3170 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3171 			"Code address too high.");
3172 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3173 
3174 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3175 	return;
3176 invvpid:
3177 	asm volatile (".code32;"
3178 		      "invvpid (%eax), %eax;"
3179 		      "lret;"
3180 		      ".code64");
3181 	__builtin_unreachable();
3182 }
3183 
3184 static void invvpid_test_compatibility_mode(void)
3185 {
3186 	bool fault;
3187 
3188 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3189 	report("Compatibility mode INVVPID raises #UD", fault);
3190 }
3191 
3192 static void invvpid_test_not_in_vmx_operation(void)
3193 {
3194 	bool fault;
3195 
3196 	TEST_ASSERT(!vmx_off());
3197 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3198 	report("INVVPID outside of VMX operation raises #UD", fault);
3199 	TEST_ASSERT(!vmx_on());
3200 }
3201 
3202 /*
3203  * This does not test real-address mode, virtual-8086 mode, protected mode,
3204  * or CPL > 0.
3205  */
3206 static void invvpid_test_v2(void)
3207 {
3208 	u64 msr;
3209 	int i;
3210 	unsigned types = 0;
3211 	unsigned type;
3212 
3213 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3214 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3215 		test_skip("VPID not supported");
3216 
3217 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3218 
3219 	if (!(msr & VPID_CAP_INVVPID))
3220 		test_skip("INVVPID not supported.\n");
3221 
3222 	if (msr & VPID_CAP_INVVPID_ADDR)
3223 		types |= 1u << INVVPID_ADDR;
3224 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3225 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3226 	if (msr & VPID_CAP_INVVPID_ALL)
3227 		types |= 1u << INVVPID_ALL;
3228 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3229 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3230 
3231 	if (!types)
3232 		test_skip("No INVVPID types supported.\n");
3233 
3234 	for (i = -127; i < 128; i++)
3235 		try_invvpid(i, 0xffff, 0);
3236 
3237 	/*
3238 	 * VPID must not be more than 16 bits.
3239 	 */
3240 	for (i = 0; i < 64; i++)
3241 		for (type = 0; type < 4; type++)
3242 			if (types & (1u << type))
3243 				try_invvpid(type, 1ul << i, 0);
3244 
3245 	/*
3246 	 * VPID must not be zero, except for "all contexts."
3247 	 */
3248 	for (type = 0; type < 4; type++)
3249 		if (types & (1u << type))
3250 			try_invvpid(type, 0, 0);
3251 
3252 	/*
3253 	 * The gla operand is only validated for single-address INVVPID.
3254 	 */
3255 	if (types & (1u << INVVPID_ADDR))
3256 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3257 
3258 	invvpid_test_gp();
3259 	invvpid_test_ss();
3260 	invvpid_test_pf();
3261 	invvpid_test_compatibility_mode();
3262 	invvpid_test_not_in_vmx_operation();
3263 }
3264 
3265 /*
3266  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3267  * at least as far as the guest-state checks. Returns false if the
3268  * VMLAUNCH fails early and execution falls through to the next
3269  * instruction.
3270  */
3271 static bool vmlaunch_succeeds(void)
3272 {
3273 	u32 exit_reason;
3274 
3275 	/*
3276 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3277 	 * unsupported VMCS component"). The caller can then check
3278 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3279 	 */
3280 	vmcs_write(~0u, 0);
3281 
3282 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3283 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3284 				   :
3285 				   : "r" ((u64)HOST_RSP)
3286 				   : "cc", "memory"
3287 				   : success);
3288 	return false;
3289 success:
3290 	exit_reason = vmcs_read(EXI_REASON);
3291 	TEST_ASSERT(exit_reason == (VMX_FAIL_STATE | VMX_ENTRY_FAILURE) ||
3292 		    exit_reason == (VMX_FAIL_MSR | VMX_ENTRY_FAILURE));
3293 	return true;
3294 }
3295 
3296 /*
3297  * Try to launch the current VMCS.
3298  */
3299 static void test_vmx_controls(bool controls_valid, bool xfail)
3300 {
3301 	bool success = vmlaunch_succeeds();
3302 	u32 vmx_inst_err;
3303 
3304 	report_xfail("vmlaunch %s", xfail, success == controls_valid,
3305 		     controls_valid ? "succeeds" : "fails");
3306 	if (!success) {
3307 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3308 		report("VMX inst error is %d (actual %d)",
3309 		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
3310 		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
3311 	}
3312 }
3313 
3314 /*
3315  * Test a particular value of a VM-execution control bit, if the value
3316  * is required or if the value is zero.
3317  */
3318 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3319 				    enum Encoding encoding, unsigned bit,
3320 				    unsigned val)
3321 {
3322 	u32 mask = 1u << bit;
3323 	bool expected;
3324 	u32 controls;
3325 
3326 	if (msr.set & mask)
3327 		TEST_ASSERT(msr.clr & mask);
3328 
3329 	/*
3330 	 * We can't arbitrarily turn on a control bit, because it may
3331 	 * introduce dependencies on other VMCS fields. So, we only
3332 	 * test turning on bits that have a required setting.
3333 	 */
3334 	if (val && (msr.clr & mask) && !(msr.set & mask))
3335 		return;
3336 
3337 	report_prefix_pushf("%s %s bit %d",
3338 			    val ? "Set" : "Clear", name, bit);
3339 
3340 	controls = vmcs_read(encoding);
3341 	if (val) {
3342 		vmcs_write(encoding, msr.set | mask);
3343 		expected = (msr.clr & mask);
3344 	} else {
3345 		vmcs_write(encoding, msr.set & ~mask);
3346 		expected = !(msr.set & mask);
3347 	}
3348 	test_vmx_controls(expected, false);
3349 	vmcs_write(encoding, controls);
3350 	report_prefix_pop();
3351 }
3352 
3353 /*
3354  * Test reserved values of a VM-execution control bit, based on the
3355  * allowed bit settings from the corresponding VMX capability MSR.
3356  */
3357 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3358 			      enum Encoding encoding, unsigned bit)
3359 {
3360 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3361 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3362 }
3363 
3364 /*
3365  * Reserved bits in the pin-based VM-execution controls must be set
3366  * properly. Software may consult the VMX capability MSRs to determine
3367  * the proper settings.
3368  * [Intel SDM]
3369  */
3370 static void test_pin_based_ctls(void)
3371 {
3372 	unsigned bit;
3373 
3374 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3375 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3376 	for (bit = 0; bit < 32; bit++)
3377 		test_rsvd_ctl_bit("pin-based controls",
3378 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3379 }
3380 
3381 /*
3382  * Reserved bits in the primary processor-based VM-execution controls
3383  * must be set properly. Software may consult the VMX capability MSRs
3384  * to determine the proper settings.
3385  * [Intel SDM]
3386  */
3387 static void test_primary_processor_based_ctls(void)
3388 {
3389 	unsigned bit;
3390 
3391 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3392 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3393 	for (bit = 0; bit < 32; bit++)
3394 		test_rsvd_ctl_bit("primary processor-based controls",
3395 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3396 }
3397 
3398 /*
3399  * If the "activate secondary controls" primary processor-based
3400  * VM-execution control is 1, reserved bits in the secondary
3401  * processor-based VM-execution controls must be cleared. Software may
3402  * consult the VMX capability MSRs to determine which bits are
3403  * reserved.
3404  * If the "activate secondary controls" primary processor-based
3405  * VM-execution control is 0 (or if the processor does not support the
3406  * 1-setting of that control), no checks are performed on the
3407  * secondary processor-based VM-execution controls.
3408  * [Intel SDM]
3409  */
3410 static void test_secondary_processor_based_ctls(void)
3411 {
3412 	u32 primary;
3413 	u32 secondary;
3414 	unsigned bit;
3415 
3416 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3417 		return;
3418 
3419 	primary = vmcs_read(CPU_EXEC_CTRL0);
3420 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3421 
3422 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3423 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3424 	for (bit = 0; bit < 32; bit++)
3425 		test_rsvd_ctl_bit("secondary processor-based controls",
3426 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3427 
3428 	/*
3429 	 * When the "activate secondary controls" VM-execution control
3430 	 * is clear, there are no checks on the secondary controls.
3431 	 */
3432 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3433 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3434 	report("Secondary processor-based controls ignored",
3435 	       vmlaunch_succeeds());
3436 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3437 	vmcs_write(CPU_EXEC_CTRL0, primary);
3438 }
3439 
3440 static void try_cr3_target_count(unsigned i, unsigned max)
3441 {
3442 	report_prefix_pushf("CR3 target count 0x%x", i);
3443 	vmcs_write(CR3_TARGET_COUNT, i);
3444 	test_vmx_controls(i <= max, false);
3445 	report_prefix_pop();
3446 }
3447 
3448 /*
3449  * The CR3-target count must not be greater than 4. Future processors
3450  * may support a different number of CR3-target values. Software
3451  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3452  * number of values supported.
3453  * [Intel SDM]
3454  */
3455 static void test_cr3_targets(void)
3456 {
3457 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3458 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3459 	unsigned i;
3460 
3461 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3462 	TEST_ASSERT(supported_targets <= 256);
3463 
3464 	try_cr3_target_count(-1u, supported_targets);
3465 	try_cr3_target_count(0x80000000, supported_targets);
3466 	try_cr3_target_count(0x7fffffff, supported_targets);
3467 	for (i = 0; i <= supported_targets + 1; i++)
3468 		try_cr3_target_count(i, supported_targets);
3469 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3470 }
3471 
3472 /*
3473  * Test a particular address setting in the VMCS
3474  */
3475 static void test_vmcs_addr(const char *name,
3476 			   enum Encoding encoding,
3477 			   u64 align,
3478 			   bool ignored,
3479 			   bool xfail_beyond_mapped_ram,
3480 			   u64 addr)
3481 {
3482 	bool xfail =
3483 		(xfail_beyond_mapped_ram &&
3484 		 addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - align &&
3485 		 addr < (1ul << cpuid_maxphyaddr()));
3486 
3487 	report_prefix_pushf("%s = %lx", name, addr);
3488 	vmcs_write(encoding, addr);
3489 	test_vmx_controls(ignored || (IS_ALIGNED(addr, align) &&
3490 				  addr < (1ul << cpuid_maxphyaddr())),
3491 			  xfail);
3492 	report_prefix_pop();
3493 	xfail = false;
3494 }
3495 
3496 /*
3497  * Test interesting values for a VMCS address
3498  */
3499 static void test_vmcs_addr_values(const char *name,
3500 				  enum Encoding encoding,
3501 				  u64 align,
3502 				  bool ignored,
3503 				  bool xfail_beyond_mapped_ram,
3504 				  u32 bit_start, u32 bit_end)
3505 {
3506 	unsigned i;
3507 	u64 orig_val = vmcs_read(encoding);
3508 
3509 	for (i = bit_start; i <= bit_end; i++)
3510 		test_vmcs_addr(name, encoding, align, ignored,
3511 			       xfail_beyond_mapped_ram, 1ul << i);
3512 
3513 	test_vmcs_addr(name, encoding, align, ignored,
3514 		       xfail_beyond_mapped_ram, PAGE_SIZE - 1);
3515 	test_vmcs_addr(name, encoding, align, ignored,
3516 		       xfail_beyond_mapped_ram, PAGE_SIZE);
3517 	test_vmcs_addr(name, encoding, align, ignored,
3518 		       xfail_beyond_mapped_ram,
3519 		      (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3520 	test_vmcs_addr(name, encoding, align, ignored,
3521 		       xfail_beyond_mapped_ram, -1ul);
3522 
3523 	vmcs_write(encoding, orig_val);
3524 }
3525 
3526 /*
3527  * Test a physical address reference in the VMCS, when the corresponding
3528  * feature is enabled and when the corresponding feature is disabled.
3529  */
3530 static void test_vmcs_addr_reference(u32 control_bit, enum Encoding field,
3531 				     const char *field_name,
3532 				     const char *control_name, u64 align,
3533 				     bool xfail_beyond_mapped_ram,
3534 				     bool control_primary)
3535 {
3536 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3537 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3538 	u64 page_addr;
3539 
3540 	if (control_primary) {
3541 		if (!(ctrl_cpu_rev[0].clr & control_bit))
3542 			return;
3543 	} else {
3544 		if (!(ctrl_cpu_rev[1].clr & control_bit))
3545 			return;
3546 	}
3547 
3548 	page_addr = vmcs_read(field);
3549 
3550 	report_prefix_pushf("%s enabled", control_name);
3551 	if (control_primary) {
3552 		vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3553 	} else {
3554 		vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3555 		vmcs_write(CPU_EXEC_CTRL1, secondary | control_bit);
3556 	}
3557 
3558 	test_vmcs_addr_values(field_name, field, align, false,
3559 			      xfail_beyond_mapped_ram, 0, 63);
3560 	report_prefix_pop();
3561 
3562 	report_prefix_pushf("%s disabled", control_name);
3563 	if (control_primary) {
3564 		vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3565 	} else {
3566 		vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3567 		vmcs_write(CPU_EXEC_CTRL1, secondary & ~control_bit);
3568 	}
3569 
3570 	test_vmcs_addr_values(field_name, field, align, true, false, 0, 63);
3571 	report_prefix_pop();
3572 
3573 	vmcs_write(field, page_addr);
3574 	vmcs_write(CPU_EXEC_CTRL0, primary);
3575 }
3576 
3577 /*
3578  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3579  * each I/O-bitmap address must be 0. Neither address should set any
3580  * bits beyond the processor's physical-address width.
3581  * [Intel SDM]
3582  */
3583 static void test_io_bitmaps(void)
3584 {
3585 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3586 				 "I/O bitmap A", "Use I/O bitmaps",
3587 				 PAGE_SIZE, false, true);
3588 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3589 				 "I/O bitmap B", "Use I/O bitmaps",
3590 				 PAGE_SIZE, false, true);
3591 }
3592 
3593 /*
3594  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3595  * the MSR-bitmap address must be 0. The address should not set any
3596  * bits beyond the processor's physical-address width.
3597  * [Intel SDM]
3598  */
3599 static void test_msr_bitmap(void)
3600 {
3601 	test_vmcs_addr_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3602 				 "MSR bitmap", "Use MSR bitmaps",
3603 				 PAGE_SIZE, false, true);
3604 }
3605 
3606 /*
3607  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3608  * address must satisfy the following checks:
3609  * - Bits 11:0 of the address must be 0.
3610  * - The address should not set any bits beyond the processor's
3611  *   physical-address width.
3612  * [Intel SDM]
3613  */
3614 static void test_apic_virt_addr(void)
3615 {
3616 	test_vmcs_addr_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3617 				 "virtual-APIC address", "Use TPR shadow",
3618 				 PAGE_SIZE, true, true);
3619 }
3620 
3621 /*
3622  * If the "virtualize APIC-accesses" VM-execution control is 1, the
3623  * APIC-access address must satisfy the following checks:
3624  *  - Bits 11:0 of the address must be 0.
3625  *  - The address should not set any bits beyond the processor's
3626  *    physical-address width.
3627  * [Intel SDM]
3628  */
3629 static void test_apic_access_addr(void)
3630 {
3631 	void *apic_access_page = alloc_page();
3632 
3633 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_page));
3634 
3635 	test_vmcs_addr_reference(CPU_VIRT_APIC_ACCESSES, APIC_ACCS_ADDR,
3636 				 "APIC-access address",
3637 				 "virtualize APIC-accesses", PAGE_SIZE,
3638 				 false, false);
3639 }
3640 
3641 static bool set_bit_pattern(u8 mask, u32 *secondary)
3642 {
3643 	u8 i;
3644 	bool flag = false;
3645 	u32 test_bits[3] = {
3646 		CPU_VIRT_X2APIC,
3647 		CPU_APIC_REG_VIRT,
3648 		CPU_VINTD
3649 	};
3650 
3651         for (i = 0; i < ARRAY_SIZE(test_bits); i++) {
3652 		if ((mask & (1u << i)) &&
3653 		    (ctrl_cpu_rev[1].clr & test_bits[i])) {
3654 			*secondary |= test_bits[i];
3655 			flag = true;
3656 		}
3657 	}
3658 
3659 	return (flag);
3660 }
3661 
3662 /*
3663  * If the "use TPR shadow" VM-execution control is 0, the following
3664  * VM-execution controls must also be 0:
3665  * 	- virtualize x2APIC mode
3666  *	- APIC-register virtualization
3667  *	- virtual-interrupt delivery
3668  *    [Intel SDM]
3669  *
3670  * 2. If the "virtualize x2APIC mode" VM-execution control is 1, the
3671  *    "virtualize APIC accesses" VM-execution control must be 0.
3672  *    [Intel SDM]
3673  */
3674 static void test_apic_virtual_ctls(void)
3675 {
3676 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3677 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3678 	u32 primary = saved_primary;
3679 	u32 secondary = saved_secondary;
3680 	bool ctrl = false;
3681 	char str[10] = "disabled";
3682 	u8 i = 0, j;
3683 
3684 	/*
3685 	 * First test
3686 	 */
3687 	if (!((ctrl_cpu_rev[0].clr & (CPU_SECONDARY | CPU_TPR_SHADOW)) ==
3688 	    (CPU_SECONDARY | CPU_TPR_SHADOW)))
3689 		return;
3690 
3691 	primary |= CPU_SECONDARY;
3692 	primary &= ~CPU_TPR_SHADOW;
3693 	vmcs_write(CPU_EXEC_CTRL0, primary);
3694 
3695 	while (1) {
3696 		for (j = 1; j < 8; j++) {
3697 			secondary &= ~(CPU_VIRT_X2APIC | CPU_APIC_REG_VIRT | CPU_VINTD);
3698 			if (primary & CPU_TPR_SHADOW) {
3699 				ctrl = true;
3700 			} else {
3701 				if (! set_bit_pattern(j, &secondary))
3702 					ctrl = true;
3703 				else
3704 					ctrl = false;
3705 			}
3706 
3707 			vmcs_write(CPU_EXEC_CTRL1, secondary);
3708 			report_prefix_pushf("Use TPR shadow %s, virtualize x2APIC mode %s, APIC-register virtualization %s, virtual-interrupt delivery %s",
3709 				str, (secondary & CPU_VIRT_X2APIC) ? "enabled" : "disabled", (secondary & CPU_APIC_REG_VIRT) ? "enabled" : "disabled", (secondary & CPU_VINTD) ? "enabled" : "disabled");
3710 			test_vmx_controls(ctrl, false);
3711 			report_prefix_pop();
3712 		}
3713 
3714 		if (i == 1)
3715 			break;
3716 		i++;
3717 
3718 		primary |= CPU_TPR_SHADOW;
3719 		vmcs_write(CPU_EXEC_CTRL0, primary);
3720 		strcpy(str, "enabled");
3721 	}
3722 
3723 	/*
3724 	 * Second test
3725 	 */
3726 	u32 apic_virt_ctls = (CPU_VIRT_X2APIC | CPU_VIRT_APIC_ACCESSES);
3727 
3728 	primary = saved_primary;
3729 	secondary = saved_secondary;
3730 	if (!((ctrl_cpu_rev[1].clr & apic_virt_ctls) == apic_virt_ctls))
3731 		return;
3732 
3733 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3734 	secondary &= ~CPU_VIRT_APIC_ACCESSES;
3735 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_X2APIC);
3736 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access disabled");
3737 	test_vmx_controls(true, false);
3738 	report_prefix_pop();
3739 
3740 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_APIC_ACCESSES);
3741 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access enabled");
3742 	test_vmx_controls(true, false);
3743 	report_prefix_pop();
3744 
3745 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_X2APIC);
3746 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access enabled");
3747 	test_vmx_controls(false, false);
3748 	report_prefix_pop();
3749 
3750 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_APIC_ACCESSES);
3751 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access disabled");
3752 	test_vmx_controls(true, false);
3753 	report_prefix_pop();
3754 
3755 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3756 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3757 }
3758 
3759 /*
3760  * If the "virtual-interrupt delivery" VM-execution control is 1, the
3761  * "external-interrupt exiting" VM-execution control must be 1.
3762  * [Intel SDM]
3763  */
3764 static void test_virtual_intr_ctls(void)
3765 {
3766 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3767 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3768 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3769 	u32 primary = saved_primary;
3770 	u32 secondary = saved_secondary;
3771 	u32 pin = saved_pin;
3772 
3773 	if (!((ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3774 	    (ctrl_pin_rev.clr & PIN_EXTINT)))
3775 		return;
3776 
3777 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3778 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VINTD);
3779 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3780 	report_prefix_pushf("Virtualize interrupt-delivery disabled; external-interrupt exiting disabled");
3781 	test_vmx_controls(true, false);
3782 	report_prefix_pop();
3783 
3784 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VINTD);
3785 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3786 	test_vmx_controls(false, false);
3787 	report_prefix_pop();
3788 
3789 	vmcs_write(PIN_CONTROLS, pin | PIN_EXTINT);
3790 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting enabled");
3791 	test_vmx_controls(true, false);
3792 	report_prefix_pop();
3793 
3794 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3795 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3796 	test_vmx_controls(false, false);
3797 	report_prefix_pop();
3798 
3799 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3800 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3801 	vmcs_write(PIN_CONTROLS, saved_pin);
3802 }
3803 
3804 static void test_pi_desc_addr(u64 addr, bool ctrl)
3805 {
3806 	vmcs_write(POSTED_INTR_DESC_ADDR, addr);
3807 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-descriptor-address 0x%lx", addr);
3808 	test_vmx_controls(ctrl, false);
3809 	report_prefix_pop();
3810 }
3811 
3812 /*
3813  * If the “process posted interrupts†VM-execution control is 1, the
3814  * following must be true:
3815  *
3816  *	- The “virtual-interrupt delivery†VM-execution control is 1.
3817  *	- The “acknowledge interrupt on exit†VM-exit control is 1.
3818  *	- The posted-interrupt notification vector has a value in the
3819  *	- range 0–255 (bits 15:8 are all 0).
3820  *	- Bits 5:0 of the posted-interrupt descriptor address are all 0.
3821  *	- The posted-interrupt descriptor address does not set any bits
3822  *	  beyond the processor's physical-address width.
3823  * [Intel SDM]
3824  */
3825 static void test_posted_intr(void)
3826 {
3827 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3828 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3829 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3830 	u32 exit_ctl_saved = vmcs_read(EXI_CONTROLS);
3831 	u32 primary = saved_primary;
3832 	u32 secondary = saved_secondary;
3833 	u32 pin = saved_pin;
3834 	u32 exit_ctl = exit_ctl_saved;
3835 	u16 vec;
3836 	int i;
3837 
3838 	if (!((ctrl_pin_rev.clr & PIN_POST_INTR) &&
3839 	    (ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3840 	    (ctrl_exit_rev.clr & EXI_INTA)))
3841 		return;
3842 
3843 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3844 
3845 	/*
3846 	 * Test virtual-interrupt-delivery and acknowledge-interrupt-on-exit
3847 	 */
3848 	pin |= PIN_POST_INTR;
3849 	vmcs_write(PIN_CONTROLS, pin);
3850 	secondary &= ~CPU_VINTD;
3851 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3852 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled");
3853 	test_vmx_controls(false, false);
3854 	report_prefix_pop();
3855 
3856 	secondary |= CPU_VINTD;
3857 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3858 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled");
3859 	test_vmx_controls(false, false);
3860 	report_prefix_pop();
3861 
3862 	exit_ctl &= ~EXI_INTA;
3863 	vmcs_write(EXI_CONTROLS, exit_ctl);
3864 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit disabled");
3865 	test_vmx_controls(false, false);
3866 	report_prefix_pop();
3867 
3868 	exit_ctl |= EXI_INTA;
3869 	vmcs_write(EXI_CONTROLS, exit_ctl);
3870 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
3871 	test_vmx_controls(true, false);
3872 	report_prefix_pop();
3873 
3874 	secondary &= ~CPU_VINTD;
3875 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3876 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled; acknowledge-interrupt-on-exit enabled");
3877 	test_vmx_controls(false, false);
3878 	report_prefix_pop();
3879 
3880 	secondary |= CPU_VINTD;
3881 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3882 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
3883 	test_vmx_controls(true, false);
3884 	report_prefix_pop();
3885 
3886 	/*
3887 	 * Test posted-interrupt notification vector
3888 	 */
3889 	for (i = 0; i < 8; i++) {
3890 		vec = (1ul << i);
3891 		vmcs_write(PINV, vec);
3892 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3893 		test_vmx_controls(true, false);
3894 		report_prefix_pop();
3895 	}
3896 	for (i = 8; i < 16; i++) {
3897 		vec = (1ul << i);
3898 		vmcs_write(PINV, vec);
3899 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3900 		test_vmx_controls(false, false);
3901 		report_prefix_pop();
3902 	}
3903 
3904 	vec &= ~(0xff << 8);
3905 	vmcs_write(PINV, vec);
3906 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3907 	test_vmx_controls(true, false);
3908 	report_prefix_pop();
3909 
3910 	/*
3911 	 * Test posted-interrupt descriptor addresss
3912 	 */
3913 	for (i = 0; i < 6; i++) {
3914 		test_pi_desc_addr(1ul << i, false);
3915 	}
3916 
3917 	test_pi_desc_addr(0xf0, false);
3918 	test_pi_desc_addr(0xff, false);
3919 	test_pi_desc_addr(0x0f, false);
3920 	test_pi_desc_addr(0x8000, true);
3921 	test_pi_desc_addr(0x00, true);
3922 	test_pi_desc_addr(0xc000, true);
3923 
3924 	test_vmcs_addr_values("process-posted interrupts",
3925 			       POSTED_INTR_DESC_ADDR, 64,
3926 			       false, false, 0, 63);
3927 
3928 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3929 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3930 	vmcs_write(PIN_CONTROLS, saved_pin);
3931 }
3932 
3933 static void test_apic_ctls(void)
3934 {
3935 	test_apic_virt_addr();
3936 	test_apic_access_addr();
3937 	test_apic_virtual_ctls();
3938 	test_virtual_intr_ctls();
3939 	test_posted_intr();
3940 }
3941 
3942 /*
3943  * If the “enable VPID†VM-execution control is 1, the value of the
3944  * of the VPID VM-execution control field must not be 0000H.
3945  * [Intel SDM]
3946  */
3947 static void test_vpid(void)
3948 {
3949 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3950 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3951 	u16 vpid = 0x0000;
3952 	int i;
3953 
3954 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
3955 	    (ctrl_cpu_rev[1].clr & CPU_VPID))) {
3956 		test_skip("Secondary controls and/or VPID not supported");
3957 		return;
3958 	}
3959 
3960 	vmcs_write(CPU_EXEC_CTRL0, saved_primary | CPU_SECONDARY);
3961 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary & ~CPU_VPID);
3962 	vmcs_write(VPID, vpid);
3963 	report_prefix_pushf("VPID disabled; VPID value %x", vpid);
3964 	test_vmx_controls(true, false);
3965 	report_prefix_pop();
3966 
3967 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary | CPU_VPID);
3968 	report_prefix_pushf("VPID enabled; VPID value %x", vpid);
3969 	test_vmx_controls(false, false);
3970 	report_prefix_pop();
3971 
3972 	for (i = 0; i < 16; i++) {
3973 		vpid = (short)1 << i;;
3974 		vmcs_write(VPID, vpid);
3975 		report_prefix_pushf("VPID enabled; VPID value %x", vpid);
3976 		test_vmx_controls(true, false);
3977 		report_prefix_pop();
3978 	}
3979 
3980 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3981 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3982 }
3983 
3984 static void set_vtpr(unsigned vtpr)
3985 {
3986 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
3987 }
3988 
3989 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
3990 {
3991 	bool valid = true;
3992 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3993 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3994 
3995 	if ((primary & CPU_TPR_SHADOW) &&
3996 	    (!(primary & CPU_SECONDARY) ||
3997 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
3998 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
3999 
4000 	set_vtpr(vtpr);
4001 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
4002 	    threshold, (vtpr >> 4) & 0xf);
4003 	test_vmx_controls(valid, false);
4004 	report_prefix_pop();
4005 }
4006 
4007 static void test_invalid_event_injection(void)
4008 {
4009 	u32 ent_intr_info_save = vmcs_read(ENT_INTR_INFO);
4010 	u32 ent_intr_error_save = vmcs_read(ENT_INTR_ERROR);
4011 	u32 ent_inst_len_save = vmcs_read(ENT_INST_LEN);
4012 	u32 primary_save = vmcs_read(CPU_EXEC_CTRL0);
4013 	u32 secondary_save = vmcs_read(CPU_EXEC_CTRL1);
4014 	u64 guest_cr0_save = vmcs_read(GUEST_CR0);
4015 	u32 ent_intr_info_base = INTR_INFO_VALID_MASK;
4016 	u32 ent_intr_info, ent_intr_err, ent_intr_len;
4017 	u32 cnt;
4018 
4019 	/* Setup */
4020 	report_prefix_push("invalid event injection");
4021 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4022 	vmcs_write(ENT_INST_LEN, 0x00000001);
4023 
4024 	/* The field’s interruption type is not set to a reserved value. */
4025 	ent_intr_info = ent_intr_info_base | INTR_TYPE_RESERVED | DE_VECTOR;
4026 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4027 			    "RESERVED interruption type invalid [-]",
4028 			    ent_intr_info);
4029 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4030 	test_vmx_controls(false, false);
4031 	report_prefix_pop();
4032 
4033 	ent_intr_info = ent_intr_info_base | INTR_TYPE_EXT_INTR |
4034 			DE_VECTOR;
4035 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4036 			    "RESERVED interruption type invalid [+]",
4037 			    ent_intr_info);
4038 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4039 	test_vmx_controls(true, false);
4040 	report_prefix_pop();
4041 
4042 	/* If the interruption type is other event, the vector is 0. */
4043 	ent_intr_info = ent_intr_info_base | INTR_TYPE_OTHER_EVENT | DB_VECTOR;
4044 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4045 			    "(OTHER EVENT && vector != 0) invalid [-]",
4046 			    ent_intr_info);
4047 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4048 	test_vmx_controls(false, false);
4049 	report_prefix_pop();
4050 
4051 	/* If the interruption type is NMI, the vector is 2 (negative case). */
4052 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | DE_VECTOR;
4053 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4054 			    "(NMI && vector != 2) invalid [-]", ent_intr_info);
4055 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4056 	test_vmx_controls(false, false);
4057 	report_prefix_pop();
4058 
4059 	/* If the interruption type is NMI, the vector is 2 (positive case). */
4060 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | NMI_VECTOR;
4061 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4062 			    "(NMI && vector == 2) valid [+]", ent_intr_info);
4063 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4064 	test_vmx_controls(true, false);
4065 	report_prefix_pop();
4066 
4067 	/*
4068 	 * If the interruption type
4069 	 * is HW exception, the vector is at most 31.
4070 	 */
4071 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION | 0x20;
4072 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4073 			    "(HW exception && vector > 31) invalid [-]",
4074 			    ent_intr_info);
4075 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4076 	test_vmx_controls(false, false);
4077 	report_prefix_pop();
4078 
4079 	/*
4080 	 * deliver-error-code is 1 iff either
4081 	 * (a) the "unrestricted guest" VM-execution control is 0
4082 	 * (b) CR0.PE is set.
4083 	 */
4084 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4085 			GP_VECTOR;
4086 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4087 			    "error code <-> (!URG || prot_mode) [-]",
4088 			    ent_intr_info);
4089 	disable_unrestricted_guest();
4090 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4091 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4092 	test_vmx_controls(false, false);
4093 	report_prefix_pop();
4094 
4095 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4096 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4097 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4098 			    "error code <-> (!URG || prot_mode) [+]",
4099 			    ent_intr_info);
4100 	disable_unrestricted_guest();
4101 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4102 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4103 	test_vmx_controls(true, false);
4104 	report_prefix_pop();
4105 
4106 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4107 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4108 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4109 			    "error code <-> (!URG || prot_mode) [-]",
4110 			    ent_intr_info);
4111 	enable_unrestricted_guest();
4112 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4113 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4114 	test_vmx_controls(false, false);
4115 	report_prefix_pop();
4116 
4117 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4118 			GP_VECTOR;
4119 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4120 			    "error code <-> (!URG || prot_mode) [-]",
4121 			    ent_intr_info);
4122 	vmcs_write(GUEST_CR0, guest_cr0_save | X86_CR0_PE);
4123 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4124 	test_vmx_controls(false, false);
4125 	report_prefix_pop();
4126 
4127 	/* deliver-error-code is 1 iff the interruption type is HW exception */
4128 	report_prefix_push("error code <-> HW exception");
4129 	for (cnt = 0; cnt < 8; cnt++) {
4130 		u32 exception_type_mask = cnt << 8;
4131 		u32 deliver_error_code_mask =
4132 			exception_type_mask != INTR_TYPE_HARD_EXCEPTION ?
4133 			INTR_INFO_DELIVER_CODE_MASK : 0;
4134 
4135 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4136 				exception_type_mask | GP_VECTOR;
4137 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4138 				    ent_intr_info);
4139 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4140 		test_vmx_controls(false, false);
4141 		report_prefix_pop();
4142 	}
4143 	report_prefix_pop();
4144 
4145 	/*
4146 	 * deliver-error-code is 1 iff the the vector
4147 	 * indicates an exception that would normally deliver an error code
4148 	 */
4149 	report_prefix_push("error code <-> vector delivers error code");
4150 	for (cnt = 0; cnt < 32; cnt++) {
4151 		bool has_error_code = false;
4152 		u32 deliver_error_code_mask;
4153 
4154 		switch (cnt) {
4155 		case DF_VECTOR:
4156 		case TS_VECTOR:
4157 		case NP_VECTOR:
4158 		case SS_VECTOR:
4159 		case GP_VECTOR:
4160 		case PF_VECTOR:
4161 		case AC_VECTOR:
4162 			has_error_code = true;
4163 		}
4164 
4165 		/* Negative case */
4166 		deliver_error_code_mask = has_error_code ?
4167 						0 :
4168 						INTR_INFO_DELIVER_CODE_MASK;
4169 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4170 				INTR_TYPE_HARD_EXCEPTION | cnt;
4171 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4172 				    ent_intr_info);
4173 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4174 		test_vmx_controls(false, false);
4175 		report_prefix_pop();
4176 
4177 		/* Positive case */
4178 		deliver_error_code_mask = has_error_code ?
4179 						INTR_INFO_DELIVER_CODE_MASK :
4180 						0;
4181 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4182 				INTR_TYPE_HARD_EXCEPTION | cnt;
4183 		report_prefix_pushf("VM-entry intr info=0x%x [+]",
4184 				    ent_intr_info);
4185 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4186 		test_vmx_controls(true, false);
4187 		report_prefix_pop();
4188 	}
4189 	report_prefix_pop();
4190 
4191 	/* Reserved bits in the field (30:12) are 0. */
4192 	report_prefix_push("reserved bits clear");
4193 	for (cnt = 12; cnt <= 30; cnt++) {
4194 		ent_intr_info = ent_intr_info_base |
4195 				INTR_INFO_DELIVER_CODE_MASK |
4196 				INTR_TYPE_HARD_EXCEPTION | GP_VECTOR |
4197 				(1U << cnt);
4198 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4199 				    ent_intr_info);
4200 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4201 		test_vmx_controls(false, false);
4202 		report_prefix_pop();
4203 	}
4204 	report_prefix_pop();
4205 
4206 	/*
4207 	 * If deliver-error-code is 1
4208 	 * bits 31:15 of the VM-entry exception error-code field are 0.
4209 	 */
4210 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4211 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4212 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4213 			    "VM-entry exception error code[31:15] clear",
4214 			    ent_intr_info);
4215 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4216 	for (cnt = 15; cnt <= 31; cnt++) {
4217 		ent_intr_err = 1U << cnt;
4218 		report_prefix_pushf("VM-entry intr error=0x%x [-]",
4219 				    ent_intr_err);
4220 		vmcs_write(ENT_INTR_ERROR, ent_intr_err);
4221 		test_vmx_controls(false, false);
4222 		report_prefix_pop();
4223 	}
4224 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4225 	report_prefix_pop();
4226 
4227 	/*
4228 	 * If the interruption type is software interrupt, software exception,
4229 	 * or privileged software exception, the VM-entry instruction-length
4230 	 * field is in the range 0–15.
4231 	 */
4232 
4233 	for (cnt = 0; cnt < 3; cnt++) {
4234 		switch (cnt) {
4235 		case 0:
4236 			ent_intr_info = ent_intr_info_base |
4237 					INTR_TYPE_SOFT_INTR;
4238 			break;
4239 		case 1:
4240 			ent_intr_info = ent_intr_info_base |
4241 					INTR_TYPE_SOFT_EXCEPTION;
4242 			break;
4243 		case 2:
4244 			ent_intr_info = ent_intr_info_base |
4245 					INTR_TYPE_PRIV_SW_EXCEPTION;
4246 			break;
4247 		}
4248 		report_prefix_pushf("%s, VM-entry intr info=0x%x",
4249 				    "VM-entry instruction-length check",
4250 				    ent_intr_info);
4251 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4252 
4253 		/* Instruction length set to -1 (0xFFFFFFFF) should fail */
4254 		ent_intr_len = -1;
4255 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4256 				    ent_intr_len);
4257 		vmcs_write(ENT_INST_LEN, ent_intr_len);
4258 		test_vmx_controls(false, false);
4259 		report_prefix_pop();
4260 
4261 		/* Instruction length set to 16 should fail */
4262 		ent_intr_len = 0x00000010;
4263 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4264 				    ent_intr_len);
4265 		vmcs_write(ENT_INST_LEN, 0x00000010);
4266 		test_vmx_controls(false, false);
4267 		report_prefix_pop();
4268 
4269 		report_prefix_pop();
4270 	}
4271 
4272 	/* Cleanup */
4273 	vmcs_write(ENT_INTR_INFO, ent_intr_info_save);
4274 	vmcs_write(ENT_INTR_ERROR, ent_intr_error_save);
4275 	vmcs_write(ENT_INST_LEN, ent_inst_len_save);
4276 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4277 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4278 	vmcs_write(GUEST_CR0, guest_cr0_save);
4279 	report_prefix_pop();
4280 }
4281 
4282 /*
4283  * Test interesting vTPR values for a given TPR threshold.
4284  */
4285 static void test_vtpr_values(unsigned threshold)
4286 {
4287 	try_tpr_threshold_and_vtpr(threshold, (threshold - 1) << 4);
4288 	try_tpr_threshold_and_vtpr(threshold, threshold << 4);
4289 	try_tpr_threshold_and_vtpr(threshold, (threshold + 1) << 4);
4290 }
4291 
4292 static void try_tpr_threshold(unsigned threshold)
4293 {
4294 	bool valid = true;
4295 
4296 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4297 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4298 
4299 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
4300 	    (secondary & CPU_VINTD)))
4301 		valid = !(threshold >> 4);
4302 
4303 	set_vtpr(-1);
4304 	vmcs_write(TPR_THRESHOLD, threshold);
4305 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
4306 	test_vmx_controls(valid, false);
4307 	report_prefix_pop();
4308 
4309 	if (valid)
4310 		test_vtpr_values(threshold);
4311 }
4312 
4313 /*
4314  * Test interesting TPR threshold values.
4315  */
4316 static void test_tpr_threshold_values(void)
4317 {
4318 	unsigned i;
4319 
4320 	for (i = 0; i < 0x10; i++)
4321 		try_tpr_threshold(i);
4322 	for (i = 4; i < 32; i++)
4323 		try_tpr_threshold(1u << i);
4324 	try_tpr_threshold(-1u);
4325 	try_tpr_threshold(0x7fffffff);
4326 }
4327 
4328 /*
4329  * This test covers the following two VM entry checks:
4330  *
4331  *      i) If the "use TPR shadow" VM-execution control is 1 and the
4332  *         "virtual-interrupt delivery" VM-execution control is 0, bits
4333  *         31:4 of the TPR threshold VM-execution control field must
4334 	   be 0.
4335  *         [Intel SDM]
4336  *
4337  *      ii) If the "use TPR shadow" VM-execution control is 1, the
4338  *          "virtual-interrupt delivery" VM-execution control is 0
4339  *          and the "virtualize APIC accesses" VM-execution control
4340  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
4341  *          control field must not be greater than the value of bits
4342  *          7:4 of VTPR.
4343  *          [Intel SDM]
4344  */
4345 static void test_tpr_threshold(void)
4346 {
4347 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4348 	void *virtual_apic_page;
4349 
4350 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
4351 		return;
4352 
4353 	virtual_apic_page = alloc_page();
4354 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
4355 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
4356 
4357 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
4358 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
4359 	test_tpr_threshold_values();
4360 	report_prefix_pop();
4361 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
4362 	report_prefix_pushf("Use TPR shadow enabled, secondary controls disabled");
4363 	test_tpr_threshold_values();
4364 	report_prefix_pop();
4365 
4366 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4367 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES)))) {
4368 		vmcs_write(CPU_EXEC_CTRL0, primary);
4369 		return;
4370 	}
4371 
4372 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4373 
4374 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
4375 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
4376 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4377 		test_tpr_threshold_values();
4378 		report_prefix_pop();
4379 
4380 		vmcs_write(CPU_EXEC_CTRL0,
4381 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4382 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4383 		test_tpr_threshold_values();
4384 		report_prefix_pop();
4385 	}
4386 
4387 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
4388 		vmcs_write(CPU_EXEC_CTRL0,
4389 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4390 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
4391 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4392 		test_tpr_threshold_values();
4393 		report_prefix_pop();
4394 
4395 		vmcs_write(CPU_EXEC_CTRL0,
4396 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4397 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4398 		test_tpr_threshold_values();
4399 		report_prefix_pop();
4400 	}
4401 
4402 	if ((ctrl_cpu_rev[1].clr &
4403 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
4404 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
4405 		vmcs_write(CPU_EXEC_CTRL0,
4406 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4407 		vmcs_write(CPU_EXEC_CTRL1,
4408 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
4409 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4410 		test_tpr_threshold_values();
4411 		report_prefix_pop();
4412 
4413 		vmcs_write(CPU_EXEC_CTRL0,
4414 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4415 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4416 		test_tpr_threshold_values();
4417 		report_prefix_pop();
4418 	}
4419 
4420 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4421 	vmcs_write(CPU_EXEC_CTRL0, primary);
4422 }
4423 
4424 /*
4425  * This test verifies the following two vmentry checks:
4426  *
4427  *  If the "NMI exiting" VM-execution control is 0, "Virtual NMIs"
4428  *  VM-execution control must be 0.
4429  *  [Intel SDM]
4430  *
4431  *  If the “virtual NMIs” VM-execution control is 0, the “NMI-window
4432  *  exiting” VM-execution control must be 0.
4433  *  [Intel SDM]
4434  */
4435 static void test_nmi_ctrls(void)
4436 {
4437 	u32 pin_ctrls, cpu_ctrls0, test_pin_ctrls, test_cpu_ctrls0;
4438 
4439 	if ((ctrl_pin_rev.clr & (PIN_NMI | PIN_VIRT_NMI)) !=
4440 	    (PIN_NMI | PIN_VIRT_NMI)) {
4441 		test_skip("NMI exiting and Virtual NMIs are not supported !");
4442 		return;
4443 	}
4444 
4445 	/* Save the controls so that we can restore them after our tests */
4446 	pin_ctrls = vmcs_read(PIN_CONTROLS);
4447 	cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
4448 
4449 	test_pin_ctrls = pin_ctrls & ~(PIN_NMI | PIN_VIRT_NMI);
4450 	test_cpu_ctrls0 = cpu_ctrls0 & ~CPU_NMI_WINDOW;
4451 
4452 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4453 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs disabled");
4454 	test_vmx_controls(true, false);
4455 	report_prefix_pop();
4456 
4457 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_VIRT_NMI);
4458 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs enabled");
4459 	test_vmx_controls(false, false);
4460 	report_prefix_pop();
4461 
4462 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4463 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs enabled");
4464 	test_vmx_controls(true, false);
4465 	report_prefix_pop();
4466 
4467 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_NMI);
4468 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs disabled");
4469 	test_vmx_controls(true, false);
4470 	report_prefix_pop();
4471 
4472 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
4473 		report_info("NMI-window exiting is not supported, skipping...");
4474 		goto done;
4475 	}
4476 
4477 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4478 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4479 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting enabled");
4480 	test_vmx_controls(false, false);
4481 	report_prefix_pop();
4482 
4483 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4484 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4485 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting disabled");
4486 	test_vmx_controls(true, false);
4487 	report_prefix_pop();
4488 
4489 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4490 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4491 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting enabled");
4492 	test_vmx_controls(true, false);
4493 	report_prefix_pop();
4494 
4495 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4496 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4497 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting disabled");
4498 	test_vmx_controls(true, false);
4499 	report_prefix_pop();
4500 
4501 	/* Restore the controls to their original values */
4502 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
4503 done:
4504 	vmcs_write(PIN_CONTROLS, pin_ctrls);
4505 }
4506 
4507 static void test_eptp_ad_bit(u64 eptp, bool ctrl)
4508 {
4509 	vmcs_write(EPTP, eptp);
4510 	report_prefix_pushf("Enable-EPT enabled; EPT accessed and dirty flag %s",
4511 	    (eptp & EPTP_AD_FLAG) ? "1": "0");
4512 	test_vmx_controls(ctrl, false);
4513 	report_prefix_pop();
4514 
4515 }
4516 
4517 /*
4518  * 1. If the "enable EPT" VM-execution control is 1, the "EPTP VM-execution"
4519  *    control field must satisfy the following checks:
4520  *
4521  *     - The EPT memory type (bits 2:0) must be a value supported by the
4522  *	 processor as indicated in the IA32_VMX_EPT_VPID_CAP MSR.
4523  *     - Bits 5:3 (1 less than the EPT page-walk length) must be 3,
4524  *	 indicating an EPT page-walk length of 4.
4525  *     - Bit 6 (enable bit for accessed and dirty flags for EPT) must be
4526  *	 0 if bit 21 of the IA32_VMX_EPT_VPID_CAP MSR is read as 0,
4527  *	 indicating that the processor does not support accessed and dirty
4528  *	 dirty flags for EPT.
4529  *     - Reserved bits 11:7 and 63:N (where N is the processor's
4530  *	 physical-address width) must all be 0.
4531  *
4532  * 2. If the "unrestricted guest" VM-execution control is 1, the
4533  *    "enable EPT" VM-execution control must also be 1.
4534  */
4535 static void test_ept_eptp(void)
4536 {
4537 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4538 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4539 	u64 eptp_saved = vmcs_read(EPTP);
4540 	u32 primary = primary_saved;
4541 	u32 secondary = secondary_saved;
4542 	u64 msr, eptp = eptp_saved;
4543 	bool un_cache = false;
4544 	bool wr_bk = false;
4545 	bool ctrl;
4546 	u32 i, maxphysaddr;
4547 	u64 j, resv_bits_mask = 0;
4548 
4549 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4550 	    (ctrl_cpu_rev[1].clr & CPU_EPT))) {
4551 		test_skip("\"CPU secondary\" and/or \"enable EPT\" execution controls are not supported !");
4552 		return;
4553 	}
4554 
4555 	/*
4556 	 * Memory type (bits 2:0)
4557 	 */
4558 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
4559 	if (msr & EPT_CAP_UC)
4560 		un_cache = true;
4561 	if (msr & EPT_CAP_WB)
4562 		wr_bk = true;
4563 
4564 	primary |= CPU_SECONDARY;
4565 	vmcs_write(CPU_EXEC_CTRL0, primary);
4566 	secondary |= CPU_EPT;
4567 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4568 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4569 	    (3ul << EPTP_PG_WALK_LEN_SHIFT);
4570 	vmcs_write(EPTP, eptp);
4571 
4572 	for (i = 0; i < 8; i++) {
4573 		if (i == 0) {
4574 			if (un_cache) {
4575 				report_info("EPT paging structure memory-type is Un-cacheable\n");
4576 				ctrl = true;
4577 			} else {
4578 				ctrl = false;
4579 			}
4580 		} else if (i == 6) {
4581 			if (wr_bk) {
4582 				report_info("EPT paging structure memory-type is Write-back\n");
4583 				ctrl = true;
4584 			} else {
4585 				ctrl = false;
4586 			}
4587 		} else {
4588 			ctrl = false;
4589 		}
4590 
4591 		eptp = (eptp & ~EPT_MEM_TYPE_MASK) | i;
4592 		vmcs_write(EPTP, eptp);
4593 		report_prefix_pushf("Enable-EPT enabled; EPT memory type %lu",
4594 		    eptp & EPT_MEM_TYPE_MASK);
4595 		test_vmx_controls(ctrl, false);
4596 		report_prefix_pop();
4597 	}
4598 
4599 	eptp = (eptp & ~EPT_MEM_TYPE_MASK) | 6ul;
4600 
4601 	/*
4602 	 * Page walk length (bits 5:3)
4603 	 */
4604 	for (i = 0; i < 8; i++) {
4605 		eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4606 		    (i << EPTP_PG_WALK_LEN_SHIFT);
4607 		if (i == 3)
4608 			ctrl = true;
4609 		else
4610 			ctrl = false;
4611 
4612 		vmcs_write(EPTP, eptp);
4613 		report_prefix_pushf("Enable-EPT enabled; EPT page walk length %lu",
4614 		    eptp & EPTP_PG_WALK_LEN_MASK);
4615 		test_vmx_controls(ctrl, false);
4616 		report_prefix_pop();
4617 	}
4618 
4619 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4620 	    3ul << EPTP_PG_WALK_LEN_SHIFT;
4621 
4622 	/*
4623 	 * Accessed and dirty flag (bit 6)
4624 	 */
4625 	if (msr & EPT_CAP_AD_FLAG) {
4626 		report_info("Processor supports accessed and dirty flag");
4627 		eptp &= ~EPTP_AD_FLAG;
4628 		test_eptp_ad_bit(eptp, true);
4629 
4630 		eptp |= EPTP_AD_FLAG;
4631 		test_eptp_ad_bit(eptp, true);
4632 	} else {
4633 		report_info("Processor does not supports accessed and dirty flag");
4634 		eptp &= ~EPTP_AD_FLAG;
4635 		test_eptp_ad_bit(eptp, true);
4636 
4637 		eptp |= EPTP_AD_FLAG;
4638 		test_eptp_ad_bit(eptp, false);
4639 	}
4640 
4641 	/*
4642 	 * Reserved bits [11:7] and [63:N]
4643 	 */
4644 	for (i = 0; i < 32; i++) {
4645 		if (i  == 0)
4646 			ctrl = true;
4647 		else
4648 			ctrl = false;
4649 
4650 		eptp = (eptp &
4651 		    ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT)) |
4652 		    (i << EPTP_RESERV_BITS_SHIFT);
4653 		vmcs_write(EPTP, eptp);
4654 		report_prefix_pushf("Enable-EPT enabled; reserved bits [11:7] %lu",
4655 		    (eptp >> EPTP_RESERV_BITS_SHIFT) &
4656 		    EPTP_RESERV_BITS_MASK);
4657 		test_vmx_controls(ctrl, false);
4658 		report_prefix_pop();
4659 	}
4660 
4661 	eptp = (eptp & ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT));
4662 
4663 	maxphysaddr = cpuid_maxphyaddr();
4664 	for (i = 0; i < (63 - maxphysaddr + 1); i++) {
4665 		resv_bits_mask |= 1ul << i;
4666 	}
4667 
4668 	for (j = 0; j < (63 - maxphysaddr + 1); j++) {
4669 		if (j  == 0)
4670 			ctrl = true;
4671 		else
4672 			ctrl = false;
4673 
4674 		eptp = (eptp & ~(resv_bits_mask << maxphysaddr)) |
4675 		    (j << maxphysaddr);
4676 		vmcs_write(EPTP, eptp);
4677 		report_prefix_pushf("Enable-EPT enabled; reserved bits [63:N] %lu",
4678 		    (eptp >> maxphysaddr) & resv_bits_mask);
4679 		test_vmx_controls(ctrl, false);
4680 		report_prefix_pop();
4681 	}
4682 
4683 	secondary &= ~(CPU_EPT | CPU_URG);
4684 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4685 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest disabled");
4686 	test_vmx_controls(true, false);
4687 	report_prefix_pop();
4688 
4689 	secondary |= CPU_URG;
4690 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4691 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest enabled");
4692 	test_vmx_controls(false, false);
4693 	report_prefix_pop();
4694 
4695 	secondary |= CPU_EPT;
4696 	enable_ept();
4697 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest enabled");
4698 	test_vmx_controls(true, false);
4699 	report_prefix_pop();
4700 
4701 	secondary &= ~CPU_URG;
4702 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4703 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest disabled");
4704 	test_vmx_controls(true, false);
4705 	report_prefix_pop();
4706 
4707 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4708 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4709 	vmcs_write(EPTP, eptp_saved);
4710 }
4711 
4712 /*
4713  * If the 'enable PML' VM-execution control is 1, the 'enable EPT'
4714  * VM-execution control must also be 1. In addition, the PML address
4715  * must satisfy the following checks:
4716  *
4717  *    * Bits 11:0 of the address must be 0.
4718  *    * The address should not set any bits beyond the processor's
4719  *	physical-address width.
4720  *
4721  *  [Intel SDM]
4722  */
4723 static void test_pml(void)
4724 {
4725 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4726 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4727 	u32 primary = primary_saved;
4728 	u32 secondary = secondary_saved;
4729 
4730 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4731 	    (ctrl_cpu_rev[1].clr & CPU_EPT) && (ctrl_cpu_rev[1].clr & CPU_PML))) {
4732 		test_skip("\"Secondary execution\" control or \"enable EPT\" control or \"enable PML\" control is not supported !");
4733 		return;
4734 	}
4735 
4736 	primary |= CPU_SECONDARY;
4737 	vmcs_write(CPU_EXEC_CTRL0, primary);
4738 	secondary &= ~(CPU_PML | CPU_EPT);
4739 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4740 	report_prefix_pushf("enable-PML disabled, enable-EPT disabled");
4741 	test_vmx_controls(true, false);
4742 	report_prefix_pop();
4743 
4744 	secondary |= CPU_PML;
4745 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4746 	report_prefix_pushf("enable-PML enabled, enable-EPT disabled");
4747 	test_vmx_controls(false, false);
4748 	report_prefix_pop();
4749 
4750 	secondary |= CPU_EPT;
4751 	enable_ept();
4752 	report_prefix_pushf("enable-PML enabled, enable-EPT enabled");
4753 	test_vmx_controls(true, false);
4754 	report_prefix_pop();
4755 
4756 	secondary &= ~CPU_PML;
4757 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4758 	report_prefix_pushf("enable-PML disabled, enable EPT enabled");
4759 	test_vmx_controls(true, false);
4760 	report_prefix_pop();
4761 
4762 	test_vmcs_addr_reference(CPU_PML, PMLADDR, "PML address", "PML",
4763 				 PAGE_SIZE, false, false);
4764 
4765 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4766 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4767 }
4768 
4769  /*
4770  * If the "activate VMX-preemption timer" VM-execution control is 0, the
4771  * the "save VMX-preemption timer value" VM-exit control must also be 0.
4772  *
4773  *  [Intel SDM]
4774  */
4775 static void test_vmx_preemption_timer(void)
4776 {
4777 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4778 	u32 saved_exit = vmcs_read(EXI_CONTROLS);
4779 	u32 pin = saved_pin;
4780 	u32 exit = saved_exit;
4781 
4782 	if (!((ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) ||
4783 	    (ctrl_pin_rev.clr & PIN_PREEMPT))) {
4784 		printf("\"Save-VMX-preemption-timer\" control and/or \"Enable-VMX-preemption-timer\" control is not supported\n");
4785 		return;
4786 	}
4787 
4788 	pin |= PIN_PREEMPT;
4789 	vmcs_write(PIN_CONTROLS, pin);
4790 	exit &= ~EXI_SAVE_PREEMPT;
4791 	vmcs_write(EXI_CONTROLS, exit);
4792 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer disabled");
4793 	test_vmx_controls(true, false);
4794 	report_prefix_pop();
4795 
4796 	exit |= EXI_SAVE_PREEMPT;
4797 	vmcs_write(EXI_CONTROLS, exit);
4798 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer enabled");
4799 	test_vmx_controls(true, false);
4800 	report_prefix_pop();
4801 
4802 	pin &= ~PIN_PREEMPT;
4803 	vmcs_write(PIN_CONTROLS, pin);
4804 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer enabled");
4805 	test_vmx_controls(false, false);
4806 	report_prefix_pop();
4807 
4808 	exit &= ~EXI_SAVE_PREEMPT;
4809 	vmcs_write(EXI_CONTROLS, exit);
4810 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer disabled");
4811 	test_vmx_controls(true, false);
4812 	report_prefix_pop();
4813 
4814 	vmcs_write(PIN_CONTROLS, saved_pin);
4815 	vmcs_write(EXI_CONTROLS, saved_exit);
4816 }
4817 
4818 /*
4819  * Tests for VM-execution control fields
4820  */
4821 static void test_vm_execution_ctls(void)
4822 {
4823 	test_pin_based_ctls();
4824 	test_primary_processor_based_ctls();
4825 	test_secondary_processor_based_ctls();
4826 	test_cr3_targets();
4827 	test_io_bitmaps();
4828 	test_msr_bitmap();
4829 	test_apic_ctls();
4830 	test_tpr_threshold();
4831 	test_nmi_ctrls();
4832 	test_pml();
4833 	test_vpid();
4834 	test_ept_eptp();
4835 	test_vmx_preemption_timer();
4836 }
4837 
4838  /*
4839   * The following checks are performed for the VM-entry MSR-load address if
4840   * the VM-entry MSR-load count field is non-zero:
4841   *
4842   *    - The lower 4 bits of the VM-entry MSR-load address must be 0.
4843   *      The address should not set any bits beyond the processor’s
4844   *      physical-address width.
4845   *
4846   *    - The address of the last byte in the VM-entry MSR-load area
4847   *      should not set any bits beyond the processor’s physical-address
4848   *      width. The address of this last byte is VM-entry MSR-load address
4849   *      + (MSR count * 16) - 1. (The arithmetic used for the computation
4850   *      uses more bits than the processor’s physical-address width.)
4851   *
4852   *
4853   *  [Intel SDM]
4854   */
4855 static void test_entry_msr_load(void)
4856 {
4857 	entry_msr_load = alloc_page();
4858 	u64 tmp;
4859 	u32 entry_msr_ld_cnt = 1;
4860 	int i;
4861 	u32 addr_len = 64;
4862 
4863 	vmcs_write(ENT_MSR_LD_CNT, entry_msr_ld_cnt);
4864 
4865 	/* Check first 4 bits of VM-entry MSR-load address */
4866 	for (i = 0; i < 4; i++) {
4867 		tmp = (u64)entry_msr_load | 1ull << i;
4868 		vmcs_write(ENTER_MSR_LD_ADDR, tmp);
4869 		report_prefix_pushf("VM-entry MSR-load addr [4:0] %lx",
4870 				    tmp & 0xf);
4871 		test_vmx_controls(false, false);
4872 		report_prefix_pop();
4873 	}
4874 
4875 	if (basic.val & (1ul << 48))
4876 		addr_len = 32;
4877 
4878 	test_vmcs_addr_values("VM-entry-MSR-load address",
4879 				ENTER_MSR_LD_ADDR, 16, false, false,
4880 				4, addr_len - 1);
4881 
4882 	/*
4883 	 * Check last byte of VM-entry MSR-load address
4884 	 */
4885 	entry_msr_load = (struct vmx_msr_entry *)((u64)entry_msr_load & ~0xf);
4886 
4887 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
4888 							i < 64; i++) {
4889 		tmp = ((u64)entry_msr_load + entry_msr_ld_cnt * 16 - 1) |
4890 			1ul << i;
4891 		vmcs_write(ENTER_MSR_LD_ADDR,
4892 			   tmp - (entry_msr_ld_cnt * 16 - 1));
4893 		test_vmx_controls(false, false);
4894 	}
4895 
4896 	vmcs_write(ENT_MSR_LD_CNT, 2);
4897 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
4898 	test_vmx_controls(false, false);
4899 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
4900 	test_vmx_controls(true, false);
4901 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
4902 	test_vmx_controls(true, false);
4903 }
4904 
4905 /*
4906  * Tests for VM-entry control fields
4907  */
4908 static void test_vm_entry_ctls(void)
4909 {
4910 	test_invalid_event_injection();
4911 	test_entry_msr_load();
4912 }
4913 
4914 /*
4915  * The following checks are performed for the VM-exit MSR-store address if
4916  * the VM-exit MSR-store count field is non-zero:
4917  *
4918  *    - The lower 4 bits of the VM-exit MSR-store address must be 0.
4919  *      The address should not set any bits beyond the processor’s
4920  *      physical-address width.
4921  *
4922  *    - The address of the last byte in the VM-exit MSR-store area
4923  *      should not set any bits beyond the processor’s physical-address
4924  *      width. The address of this last byte is VM-exit MSR-store address
4925  *      + (MSR count * 16) - 1. (The arithmetic used for the computation
4926  *      uses more bits than the processor’s physical-address width.)
4927  *
4928  * If IA32_VMX_BASIC[48] is read as 1, neither address should set any bits
4929  * in the range 63:32.
4930  *
4931  *  [Intel SDM]
4932  */
4933 static void test_exit_msr_store(void)
4934 {
4935 	exit_msr_store = alloc_page();
4936 	u64 tmp;
4937 	u32 exit_msr_st_cnt = 1;
4938 	int i;
4939 	u32 addr_len = 64;
4940 
4941 	vmcs_write(EXI_MSR_ST_CNT, exit_msr_st_cnt);
4942 
4943 	/* Check first 4 bits of VM-exit MSR-store address */
4944 	for (i = 0; i < 4; i++) {
4945 		tmp = (u64)exit_msr_store | 1ull << i;
4946 		vmcs_write(EXIT_MSR_ST_ADDR, tmp);
4947 		report_prefix_pushf("VM-exit MSR-store addr [4:0] %lx",
4948 				    tmp & 0xf);
4949 		test_vmx_controls(false, false);
4950 		report_prefix_pop();
4951 	}
4952 
4953 	if (basic.val & (1ul << 48))
4954 		addr_len = 32;
4955 
4956 	test_vmcs_addr_values("VM-exit-MSR-store address",
4957 				EXIT_MSR_ST_ADDR, 16, false, false,
4958 				4, addr_len - 1);
4959 
4960 	/*
4961 	 * Check last byte of VM-exit MSR-store address
4962 	 */
4963 	exit_msr_store = (struct vmx_msr_entry *)((u64)exit_msr_store & ~0xf);
4964 
4965 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
4966 							i < 64; i++) {
4967 		tmp = ((u64)exit_msr_store + exit_msr_st_cnt * 16 - 1) |
4968 			1ul << i;
4969 		vmcs_write(EXIT_MSR_ST_ADDR,
4970 			   tmp - (exit_msr_st_cnt * 16 - 1));
4971                 test_vmx_controls(false, false);
4972 	}
4973 
4974 	vmcs_write(EXI_MSR_ST_CNT, 2);
4975 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
4976 	test_vmx_controls(false, false);
4977 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
4978 	test_vmx_controls(true, false);
4979 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
4980 	test_vmx_controls(true, false);
4981 }
4982 
4983 /*
4984  * Tests for VM-exit controls
4985  */
4986 static void test_vm_exit_ctls(void)
4987 {
4988 	test_exit_msr_store();
4989 }
4990 
4991 /*
4992  * Check that the virtual CPU checks all of the VMX controls as
4993  * documented in the Intel SDM.
4994  */
4995 static void vmx_controls_test(void)
4996 {
4997 	/*
4998 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
4999 	 * fail due to invalid guest state, should we make it that
5000 	 * far.
5001 	 */
5002 	vmcs_write(GUEST_RFLAGS, 0);
5003 
5004 	test_vm_execution_ctls();
5005 	test_vm_entry_ctls();
5006 	test_vm_exit_ctls();
5007 }
5008 
5009 static bool valid_vmcs_for_vmentry(void)
5010 {
5011 	struct vmcs *current_vmcs = NULL;
5012 
5013 	if (vmcs_save(&current_vmcs))
5014 		return false;
5015 
5016 	return current_vmcs && !current_vmcs->hdr.shadow_vmcs;
5017 }
5018 
5019 static void try_vmentry_in_movss_shadow(void)
5020 {
5021 	u32 vm_inst_err;
5022 	u32 flags;
5023 	bool early_failure = false;
5024 	u32 expected_flags = X86_EFLAGS_FIXED;
5025 	bool valid_vmcs = valid_vmcs_for_vmentry();
5026 
5027 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
5028 
5029 	/*
5030 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
5031 	 * unsupported VMCS component").
5032 	 */
5033 	vmcs_write(~0u, 0);
5034 
5035 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
5036 			      "vmwrite %%rsp, %%rdx;"
5037 			      "mov 0f, %%rax;"
5038 			      "mov %[host_rip], %%edx;"
5039 			      "vmwrite %%rax, %%rdx;"
5040 			      "mov $-1, %%ah;"
5041 			      "sahf;"
5042 			      "mov %%ss, %%ax;"
5043 			      "mov %%ax, %%ss;"
5044 			      "vmlaunch;"
5045 			      "mov $1, %[early_failure];"
5046 			      "0: lahf;"
5047 			      "movzbl %%ah, %[flags]"
5048 			      : [early_failure] "+r" (early_failure),
5049 				[flags] "=&a" (flags)
5050 			      : [host_rsp] "i" (HOST_RSP),
5051 				[host_rip] "i" (HOST_RIP)
5052 			      : "rdx", "cc", "memory");
5053 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
5054 
5055 	report("Early VM-entry failure", early_failure);
5056 	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
5057 	       expected_flags, flags);
5058 	if (valid_vmcs)
5059 		report("VM-instruction error is %d (actual %d)",
5060 		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
5061 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
5062 }
5063 
5064 static void vmentry_movss_shadow_test(void)
5065 {
5066 	struct vmcs *orig_vmcs;
5067 
5068 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
5069 
5070 	/*
5071 	 * Set the launched flag on the current VMCS to verify the correct
5072 	 * error priority, below.
5073 	 */
5074 	test_set_guest(v2_null_test_guest);
5075 	enter_guest();
5076 
5077 	/*
5078 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
5079 	 * fail due to invalid guest state (if we make it that far).
5080 	 */
5081 	vmcs_write(GUEST_RFLAGS, 0);
5082 
5083 	/*
5084 	 * "VM entry with events blocked by MOV SS" takes precedence over
5085 	 * "VMLAUNCH with non-clear VMCS."
5086 	 */
5087 	report_prefix_push("valid current-VMCS");
5088 	try_vmentry_in_movss_shadow();
5089 	report_prefix_pop();
5090 
5091 	/*
5092 	 * VMfailInvalid takes precedence over "VM entry with events
5093 	 * blocked by MOV SS."
5094 	 */
5095 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
5096 	report_prefix_push("no current-VMCS");
5097 	try_vmentry_in_movss_shadow();
5098 	report_prefix_pop();
5099 
5100 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
5101 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5102 }
5103 
5104 #define X86_FEATURE_PCID       (1 << 17)
5105 #define X86_FEATURE_MCE        (1 << 7)
5106 
5107 static int write_cr4_checking(unsigned long val)
5108 {
5109 	asm volatile(ASM_TRY("1f")
5110 		     "mov %0, %%cr4\n\t"
5111 		     "1:": : "r" (val));
5112 	return exception_vector();
5113 }
5114 
5115 static void vmx_cr_load_test(void)
5116 {
5117 	struct cpuid _cpuid = cpuid(1);
5118 	unsigned long cr4 = read_cr4(), cr3 = read_cr3();
5119 
5120 	if (!(_cpuid.c & X86_FEATURE_PCID)) {
5121 		report_skip("PCID not detected");
5122 		return;
5123 	}
5124 	if (!(_cpuid.d & X86_FEATURE_MCE)) {
5125 		report_skip("MCE not detected");
5126 		return;
5127 	}
5128 
5129 	TEST_ASSERT(!(cr4 & (X86_CR4_PCIDE | X86_CR4_MCE)));
5130 	TEST_ASSERT(!(cr3 & X86_CR3_PCID_MASK));
5131 
5132 	/* Enable PCID for L1. */
5133 	cr4 |= X86_CR4_PCIDE;
5134 	cr3 |= 0x1;
5135 	TEST_ASSERT(!write_cr4_checking(cr4));
5136 	write_cr3(cr3);
5137 
5138 	test_set_guest(v2_null_test_guest);
5139 	vmcs_write(HOST_CR4, cr4);
5140 	vmcs_write(HOST_CR3, cr3);
5141 	enter_guest();
5142 
5143 	/*
5144 	 * No exception is expected.
5145 	 *
5146 	 * NB. KVM loads the last guest write to CR4 into CR4 read
5147 	 *     shadow. In order to trigger an exit to KVM, we can set a
5148 	 *     bit that was zero in the above CR4 write and is owned by
5149 	 *     KVM. We choose to set CR4.MCE, which shall have no side
5150 	 *     effect because normally no guest MCE (e.g., as the result
5151 	 *     of bad memory) would happen during this test.
5152 	 */
5153 	TEST_ASSERT(!write_cr4_checking(cr4 | X86_CR4_MCE));
5154 
5155 	/* Cleanup L1 state: disable PCID. */
5156 	write_cr3(cr3 & ~X86_CR3_PCID_MASK);
5157 	TEST_ASSERT(!write_cr4_checking(cr4 & ~X86_CR4_PCIDE));
5158 }
5159 
5160 static void vmx_nm_test_guest(void)
5161 {
5162 	write_cr0(read_cr0() | X86_CR0_TS);
5163 	asm volatile("fnop");
5164 }
5165 
5166 static void check_nm_exit(const char *test)
5167 {
5168 	u32 reason = vmcs_read(EXI_REASON);
5169 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
5170 	const u32 expected = INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5171 		NM_VECTOR;
5172 
5173 	report("%s", reason == VMX_EXC_NMI && intr_info == expected, test);
5174 }
5175 
5176 /*
5177  * This test checks that:
5178  *
5179  * (a) If L2 launches with CR0.TS clear, but later sets CR0.TS, then
5180  *     a subsequent #NM VM-exit is reflected to L1.
5181  *
5182  * (b) If L2 launches with CR0.TS clear and CR0.EM set, then a
5183  *     subsequent #NM VM-exit is reflected to L1.
5184  */
5185 static void vmx_nm_test(void)
5186 {
5187 	unsigned long cr0 = read_cr0();
5188 
5189 	test_set_guest(vmx_nm_test_guest);
5190 
5191 	/*
5192 	 * L1 wants to intercept #NM exceptions encountered in L2.
5193 	 */
5194 	vmcs_write(EXC_BITMAP, 1 << NM_VECTOR);
5195 
5196 	/*
5197 	 * Launch L2 with CR0.TS clear, but don't claim host ownership of
5198 	 * any CR0 bits. L2 will set CR0.TS and then try to execute fnop,
5199 	 * which will raise #NM. L0 should reflect the #NM VM-exit to L1.
5200 	 */
5201 	vmcs_write(CR0_MASK, 0);
5202 	vmcs_write(GUEST_CR0, cr0 & ~X86_CR0_TS);
5203 	enter_guest();
5204 	check_nm_exit("fnop with CR0.TS set in L2 triggers #NM VM-exit to L1");
5205 
5206 	/*
5207 	 * Re-enter L2 at the fnop instruction, with CR0.TS clear but
5208 	 * CR0.EM set. The fnop will still raise #NM, and L0 should
5209 	 * reflect the #NM VM-exit to L1.
5210 	 */
5211 	vmcs_write(GUEST_CR0, (cr0 & ~X86_CR0_TS) | X86_CR0_EM);
5212 	enter_guest();
5213 	check_nm_exit("fnop with CR0.EM set in L2 triggers #NM VM-exit to L1");
5214 
5215 	/*
5216 	 * Re-enter L2 at the fnop instruction, with both CR0.TS and
5217 	 * CR0.EM clear. There will be no #NM, and the L2 guest should
5218 	 * exit normally.
5219 	 */
5220 	vmcs_write(GUEST_CR0, cr0 & ~(X86_CR0_TS | X86_CR0_EM));
5221 	enter_guest();
5222 }
5223 
5224 bool vmx_pending_event_ipi_fired;
5225 static void vmx_pending_event_ipi_isr(isr_regs_t *regs)
5226 {
5227 	vmx_pending_event_ipi_fired = true;
5228 	eoi();
5229 }
5230 
5231 bool vmx_pending_event_guest_run;
5232 static void vmx_pending_event_guest(void)
5233 {
5234 	vmcall();
5235 	vmx_pending_event_guest_run = true;
5236 }
5237 
5238 static void vmx_pending_event_test_core(bool guest_hlt)
5239 {
5240 	int ipi_vector = 0xf1;
5241 
5242 	vmx_pending_event_ipi_fired = false;
5243 	handle_irq(ipi_vector, vmx_pending_event_ipi_isr);
5244 
5245 	vmx_pending_event_guest_run = false;
5246 	test_set_guest(vmx_pending_event_guest);
5247 
5248 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
5249 
5250 	enter_guest();
5251 	skip_exit_vmcall();
5252 
5253 	if (guest_hlt)
5254 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5255 
5256 	irq_disable();
5257 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
5258 				   APIC_DM_FIXED | ipi_vector,
5259 				   0);
5260 
5261 	enter_guest();
5262 
5263 	assert_exit_reason(VMX_EXTINT);
5264 	report("Guest did not run before host received IPI",
5265 		   !vmx_pending_event_guest_run);
5266 
5267 	irq_enable();
5268 	asm volatile ("nop");
5269 	irq_disable();
5270 	report("Got pending interrupt after IRQ enabled",
5271 		   vmx_pending_event_ipi_fired);
5272 
5273 	if (guest_hlt)
5274 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
5275 
5276 	enter_guest();
5277 	report("Guest finished running when no interrupt",
5278 		   vmx_pending_event_guest_run);
5279 }
5280 
5281 static void vmx_pending_event_test(void)
5282 {
5283 	vmx_pending_event_test_core(false);
5284 }
5285 
5286 static void vmx_pending_event_hlt_test(void)
5287 {
5288 	vmx_pending_event_test_core(true);
5289 }
5290 
5291 static int vmx_window_test_ud_count;
5292 
5293 static void vmx_window_test_ud_handler(struct ex_regs *regs)
5294 {
5295 	vmx_window_test_ud_count++;
5296 }
5297 
5298 static void vmx_nmi_window_test_guest(void)
5299 {
5300 	handle_exception(UD_VECTOR, vmx_window_test_ud_handler);
5301 
5302 	asm volatile("vmcall\n\t"
5303 		     "nop\n\t");
5304 
5305 	handle_exception(UD_VECTOR, NULL);
5306 }
5307 
5308 static void verify_nmi_window_exit(u64 rip)
5309 {
5310 	u32 exit_reason = vmcs_read(EXI_REASON);
5311 
5312 	report("Exit reason (%d) is 'NMI window'",
5313 	       exit_reason == VMX_NMI_WINDOW, exit_reason);
5314 	report("RIP (%#lx) is %#lx", vmcs_read(GUEST_RIP) == rip,
5315 	       vmcs_read(GUEST_RIP), rip);
5316 	report("Activity state (%ld) is 'ACTIVE'",
5317 	       vmcs_read(GUEST_ACTV_STATE) == ACTV_ACTIVE,
5318 	       vmcs_read(GUEST_ACTV_STATE));
5319 }
5320 
5321 static void vmx_nmi_window_test(void)
5322 {
5323 	u64 nop_addr;
5324 	void *ud_fault_addr = get_idt_addr(&boot_idt[UD_VECTOR]);
5325 
5326 	if (!(ctrl_pin_rev.clr & PIN_VIRT_NMI)) {
5327 		report_skip("CPU does not support the \"Virtual NMIs\" VM-execution control.");
5328 		return;
5329 	}
5330 
5331 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
5332 		report_skip("CPU does not support the \"NMI-window exiting\" VM-execution control.");
5333 		return;
5334 	}
5335 
5336 	vmx_window_test_ud_count = 0;
5337 
5338 	report_prefix_push("NMI-window");
5339 	test_set_guest(vmx_nmi_window_test_guest);
5340 	vmcs_set_bits(PIN_CONTROLS, PIN_VIRT_NMI);
5341 	enter_guest();
5342 	skip_exit_vmcall();
5343 	nop_addr = vmcs_read(GUEST_RIP);
5344 
5345 	/*
5346 	 * Ask for "NMI-window exiting," and expect an immediate VM-exit.
5347 	 * RIP will not advance.
5348 	 */
5349 	report_prefix_push("active, no blocking");
5350 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
5351 	enter_guest();
5352 	verify_nmi_window_exit(nop_addr);
5353 	report_prefix_pop();
5354 
5355 	/*
5356 	 * Ask for "NMI-window exiting" in a MOV-SS shadow, and expect
5357 	 * a VM-exit on the next instruction after the nop. (The nop
5358 	 * is one byte.)
5359 	 */
5360 	report_prefix_push("active, blocking by MOV-SS");
5361 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5362 	enter_guest();
5363 	verify_nmi_window_exit(nop_addr + 1);
5364 	report_prefix_pop();
5365 
5366 	/*
5367 	 * Ask for "NMI-window exiting" (with event injection), and
5368 	 * expect a VM-exit after the event is injected. (RIP should
5369 	 * be at the address specified in the IDT entry for #UD.)
5370 	 */
5371 	report_prefix_push("active, no blocking, injecting #UD");
5372 	vmcs_write(ENT_INTR_INFO,
5373 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | UD_VECTOR);
5374 	enter_guest();
5375 	verify_nmi_window_exit((u64)ud_fault_addr);
5376 	report_prefix_pop();
5377 
5378 	/*
5379 	 * Ask for "NMI-window exiting" with NMI blocking, and expect
5380 	 * a VM-exit after the next IRET (i.e. after the #UD handler
5381 	 * returns). So, RIP should be back at one byte past the nop.
5382 	 */
5383 	report_prefix_push("active, blocking by NMI");
5384 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_NMI);
5385 	enter_guest();
5386 	verify_nmi_window_exit(nop_addr + 1);
5387 	report("#UD handler executed once (actual %d times)",
5388 	       vmx_window_test_ud_count == 1,
5389 	       vmx_window_test_ud_count);
5390 	report_prefix_pop();
5391 
5392 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
5393 		report_skip("CPU does not support activity state HLT.");
5394 	} else {
5395 		/*
5396 		 * Ask for "NMI-window exiting" when entering activity
5397 		 * state HLT, and expect an immediate VM-exit. RIP is
5398 		 * still one byte past the nop.
5399 		 */
5400 		report_prefix_push("halted, no blocking");
5401 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5402 		enter_guest();
5403 		verify_nmi_window_exit(nop_addr + 1);
5404 		report_prefix_pop();
5405 
5406 		/*
5407 		 * Ask for "NMI-window exiting" when entering activity
5408 		 * state HLT (with event injection), and expect a
5409 		 * VM-exit after the event is injected. (RIP should be
5410 		 * at the address specified in the IDT entry for #UD.)
5411 		 */
5412 		report_prefix_push("halted, no blocking, injecting #UD");
5413 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5414 		vmcs_write(ENT_INTR_INFO,
5415 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5416 			   UD_VECTOR);
5417 		enter_guest();
5418 		verify_nmi_window_exit((u64)ud_fault_addr);
5419 		report_prefix_pop();
5420 	}
5421 
5422 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
5423 	enter_guest();
5424 	report_prefix_pop();
5425 }
5426 
5427 static void vmx_intr_window_test_guest(void)
5428 {
5429 	handle_exception(UD_VECTOR, vmx_window_test_ud_handler);
5430 
5431 	/*
5432 	 * The two consecutive STIs are to ensure that only the first
5433 	 * one has a shadow. Note that NOP and STI are one byte
5434 	 * instructions.
5435 	 */
5436 	asm volatile("vmcall\n\t"
5437 		     "nop\n\t"
5438 		     "sti\n\t"
5439 		     "sti\n\t");
5440 
5441 	handle_exception(UD_VECTOR, NULL);
5442 }
5443 
5444 static void verify_intr_window_exit(u64 rip)
5445 {
5446 	u32 exit_reason = vmcs_read(EXI_REASON);
5447 
5448 	report("Exit reason (%d) is 'interrupt window'",
5449 	       exit_reason == VMX_INTR_WINDOW, exit_reason);
5450 	report("RIP (%#lx) is %#lx", vmcs_read(GUEST_RIP) == rip,
5451 	       vmcs_read(GUEST_RIP), rip);
5452 	report("Activity state (%ld) is 'ACTIVE'",
5453 	       vmcs_read(GUEST_ACTV_STATE) == ACTV_ACTIVE,
5454 	       vmcs_read(GUEST_ACTV_STATE));
5455 }
5456 
5457 static void vmx_intr_window_test(void)
5458 {
5459 	u64 vmcall_addr;
5460 	u64 nop_addr;
5461 	unsigned int orig_ud_gate_type;
5462 	void *ud_fault_addr = get_idt_addr(&boot_idt[UD_VECTOR]);
5463 
5464 	if (!(ctrl_cpu_rev[0].clr & CPU_INTR_WINDOW)) {
5465 		report_skip("CPU does not support the \"interrupt-window exiting\" VM-execution control.");
5466 		return;
5467 	}
5468 
5469 	/*
5470 	 * Change the IDT entry for #UD from interrupt gate to trap gate,
5471 	 * so that it won't clear RFLAGS.IF. We don't want interrupts to
5472 	 * be disabled after vectoring a #UD.
5473 	 */
5474 	orig_ud_gate_type = boot_idt[UD_VECTOR].type;
5475 	boot_idt[UD_VECTOR].type = 15;
5476 
5477 	report_prefix_push("interrupt-window");
5478 	test_set_guest(vmx_intr_window_test_guest);
5479 	enter_guest();
5480 	assert_exit_reason(VMX_VMCALL);
5481 	vmcall_addr = vmcs_read(GUEST_RIP);
5482 
5483 	/*
5484 	 * Ask for "interrupt-window exiting" with RFLAGS.IF set and
5485 	 * no blocking; expect an immediate VM-exit. Note that we have
5486 	 * not advanced past the vmcall instruction yet, so RIP should
5487 	 * point to the vmcall instruction.
5488 	 */
5489 	report_prefix_push("active, no blocking, RFLAGS.IF=1");
5490 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5491 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_IF);
5492 	enter_guest();
5493 	verify_intr_window_exit(vmcall_addr);
5494 	report_prefix_pop();
5495 
5496 	/*
5497 	 * Ask for "interrupt-window exiting" (with event injection)
5498 	 * with RFLAGS.IF set and no blocking; expect a VM-exit after
5499 	 * the event is injected. That is, RIP should should be at the
5500 	 * address specified in the IDT entry for #UD.
5501 	 */
5502 	report_prefix_push("active, no blocking, RFLAGS.IF=1, injecting #UD");
5503 	vmcs_write(ENT_INTR_INFO,
5504 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | UD_VECTOR);
5505 	vmcall_addr = vmcs_read(GUEST_RIP);
5506 	enter_guest();
5507 	verify_intr_window_exit((u64)ud_fault_addr);
5508 	report_prefix_pop();
5509 
5510 	/*
5511 	 * Let the L2 guest run through the IRET, back to the VMCALL.
5512 	 * We have to clear the "interrupt-window exiting"
5513 	 * VM-execution control, or it would just keep causing
5514 	 * VM-exits. Then, advance past the VMCALL and set the
5515 	 * "interrupt-window exiting" VM-execution control again.
5516 	 */
5517 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5518 	enter_guest();
5519 	skip_exit_vmcall();
5520 	nop_addr = vmcs_read(GUEST_RIP);
5521 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5522 
5523 	/*
5524 	 * Ask for "interrupt-window exiting" in a MOV-SS shadow with
5525 	 * RFLAGS.IF set, and expect a VM-exit on the next
5526 	 * instruction. (NOP is one byte.)
5527 	 */
5528 	report_prefix_push("active, blocking by MOV-SS, RFLAGS.IF=1");
5529 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5530 	enter_guest();
5531 	verify_intr_window_exit(nop_addr + 1);
5532 	report_prefix_pop();
5533 
5534 	/*
5535 	 * Back up to the NOP and ask for "interrupt-window exiting"
5536 	 * in an STI shadow with RFLAGS.IF set, and expect a VM-exit
5537 	 * on the next instruction. (NOP is one byte.)
5538 	 */
5539 	report_prefix_push("active, blocking by STI, RFLAGS.IF=1");
5540 	vmcs_write(GUEST_RIP, nop_addr);
5541 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_STI);
5542 	enter_guest();
5543 	verify_intr_window_exit(nop_addr + 1);
5544 	report_prefix_pop();
5545 
5546 	/*
5547 	 * Ask for "interrupt-window exiting" with RFLAGS.IF clear,
5548 	 * and expect a VM-exit on the instruction following the STI
5549 	 * shadow. Only the first STI (which is one byte past the NOP)
5550 	 * should have a shadow. The second STI (which is two bytes
5551 	 * past the NOP) has no shadow. Therefore, the interrupt
5552 	 * window opens at three bytes past the NOP.
5553 	 */
5554 	report_prefix_push("active, RFLAGS.IF = 0");
5555 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5556 	enter_guest();
5557 	verify_intr_window_exit(nop_addr + 3);
5558 	report_prefix_pop();
5559 
5560 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
5561 		report_skip("CPU does not support activity state HLT.");
5562 	} else {
5563 		/*
5564 		 * Ask for "interrupt-window exiting" when entering
5565 		 * activity state HLT, and expect an immediate
5566 		 * VM-exit. RIP is still three bytes past the nop.
5567 		 */
5568 		report_prefix_push("halted, no blocking");
5569 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5570 		enter_guest();
5571 		verify_intr_window_exit(nop_addr + 3);
5572 		report_prefix_pop();
5573 
5574 		/*
5575 		 * Ask for "interrupt-window exiting" when entering
5576 		 * activity state HLT (with event injection), and
5577 		 * expect a VM-exit after the event is injected. That
5578 		 * is, RIP should should be at the address specified
5579 		 * in the IDT entry for #UD.
5580 		 */
5581 		report_prefix_push("halted, no blocking, injecting #UD");
5582 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5583 		vmcs_write(ENT_INTR_INFO,
5584 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5585 			   UD_VECTOR);
5586 		enter_guest();
5587 		verify_intr_window_exit((u64)ud_fault_addr);
5588 		report_prefix_pop();
5589 	}
5590 
5591 	boot_idt[UD_VECTOR].type = orig_ud_gate_type;
5592 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5593 	enter_guest();
5594 	report_prefix_pop();
5595 }
5596 
5597 #define GUEST_TSC_OFFSET (1u << 30)
5598 
5599 static u64 guest_tsc;
5600 
5601 static void vmx_store_tsc_test_guest(void)
5602 {
5603 	guest_tsc = rdtsc();
5604 }
5605 
5606 /*
5607  * This test ensures that when IA32_TSC is in the VM-exit MSR-store
5608  * list, the value saved is not subject to the TSC offset that is
5609  * applied to RDTSC/RDTSCP/RDMSR(IA32_TSC) in guest execution.
5610  */
5611 static void vmx_store_tsc_test(void)
5612 {
5613 	struct vmx_msr_entry msr_entry = { .index = MSR_IA32_TSC };
5614 	u64 low, high;
5615 
5616 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET)) {
5617 		report_skip("'Use TSC offsetting' not supported");
5618 		return;
5619 	}
5620 
5621 	test_set_guest(vmx_store_tsc_test_guest);
5622 
5623 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
5624 	vmcs_write(EXI_MSR_ST_CNT, 1);
5625 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(&msr_entry));
5626 	vmcs_write(TSC_OFFSET, GUEST_TSC_OFFSET);
5627 
5628 	low = rdtsc();
5629 	enter_guest();
5630 	high = rdtsc();
5631 
5632 	report("RDTSC value in the guest (%lu) is in range [%lu, %lu]",
5633 	       low + GUEST_TSC_OFFSET <= guest_tsc &&
5634 	       guest_tsc <= high + GUEST_TSC_OFFSET,
5635 	       guest_tsc, low + GUEST_TSC_OFFSET, high + GUEST_TSC_OFFSET);
5636 	report("IA32_TSC value saved in the VM-exit MSR-store list (%lu) is in range [%lu, %lu]",
5637 	       low <= msr_entry.value && msr_entry.value <= high,
5638 	       msr_entry.value, low, high);
5639 }
5640 
5641 static void vmx_db_test_guest(void)
5642 {
5643 	/*
5644 	 * For a hardware generated single-step #DB.
5645 	 */
5646 	asm volatile("vmcall;"
5647 		     "nop;"
5648 		     ".Lpost_nop:");
5649 	/*
5650 	 * ...in a MOVSS shadow, with pending debug exceptions.
5651 	 */
5652 	asm volatile("vmcall;"
5653 		     "nop;"
5654 		     ".Lpost_movss_nop:");
5655 	/*
5656 	 * For an L0 synthesized single-step #DB. (L0 intercepts WBINVD and
5657 	 * emulates it in software.)
5658 	 */
5659 	asm volatile("vmcall;"
5660 		     "wbinvd;"
5661 		     ".Lpost_wbinvd:");
5662 	/*
5663 	 * ...in a MOVSS shadow, with pending debug exceptions.
5664 	 */
5665 	asm volatile("vmcall;"
5666 		     "wbinvd;"
5667 		     ".Lpost_movss_wbinvd:");
5668 	/*
5669 	 * For a hardware generated single-step #DB in a transactional region.
5670 	 */
5671 	asm volatile("vmcall;"
5672 		     ".Lxbegin: xbegin .Lskip_rtm;"
5673 		     "xend;"
5674 		     ".Lskip_rtm:");
5675 }
5676 
5677 /*
5678  * Clear the pending debug exceptions and RFLAGS.TF and re-enter
5679  * L2. No #DB is delivered and L2 continues to the next point of
5680  * interest.
5681  */
5682 static void dismiss_db(void)
5683 {
5684 	vmcs_write(GUEST_PENDING_DEBUG, 0);
5685 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5686 	enter_guest();
5687 }
5688 
5689 /*
5690  * Check a variety of VMCS fields relevant to an intercepted #DB exception.
5691  * Then throw away the #DB exception and resume L2.
5692  */
5693 static void check_db_exit(bool xfail_qual, bool xfail_dr6, bool xfail_pdbg,
5694 			  void *expected_rip, u64 expected_exit_qual,
5695 			  u64 expected_dr6)
5696 {
5697 	u32 reason = vmcs_read(EXI_REASON);
5698 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
5699 	u64 exit_qual = vmcs_read(EXI_QUALIFICATION);
5700 	u64 guest_rip = vmcs_read(GUEST_RIP);
5701 	u64 guest_pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
5702 	u64 dr6 = read_dr6();
5703 	const u32 expected_intr_info = INTR_INFO_VALID_MASK |
5704 		INTR_TYPE_HARD_EXCEPTION | DB_VECTOR;
5705 
5706 	report("Expected #DB VM-exit",
5707 	       reason == VMX_EXC_NMI && intr_info == expected_intr_info);
5708 	report("Expected RIP %p (actual %lx)", (u64)expected_rip == guest_rip,
5709 	       expected_rip, guest_rip);
5710 	report_xfail("Expected pending debug exceptions 0 (actual %lx)",
5711 		     xfail_pdbg, 0 == guest_pending_dbg, guest_pending_dbg);
5712 	report_xfail("Expected exit qualification %lx (actual %lx)", xfail_qual,
5713 		     expected_exit_qual == exit_qual,
5714 		     expected_exit_qual, exit_qual);
5715 	report_xfail("Expected DR6 %lx (actual %lx)", xfail_dr6,
5716 		     expected_dr6 == dr6, expected_dr6, dr6);
5717 	dismiss_db();
5718 }
5719 
5720 /*
5721  * Assuming the guest has just exited on a VMCALL instruction, skip
5722  * over the vmcall, and set the guest's RFLAGS.TF in the VMCS. If
5723  * pending debug exceptions are non-zero, set the VMCS up as if the
5724  * previous instruction was a MOVSS that generated the indicated
5725  * pending debug exceptions. Then enter L2.
5726  */
5727 static void single_step_guest(const char *test_name, u64 starting_dr6,
5728 			      u64 pending_debug_exceptions)
5729 {
5730 	printf("\n%s\n", test_name);
5731 	skip_exit_vmcall();
5732 	write_dr6(starting_dr6);
5733 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
5734 	if (pending_debug_exceptions) {
5735 		vmcs_write(GUEST_PENDING_DEBUG, pending_debug_exceptions);
5736 		vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5737 	}
5738 	enter_guest();
5739 }
5740 
5741 /*
5742  * When L1 intercepts #DB, verify that a single-step trap clears
5743  * pending debug exceptions, populates the exit qualification field
5744  * properly, and that DR6 is not prematurely clobbered. In a
5745  * (simulated) MOVSS shadow, make sure that the pending debug
5746  * exception bits are properly accumulated into the exit qualification
5747  * field.
5748  */
5749 static void vmx_db_test(void)
5750 {
5751 	/*
5752 	 * We are going to set a few arbitrary bits in DR6 to verify that
5753 	 * (a) DR6 is not modified by an intercepted #DB, and
5754 	 * (b) stale bits in DR6 (DR6.BD, in particular) don't leak into
5755          *     the exit qualification field for a subsequent #DB exception.
5756 	 */
5757 	const u64 starting_dr6 = DR6_RESERVED | BIT(13) | DR_TRAP3 | DR_TRAP1;
5758 	extern char post_nop asm(".Lpost_nop");
5759 	extern char post_movss_nop asm(".Lpost_movss_nop");
5760 	extern char post_wbinvd asm(".Lpost_wbinvd");
5761 	extern char post_movss_wbinvd asm(".Lpost_movss_wbinvd");
5762 	extern char xbegin asm(".Lxbegin");
5763 	extern char skip_rtm asm(".Lskip_rtm");
5764 
5765 	/*
5766 	 * L1 wants to intercept #DB exceptions encountered in L2.
5767 	 */
5768 	vmcs_write(EXC_BITMAP, BIT(DB_VECTOR));
5769 
5770 	/*
5771 	 * Start L2 and run it up to the first point of interest.
5772 	 */
5773 	test_set_guest(vmx_db_test_guest);
5774 	enter_guest();
5775 
5776 	/*
5777 	 * Hardware-delivered #DB trap for single-step sets the
5778 	 * standard that L0 has to follow for emulated instructions.
5779 	 */
5780 	single_step_guest("Hardware delivered single-step", starting_dr6, 0);
5781 	check_db_exit(false, false, false, &post_nop, DR_STEP, starting_dr6);
5782 
5783 	/*
5784 	 * Hardware-delivered #DB trap for single-step in MOVSS shadow
5785 	 * also sets the standard that L0 has to follow for emulated
5786 	 * instructions. Here, we establish the VMCS pending debug
5787 	 * exceptions to indicate that the simulated MOVSS triggered a
5788 	 * data breakpoint as well as the single-step trap.
5789 	 */
5790 	single_step_guest("Hardware delivered single-step in MOVSS shadow",
5791 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0 );
5792 	check_db_exit(false, false, false, &post_movss_nop, DR_STEP | DR_TRAP0,
5793 		      starting_dr6);
5794 
5795 	/*
5796 	 * L0 synthesized #DB trap for single-step is buggy, because
5797 	 * kvm (a) clobbers DR6 too early, and (b) tries its best to
5798 	 * reconstitute the exit qualification from the prematurely
5799 	 * modified DR6, but fails miserably.
5800 	 */
5801 	single_step_guest("Software synthesized single-step", starting_dr6, 0);
5802 	check_db_exit(true, true, false, &post_wbinvd, DR_STEP, starting_dr6);
5803 
5804 	/*
5805 	 * L0 synthesized #DB trap for single-step in MOVSS shadow is
5806 	 * even worse, because L0 also leaves the pending debug
5807 	 * exceptions in the VMCS instead of accumulating them into
5808 	 * the exit qualification field for the #DB exception.
5809 	 */
5810 	single_step_guest("Software synthesized single-step in MOVSS shadow",
5811 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0);
5812 	check_db_exit(true, true, true, &post_movss_wbinvd, DR_STEP | DR_TRAP0,
5813 		      starting_dr6);
5814 
5815 	/*
5816 	 * Optional RTM test for hardware that supports RTM, to
5817 	 * demonstrate that the current volume 3 of the SDM
5818 	 * (325384-067US), table 27-1 is incorrect. Bit 16 of the exit
5819 	 * qualification for debug exceptions is not reserved. It is
5820 	 * set to 1 if a debug exception (#DB) or a breakpoint
5821 	 * exception (#BP) occurs inside an RTM region while advanced
5822 	 * debugging of RTM transactional regions is enabled.
5823 	 */
5824 	if (cpuid(7).b & BIT(11)) {
5825 		vmcs_write(ENT_CONTROLS,
5826 			   vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
5827 		/*
5828 		 * Set DR7.RTM[bit 11] and IA32_DEBUGCTL.RTM[bit 15]
5829 		 * in the guest to enable advanced debugging of RTM
5830 		 * transactional regions.
5831 		 */
5832 		vmcs_write(GUEST_DR7, BIT(11));
5833 		vmcs_write(GUEST_DEBUGCTL, BIT(15));
5834 		single_step_guest("Hardware delivered single-step in "
5835 				  "transactional region", starting_dr6, 0);
5836 		check_db_exit(false, false, false, &xbegin, BIT(16),
5837 			      starting_dr6);
5838 	} else {
5839 		vmcs_write(GUEST_RIP, (u64)&skip_rtm);
5840 		enter_guest();
5841 	}
5842 }
5843 
5844 static bool cpu_has_apicv(void)
5845 {
5846 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
5847 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
5848 		(ctrl_pin_rev.clr & PIN_POST_INTR));
5849 }
5850 
5851 static void enable_vid(void)
5852 {
5853 	void *virtual_apic_page;
5854 
5855 	assert(cpu_has_apicv());
5856 
5857 	disable_intercept_for_x2apic_msrs();
5858 
5859 	virtual_apic_page = alloc_page();
5860 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
5861 
5862 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
5863 
5864 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
5865 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
5866 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
5867 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
5868 
5869 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY | CPU_TPR_SHADOW);
5870 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VINTD | CPU_VIRT_X2APIC);
5871 }
5872 
5873 static void trigger_ioapic_scan_thread(void *data)
5874 {
5875 	/* Wait until other CPU entered L2 */
5876 	while (vmx_get_test_stage() != 1)
5877 		;
5878 
5879 	/* Trigger ioapic scan */
5880 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
5881 	vmx_set_test_stage(2);
5882 }
5883 
5884 static void irq_79_handler_guest(isr_regs_t *regs)
5885 {
5886 	eoi();
5887 
5888 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
5889 	vmcall();
5890 }
5891 
5892 /*
5893  * Constant for num of busy-loop iterations after which
5894  * a timer interrupt should have happened in host
5895  */
5896 #define TIMER_INTERRUPT_DELAY 100000000
5897 
5898 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
5899 {
5900 	handle_irq(0x79, irq_79_handler_guest);
5901 	irq_enable();
5902 
5903 	/* Signal to L1 CPU to trigger ioapic scan */
5904 	vmx_set_test_stage(1);
5905 	/* Wait until L1 CPU to trigger ioapic scan */
5906 	while (vmx_get_test_stage() != 2)
5907 		;
5908 
5909 	/*
5910 	 * Wait for L0 timer interrupt to be raised while we run in L2
5911 	 * such that L0 will process the IOAPIC scan request before
5912 	 * resuming L2
5913 	 */
5914 	delay(TIMER_INTERRUPT_DELAY);
5915 
5916 	asm volatile ("int $0x79");
5917 }
5918 
5919 static void vmx_eoi_bitmap_ioapic_scan_test(void)
5920 {
5921 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
5922 		report_skip(__func__);
5923 		return;
5924 	}
5925 
5926 	enable_vid();
5927 
5928 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
5929 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
5930 
5931 	/*
5932 	 * Launch L2.
5933 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
5934 	 * In case the reason isn't VMX_VMCALL, the asserion inside
5935 	 * skip_exit_vmcall() will fail.
5936 	 */
5937 	enter_guest();
5938 	skip_exit_vmcall();
5939 
5940 	/* Let L2 finish */
5941 	enter_guest();
5942 	report(__func__, 1);
5943 }
5944 
5945 #define HLT_WITH_RVI_VECTOR		(0xf1)
5946 
5947 bool vmx_hlt_with_rvi_guest_isr_fired;
5948 static void vmx_hlt_with_rvi_guest_isr(isr_regs_t *regs)
5949 {
5950 	vmx_hlt_with_rvi_guest_isr_fired = true;
5951 	eoi();
5952 }
5953 
5954 static void vmx_hlt_with_rvi_guest(void)
5955 {
5956 	handle_irq(HLT_WITH_RVI_VECTOR, vmx_hlt_with_rvi_guest_isr);
5957 
5958 	irq_enable();
5959 	asm volatile ("nop");
5960 
5961 	vmcall();
5962 }
5963 
5964 static void vmx_hlt_with_rvi_test(void)
5965 {
5966 	if (!cpu_has_apicv()) {
5967 		report_skip(__func__);
5968 		return;
5969 	}
5970 
5971 	enable_vid();
5972 
5973 	vmx_hlt_with_rvi_guest_isr_fired = false;
5974 	test_set_guest(vmx_hlt_with_rvi_guest);
5975 
5976 	enter_guest();
5977 	skip_exit_vmcall();
5978 
5979 	vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5980 	vmcs_write(GUEST_INT_STATUS, HLT_WITH_RVI_VECTOR);
5981 	enter_guest();
5982 
5983 	report("Interrupt raised in guest", vmx_hlt_with_rvi_guest_isr_fired);
5984 }
5985 
5986 static void set_irq_line_thread(void *data)
5987 {
5988 	/* Wait until other CPU entered L2 */
5989 	while (vmx_get_test_stage() != 1)
5990 		;
5991 
5992 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
5993 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
5994 	vmx_set_test_stage(2);
5995 }
5996 
5997 static bool irq_78_handler_vmcall_before_eoi;
5998 static void irq_78_handler_guest(isr_regs_t *regs)
5999 {
6000 	set_irq_line(0xf, 0);
6001 	if (irq_78_handler_vmcall_before_eoi)
6002 		vmcall();
6003 	eoi();
6004 	vmcall();
6005 }
6006 
6007 static void vmx_apic_passthrough_guest(void)
6008 {
6009 	handle_irq(0x78, irq_78_handler_guest);
6010 	irq_enable();
6011 
6012 	/* If requested, wait for other CPU to trigger ioapic scan */
6013 	if (vmx_get_test_stage() < 1) {
6014 		vmx_set_test_stage(1);
6015 		while (vmx_get_test_stage() != 2)
6016 			;
6017 	}
6018 
6019 	set_irq_line(0xf, 1);
6020 }
6021 
6022 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
6023 {
6024 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
6025 		report_skip(__func__);
6026 		return;
6027 	}
6028 
6029 	u64 cpu_ctrl_0 = CPU_SECONDARY;
6030 	u64 cpu_ctrl_1 = 0;
6031 
6032 	disable_intercept_for_x2apic_msrs();
6033 
6034 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
6035 
6036 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
6037 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
6038 
6039 	if (set_irq_line_from_thread) {
6040 		irq_78_handler_vmcall_before_eoi = false;
6041 		on_cpu_async(1, set_irq_line_thread, NULL);
6042 	} else {
6043 		irq_78_handler_vmcall_before_eoi = true;
6044 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
6045 		vmx_set_test_stage(2);
6046 	}
6047 	test_set_guest(vmx_apic_passthrough_guest);
6048 
6049 	if (irq_78_handler_vmcall_before_eoi) {
6050 		/* Before EOI remote_irr should still be set */
6051 		enter_guest();
6052 		skip_exit_vmcall();
6053 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
6054 			"IOAPIC pass-through: remote_irr=1 before EOI");
6055 	}
6056 
6057 	/* After EOI remote_irr should be cleared */
6058 	enter_guest();
6059 	skip_exit_vmcall();
6060 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
6061 		"IOAPIC pass-through: remote_irr=0 after EOI");
6062 
6063 	/* Let L2 finish */
6064 	enter_guest();
6065 	report(__func__, 1);
6066 }
6067 
6068 static void vmx_apic_passthrough_test(void)
6069 {
6070 	vmx_apic_passthrough(false);
6071 }
6072 
6073 static void vmx_apic_passthrough_thread_test(void)
6074 {
6075 	vmx_apic_passthrough(true);
6076 }
6077 
6078 enum vmcs_access {
6079 	ACCESS_VMREAD,
6080 	ACCESS_VMWRITE,
6081 	ACCESS_NONE,
6082 };
6083 
6084 struct vmcs_shadow_test_common {
6085 	enum vmcs_access op;
6086 	enum Reason reason;
6087 	u64 field;
6088 	u64 value;
6089 	u64 flags;
6090 	u64 time;
6091 } l1_l2_common;
6092 
6093 static inline u64 vmread_flags(u64 field, u64 *val)
6094 {
6095 	u64 flags;
6096 
6097 	asm volatile ("vmread %2, %1; pushf; pop %0"
6098 		      : "=r" (flags), "=rm" (*val) : "r" (field) : "cc");
6099 	return flags & X86_EFLAGS_ALU;
6100 }
6101 
6102 static inline u64 vmwrite_flags(u64 field, u64 val)
6103 {
6104 	u64 flags;
6105 
6106 	asm volatile ("vmwrite %1, %2; pushf; pop %0"
6107 		      : "=r"(flags) : "rm" (val), "r" (field) : "cc");
6108 	return flags & X86_EFLAGS_ALU;
6109 }
6110 
6111 static void vmx_vmcs_shadow_test_guest(void)
6112 {
6113 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6114 	u64 start;
6115 
6116 	while (c->op != ACCESS_NONE) {
6117 		start = rdtsc();
6118 		switch (c->op) {
6119 		default:
6120 			c->flags = -1ull;
6121 			break;
6122 		case ACCESS_VMREAD:
6123 			c->flags = vmread_flags(c->field, &c->value);
6124 			break;
6125 		case ACCESS_VMWRITE:
6126 			c->flags = vmwrite_flags(c->field, 0);
6127 			break;
6128 		}
6129 		c->time = rdtsc() - start;
6130 		vmcall();
6131 	}
6132 }
6133 
6134 static u64 vmread_from_shadow(u64 field)
6135 {
6136 	struct vmcs *primary;
6137 	struct vmcs *shadow;
6138 	u64 value;
6139 
6140 	TEST_ASSERT(!vmcs_save(&primary));
6141 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6142 	TEST_ASSERT(!make_vmcs_current(shadow));
6143 	value = vmcs_read(field);
6144 	TEST_ASSERT(!make_vmcs_current(primary));
6145 	return value;
6146 }
6147 
6148 static u64 vmwrite_to_shadow(u64 field, u64 value)
6149 {
6150 	struct vmcs *primary;
6151 	struct vmcs *shadow;
6152 
6153 	TEST_ASSERT(!vmcs_save(&primary));
6154 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6155 	TEST_ASSERT(!make_vmcs_current(shadow));
6156 	vmcs_write(field, value);
6157 	value = vmcs_read(field);
6158 	TEST_ASSERT(!make_vmcs_current(primary));
6159 	return value;
6160 }
6161 
6162 static void vmcs_shadow_test_access(u8 *bitmap[2], enum vmcs_access access)
6163 {
6164 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6165 
6166 	c->op = access;
6167 	vmcs_write(VMX_INST_ERROR, 0);
6168 	enter_guest();
6169 	c->reason = vmcs_read(EXI_REASON) & 0xffff;
6170 	if (c->reason != VMX_VMCALL) {
6171 		skip_exit_insn();
6172 		enter_guest();
6173 	}
6174 	skip_exit_vmcall();
6175 }
6176 
6177 static void vmcs_shadow_test_field(u8 *bitmap[2], u64 field)
6178 {
6179 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6180 	struct vmcs *shadow;
6181 	u64 value;
6182 	uintptr_t flags[2];
6183 	bool good_shadow;
6184 	u32 vmx_inst_error;
6185 
6186 	report_prefix_pushf("field %lx", field);
6187 	c->field = field;
6188 
6189 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6190 	if (shadow != (struct vmcs *)-1ull) {
6191 		flags[ACCESS_VMREAD] = vmread_flags(field, &value);
6192 		flags[ACCESS_VMWRITE] = vmwrite_flags(field, value);
6193 		good_shadow = !flags[ACCESS_VMREAD] && !flags[ACCESS_VMWRITE];
6194 	} else {
6195 		/*
6196 		 * When VMCS link pointer is -1ull, VMWRITE/VMREAD on
6197 		 * shadowed-fields should fail with setting RFLAGS.CF.
6198 		 */
6199 		flags[ACCESS_VMREAD] = X86_EFLAGS_CF;
6200 		flags[ACCESS_VMWRITE] = X86_EFLAGS_CF;
6201 		good_shadow = false;
6202 	}
6203 
6204 	/* Intercept both VMREAD and VMWRITE. */
6205 	report_prefix_push("no VMREAD/VMWRITE permission");
6206 	/* VMWRITE/VMREAD done on reserved-bit should always intercept */
6207 	if (!(field >> VMCS_FIELD_RESERVED_SHIFT)) {
6208 		set_bit(field, bitmap[ACCESS_VMREAD]);
6209 		set_bit(field, bitmap[ACCESS_VMWRITE]);
6210 	}
6211 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6212 	report("not shadowed for VMWRITE", c->reason == VMX_VMWRITE);
6213 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6214 	report("not shadowed for VMREAD", c->reason == VMX_VMREAD);
6215 	report_prefix_pop();
6216 
6217 	if (field >> VMCS_FIELD_RESERVED_SHIFT)
6218 		goto out;
6219 
6220 	/* Permit shadowed VMREAD. */
6221 	report_prefix_push("VMREAD permission only");
6222 	clear_bit(field, bitmap[ACCESS_VMREAD]);
6223 	set_bit(field, bitmap[ACCESS_VMWRITE]);
6224 	if (good_shadow)
6225 		value = vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6226 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6227 	report("not shadowed for VMWRITE", c->reason == VMX_VMWRITE);
6228 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6229 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6230 	report("shadowed for VMREAD (in %ld cycles)", c->reason == VMX_VMCALL,
6231 	       c->time);
6232 	report("ALU flags after VMREAD (%lx) are as expected (%lx)",
6233 	       c->flags == flags[ACCESS_VMREAD],
6234 	       c->flags, flags[ACCESS_VMREAD]);
6235 	if (good_shadow)
6236 		report("value read from shadow (%lx) is as expected (%lx)",
6237 		       c->value == value, c->value, value);
6238 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
6239 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6240 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6241 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6242 	report_prefix_pop();
6243 
6244 	/* Permit shadowed VMWRITE. */
6245 	report_prefix_push("VMWRITE permission only");
6246 	set_bit(field, bitmap[ACCESS_VMREAD]);
6247 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
6248 	if (good_shadow)
6249 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6250 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6251 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6252 	report("shadowed for VMWRITE (in %ld cycles)", c->reason == VMX_VMCALL,
6253 		c->time);
6254 	report("ALU flags after VMWRITE (%lx) are as expected (%lx)",
6255 	       c->flags == flags[ACCESS_VMREAD],
6256 	       c->flags, flags[ACCESS_VMREAD]);
6257 	if (good_shadow) {
6258 		value = vmread_from_shadow(field);
6259 		report("shadow VMCS value (%lx) is as expected (%lx)",
6260 		       value == 0, value, 0ul);
6261 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
6262 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6263 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6264 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6265 	}
6266 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6267 	report("not shadowed for VMREAD", c->reason == VMX_VMREAD);
6268 	report_prefix_pop();
6269 
6270 	/* Permit shadowed VMREAD and VMWRITE. */
6271 	report_prefix_push("VMREAD and VMWRITE permission");
6272 	clear_bit(field, bitmap[ACCESS_VMREAD]);
6273 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
6274 	if (good_shadow)
6275 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6276 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6277 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6278 	report("shadowed for VMWRITE (in %ld cycles)", c->reason == VMX_VMCALL,
6279 		c->time);
6280 	report("ALU flags after VMWRITE (%lx) are as expected (%lx)",
6281 	       c->flags == flags[ACCESS_VMREAD],
6282 	       c->flags, flags[ACCESS_VMREAD]);
6283 	if (good_shadow) {
6284 		value = vmread_from_shadow(field);
6285 		report("shadow VMCS value (%lx) is as expected (%lx)",
6286 		       value == 0, value, 0ul);
6287 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
6288 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6289 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6290 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6291 	}
6292 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6293 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6294 	report("shadowed for VMREAD (in %ld cycles)", c->reason == VMX_VMCALL,
6295 	       c->time);
6296 	report("ALU flags after VMREAD (%lx) are as expected (%lx)",
6297 	       c->flags == flags[ACCESS_VMREAD],
6298 	       c->flags, flags[ACCESS_VMREAD]);
6299 	if (good_shadow)
6300 		report("value read from shadow (%lx) is as expected (%lx)",
6301 		       c->value == 0, c->value, 0ul);
6302 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
6303 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6304 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6305 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6306 	report_prefix_pop();
6307 
6308 out:
6309 	report_prefix_pop();
6310 }
6311 
6312 static void vmx_vmcs_shadow_test_body(u8 *bitmap[2])
6313 {
6314 	unsigned base;
6315 	unsigned index;
6316 	unsigned bit;
6317 	unsigned highest_index = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
6318 
6319 	/* Run test on all possible valid VMCS fields */
6320 	for (base = 0;
6321 	     base < (1 << VMCS_FIELD_RESERVED_SHIFT);
6322 	     base += (1 << VMCS_FIELD_TYPE_SHIFT))
6323 		for (index = 0; index <= highest_index; index++)
6324 			vmcs_shadow_test_field(bitmap, base + index);
6325 
6326 	/*
6327 	 * Run tests on some invalid VMCS fields
6328 	 * (Have reserved bit set).
6329 	 */
6330 	for (bit = VMCS_FIELD_RESERVED_SHIFT; bit < VMCS_FIELD_BIT_SIZE; bit++)
6331 		vmcs_shadow_test_field(bitmap, (1ull << bit));
6332 }
6333 
6334 static void vmx_vmcs_shadow_test(void)
6335 {
6336 	u8 *bitmap[2];
6337 	struct vmcs *shadow;
6338 
6339 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
6340 		printf("\t'Activate secondary controls' not supported.\n");
6341 		return;
6342 	}
6343 
6344 	if (!(ctrl_cpu_rev[1].clr & CPU_SHADOW_VMCS)) {
6345 		printf("\t'VMCS shadowing' not supported.\n");
6346 		return;
6347 	}
6348 
6349 	if (!(rdmsr(MSR_IA32_VMX_MISC) &
6350 	      MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) {
6351 		printf("\tVMWRITE can't modify VM-exit information fields.\n");
6352 		return;
6353 	}
6354 
6355 	test_set_guest(vmx_vmcs_shadow_test_guest);
6356 
6357 	bitmap[ACCESS_VMREAD] = alloc_page();
6358 	bitmap[ACCESS_VMWRITE] = alloc_page();
6359 
6360 	vmcs_write(VMREAD_BITMAP, virt_to_phys(bitmap[ACCESS_VMREAD]));
6361 	vmcs_write(VMWRITE_BITMAP, virt_to_phys(bitmap[ACCESS_VMWRITE]));
6362 
6363 	shadow = alloc_page();
6364 	shadow->hdr.revision_id = basic.revision;
6365 	shadow->hdr.shadow_vmcs = 1;
6366 	TEST_ASSERT(!vmcs_clear(shadow));
6367 
6368 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_RDTSC);
6369 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
6370 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_SHADOW_VMCS);
6371 
6372 	vmcs_write(VMCS_LINK_PTR, virt_to_phys(shadow));
6373 	report_prefix_push("valid link pointer");
6374 	vmx_vmcs_shadow_test_body(bitmap);
6375 	report_prefix_pop();
6376 
6377 	vmcs_write(VMCS_LINK_PTR, -1ull);
6378 	report_prefix_push("invalid link pointer");
6379 	vmx_vmcs_shadow_test_body(bitmap);
6380 	report_prefix_pop();
6381 
6382 	l1_l2_common.op = ACCESS_NONE;
6383 	enter_guest();
6384 }
6385 
6386 
6387 
6388 static int invalid_msr_init(struct vmcs *vmcs)
6389 {
6390 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
6391 		printf("\tPreemption timer is not supported\n");
6392 		return VMX_TEST_EXIT;
6393 	}
6394 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
6395 	preempt_val = 10000000;
6396 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
6397 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
6398 
6399 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
6400 		printf("\tSave preemption value is not supported\n");
6401 
6402 	vmcs_write(ENT_MSR_LD_CNT, 1);
6403 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)0x13370000);
6404 
6405 	return VMX_TEST_START;
6406 }
6407 
6408 
6409 static void invalid_msr_main(void)
6410 {
6411 	report("Invalid MSR load", 0);
6412 }
6413 
6414 static int invalid_msr_exit_handler(void)
6415 {
6416 	report("Invalid MSR load", 0);
6417 	print_vmexit_info();
6418 	return VMX_TEST_EXIT;
6419 }
6420 
6421 static int invalid_msr_entry_failure(struct vmentry_failure *failure)
6422 {
6423 	ulong reason;
6424 
6425 	reason = vmcs_read(EXI_REASON);
6426 	report("Invalid MSR load", reason == (0x80000000u | VMX_FAIL_MSR));
6427 	return VMX_TEST_VMEXIT;
6428 }
6429 
6430 
6431 #define TEST(name) { #name, .v2 = name }
6432 
6433 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
6434 struct vmx_test vmx_tests[] = {
6435 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
6436 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
6437 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
6438 		preemption_timer_exit_handler, NULL, {0} },
6439 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
6440 		test_ctrl_pat_exit_handler, NULL, {0} },
6441 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
6442 		test_ctrl_efer_exit_handler, NULL, {0} },
6443 	{ "CR shadowing", NULL, cr_shadowing_main,
6444 		cr_shadowing_exit_handler, NULL, {0} },
6445 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
6446 		NULL, {0} },
6447 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
6448 		insn_intercept_exit_handler, NULL, {0} },
6449 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
6450 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
6451 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
6452 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
6453 	{ "interrupt", interrupt_init, interrupt_main,
6454 		interrupt_exit_handler, NULL, {0} },
6455 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
6456 		NULL, {0} },
6457 	{ "MSR switch", msr_switch_init, msr_switch_main,
6458 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
6459 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
6460 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
6461 		disable_rdtscp_exit_handler, NULL, {0} },
6462 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
6463 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
6464 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
6465 		exit_monitor_from_l2_handler, NULL, {0} },
6466 	{ "invalid_msr", invalid_msr_init, invalid_msr_main,
6467 		invalid_msr_exit_handler, NULL, {0}, invalid_msr_entry_failure},
6468 	/* Basic V2 tests. */
6469 	TEST(v2_null_test),
6470 	TEST(v2_multiple_entries_test),
6471 	TEST(fixture_test_case1),
6472 	TEST(fixture_test_case2),
6473 	/* Opcode tests. */
6474 	TEST(invvpid_test_v2),
6475 	/* VM-entry tests */
6476 	TEST(vmx_controls_test),
6477 	TEST(vmentry_movss_shadow_test),
6478 	/* APICv tests */
6479 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
6480 	TEST(vmx_hlt_with_rvi_test),
6481 	/* APIC pass-through tests */
6482 	TEST(vmx_apic_passthrough_test),
6483 	TEST(vmx_apic_passthrough_thread_test),
6484 	/* VMCS Shadowing tests */
6485 	TEST(vmx_vmcs_shadow_test),
6486 	/* Regression tests */
6487 	TEST(vmx_cr_load_test),
6488 	TEST(vmx_nm_test),
6489 	TEST(vmx_db_test),
6490 	TEST(vmx_nmi_window_test),
6491 	TEST(vmx_intr_window_test),
6492 	TEST(vmx_pending_event_test),
6493 	TEST(vmx_pending_event_hlt_test),
6494 	TEST(vmx_store_tsc_test),
6495 	/* EPT access tests. */
6496 	TEST(ept_access_test_not_present),
6497 	TEST(ept_access_test_read_only),
6498 	TEST(ept_access_test_write_only),
6499 	TEST(ept_access_test_read_write),
6500 	TEST(ept_access_test_execute_only),
6501 	TEST(ept_access_test_read_execute),
6502 	TEST(ept_access_test_write_execute),
6503 	TEST(ept_access_test_read_write_execute),
6504 	TEST(ept_access_test_reserved_bits),
6505 	TEST(ept_access_test_ignored_bits),
6506 	TEST(ept_access_test_paddr_not_present_ad_disabled),
6507 	TEST(ept_access_test_paddr_not_present_ad_enabled),
6508 	TEST(ept_access_test_paddr_read_only_ad_disabled),
6509 	TEST(ept_access_test_paddr_read_only_ad_enabled),
6510 	TEST(ept_access_test_paddr_read_write),
6511 	TEST(ept_access_test_paddr_read_write_execute),
6512 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
6513 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
6514 	TEST(ept_access_test_paddr_not_present_page_fault),
6515 	TEST(ept_access_test_force_2m_page),
6516 	{ NULL, NULL, NULL, NULL, NULL, {0} },
6517 };
6518