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