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