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