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