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