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