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