xref: /kvm-unit-tests/x86/vmx_tests.c (revision 7efc08a51246b60dbd1bcb3be87f33a1aae928c6)
1 /*
2  * All test cases of nested virtualization should be in this file
3  *
4  * Author : Arthur Chunqi Li <yzt356@gmail.com>
5  */
6 #include "vmx.h"
7 #include "msr.h"
8 #include "processor.h"
9 #include "vm.h"
10 #include "fwcfg.h"
11 #include "isr.h"
12 #include "desc.h"
13 #include "apic.h"
14 #include "types.h"
15 #include "vmalloc.h"
16 #include "alloc_page.h"
17 
18 #define NONCANONICAL            0xaaaaaaaaaaaaaaaaull
19 
20 #define VPID_CAP_INVVPID_TYPES_SHIFT 40
21 
22 u64 ia32_pat;
23 u64 ia32_efer;
24 void *io_bitmap_a, *io_bitmap_b;
25 u16 ioport;
26 
27 unsigned long *pml4;
28 u64 eptp;
29 void *data_page1, *data_page2;
30 
31 void *pml_log;
32 #define PML_INDEX 512
33 
34 static inline unsigned ffs(unsigned x)
35 {
36 	int pos = -1;
37 
38 	__asm__ __volatile__("bsf %1, %%eax; cmovnz %%eax, %0"
39 			     : "+r"(pos) : "rm"(x) : "eax");
40 	return pos + 1;
41 }
42 
43 static inline void vmcall()
44 {
45 	asm volatile("vmcall");
46 }
47 
48 void basic_guest_main()
49 {
50 	report("Basic VMX test", 1);
51 }
52 
53 int basic_exit_handler()
54 {
55 	report("Basic VMX test", 0);
56 	print_vmexit_info();
57 	return VMX_TEST_EXIT;
58 }
59 
60 void vmenter_main()
61 {
62 	u64 rax;
63 	u64 rsp, resume_rsp;
64 
65 	report("test vmlaunch", 1);
66 
67 	asm volatile(
68 		"mov %%rsp, %0\n\t"
69 		"mov %3, %%rax\n\t"
70 		"vmcall\n\t"
71 		"mov %%rax, %1\n\t"
72 		"mov %%rsp, %2\n\t"
73 		: "=r"(rsp), "=r"(rax), "=r"(resume_rsp)
74 		: "g"(0xABCD));
75 	report("test vmresume", (rax == 0xFFFF) && (rsp == resume_rsp));
76 }
77 
78 int vmenter_exit_handler()
79 {
80 	u64 guest_rip;
81 	ulong reason;
82 
83 	guest_rip = vmcs_read(GUEST_RIP);
84 	reason = vmcs_read(EXI_REASON) & 0xff;
85 	switch (reason) {
86 	case VMX_VMCALL:
87 		if (regs.rax != 0xABCD) {
88 			report("test vmresume", 0);
89 			return VMX_TEST_VMEXIT;
90 		}
91 		regs.rax = 0xFFFF;
92 		vmcs_write(GUEST_RIP, guest_rip + 3);
93 		return VMX_TEST_RESUME;
94 	default:
95 		report("test vmresume", 0);
96 		print_vmexit_info();
97 	}
98 	return VMX_TEST_VMEXIT;
99 }
100 
101 u32 preempt_scale;
102 volatile unsigned long long tsc_val;
103 volatile u32 preempt_val;
104 u64 saved_rip;
105 
106 int preemption_timer_init()
107 {
108 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
109 		printf("\tPreemption timer is not supported\n");
110 		return VMX_TEST_EXIT;
111 	}
112 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
113 	preempt_val = 10000000;
114 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
115 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
116 
117 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
118 		printf("\tSave preemption value is not supported\n");
119 
120 	return VMX_TEST_START;
121 }
122 
123 void preemption_timer_main()
124 {
125 	tsc_val = rdtsc();
126 	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
127 		vmx_set_test_stage(0);
128 		vmcall();
129 		if (vmx_get_test_stage() == 1)
130 			vmcall();
131 	}
132 	vmx_set_test_stage(1);
133 	while (vmx_get_test_stage() == 1) {
134 		if (((rdtsc() - tsc_val) >> preempt_scale)
135 				> 10 * preempt_val) {
136 			vmx_set_test_stage(2);
137 			vmcall();
138 		}
139 	}
140 	tsc_val = rdtsc();
141 	asm volatile ("hlt");
142 	vmcall();
143 	vmx_set_test_stage(5);
144 	vmcall();
145 }
146 
147 int preemption_timer_exit_handler()
148 {
149 	bool guest_halted;
150 	u64 guest_rip;
151 	ulong reason;
152 	u32 insn_len;
153 	u32 ctrl_exit;
154 
155 	guest_rip = vmcs_read(GUEST_RIP);
156 	reason = vmcs_read(EXI_REASON) & 0xff;
157 	insn_len = vmcs_read(EXI_INST_LEN);
158 	switch (reason) {
159 	case VMX_PREEMPT:
160 		switch (vmx_get_test_stage()) {
161 		case 1:
162 		case 2:
163 			report("busy-wait for preemption timer",
164 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
165 			       preempt_val);
166 			vmx_set_test_stage(3);
167 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
168 			return VMX_TEST_RESUME;
169 		case 3:
170 			guest_halted =
171 				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
172 			report("preemption timer during hlt",
173 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
174 			       preempt_val && guest_halted);
175 			vmx_set_test_stage(4);
176 			vmcs_write(PIN_CONTROLS,
177 				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
178 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
179 			return VMX_TEST_RESUME;
180 		case 4:
181 			report("preemption timer with 0 value",
182 			       saved_rip == guest_rip);
183 			break;
184 		default:
185 			report("Invalid stage.", false);
186 			print_vmexit_info();
187 			break;
188 		}
189 		break;
190 	case VMX_VMCALL:
191 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
192 		switch (vmx_get_test_stage()) {
193 		case 0:
194 			report("Keep preemption value",
195 			       vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val);
196 			vmx_set_test_stage(1);
197 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
198 			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
199 				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
200 			vmcs_write(EXI_CONTROLS, ctrl_exit);
201 			return VMX_TEST_RESUME;
202 		case 1:
203 			report("Save preemption value",
204 			       vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val);
205 			return VMX_TEST_RESUME;
206 		case 2:
207 			report("busy-wait for preemption timer", 0);
208 			vmx_set_test_stage(3);
209 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
210 			return VMX_TEST_RESUME;
211 		case 3:
212 			report("preemption timer during hlt", 0);
213 			vmx_set_test_stage(4);
214 			/* fall through */
215 		case 4:
216 			vmcs_write(PIN_CONTROLS,
217 				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
218 			vmcs_write(PREEMPT_TIMER_VALUE, 0);
219 			saved_rip = guest_rip + insn_len;
220 			return VMX_TEST_RESUME;
221 		case 5:
222 			report("preemption timer with 0 value (vmcall stage 5)", 0);
223 			break;
224 		default:
225 			// Should not reach here
226 			report("unexpected stage, %d", false,
227 			       vmx_get_test_stage());
228 			print_vmexit_info();
229 			return VMX_TEST_VMEXIT;
230 		}
231 		break;
232 	default:
233 		report("Unknown exit reason, %ld", false, reason);
234 		print_vmexit_info();
235 	}
236 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
237 	return VMX_TEST_VMEXIT;
238 }
239 
240 void msr_bmp_init()
241 {
242 	void *msr_bitmap;
243 	u32 ctrl_cpu0;
244 
245 	msr_bitmap = alloc_page();
246 	memset(msr_bitmap, 0x0, PAGE_SIZE);
247 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
248 	ctrl_cpu0 |= CPU_MSR_BITMAP;
249 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
250 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
251 }
252 
253 static int test_ctrl_pat_init()
254 {
255 	u64 ctrl_ent;
256 	u64 ctrl_exi;
257 
258 	msr_bmp_init();
259 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
260 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
261 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
262 		printf("\tSave/load PAT is not supported\n");
263 		return 1;
264 	}
265 
266 	ctrl_ent = vmcs_read(ENT_CONTROLS);
267 	ctrl_exi = vmcs_read(EXI_CONTROLS);
268 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
269 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
270 	vmcs_write(ENT_CONTROLS, ctrl_ent);
271 	vmcs_write(EXI_CONTROLS, ctrl_exi);
272 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
273 	vmcs_write(GUEST_PAT, 0x0);
274 	vmcs_write(HOST_PAT, ia32_pat);
275 	return VMX_TEST_START;
276 }
277 
278 static void test_ctrl_pat_main()
279 {
280 	u64 guest_ia32_pat;
281 
282 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
283 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
284 		printf("\tENT_LOAD_PAT is not supported.\n");
285 	else {
286 		if (guest_ia32_pat != 0) {
287 			report("Entry load PAT", 0);
288 			return;
289 		}
290 	}
291 	wrmsr(MSR_IA32_CR_PAT, 0x6);
292 	vmcall();
293 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
294 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
295 		report("Entry load PAT", guest_ia32_pat == ia32_pat);
296 }
297 
298 static int test_ctrl_pat_exit_handler()
299 {
300 	u64 guest_rip;
301 	ulong reason;
302 	u64 guest_pat;
303 
304 	guest_rip = vmcs_read(GUEST_RIP);
305 	reason = vmcs_read(EXI_REASON) & 0xff;
306 	switch (reason) {
307 	case VMX_VMCALL:
308 		guest_pat = vmcs_read(GUEST_PAT);
309 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
310 			printf("\tEXI_SAVE_PAT is not supported\n");
311 			vmcs_write(GUEST_PAT, 0x6);
312 		} else {
313 			report("Exit save PAT", guest_pat == 0x6);
314 		}
315 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
316 			printf("\tEXI_LOAD_PAT is not supported\n");
317 		else
318 			report("Exit load PAT", rdmsr(MSR_IA32_CR_PAT) == ia32_pat);
319 		vmcs_write(GUEST_PAT, ia32_pat);
320 		vmcs_write(GUEST_RIP, guest_rip + 3);
321 		return VMX_TEST_RESUME;
322 	default:
323 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
324 		break;
325 	}
326 	return VMX_TEST_VMEXIT;
327 }
328 
329 static int test_ctrl_efer_init()
330 {
331 	u64 ctrl_ent;
332 	u64 ctrl_exi;
333 
334 	msr_bmp_init();
335 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
336 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
337 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
338 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
339 	ia32_efer = rdmsr(MSR_EFER);
340 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
341 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
342 	return VMX_TEST_START;
343 }
344 
345 static void test_ctrl_efer_main()
346 {
347 	u64 guest_ia32_efer;
348 
349 	guest_ia32_efer = rdmsr(MSR_EFER);
350 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
351 		printf("\tENT_LOAD_EFER is not supported.\n");
352 	else {
353 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
354 			report("Entry load EFER", 0);
355 			return;
356 		}
357 	}
358 	wrmsr(MSR_EFER, ia32_efer);
359 	vmcall();
360 	guest_ia32_efer = rdmsr(MSR_EFER);
361 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
362 		report("Entry load EFER", guest_ia32_efer == ia32_efer);
363 }
364 
365 static int test_ctrl_efer_exit_handler()
366 {
367 	u64 guest_rip;
368 	ulong reason;
369 	u64 guest_efer;
370 
371 	guest_rip = vmcs_read(GUEST_RIP);
372 	reason = vmcs_read(EXI_REASON) & 0xff;
373 	switch (reason) {
374 	case VMX_VMCALL:
375 		guest_efer = vmcs_read(GUEST_EFER);
376 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
377 			printf("\tEXI_SAVE_EFER is not supported\n");
378 			vmcs_write(GUEST_EFER, ia32_efer);
379 		} else {
380 			report("Exit save EFER", guest_efer == ia32_efer);
381 		}
382 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
383 			printf("\tEXI_LOAD_EFER is not supported\n");
384 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
385 		} else {
386 			report("Exit load EFER", rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX));
387 		}
388 		vmcs_write(GUEST_PAT, ia32_efer);
389 		vmcs_write(GUEST_RIP, guest_rip + 3);
390 		return VMX_TEST_RESUME;
391 	default:
392 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
393 		break;
394 	}
395 	return VMX_TEST_VMEXIT;
396 }
397 
398 u32 guest_cr0, guest_cr4;
399 
400 static void cr_shadowing_main()
401 {
402 	u32 cr0, cr4, tmp;
403 
404 	// Test read through
405 	vmx_set_test_stage(0);
406 	guest_cr0 = read_cr0();
407 	if (vmx_get_test_stage() == 1)
408 		report("Read through CR0", 0);
409 	else
410 		vmcall();
411 	vmx_set_test_stage(1);
412 	guest_cr4 = read_cr4();
413 	if (vmx_get_test_stage() == 2)
414 		report("Read through CR4", 0);
415 	else
416 		vmcall();
417 	// Test write through
418 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
419 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
420 	vmx_set_test_stage(2);
421 	write_cr0(guest_cr0);
422 	if (vmx_get_test_stage() == 3)
423 		report("Write throuth CR0", 0);
424 	else
425 		vmcall();
426 	vmx_set_test_stage(3);
427 	write_cr4(guest_cr4);
428 	if (vmx_get_test_stage() == 4)
429 		report("Write through CR4", 0);
430 	else
431 		vmcall();
432 	// Test read shadow
433 	vmx_set_test_stage(4);
434 	vmcall();
435 	cr0 = read_cr0();
436 	if (vmx_get_test_stage() != 5)
437 		report("Read shadowing CR0", cr0 == guest_cr0);
438 	vmx_set_test_stage(5);
439 	cr4 = read_cr4();
440 	if (vmx_get_test_stage() != 6)
441 		report("Read shadowing CR4", cr4 == guest_cr4);
442 	// Test write shadow (same value with shadow)
443 	vmx_set_test_stage(6);
444 	write_cr0(guest_cr0);
445 	if (vmx_get_test_stage() == 7)
446 		report("Write shadowing CR0 (same value with shadow)", 0);
447 	else
448 		vmcall();
449 	vmx_set_test_stage(7);
450 	write_cr4(guest_cr4);
451 	if (vmx_get_test_stage() == 8)
452 		report("Write shadowing CR4 (same value with shadow)", 0);
453 	else
454 		vmcall();
455 	// Test write shadow (different value)
456 	vmx_set_test_stage(8);
457 	tmp = guest_cr0 ^ X86_CR0_TS;
458 	asm volatile("mov %0, %%rsi\n\t"
459 		"mov %%rsi, %%cr0\n\t"
460 		::"m"(tmp)
461 		:"rsi", "memory", "cc");
462 	report("Write shadowing different X86_CR0_TS", vmx_get_test_stage() == 9);
463 	vmx_set_test_stage(9);
464 	tmp = guest_cr0 ^ X86_CR0_MP;
465 	asm volatile("mov %0, %%rsi\n\t"
466 		"mov %%rsi, %%cr0\n\t"
467 		::"m"(tmp)
468 		:"rsi", "memory", "cc");
469 	report("Write shadowing different X86_CR0_MP", vmx_get_test_stage() == 10);
470 	vmx_set_test_stage(10);
471 	tmp = guest_cr4 ^ X86_CR4_TSD;
472 	asm volatile("mov %0, %%rsi\n\t"
473 		"mov %%rsi, %%cr4\n\t"
474 		::"m"(tmp)
475 		:"rsi", "memory", "cc");
476 	report("Write shadowing different X86_CR4_TSD", vmx_get_test_stage() == 11);
477 	vmx_set_test_stage(11);
478 	tmp = guest_cr4 ^ X86_CR4_DE;
479 	asm volatile("mov %0, %%rsi\n\t"
480 		"mov %%rsi, %%cr4\n\t"
481 		::"m"(tmp)
482 		:"rsi", "memory", "cc");
483 	report("Write shadowing different X86_CR4_DE", vmx_get_test_stage() == 12);
484 }
485 
486 static int cr_shadowing_exit_handler()
487 {
488 	u64 guest_rip;
489 	ulong reason;
490 	u32 insn_len;
491 	u32 exit_qual;
492 
493 	guest_rip = vmcs_read(GUEST_RIP);
494 	reason = vmcs_read(EXI_REASON) & 0xff;
495 	insn_len = vmcs_read(EXI_INST_LEN);
496 	exit_qual = vmcs_read(EXI_QUALIFICATION);
497 	switch (reason) {
498 	case VMX_VMCALL:
499 		switch (vmx_get_test_stage()) {
500 		case 0:
501 			report("Read through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
502 			break;
503 		case 1:
504 			report("Read through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
505 			break;
506 		case 2:
507 			report("Write through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
508 			break;
509 		case 3:
510 			report("Write through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
511 			break;
512 		case 4:
513 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
514 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
515 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
516 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
517 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
518 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
519 			break;
520 		case 6:
521 			report("Write shadowing CR0 (same value)",
522 					guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)));
523 			break;
524 		case 7:
525 			report("Write shadowing CR4 (same value)",
526 					guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)));
527 			break;
528 		default:
529 			// Should not reach here
530 			report("unexpected stage, %d", false,
531 			       vmx_get_test_stage());
532 			print_vmexit_info();
533 			return VMX_TEST_VMEXIT;
534 		}
535 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
536 		return VMX_TEST_RESUME;
537 	case VMX_CR:
538 		switch (vmx_get_test_stage()) {
539 		case 4:
540 			report("Read shadowing CR0", 0);
541 			vmx_inc_test_stage();
542 			break;
543 		case 5:
544 			report("Read shadowing CR4", 0);
545 			vmx_inc_test_stage();
546 			break;
547 		case 6:
548 			report("Write shadowing CR0 (same value)", 0);
549 			vmx_inc_test_stage();
550 			break;
551 		case 7:
552 			report("Write shadowing CR4 (same value)", 0);
553 			vmx_inc_test_stage();
554 			break;
555 		case 8:
556 		case 9:
557 			// 0x600 encodes "mov %esi, %cr0"
558 			if (exit_qual == 0x600)
559 				vmx_inc_test_stage();
560 			break;
561 		case 10:
562 		case 11:
563 			// 0x604 encodes "mov %esi, %cr4"
564 			if (exit_qual == 0x604)
565 				vmx_inc_test_stage();
566 			break;
567 		default:
568 			// Should not reach here
569 			report("unexpected stage, %d", false,
570 			       vmx_get_test_stage());
571 			print_vmexit_info();
572 			return VMX_TEST_VMEXIT;
573 		}
574 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
575 		return VMX_TEST_RESUME;
576 	default:
577 		report("Unknown exit reason, %ld", false, reason);
578 		print_vmexit_info();
579 	}
580 	return VMX_TEST_VMEXIT;
581 }
582 
583 static int iobmp_init()
584 {
585 	u32 ctrl_cpu0;
586 
587 	io_bitmap_a = alloc_page();
588 	io_bitmap_b = alloc_page();
589 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
590 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
591 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
592 	ctrl_cpu0 |= CPU_IO_BITMAP;
593 	ctrl_cpu0 &= (~CPU_IO);
594 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
595 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
596 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
597 	return VMX_TEST_START;
598 }
599 
600 static void iobmp_main()
601 {
602 	// stage 0, test IO pass
603 	vmx_set_test_stage(0);
604 	inb(0x5000);
605 	outb(0x0, 0x5000);
606 	report("I/O bitmap - I/O pass", vmx_get_test_stage() == 0);
607 	// test IO width, in/out
608 	((u8 *)io_bitmap_a)[0] = 0xFF;
609 	vmx_set_test_stage(2);
610 	inb(0x0);
611 	report("I/O bitmap - trap in", vmx_get_test_stage() == 3);
612 	vmx_set_test_stage(3);
613 	outw(0x0, 0x0);
614 	report("I/O bitmap - trap out", vmx_get_test_stage() == 4);
615 	vmx_set_test_stage(4);
616 	inl(0x0);
617 	report("I/O bitmap - I/O width, long", vmx_get_test_stage() == 5);
618 	// test low/high IO port
619 	vmx_set_test_stage(5);
620 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
621 	inb(0x5000);
622 	report("I/O bitmap - I/O port, low part", vmx_get_test_stage() == 6);
623 	vmx_set_test_stage(6);
624 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
625 	inb(0x9000);
626 	report("I/O bitmap - I/O port, high part", vmx_get_test_stage() == 7);
627 	// test partial pass
628 	vmx_set_test_stage(7);
629 	inl(0x4FFF);
630 	report("I/O bitmap - partial pass", vmx_get_test_stage() == 8);
631 	// test overrun
632 	vmx_set_test_stage(8);
633 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
634 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
635 	inl(0xFFFF);
636 	report("I/O bitmap - overrun", vmx_get_test_stage() == 9);
637 	vmx_set_test_stage(9);
638 	vmcall();
639 	outb(0x0, 0x0);
640 	report("I/O bitmap - ignore unconditional exiting",
641 	       vmx_get_test_stage() == 9);
642 	vmx_set_test_stage(10);
643 	vmcall();
644 	outb(0x0, 0x0);
645 	report("I/O bitmap - unconditional exiting",
646 	       vmx_get_test_stage() == 11);
647 }
648 
649 static int iobmp_exit_handler()
650 {
651 	u64 guest_rip;
652 	ulong reason, exit_qual;
653 	u32 insn_len, ctrl_cpu0;
654 
655 	guest_rip = vmcs_read(GUEST_RIP);
656 	reason = vmcs_read(EXI_REASON) & 0xff;
657 	exit_qual = vmcs_read(EXI_QUALIFICATION);
658 	insn_len = vmcs_read(EXI_INST_LEN);
659 	switch (reason) {
660 	case VMX_IO:
661 		switch (vmx_get_test_stage()) {
662 		case 0:
663 		case 1:
664 			vmx_inc_test_stage();
665 			break;
666 		case 2:
667 			report("I/O bitmap - I/O width, byte",
668 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE);
669 			report("I/O bitmap - I/O direction, in", exit_qual & VMX_IO_IN);
670 			vmx_inc_test_stage();
671 			break;
672 		case 3:
673 			report("I/O bitmap - I/O width, word",
674 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD);
675 			report("I/O bitmap - I/O direction, out",
676 					!(exit_qual & VMX_IO_IN));
677 			vmx_inc_test_stage();
678 			break;
679 		case 4:
680 			report("I/O bitmap - I/O width, long",
681 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG);
682 			vmx_inc_test_stage();
683 			break;
684 		case 5:
685 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
686 				vmx_inc_test_stage();
687 			break;
688 		case 6:
689 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
690 				vmx_inc_test_stage();
691 			break;
692 		case 7:
693 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
694 				vmx_inc_test_stage();
695 			break;
696 		case 8:
697 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
698 				vmx_inc_test_stage();
699 			break;
700 		case 9:
701 		case 10:
702 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
703 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
704 			vmx_inc_test_stage();
705 			break;
706 		default:
707 			// Should not reach here
708 			report("unexpected stage, %d", false,
709 			       vmx_get_test_stage());
710 			print_vmexit_info();
711 			return VMX_TEST_VMEXIT;
712 		}
713 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
714 		return VMX_TEST_RESUME;
715 	case VMX_VMCALL:
716 		switch (vmx_get_test_stage()) {
717 		case 9:
718 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
719 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
720 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
721 			break;
722 		case 10:
723 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
724 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
725 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
726 			break;
727 		default:
728 			// Should not reach here
729 			report("unexpected stage, %d", false,
730 			       vmx_get_test_stage());
731 			print_vmexit_info();
732 			return VMX_TEST_VMEXIT;
733 		}
734 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
735 		return VMX_TEST_RESUME;
736 	default:
737 		printf("guest_rip = %#lx\n", guest_rip);
738 		printf("\tERROR : Undefined exit reason, reason = %ld.\n", reason);
739 		break;
740 	}
741 	return VMX_TEST_VMEXIT;
742 }
743 
744 #define INSN_CPU0		0
745 #define INSN_CPU1		1
746 #define INSN_ALWAYS_TRAP	2
747 
748 #define FIELD_EXIT_QUAL		(1 << 0)
749 #define FIELD_INSN_INFO		(1 << 1)
750 
751 asm(
752 	"insn_hlt: hlt;ret\n\t"
753 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
754 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
755 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
756 	"insn_rdtsc: rdtsc;ret\n\t"
757 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
758 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
759 #ifdef __x86_64__
760 	"insn_cr8_load: mov %rax,%cr8;ret\n\t"
761 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
762 #endif
763 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
764 	"insn_pause: pause;ret\n\t"
765 	"insn_wbinvd: wbinvd;ret\n\t"
766 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
767 	"insn_invd: invd;ret\n\t"
768 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
769 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
770 	"insn_sidt: sidt idt_descr;ret\n\t"
771 	"insn_lidt: lidt idt_descr;ret\n\t"
772 	"insn_sldt: sldt %ax;ret\n\t"
773 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
774 	"insn_str: str %ax;ret\n\t"
775 	"insn_rdrand: rdrand %rax;ret\n\t"
776 	"insn_rdseed: rdseed %rax;ret\n\t"
777 );
778 extern void insn_hlt();
779 extern void insn_invlpg();
780 extern void insn_mwait();
781 extern void insn_rdpmc();
782 extern void insn_rdtsc();
783 extern void insn_cr3_load();
784 extern void insn_cr3_store();
785 #ifdef __x86_64__
786 extern void insn_cr8_load();
787 extern void insn_cr8_store();
788 #endif
789 extern void insn_monitor();
790 extern void insn_pause();
791 extern void insn_wbinvd();
792 extern void insn_sgdt();
793 extern void insn_lgdt();
794 extern void insn_sidt();
795 extern void insn_lidt();
796 extern void insn_sldt();
797 extern void insn_lldt();
798 extern void insn_str();
799 extern void insn_cpuid();
800 extern void insn_invd();
801 extern void insn_rdrand();
802 extern void insn_rdseed();
803 
804 u32 cur_insn;
805 u64 cr3;
806 
807 struct insn_table {
808 	const char *name;
809 	u32 flag;
810 	void (*insn_func)();
811 	u32 type;
812 	u32 reason;
813 	ulong exit_qual;
814 	u32 insn_info;
815 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
816 	// which field need to be tested, reason is always tested
817 	u32 test_field;
818 };
819 
820 /*
821  * Add more test cases of instruction intercept here. Elements in this
822  * table is:
823  *	name/control flag/insn function/type/exit reason/exit qulification/
824  *	instruction info/field to test
825  * The last field defines which fields (exit_qual and insn_info) need to be
826  * tested in exit handler. If set to 0, only "reason" is checked.
827  */
828 static struct insn_table insn_table[] = {
829 	// Flags for Primary Processor-Based VM-Execution Controls
830 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
831 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
832 		0x12345678, 0, FIELD_EXIT_QUAL},
833 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0},
834 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
835 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
836 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
837 		FIELD_EXIT_QUAL},
838 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
839 		FIELD_EXIT_QUAL},
840 #ifdef __x86_64__
841 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
842 		FIELD_EXIT_QUAL},
843 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
844 		FIELD_EXIT_QUAL},
845 #endif
846 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0},
847 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
848 	// Flags for Secondary Processor-Based VM-Execution Controls
849 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
850 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
851 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
852 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
853 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
854 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
855 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
856 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
857 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
858 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
859 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
860 	// Instructions always trap
861 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
862 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
863 	// Instructions never trap
864 	{NULL},
865 };
866 
867 static int insn_intercept_init()
868 {
869 	u32 ctrl_cpu;
870 
871 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
872 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
873 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
874 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
875 	cr3 = read_cr3();
876 	return VMX_TEST_START;
877 }
878 
879 static void insn_intercept_main()
880 {
881 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
882 		vmx_set_test_stage(cur_insn * 2);
883 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
884 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
885 		    (insn_table[cur_insn].type == INSN_CPU1 &&
886 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
887 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
888 			       insn_table[cur_insn].type - INSN_CPU0,
889 			       insn_table[cur_insn].name);
890 			continue;
891 		}
892 
893 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
894 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
895 		    (insn_table[cur_insn].type == INSN_CPU1 &&
896 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
897 			/* skip hlt, it stalls the guest and is tested below */
898 			if (insn_table[cur_insn].insn_func != insn_hlt)
899 				insn_table[cur_insn].insn_func();
900 			report("execute %s", vmx_get_test_stage() == cur_insn * 2,
901 					insn_table[cur_insn].name);
902 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
903 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
904 			       insn_table[cur_insn].type - INSN_CPU0,
905 			       insn_table[cur_insn].name);
906 
907 		vmcall();
908 
909 		insn_table[cur_insn].insn_func();
910 		report("intercept %s", vmx_get_test_stage() == cur_insn * 2 + 1,
911 				insn_table[cur_insn].name);
912 
913 		vmx_set_test_stage(cur_insn * 2 + 1);
914 		vmcall();
915 	}
916 }
917 
918 static int insn_intercept_exit_handler()
919 {
920 	u64 guest_rip;
921 	u32 reason;
922 	ulong exit_qual;
923 	u32 insn_len;
924 	u32 insn_info;
925 	bool pass;
926 
927 	guest_rip = vmcs_read(GUEST_RIP);
928 	reason = vmcs_read(EXI_REASON) & 0xff;
929 	exit_qual = vmcs_read(EXI_QUALIFICATION);
930 	insn_len = vmcs_read(EXI_INST_LEN);
931 	insn_info = vmcs_read(EXI_INST_INFO);
932 
933 	if (reason == VMX_VMCALL) {
934 		u32 val = 0;
935 
936 		if (insn_table[cur_insn].type == INSN_CPU0)
937 			val = vmcs_read(CPU_EXEC_CTRL0);
938 		else if (insn_table[cur_insn].type == INSN_CPU1)
939 			val = vmcs_read(CPU_EXEC_CTRL1);
940 
941 		if (vmx_get_test_stage() & 1)
942 			val &= ~insn_table[cur_insn].flag;
943 		else
944 			val |= insn_table[cur_insn].flag;
945 
946 		if (insn_table[cur_insn].type == INSN_CPU0)
947 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
948 		else if (insn_table[cur_insn].type == INSN_CPU1)
949 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
950 	} else {
951 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
952 			insn_table[cur_insn].reason == reason;
953 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
954 		    insn_table[cur_insn].exit_qual != exit_qual)
955 			pass = false;
956 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
957 		    insn_table[cur_insn].insn_info != insn_info)
958 			pass = false;
959 		if (pass)
960 			vmx_inc_test_stage();
961 	}
962 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
963 	return VMX_TEST_RESUME;
964 }
965 
966 
967 /* Enables EPT and sets up the identity map. */
968 static int setup_ept(bool enable_ad)
969 {
970 	unsigned long end_of_memory;
971 	u32 ctrl_cpu[2];
972 
973 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
974 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
975 		printf("\tEPT is not supported");
976 		return 1;
977 	}
978 
979 
980 	if (!(ept_vpid.val & EPT_CAP_UC) &&
981 			!(ept_vpid.val & EPT_CAP_WB)) {
982 		printf("\tEPT paging-structure memory type "
983 				"UC&WB are not supported\n");
984 		return 1;
985 	}
986 	if (ept_vpid.val & EPT_CAP_UC)
987 		eptp = EPT_MEM_TYPE_UC;
988 	else
989 		eptp = EPT_MEM_TYPE_WB;
990 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
991 		printf("\tPWL4 is not supported\n");
992 		return 1;
993 	}
994 	ctrl_cpu[0] = vmcs_read(CPU_EXEC_CTRL0);
995 	ctrl_cpu[1] = vmcs_read(CPU_EXEC_CTRL1);
996 	ctrl_cpu[0] = (ctrl_cpu[0] | CPU_SECONDARY)
997 		& ctrl_cpu_rev[0].clr;
998 	ctrl_cpu[1] = (ctrl_cpu[1] | CPU_EPT)
999 		& ctrl_cpu_rev[1].clr;
1000 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu[0]);
1001 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu[1]);
1002 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1003 	pml4 = alloc_page();
1004 	memset(pml4, 0, PAGE_SIZE);
1005 	eptp |= virt_to_phys(pml4);
1006 	if (enable_ad)
1007 		eptp |= EPTP_AD_FLAG;
1008 	vmcs_write(EPTP, eptp);
1009 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1010 	if (end_of_memory < (1ul << 32))
1011 		end_of_memory = (1ul << 32);
1012 	/* Cannot use large EPT pages if we need to track EPT
1013 	 * accessed/dirty bits at 4K granularity.
1014 	 */
1015 	setup_ept_range(pml4, 0, end_of_memory, 0,
1016 			!enable_ad && ept_2m_supported(),
1017 			EPT_WA | EPT_RA | EPT_EA);
1018 	return 0;
1019 }
1020 
1021 static void ept_enable_ad_bits(void)
1022 {
1023 	eptp |= EPTP_AD_FLAG;
1024 	vmcs_write(EPTP, eptp);
1025 }
1026 
1027 static void ept_disable_ad_bits(void)
1028 {
1029 	eptp &= ~EPTP_AD_FLAG;
1030 	vmcs_write(EPTP, eptp);
1031 }
1032 
1033 static void ept_enable_ad_bits_or_skip_test(void)
1034 {
1035 	if (!ept_ad_bits_supported())
1036 		test_skip("EPT AD bits not supported.");
1037 	ept_enable_ad_bits();
1038 }
1039 
1040 static int apic_version;
1041 
1042 static int ept_init_common(bool have_ad)
1043 {
1044 	if (setup_ept(have_ad))
1045 		return VMX_TEST_EXIT;
1046 	data_page1 = alloc_page();
1047 	data_page2 = alloc_page();
1048 	memset(data_page1, 0x0, PAGE_SIZE);
1049 	memset(data_page2, 0x0, PAGE_SIZE);
1050 	*((u32 *)data_page1) = MAGIC_VAL_1;
1051 	*((u32 *)data_page2) = MAGIC_VAL_2;
1052 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1053 			EPT_RA | EPT_WA | EPT_EA);
1054 
1055 	apic_version = apic_read(APIC_LVR);
1056 	return VMX_TEST_START;
1057 }
1058 
1059 static int ept_init()
1060 {
1061 	return ept_init_common(false);
1062 }
1063 
1064 static void ept_common()
1065 {
1066 	vmx_set_test_stage(0);
1067 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1068 			*((u32 *)data_page1) != MAGIC_VAL_1)
1069 		report("EPT basic framework - read", 0);
1070 	else {
1071 		*((u32 *)data_page2) = MAGIC_VAL_3;
1072 		vmcall();
1073 		if (vmx_get_test_stage() == 1) {
1074 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1075 					*((u32 *)data_page2) == MAGIC_VAL_2)
1076 				report("EPT basic framework", 1);
1077 			else
1078 				report("EPT basic framework - remap", 1);
1079 		}
1080 	}
1081 	// Test EPT Misconfigurations
1082 	vmx_set_test_stage(1);
1083 	vmcall();
1084 	*((u32 *)data_page1) = MAGIC_VAL_1;
1085 	if (vmx_get_test_stage() != 2) {
1086 		report("EPT misconfigurations", 0);
1087 		goto t1;
1088 	}
1089 	vmx_set_test_stage(2);
1090 	vmcall();
1091 	*((u32 *)data_page1) = MAGIC_VAL_1;
1092 	report("EPT misconfigurations", vmx_get_test_stage() == 3);
1093 t1:
1094 	// Test EPT violation
1095 	vmx_set_test_stage(3);
1096 	vmcall();
1097 	*((u32 *)data_page1) = MAGIC_VAL_1;
1098 	report("EPT violation - page permission", vmx_get_test_stage() == 4);
1099 	// Violation caused by EPT paging structure
1100 	vmx_set_test_stage(4);
1101 	vmcall();
1102 	*((u32 *)data_page1) = MAGIC_VAL_2;
1103 	report("EPT violation - paging structure", vmx_get_test_stage() == 5);
1104 }
1105 
1106 static void ept_main()
1107 {
1108 	ept_common();
1109 
1110 	// Test EPT access to L1 MMIO
1111 	vmx_set_test_stage(6);
1112 	report("EPT - MMIO access", *((u32 *)0xfee00030UL) == apic_version);
1113 
1114 	// Test invalid operand for INVEPT
1115 	vmcall();
1116 	report("EPT - unsupported INVEPT", vmx_get_test_stage() == 7);
1117 }
1118 
1119 bool invept_test(int type, u64 eptp)
1120 {
1121 	bool ret, supported;
1122 
1123 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1124 	ret = invept(type, eptp);
1125 
1126 	if (ret == !supported)
1127 		return false;
1128 
1129 	if (!supported)
1130 		printf("WARNING: unsupported invept passed!\n");
1131 	else
1132 		printf("WARNING: invept failed!\n");
1133 
1134 	return true;
1135 }
1136 
1137 static int pml_exit_handler(void)
1138 {
1139 	u16 index, count;
1140 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1141 	u64 *pmlbuf = pml_log;
1142 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1143 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1144 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1145 
1146 	switch (reason) {
1147 	case VMX_VMCALL:
1148 		switch (vmx_get_test_stage()) {
1149 		case 0:
1150 			index = vmcs_read(GUEST_PML_INDEX);
1151 			for (count = index + 1; count < PML_INDEX; count++) {
1152 				if (pmlbuf[count] == (u64)data_page2) {
1153 					vmx_inc_test_stage();
1154 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1155 					break;
1156 				}
1157 			}
1158 			break;
1159 		case 1:
1160 			index = vmcs_read(GUEST_PML_INDEX);
1161 			/* Keep clearing the dirty bit till a overflow */
1162 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1163 			break;
1164 		default:
1165 			report("unexpected stage, %d.", false,
1166 			       vmx_get_test_stage());
1167 			print_vmexit_info();
1168 			return VMX_TEST_VMEXIT;
1169 		}
1170 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1171 		return VMX_TEST_RESUME;
1172 	case VMX_PML_FULL:
1173 		vmx_inc_test_stage();
1174 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1175 		return VMX_TEST_RESUME;
1176 	default:
1177 		report("Unknown exit reason, %ld", false, reason);
1178 		print_vmexit_info();
1179 	}
1180 	return VMX_TEST_VMEXIT;
1181 }
1182 
1183 static int ept_exit_handler_common(bool have_ad)
1184 {
1185 	u64 guest_rip;
1186 	u64 guest_cr3;
1187 	ulong reason;
1188 	u32 insn_len;
1189 	u32 exit_qual;
1190 	static unsigned long data_page1_pte, data_page1_pte_pte;
1191 
1192 	guest_rip = vmcs_read(GUEST_RIP);
1193 	guest_cr3 = vmcs_read(GUEST_CR3);
1194 	reason = vmcs_read(EXI_REASON) & 0xff;
1195 	insn_len = vmcs_read(EXI_INST_LEN);
1196 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1197 	switch (reason) {
1198 	case VMX_VMCALL:
1199 		switch (vmx_get_test_stage()) {
1200 		case 0:
1201 			check_ept_ad(pml4, guest_cr3,
1202 				     (unsigned long)data_page1,
1203 				     have_ad ? EPT_ACCESS_FLAG : 0,
1204 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1205 			check_ept_ad(pml4, guest_cr3,
1206 				     (unsigned long)data_page2,
1207 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1208 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1209 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1210 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1211 			if (have_ad)
1212 				ept_sync(INVEPT_SINGLE, eptp);;
1213 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1214 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1215 				vmx_inc_test_stage();
1216 				install_ept(pml4, (unsigned long)data_page2,
1217 						(unsigned long)data_page2,
1218 						EPT_RA | EPT_WA | EPT_EA);
1219 			} else
1220 				report("EPT basic framework - write", 0);
1221 			break;
1222 		case 1:
1223 			install_ept(pml4, (unsigned long)data_page1,
1224  				(unsigned long)data_page1, EPT_WA);
1225 			ept_sync(INVEPT_SINGLE, eptp);
1226 			break;
1227 		case 2:
1228 			install_ept(pml4, (unsigned long)data_page1,
1229  				(unsigned long)data_page1,
1230  				EPT_RA | EPT_WA | EPT_EA |
1231  				(2 << EPT_MEM_TYPE_SHIFT));
1232 			ept_sync(INVEPT_SINGLE, eptp);
1233 			break;
1234 		case 3:
1235 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1236 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1237 						1, &data_page1_pte));
1238 			set_ept_pte(pml4, (unsigned long)data_page1,
1239 				1, data_page1_pte & ~EPT_PRESENT);
1240 			ept_sync(INVEPT_SINGLE, eptp);
1241 			break;
1242 		case 4:
1243 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1244 						2, &data_page1_pte));
1245 			data_page1_pte &= PAGE_MASK;
1246 			TEST_ASSERT(get_ept_pte(pml4, data_page1_pte,
1247 						2, &data_page1_pte_pte));
1248 			set_ept_pte(pml4, data_page1_pte, 2,
1249 				data_page1_pte_pte & ~EPT_PRESENT);
1250 			ept_sync(INVEPT_SINGLE, eptp);
1251 			break;
1252 		case 6:
1253 			if (!invept_test(0, eptp))
1254 				vmx_inc_test_stage();
1255 			break;
1256 		// Should not reach here
1257 		default:
1258 			report("ERROR - unexpected stage, %d.", false,
1259 			       vmx_get_test_stage());
1260 			print_vmexit_info();
1261 			return VMX_TEST_VMEXIT;
1262 		}
1263 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1264 		return VMX_TEST_RESUME;
1265 	case VMX_EPT_MISCONFIG:
1266 		switch (vmx_get_test_stage()) {
1267 		case 1:
1268 		case 2:
1269 			vmx_inc_test_stage();
1270 			install_ept(pml4, (unsigned long)data_page1,
1271  				(unsigned long)data_page1,
1272  				EPT_RA | EPT_WA | EPT_EA);
1273 			ept_sync(INVEPT_SINGLE, eptp);
1274 			break;
1275 		// Should not reach here
1276 		default:
1277 			report("ERROR - unexpected stage, %d.", false,
1278 			       vmx_get_test_stage());
1279 			print_vmexit_info();
1280 			return VMX_TEST_VMEXIT;
1281 		}
1282 		return VMX_TEST_RESUME;
1283 	case VMX_EPT_VIOLATION:
1284 		switch(vmx_get_test_stage()) {
1285 		case 3:
1286 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1287 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1288 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1289 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1290 					EPT_VLT_PADDR))
1291 				vmx_inc_test_stage();
1292 			set_ept_pte(pml4, (unsigned long)data_page1,
1293 				1, data_page1_pte | (EPT_PRESENT));
1294 			ept_sync(INVEPT_SINGLE, eptp);
1295 			break;
1296 		case 4:
1297 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1298 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1299 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1300 			if (exit_qual == (EPT_VLT_RD |
1301 					  (have_ad ? EPT_VLT_WR : 0) |
1302 					  EPT_VLT_LADDR_VLD))
1303 				vmx_inc_test_stage();
1304 			set_ept_pte(pml4, data_page1_pte, 2,
1305 				data_page1_pte_pte | (EPT_PRESENT));
1306 			ept_sync(INVEPT_SINGLE, eptp);
1307 			break;
1308 		default:
1309 			// Should not reach here
1310 			report("ERROR : unexpected stage, %d", false,
1311 			       vmx_get_test_stage());
1312 			print_vmexit_info();
1313 			return VMX_TEST_VMEXIT;
1314 		}
1315 		return VMX_TEST_RESUME;
1316 	default:
1317 		report("Unknown exit reason, %ld", false, reason);
1318 		print_vmexit_info();
1319 	}
1320 	return VMX_TEST_VMEXIT;
1321 }
1322 
1323 static int ept_exit_handler()
1324 {
1325 	return ept_exit_handler_common(false);
1326 }
1327 
1328 static int eptad_init()
1329 {
1330 	int r = ept_init_common(true);
1331 
1332 	if (r == VMX_TEST_EXIT)
1333 		return r;
1334 
1335 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1336 		printf("\tEPT A/D bits are not supported");
1337 		return VMX_TEST_EXIT;
1338 	}
1339 
1340 	return r;
1341 }
1342 
1343 static int pml_init()
1344 {
1345 	u32 ctrl_cpu;
1346 	int r = eptad_init();
1347 
1348 	if (r == VMX_TEST_EXIT)
1349 		return r;
1350 
1351 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1352 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1353 		printf("\tPML is not supported");
1354 		return VMX_TEST_EXIT;
1355 	}
1356 
1357 	pml_log = alloc_page();
1358 	memset(pml_log, 0x0, PAGE_SIZE);
1359 	vmcs_write(PMLADDR, (u64)pml_log);
1360 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1361 
1362 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1363 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1364 
1365 	return VMX_TEST_START;
1366 }
1367 
1368 static void pml_main()
1369 {
1370 	int count = 0;
1371 
1372 	vmx_set_test_stage(0);
1373 	*((u32 *)data_page2) = 0x1;
1374 	vmcall();
1375 	report("PML - Dirty GPA Logging", vmx_get_test_stage() == 1);
1376 
1377 	while (vmx_get_test_stage() == 1) {
1378 		vmcall();
1379 		*((u32 *)data_page2) = 0x1;
1380 		if (count++ > PML_INDEX)
1381 			break;
1382 	}
1383 	report("PML Full Event", vmx_get_test_stage() == 2);
1384 }
1385 
1386 static void eptad_main()
1387 {
1388 	ept_common();
1389 }
1390 
1391 static int eptad_exit_handler()
1392 {
1393 	return ept_exit_handler_common(true);
1394 }
1395 
1396 bool invvpid_test(int type, u16 vpid)
1397 {
1398 	bool ret, supported;
1399 
1400 	supported = ept_vpid.val &
1401 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1402 	ret = invvpid(type, vpid, 0);
1403 
1404 	if (ret == !supported)
1405 		return false;
1406 
1407 	if (!supported)
1408 		printf("WARNING: unsupported invvpid passed!\n");
1409 	else
1410 		printf("WARNING: invvpid failed!\n");
1411 
1412 	return true;
1413 }
1414 
1415 static int vpid_init()
1416 {
1417 	u32 ctrl_cpu1;
1418 
1419 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1420 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1421 		printf("\tVPID is not supported");
1422 		return VMX_TEST_EXIT;
1423 	}
1424 
1425 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1426 	ctrl_cpu1 |= CPU_VPID;
1427 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1428 	return VMX_TEST_START;
1429 }
1430 
1431 static void vpid_main()
1432 {
1433 	vmx_set_test_stage(0);
1434 	vmcall();
1435 	report("INVVPID SINGLE ADDRESS", vmx_get_test_stage() == 1);
1436 	vmx_set_test_stage(2);
1437 	vmcall();
1438 	report("INVVPID SINGLE", vmx_get_test_stage() == 3);
1439 	vmx_set_test_stage(4);
1440 	vmcall();
1441 	report("INVVPID ALL", vmx_get_test_stage() == 5);
1442 }
1443 
1444 static int vpid_exit_handler()
1445 {
1446 	u64 guest_rip;
1447 	ulong reason;
1448 	u32 insn_len;
1449 
1450 	guest_rip = vmcs_read(GUEST_RIP);
1451 	reason = vmcs_read(EXI_REASON) & 0xff;
1452 	insn_len = vmcs_read(EXI_INST_LEN);
1453 
1454 	switch (reason) {
1455 	case VMX_VMCALL:
1456 		switch(vmx_get_test_stage()) {
1457 		case 0:
1458 			if (!invvpid_test(INVVPID_ADDR, 1))
1459 				vmx_inc_test_stage();
1460 			break;
1461 		case 2:
1462 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1463 				vmx_inc_test_stage();
1464 			break;
1465 		case 4:
1466 			if (!invvpid_test(INVVPID_ALL, 1))
1467 				vmx_inc_test_stage();
1468 			break;
1469 		default:
1470 			report("ERROR: unexpected stage, %d", false,
1471 					vmx_get_test_stage());
1472 			print_vmexit_info();
1473 			return VMX_TEST_VMEXIT;
1474 		}
1475 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1476 		return VMX_TEST_RESUME;
1477 	default:
1478 		report("Unknown exit reason, %ld", false, reason);
1479 		print_vmexit_info();
1480 	}
1481 	return VMX_TEST_VMEXIT;
1482 }
1483 
1484 #define TIMER_VECTOR	222
1485 
1486 static volatile bool timer_fired;
1487 
1488 static void timer_isr(isr_regs_t *regs)
1489 {
1490 	timer_fired = true;
1491 	apic_write(APIC_EOI, 0);
1492 }
1493 
1494 static int interrupt_init(struct vmcs *vmcs)
1495 {
1496 	msr_bmp_init();
1497 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1498 	handle_irq(TIMER_VECTOR, timer_isr);
1499 	return VMX_TEST_START;
1500 }
1501 
1502 static void interrupt_main(void)
1503 {
1504 	long long start, loops;
1505 
1506 	vmx_set_test_stage(0);
1507 
1508 	apic_write(APIC_LVTT, TIMER_VECTOR);
1509 	irq_enable();
1510 
1511 	apic_write(APIC_TMICT, 1);
1512 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1513 		asm volatile ("nop");
1514 	report("direct interrupt while running guest", timer_fired);
1515 
1516 	apic_write(APIC_TMICT, 0);
1517 	irq_disable();
1518 	vmcall();
1519 	timer_fired = false;
1520 	apic_write(APIC_TMICT, 1);
1521 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1522 		asm volatile ("nop");
1523 	report("intercepted interrupt while running guest", timer_fired);
1524 
1525 	irq_enable();
1526 	apic_write(APIC_TMICT, 0);
1527 	irq_disable();
1528 	vmcall();
1529 	timer_fired = false;
1530 	start = rdtsc();
1531 	apic_write(APIC_TMICT, 1000000);
1532 
1533 	asm volatile ("sti; hlt");
1534 
1535 	report("direct interrupt + hlt",
1536 	       rdtsc() - start > 1000000 && timer_fired);
1537 
1538 	apic_write(APIC_TMICT, 0);
1539 	irq_disable();
1540 	vmcall();
1541 	timer_fired = false;
1542 	start = rdtsc();
1543 	apic_write(APIC_TMICT, 1000000);
1544 
1545 	asm volatile ("sti; hlt");
1546 
1547 	report("intercepted interrupt + hlt",
1548 	       rdtsc() - start > 10000 && timer_fired);
1549 
1550 	apic_write(APIC_TMICT, 0);
1551 	irq_disable();
1552 	vmcall();
1553 	timer_fired = false;
1554 	start = rdtsc();
1555 	apic_write(APIC_TMICT, 1000000);
1556 
1557 	irq_enable();
1558 	asm volatile ("nop");
1559 	vmcall();
1560 
1561 	report("direct interrupt + activity state hlt",
1562 	       rdtsc() - start > 10000 && timer_fired);
1563 
1564 	apic_write(APIC_TMICT, 0);
1565 	irq_disable();
1566 	vmcall();
1567 	timer_fired = false;
1568 	start = rdtsc();
1569 	apic_write(APIC_TMICT, 1000000);
1570 
1571 	irq_enable();
1572 	asm volatile ("nop");
1573 	vmcall();
1574 
1575 	report("intercepted interrupt + activity state hlt",
1576 	       rdtsc() - start > 10000 && timer_fired);
1577 
1578 	apic_write(APIC_TMICT, 0);
1579 	irq_disable();
1580 	vmx_set_test_stage(7);
1581 	vmcall();
1582 	timer_fired = false;
1583 	apic_write(APIC_TMICT, 1);
1584 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1585 		asm volatile ("nop");
1586 	report("running a guest with interrupt acknowledgement set", timer_fired);
1587 }
1588 
1589 static int interrupt_exit_handler(void)
1590 {
1591 	u64 guest_rip = vmcs_read(GUEST_RIP);
1592 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1593 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1594 
1595 	switch (reason) {
1596 	case VMX_VMCALL:
1597 		switch (vmx_get_test_stage()) {
1598 		case 0:
1599 		case 2:
1600 		case 5:
1601 			vmcs_write(PIN_CONTROLS,
1602 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1603 			break;
1604 		case 7:
1605 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1606 			vmcs_write(PIN_CONTROLS,
1607 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1608 			break;
1609 		case 1:
1610 		case 3:
1611 			vmcs_write(PIN_CONTROLS,
1612 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1613 			break;
1614 		case 4:
1615 		case 6:
1616 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1617 			break;
1618 		}
1619 		vmx_inc_test_stage();
1620 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1621 		return VMX_TEST_RESUME;
1622 	case VMX_EXTINT:
1623 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1624 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1625 			handle_external_interrupt(vector);
1626 		} else {
1627 			irq_enable();
1628 			asm volatile ("nop");
1629 			irq_disable();
1630 		}
1631 		if (vmx_get_test_stage() >= 2)
1632 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1633 		return VMX_TEST_RESUME;
1634 	default:
1635 		report("Unknown exit reason, %ld", false, reason);
1636 		print_vmexit_info();
1637 	}
1638 
1639 	return VMX_TEST_VMEXIT;
1640 }
1641 
1642 static int dbgctls_init(struct vmcs *vmcs)
1643 {
1644 	u64 dr7 = 0x402;
1645 	u64 zero = 0;
1646 
1647 	msr_bmp_init();
1648 	asm volatile(
1649 		"mov %0,%%dr0\n\t"
1650 		"mov %0,%%dr1\n\t"
1651 		"mov %0,%%dr2\n\t"
1652 		"mov %1,%%dr7\n\t"
1653 		: : "r" (zero), "r" (dr7));
1654 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1655 	vmcs_write(GUEST_DR7, 0x404);
1656 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1657 
1658 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1659 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1660 
1661 	return VMX_TEST_START;
1662 }
1663 
1664 static void dbgctls_main(void)
1665 {
1666 	u64 dr7, debugctl;
1667 
1668 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1669 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1670 	/* Commented out: KVM does not support DEBUGCTL so far */
1671 	(void)debugctl;
1672 	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);
1673 
1674 	dr7 = 0x408;
1675 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1676 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1677 
1678 	vmx_set_test_stage(0);
1679 	vmcall();
1680 	report("Save debug controls", vmx_get_test_stage() == 1);
1681 
1682 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1683 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1684 		printf("\tDebug controls are always loaded/saved\n");
1685 		return;
1686 	}
1687 	vmx_set_test_stage(2);
1688 	vmcall();
1689 
1690 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1691 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1692 	/* Commented out: KVM does not support DEBUGCTL so far */
1693 	(void)debugctl;
1694 	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);
1695 
1696 	dr7 = 0x408;
1697 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1698 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1699 
1700 	vmx_set_test_stage(3);
1701 	vmcall();
1702 	report("Don't save debug controls", vmx_get_test_stage() == 4);
1703 }
1704 
1705 static int dbgctls_exit_handler(void)
1706 {
1707 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1708 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1709 	u64 guest_rip = vmcs_read(GUEST_RIP);
1710 	u64 dr7, debugctl;
1711 
1712 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1713 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1714 
1715 	switch (reason) {
1716 	case VMX_VMCALL:
1717 		switch (vmx_get_test_stage()) {
1718 		case 0:
1719 			if (dr7 == 0x400 && debugctl == 0 &&
1720 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1721 			    Commented out: KVM does not support DEBUGCTL so far
1722 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1723 				vmx_inc_test_stage();
1724 			break;
1725 		case 2:
1726 			dr7 = 0x402;
1727 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1728 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1729 			vmcs_write(GUEST_DR7, 0x404);
1730 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1731 
1732 			vmcs_write(ENT_CONTROLS,
1733 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1734 			vmcs_write(EXI_CONTROLS,
1735 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1736 			break;
1737 		case 3:
1738 			if (dr7 == 0x400 && debugctl == 0 &&
1739 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1740 			    Commented out: KVM does not support DEBUGCTL so far
1741 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1742 				vmx_inc_test_stage();
1743 			break;
1744 		}
1745 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1746 		return VMX_TEST_RESUME;
1747 	default:
1748 		report("Unknown exit reason, %d", false, reason);
1749 		print_vmexit_info();
1750 	}
1751 	return VMX_TEST_VMEXIT;
1752 }
1753 
1754 struct vmx_msr_entry {
1755 	u32 index;
1756 	u32 reserved;
1757 	u64 value;
1758 } __attribute__((packed));
1759 
1760 #define MSR_MAGIC 0x31415926
1761 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1762 
1763 static int msr_switch_init(struct vmcs *vmcs)
1764 {
1765 	msr_bmp_init();
1766 	exit_msr_store = alloc_page();
1767 	exit_msr_load = alloc_page();
1768 	entry_msr_load = alloc_page();
1769 	memset(exit_msr_store, 0, PAGE_SIZE);
1770 	memset(exit_msr_load, 0, PAGE_SIZE);
1771 	memset(entry_msr_load, 0, PAGE_SIZE);
1772 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1773 	entry_msr_load[0].value = MSR_MAGIC;
1774 
1775 	vmx_set_test_stage(1);
1776 	vmcs_write(ENT_MSR_LD_CNT, 1);
1777 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1778 	vmcs_write(EXI_MSR_ST_CNT, 1);
1779 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1780 	vmcs_write(EXI_MSR_LD_CNT, 1);
1781 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1782 	return VMX_TEST_START;
1783 }
1784 
1785 static void msr_switch_main()
1786 {
1787 	if (vmx_get_test_stage() == 1) {
1788 		report("VM entry MSR load",
1789 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
1790 		vmx_set_test_stage(2);
1791 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1792 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1793 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1794 		exit_msr_load[0].value = MSR_MAGIC + 2;
1795 	}
1796 	vmcall();
1797 }
1798 
1799 static int msr_switch_exit_handler()
1800 {
1801 	ulong reason;
1802 
1803 	reason = vmcs_read(EXI_REASON);
1804 	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
1805 		report("VM exit MSR store",
1806 			exit_msr_store[0].value == MSR_MAGIC + 1);
1807 		report("VM exit MSR load",
1808 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
1809 		vmx_set_test_stage(3);
1810 		entry_msr_load[0].index = MSR_FS_BASE;
1811 		return VMX_TEST_RESUME;
1812 	}
1813 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1814 		__func__, vmx_get_test_stage(), reason);
1815 	return VMX_TEST_EXIT;
1816 }
1817 
1818 static int msr_switch_entry_failure(struct vmentry_failure *failure)
1819 {
1820 	ulong reason;
1821 
1822 	if (failure->early) {
1823 		printf("ERROR %s: early exit\n", __func__);
1824 		return VMX_TEST_EXIT;
1825 	}
1826 
1827 	reason = vmcs_read(EXI_REASON);
1828 	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
1829 	    vmx_get_test_stage() == 3) {
1830 		report("VM entry MSR load: try to load FS_BASE",
1831 			vmcs_read(EXI_QUALIFICATION) == 1);
1832 		return VMX_TEST_VMEXIT;
1833 	}
1834 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1835 		__func__, vmx_get_test_stage(), reason);
1836 	return VMX_TEST_EXIT;
1837 }
1838 
1839 static int vmmcall_init(struct vmcs *vmcs	)
1840 {
1841 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1842 	return VMX_TEST_START;
1843 }
1844 
1845 static void vmmcall_main(void)
1846 {
1847 	asm volatile(
1848 		"mov $0xABCD, %%rax\n\t"
1849 		"vmmcall\n\t"
1850 		::: "rax");
1851 
1852 	report("VMMCALL", 0);
1853 }
1854 
1855 static int vmmcall_exit_handler()
1856 {
1857 	ulong reason;
1858 
1859 	reason = vmcs_read(EXI_REASON);
1860 	switch (reason) {
1861 	case VMX_VMCALL:
1862 		printf("here\n");
1863 		report("VMMCALL triggers #UD", 0);
1864 		break;
1865 	case VMX_EXC_NMI:
1866 		report("VMMCALL triggers #UD",
1867 		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
1868 		break;
1869 	default:
1870 		report("Unknown exit reason, %ld", false, reason);
1871 		print_vmexit_info();
1872 	}
1873 
1874 	return VMX_TEST_VMEXIT;
1875 }
1876 
1877 static int disable_rdtscp_init(struct vmcs *vmcs)
1878 {
1879 	u32 ctrl_cpu1;
1880 
1881 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
1882 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1883 		ctrl_cpu1 &= ~CPU_RDTSCP;
1884 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1885 	}
1886 
1887 	return VMX_TEST_START;
1888 }
1889 
1890 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
1891 {
1892 	switch (vmx_get_test_stage()) {
1893 	case 0:
1894 		report("RDTSCP triggers #UD", true);
1895 		vmx_inc_test_stage();
1896 		regs->rip += 3;
1897 		break;
1898 	case 2:
1899 		report("RDPID triggers #UD", true);
1900 		vmx_inc_test_stage();
1901 		regs->rip += 4;
1902 		break;
1903 	}
1904 	return;
1905 
1906 }
1907 
1908 static void disable_rdtscp_main(void)
1909 {
1910 	/* Test that #UD is properly injected in L2.  */
1911 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
1912 
1913 	vmx_set_test_stage(0);
1914 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
1915 	vmcall();
1916 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
1917 	vmcall();
1918 }
1919 
1920 static int disable_rdtscp_exit_handler(void)
1921 {
1922 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1923 
1924 	switch (reason) {
1925 	case VMX_VMCALL:
1926 		switch (vmx_get_test_stage()) {
1927 		case 0:
1928 			report("RDTSCP triggers #UD", false);
1929 			vmx_inc_test_stage();
1930 			/* fallthrough */
1931 		case 1:
1932 			vmx_inc_test_stage();
1933 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
1934 			return VMX_TEST_RESUME;
1935 		case 2:
1936 			report("RDPID triggers #UD", false);
1937 			break;
1938 		}
1939 		break;
1940 
1941 	default:
1942 		report("Unknown exit reason, %d", false, reason);
1943 		print_vmexit_info();
1944 	}
1945 	return VMX_TEST_VMEXIT;
1946 }
1947 
1948 int int3_init()
1949 {
1950 	vmcs_write(EXC_BITMAP, ~0u);
1951 	return VMX_TEST_START;
1952 }
1953 
1954 void int3_guest_main()
1955 {
1956 	asm volatile ("int3");
1957 }
1958 
1959 int int3_exit_handler()
1960 {
1961 	u32 reason = vmcs_read(EXI_REASON);
1962 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
1963 
1964 	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
1965 	       (intr_info & INTR_INFO_VALID_MASK) &&
1966 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
1967 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
1968 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
1969 
1970 	return VMX_TEST_VMEXIT;
1971 }
1972 
1973 int into_init()
1974 {
1975 	vmcs_write(EXC_BITMAP, ~0u);
1976 	return VMX_TEST_START;
1977 }
1978 
1979 void into_guest_main()
1980 {
1981 	struct far_pointer32 fp = {
1982 		.offset = (uintptr_t)&&into,
1983 		.selector = KERNEL_CS32,
1984 	};
1985 	register uintptr_t rsp asm("rsp");
1986 
1987 	if (fp.offset != (uintptr_t)&&into) {
1988 		printf("Code address too high.\n");
1989 		return;
1990 	}
1991 	if ((u32)rsp != rsp) {
1992 		printf("Stack address too high.\n");
1993 		return;
1994 	}
1995 
1996 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
1997 	return;
1998 into:
1999 	asm volatile (".code32;"
2000 		      "movl $0x7fffffff, %eax;"
2001 		      "addl %eax, %eax;"
2002 		      "into;"
2003 		      "lret;"
2004 		      ".code64");
2005 	__builtin_unreachable();
2006 }
2007 
2008 int into_exit_handler()
2009 {
2010 	u32 reason = vmcs_read(EXI_REASON);
2011 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2012 
2013 	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
2014 	       (intr_info & INTR_INFO_VALID_MASK) &&
2015 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2016 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2017 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2018 
2019 	return VMX_TEST_VMEXIT;
2020 }
2021 
2022 static void exit_monitor_from_l2_main(void)
2023 {
2024 	printf("Calling exit(0) from l2...\n");
2025 	exit(0);
2026 }
2027 
2028 static int exit_monitor_from_l2_handler(void)
2029 {
2030 	report("The guest should have killed the VMM", false);
2031 	return VMX_TEST_EXIT;
2032 }
2033 
2034 static void assert_exit_reason(u64 expected)
2035 {
2036 	u64 actual = vmcs_read(EXI_REASON);
2037 
2038 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2039 			   exit_reason_description(expected),
2040 			   exit_reason_description(actual));
2041 }
2042 
2043 static void skip_exit_vmcall()
2044 {
2045 	u64 guest_rip = vmcs_read(GUEST_RIP);
2046 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2047 
2048 	assert_exit_reason(VMX_VMCALL);
2049 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2050 }
2051 
2052 static void v2_null_test_guest(void)
2053 {
2054 }
2055 
2056 static void v2_null_test(void)
2057 {
2058 	test_set_guest(v2_null_test_guest);
2059 	enter_guest();
2060 	report(__func__, 1);
2061 }
2062 
2063 static void v2_multiple_entries_test_guest(void)
2064 {
2065 	vmx_set_test_stage(1);
2066 	vmcall();
2067 	vmx_set_test_stage(2);
2068 }
2069 
2070 static void v2_multiple_entries_test(void)
2071 {
2072 	test_set_guest(v2_multiple_entries_test_guest);
2073 	enter_guest();
2074 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2075 	skip_exit_vmcall();
2076 	enter_guest();
2077 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2078 	report(__func__, 1);
2079 }
2080 
2081 static int fixture_test_data = 1;
2082 
2083 static void fixture_test_teardown(void *data)
2084 {
2085 	*((int *) data) = 1;
2086 }
2087 
2088 static void fixture_test_guest(void)
2089 {
2090 	fixture_test_data++;
2091 }
2092 
2093 
2094 static void fixture_test_setup(void)
2095 {
2096 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2097 			   "fixture_test_teardown didn't run?!");
2098 	fixture_test_data = 2;
2099 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2100 	test_set_guest(fixture_test_guest);
2101 }
2102 
2103 static void fixture_test_case1(void)
2104 {
2105 	fixture_test_setup();
2106 	TEST_ASSERT_EQ(2, fixture_test_data);
2107 	enter_guest();
2108 	TEST_ASSERT_EQ(3, fixture_test_data);
2109 	report(__func__, 1);
2110 }
2111 
2112 static void fixture_test_case2(void)
2113 {
2114 	fixture_test_setup();
2115 	TEST_ASSERT_EQ(2, fixture_test_data);
2116 	enter_guest();
2117 	TEST_ASSERT_EQ(3, fixture_test_data);
2118 	report(__func__, 1);
2119 }
2120 
2121 enum ept_access_op {
2122 	OP_READ,
2123 	OP_WRITE,
2124 	OP_EXEC,
2125 	OP_FLUSH_TLB,
2126 	OP_EXIT,
2127 };
2128 
2129 static struct ept_access_test_data {
2130 	unsigned long gpa;
2131 	unsigned long *gva;
2132 	unsigned long hpa;
2133 	unsigned long *hva;
2134 	enum ept_access_op op;
2135 } ept_access_test_data;
2136 
2137 extern unsigned char ret42_start;
2138 extern unsigned char ret42_end;
2139 
2140 /* Returns 42. */
2141 asm(
2142 	".align 64\n"
2143 	"ret42_start:\n"
2144 	"mov $42, %eax\n"
2145 	"ret\n"
2146 	"ret42_end:\n"
2147 );
2148 
2149 static void
2150 diagnose_ept_violation_qual(u64 expected, u64 actual)
2151 {
2152 
2153 #define DIAGNOSE(flag)							\
2154 do {									\
2155 	if ((expected & flag) != (actual & flag))			\
2156 		printf(#flag " %sexpected\n",				\
2157 		       (expected & flag) ? "" : "un");			\
2158 } while (0)
2159 
2160 	DIAGNOSE(EPT_VLT_RD);
2161 	DIAGNOSE(EPT_VLT_WR);
2162 	DIAGNOSE(EPT_VLT_FETCH);
2163 	DIAGNOSE(EPT_VLT_PERM_RD);
2164 	DIAGNOSE(EPT_VLT_PERM_WR);
2165 	DIAGNOSE(EPT_VLT_PERM_EX);
2166 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2167 	DIAGNOSE(EPT_VLT_PADDR);
2168 
2169 #undef DIAGNOSE
2170 }
2171 
2172 static void do_ept_access_op(enum ept_access_op op)
2173 {
2174 	ept_access_test_data.op = op;
2175 	enter_guest();
2176 }
2177 
2178 /*
2179  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2180  * needed by tests that modify guest PTEs.
2181  */
2182 static void ept_access_test_guest_flush_tlb(void)
2183 {
2184 	do_ept_access_op(OP_FLUSH_TLB);
2185 	skip_exit_vmcall();
2186 }
2187 
2188 /*
2189  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2190  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2191  * a huge page.
2192  */
2193 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2194 				 unsigned long clear, unsigned long set)
2195 {
2196 	struct ept_access_test_data *data = &ept_access_test_data;
2197 	unsigned long orig_pte;
2198 	unsigned long pte;
2199 
2200 	/* Screw with the mapping at the requested level. */
2201 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2202 	pte = orig_pte;
2203 	if (mkhuge)
2204 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2205 	else
2206 		pte = orig_pte;
2207 	pte = (pte & ~clear) | set;
2208 	set_ept_pte(pml4, gpa, level, pte);
2209 	ept_sync(INVEPT_SINGLE, eptp);
2210 
2211 	return orig_pte;
2212 }
2213 
2214 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2215 {
2216 	set_ept_pte(pml4, gpa, level, orig_pte);
2217 }
2218 
2219 static void do_ept_violation(bool leaf, enum ept_access_op op,
2220 			     u64 expected_qual, u64 expected_paddr)
2221 {
2222 	u64 qual;
2223 
2224 	/* Try the access and observe the violation. */
2225 	do_ept_access_op(op);
2226 
2227 	assert_exit_reason(VMX_EPT_VIOLATION);
2228 
2229 	qual = vmcs_read(EXI_QUALIFICATION);
2230 
2231 	diagnose_ept_violation_qual(expected_qual, qual);
2232 	TEST_EXPECT_EQ(expected_qual, qual);
2233 
2234 	#if 0
2235 	/* Disable for now otherwise every test will fail */
2236 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2237 		       (unsigned long) (
2238 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2239 	#endif
2240 	/*
2241 	 * TODO: tests that probe expected_paddr in pages other than the one at
2242 	 * the beginning of the 1g region.
2243 	 */
2244 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2245 }
2246 
2247 static void
2248 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2249 			      unsigned long set, enum ept_access_op op,
2250 			      u64 expected_qual)
2251 {
2252 	struct ept_access_test_data *data = &ept_access_test_data;
2253 	unsigned long orig_pte;
2254 
2255 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2256 
2257 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2258 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2259 					 data->gpa);
2260 
2261 	/* Fix the violation and resume the op loop. */
2262 	ept_untwiddle(data->gpa, level, orig_pte);
2263 	enter_guest();
2264 	skip_exit_vmcall();
2265 }
2266 
2267 static void
2268 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2269 		       enum ept_access_op op, u64 expected_qual)
2270 {
2271 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2272 				      expected_qual);
2273 	if (ept_huge_pages_supported(level))
2274 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2275 					      expected_qual);
2276 }
2277 
2278 static void ept_violation(unsigned long clear, unsigned long set,
2279 			  enum ept_access_op op, u64 expected_qual)
2280 {
2281 	ept_violation_at_level(1, clear, set, op, expected_qual);
2282 	ept_violation_at_level(2, clear, set, op, expected_qual);
2283 	ept_violation_at_level(3, clear, set, op, expected_qual);
2284 	ept_violation_at_level(4, clear, set, op, expected_qual);
2285 }
2286 
2287 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2288 				       u64 expected_qual)
2289 {
2290 	ept_violation(EPT_PRESENT, access, op,
2291 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2292 }
2293 
2294 /*
2295  * For translations that don't involve a GVA, that is physical address (paddr)
2296  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2297  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2298  * translations don't involve GVAs, such as when the hardware does the guest
2299  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2300  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2301  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2302  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2303  *
2304  * Note that paddr violations can also be triggered by loading PAE page tables
2305  * with wonky addresses. We don't test that yet.
2306  *
2307  * This function modifies the EPT entry that maps the GPA that the guest page
2308  * table entry mapping ept_access_data.gva resides on.
2309  *
2310  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2311  *
2312  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2313  *
2314  *	@op		Guest operation to perform with ept_access_data.gva.
2315  *
2316  *	@expect_violation
2317  *			Is a violation expected during the paddr access?
2318  *
2319  *	@expected_qual	Expected qualification for the EPT violation.
2320  *			EPT_VLT_PADDR should be clear.
2321  */
2322 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2323 			     enum ept_access_op op, bool expect_violation,
2324 			     u64 expected_qual)
2325 {
2326 	struct ept_access_test_data *data = &ept_access_test_data;
2327 	unsigned long *ptep;
2328 	unsigned long gpa;
2329 	unsigned long orig_epte;
2330 
2331 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2332 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2333 	TEST_ASSERT(ptep);
2334 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2335 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2336 	ept_access_test_guest_flush_tlb();
2337 
2338 	/*
2339 	 * Now modify the access bits on the EPT entry for the GPA that the
2340 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2341 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2342 	 * constructed our test such that those other 511 PTEs aren't used by
2343 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2344 	 * PTE we're modifying is at the beginning of a 4K page and the
2345 	 * following 511 entires are also under our control (and not touched by
2346 	 * the guest).
2347 	 */
2348 	gpa = virt_to_phys(ptep);
2349 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2350 	/*
2351 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2352 	 * otherwise our level=1 twiddling below will fail. We use the
2353 	 * identity map (gpa = gpa) since page tables are shared with the host.
2354 	 */
2355 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2356 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2357 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2358 
2359 	if (expect_violation) {
2360 		do_ept_violation(/*leaf=*/true, op,
2361 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2362 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2363 		do_ept_access_op(op);
2364 	} else {
2365 		do_ept_access_op(op);
2366 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2367 	}
2368 
2369 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2370 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2371 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2372 
2373 	skip_exit_vmcall();
2374 }
2375 
2376 static void ept_access_allowed_paddr(unsigned long ept_access,
2377 				     unsigned long pte_ad,
2378 				     enum ept_access_op op)
2379 {
2380 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2381 			 /*expected_qual=*/-1);
2382 }
2383 
2384 static void ept_access_violation_paddr(unsigned long ept_access,
2385 				       unsigned long pte_ad,
2386 				       enum ept_access_op op,
2387 				       u64 expected_qual)
2388 {
2389 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2390 			 expected_qual);
2391 }
2392 
2393 
2394 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2395 					unsigned long clear,
2396 					unsigned long set,
2397 					enum ept_access_op op)
2398 {
2399 	struct ept_access_test_data *data = &ept_access_test_data;
2400 	unsigned long orig_pte;
2401 
2402 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2403 
2404 	/* No violation. Should proceed to vmcall. */
2405 	do_ept_access_op(op);
2406 	skip_exit_vmcall();
2407 
2408 	ept_untwiddle(data->gpa, level, orig_pte);
2409 }
2410 
2411 static void ept_allowed_at_level(int level, unsigned long clear,
2412 				 unsigned long set, enum ept_access_op op)
2413 {
2414 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2415 	if (ept_huge_pages_supported(level))
2416 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2417 }
2418 
2419 static void ept_allowed(unsigned long clear, unsigned long set,
2420 			enum ept_access_op op)
2421 {
2422 	ept_allowed_at_level(1, clear, set, op);
2423 	ept_allowed_at_level(2, clear, set, op);
2424 	ept_allowed_at_level(3, clear, set, op);
2425 	ept_allowed_at_level(4, clear, set, op);
2426 }
2427 
2428 static void ept_ignored_bit(int bit)
2429 {
2430 	/* Set the bit. */
2431 	ept_allowed(0, 1ul << bit, OP_READ);
2432 	ept_allowed(0, 1ul << bit, OP_WRITE);
2433 	ept_allowed(0, 1ul << bit, OP_EXEC);
2434 
2435 	/* Clear the bit. */
2436 	ept_allowed(1ul << bit, 0, OP_READ);
2437 	ept_allowed(1ul << bit, 0, OP_WRITE);
2438 	ept_allowed(1ul << bit, 0, OP_EXEC);
2439 }
2440 
2441 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2442 {
2443 	ept_allowed(EPT_PRESENT, access, op);
2444 }
2445 
2446 
2447 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2448 					     unsigned long clear,
2449 					     unsigned long set,
2450 					     enum ept_access_op op)
2451 {
2452 	struct ept_access_test_data *data = &ept_access_test_data;
2453 	unsigned long orig_pte;
2454 
2455 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2456 
2457 	do_ept_access_op(op);
2458 	assert_exit_reason(VMX_EPT_MISCONFIG);
2459 
2460 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2461 	#if 0
2462 	/* broken: */
2463 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2464 	#endif
2465 	#if 0
2466 	/*
2467 	 * broken:
2468 	 * According to description of exit qual for EPT violation,
2469 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2470 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2471 	 * to be set for msiconfig.
2472 	 */
2473 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2474 		       (unsigned long) (
2475 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2476 	#endif
2477 
2478 	/* Fix the violation and resume the op loop. */
2479 	ept_untwiddle(data->gpa, level, orig_pte);
2480 	enter_guest();
2481 	skip_exit_vmcall();
2482 }
2483 
2484 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2485 					  unsigned long clear,
2486 					  unsigned long set)
2487 {
2488 	/* The op shouldn't matter (read, write, exec), so try them all! */
2489 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2490 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2491 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2492 }
2493 
2494 static void ept_misconfig_at_level(int level, unsigned long clear,
2495 				   unsigned long set)
2496 {
2497 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2498 	if (ept_huge_pages_supported(level))
2499 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2500 }
2501 
2502 static void ept_misconfig(unsigned long clear, unsigned long set)
2503 {
2504 	ept_misconfig_at_level(1, clear, set);
2505 	ept_misconfig_at_level(2, clear, set);
2506 	ept_misconfig_at_level(3, clear, set);
2507 	ept_misconfig_at_level(4, clear, set);
2508 }
2509 
2510 static void ept_access_misconfig(unsigned long access)
2511 {
2512 	ept_misconfig(EPT_PRESENT, access);
2513 }
2514 
2515 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2516 {
2517 	/* Setting the bit causes a misconfig. */
2518 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2519 
2520 	/* Making the entry non-present turns reserved bits into ignored. */
2521 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2522 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2523 }
2524 
2525 static void ept_reserved_bit_at_level_huge(int level, int bit)
2526 {
2527 	/* Setting the bit causes a misconfig. */
2528 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2529 
2530 	/* Making the entry non-present turns reserved bits into ignored. */
2531 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2532 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2533 }
2534 
2535 static void ept_reserved_bit_at_level(int level, int bit)
2536 {
2537 	/* Setting the bit causes a misconfig. */
2538 	ept_misconfig_at_level(level, 0, 1ul << bit);
2539 
2540 	/* Making the entry non-present turns reserved bits into ignored. */
2541 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2542 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2543 }
2544 
2545 static void ept_reserved_bit(int bit)
2546 {
2547 	ept_reserved_bit_at_level(1, bit);
2548 	ept_reserved_bit_at_level(2, bit);
2549 	ept_reserved_bit_at_level(3, bit);
2550 	ept_reserved_bit_at_level(4, bit);
2551 }
2552 
2553 #define PAGE_2M_ORDER 9
2554 #define PAGE_1G_ORDER 18
2555 
2556 static void *get_1g_page(void)
2557 {
2558 	static void *alloc;
2559 
2560 	if (!alloc)
2561 		alloc = alloc_pages(PAGE_1G_ORDER);
2562 	return alloc;
2563 }
2564 
2565 static void ept_access_test_teardown(void *unused)
2566 {
2567 	/* Exit the guest cleanly. */
2568 	do_ept_access_op(OP_EXIT);
2569 }
2570 
2571 static void ept_access_test_guest(void)
2572 {
2573 	struct ept_access_test_data *data = &ept_access_test_data;
2574 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2575 
2576 	while (true) {
2577 		switch (data->op) {
2578 		case OP_READ:
2579 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2580 			break;
2581 		case OP_WRITE:
2582 			*data->gva = MAGIC_VAL_2;
2583 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2584 			*data->gva = MAGIC_VAL_1;
2585 			break;
2586 		case OP_EXEC:
2587 			TEST_ASSERT_EQ(42, code());
2588 			break;
2589 		case OP_FLUSH_TLB:
2590 			write_cr3(read_cr3());
2591 			break;
2592 		case OP_EXIT:
2593 			return;
2594 		default:
2595 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2596 		}
2597 		vmcall();
2598 	}
2599 }
2600 
2601 static void ept_access_test_setup(void)
2602 {
2603 	struct ept_access_test_data *data = &ept_access_test_data;
2604 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2605 	unsigned long size = npages * PAGE_SIZE;
2606 	unsigned long *page_table = current_page_table();
2607 	unsigned long pte;
2608 
2609 	if (setup_ept(false))
2610 		test_skip("EPT not supported");
2611 
2612 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2613 	if (cpuid_maxphyaddr() < 40)
2614 		test_skip("Test needs MAXPHYADDR >= 40");
2615 
2616 	test_set_guest(ept_access_test_guest);
2617 	test_add_teardown(ept_access_test_teardown, NULL);
2618 
2619 	data->hva = get_1g_page();
2620 	TEST_ASSERT(data->hva);
2621 	data->hpa = virt_to_phys(data->hva);
2622 
2623 	data->gpa = 1ul << 39;
2624 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2625 				   size);
2626 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2627 	install_pages(page_table, data->gpa, size, data->gva);
2628 
2629 	/*
2630 	 * Make sure nothing's mapped here so the tests that screw with the
2631 	 * pml4 entry don't inadvertently break something.
2632 	 */
2633 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2634 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2635 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2636 
2637 	data->hva[0] = MAGIC_VAL_1;
2638 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2639 }
2640 
2641 static void ept_access_test_not_present(void)
2642 {
2643 	ept_access_test_setup();
2644 	/* --- */
2645 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2646 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2647 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2648 }
2649 
2650 static void ept_access_test_read_only(void)
2651 {
2652 	ept_access_test_setup();
2653 
2654 	/* r-- */
2655 	ept_access_allowed(EPT_RA, OP_READ);
2656 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2657 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2658 }
2659 
2660 static void ept_access_test_write_only(void)
2661 {
2662 	ept_access_test_setup();
2663 	/* -w- */
2664 	ept_access_misconfig(EPT_WA);
2665 }
2666 
2667 static void ept_access_test_read_write(void)
2668 {
2669 	ept_access_test_setup();
2670 	/* rw- */
2671 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2672 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2673 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2674 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2675 }
2676 
2677 
2678 static void ept_access_test_execute_only(void)
2679 {
2680 	ept_access_test_setup();
2681 	/* --x */
2682 	if (ept_execute_only_supported()) {
2683 		ept_access_violation(EPT_EA, OP_READ,
2684 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2685 		ept_access_violation(EPT_EA, OP_WRITE,
2686 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2687 		ept_access_allowed(EPT_EA, OP_EXEC);
2688 	} else {
2689 		ept_access_misconfig(EPT_EA);
2690 	}
2691 }
2692 
2693 static void ept_access_test_read_execute(void)
2694 {
2695 	ept_access_test_setup();
2696 	/* r-x */
2697 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2698 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2699 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2700 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2701 }
2702 
2703 static void ept_access_test_write_execute(void)
2704 {
2705 	ept_access_test_setup();
2706 	/* -wx */
2707 	ept_access_misconfig(EPT_WA | EPT_EA);
2708 }
2709 
2710 static void ept_access_test_read_write_execute(void)
2711 {
2712 	ept_access_test_setup();
2713 	/* rwx */
2714 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2715 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2716 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2717 }
2718 
2719 static void ept_access_test_reserved_bits(void)
2720 {
2721 	int i;
2722 	int maxphyaddr;
2723 
2724 	ept_access_test_setup();
2725 
2726 	/* Reserved bits above maxphyaddr. */
2727 	maxphyaddr = cpuid_maxphyaddr();
2728 	for (i = maxphyaddr; i <= 51; i++) {
2729 		report_prefix_pushf("reserved_bit=%d", i);
2730 		ept_reserved_bit(i);
2731 		report_prefix_pop();
2732 	}
2733 
2734 	/* Level-specific reserved bits. */
2735 	ept_reserved_bit_at_level_nohuge(2, 3);
2736 	ept_reserved_bit_at_level_nohuge(2, 4);
2737 	ept_reserved_bit_at_level_nohuge(2, 5);
2738 	ept_reserved_bit_at_level_nohuge(2, 6);
2739 	/* 2M alignment. */
2740 	for (i = 12; i < 20; i++) {
2741 		report_prefix_pushf("reserved_bit=%d", i);
2742 		ept_reserved_bit_at_level_huge(2, i);
2743 		report_prefix_pop();
2744 	}
2745 	ept_reserved_bit_at_level_nohuge(3, 3);
2746 	ept_reserved_bit_at_level_nohuge(3, 4);
2747 	ept_reserved_bit_at_level_nohuge(3, 5);
2748 	ept_reserved_bit_at_level_nohuge(3, 6);
2749 	/* 1G alignment. */
2750 	for (i = 12; i < 29; i++) {
2751 		report_prefix_pushf("reserved_bit=%d", i);
2752 		ept_reserved_bit_at_level_huge(3, i);
2753 		report_prefix_pop();
2754 	}
2755 	ept_reserved_bit_at_level(4, 3);
2756 	ept_reserved_bit_at_level(4, 4);
2757 	ept_reserved_bit_at_level(4, 5);
2758 	ept_reserved_bit_at_level(4, 6);
2759 	ept_reserved_bit_at_level(4, 7);
2760 }
2761 
2762 static void ept_access_test_ignored_bits(void)
2763 {
2764 	ept_access_test_setup();
2765 	/*
2766 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2767 	 * far as translation is concerned even if AD bits are enabled in the
2768 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2769 	 * control is 0.
2770 	 */
2771 	ept_ignored_bit(8);
2772 	ept_ignored_bit(9);
2773 	ept_ignored_bit(10);
2774 	ept_ignored_bit(11);
2775 	ept_ignored_bit(52);
2776 	ept_ignored_bit(53);
2777 	ept_ignored_bit(54);
2778 	ept_ignored_bit(55);
2779 	ept_ignored_bit(56);
2780 	ept_ignored_bit(57);
2781 	ept_ignored_bit(58);
2782 	ept_ignored_bit(59);
2783 	ept_ignored_bit(60);
2784 	ept_ignored_bit(61);
2785 	ept_ignored_bit(62);
2786 	ept_ignored_bit(63);
2787 }
2788 
2789 static void ept_access_test_paddr_not_present_ad_disabled(void)
2790 {
2791 	ept_access_test_setup();
2792 	ept_disable_ad_bits();
2793 
2794 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2795 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2796 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2797 }
2798 
2799 static void ept_access_test_paddr_not_present_ad_enabled(void)
2800 {
2801 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2802 
2803 	ept_access_test_setup();
2804 	ept_enable_ad_bits_or_skip_test();
2805 
2806 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2807 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2808 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2809 }
2810 
2811 static void ept_access_test_paddr_read_only_ad_disabled(void)
2812 {
2813 	/*
2814 	 * When EPT AD bits are disabled, all accesses to guest paging
2815 	 * structures are reported separately as a read and (after
2816 	 * translation of the GPA to host physical address) a read+write
2817 	 * if the A/D bits have to be set.
2818 	 */
2819 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2820 
2821 	ept_access_test_setup();
2822 	ept_disable_ad_bits();
2823 
2824 	/* Can't update A bit, so all accesses fail. */
2825 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2826 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2827 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2828 	/* AD bits disabled, so only writes try to update the D bit. */
2829 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
2830 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2831 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
2832 	/* Both A and D already set, so read-only is OK. */
2833 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
2834 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
2835 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
2836 }
2837 
2838 static void ept_access_test_paddr_read_only_ad_enabled(void)
2839 {
2840 	/*
2841 	 * When EPT AD bits are enabled, all accesses to guest paging
2842 	 * structures are considered writes as far as EPT translation
2843 	 * is concerned.
2844 	 */
2845 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2846 
2847 	ept_access_test_setup();
2848 	ept_enable_ad_bits_or_skip_test();
2849 
2850 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2851 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2852 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2853 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
2854 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2855 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
2856 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
2857 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
2858 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
2859 }
2860 
2861 static void ept_access_test_paddr_read_write(void)
2862 {
2863 	ept_access_test_setup();
2864 	/* Read-write access to paging structure. */
2865 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
2866 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
2867 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
2868 }
2869 
2870 static void ept_access_test_paddr_read_write_execute(void)
2871 {
2872 	ept_access_test_setup();
2873 	/* RWX access to paging structure. */
2874 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
2875 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
2876 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
2877 }
2878 
2879 static void ept_access_test_paddr_read_execute_ad_disabled(void)
2880 {
2881   	/*
2882 	 * When EPT AD bits are disabled, all accesses to guest paging
2883 	 * structures are reported separately as a read and (after
2884 	 * translation of the GPA to host physical address) a read+write
2885 	 * if the A/D bits have to be set.
2886 	 */
2887 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2888 
2889 	ept_access_test_setup();
2890 	ept_disable_ad_bits();
2891 
2892 	/* Can't update A bit, so all accesses fail. */
2893 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2894 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2895 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2896 	/* AD bits disabled, so only writes try to update the D bit. */
2897 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
2898 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2899 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
2900 	/* Both A and D already set, so read-only is OK. */
2901 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
2902 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
2903 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
2904 }
2905 
2906 static void ept_access_test_paddr_read_execute_ad_enabled(void)
2907 {
2908 	/*
2909 	 * When EPT AD bits are enabled, all accesses to guest paging
2910 	 * structures are considered writes as far as EPT translation
2911 	 * is concerned.
2912 	 */
2913 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2914 
2915 	ept_access_test_setup();
2916 	ept_enable_ad_bits_or_skip_test();
2917 
2918 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2919 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2920 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2921 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
2922 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2923 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
2924 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
2925 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
2926 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
2927 }
2928 
2929 static void ept_access_test_paddr_not_present_page_fault(void)
2930 {
2931 	ept_access_test_setup();
2932 	/*
2933 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
2934 	 * page is read-only in EPT but GVA is also mapped read only in PT.
2935 	 * Thus guest page fault before host takes EPT violation for trying to
2936 	 * update A bit.
2937 	 */
2938 }
2939 
2940 static void ept_access_test_force_2m_page(void)
2941 {
2942 	ept_access_test_setup();
2943 
2944 	TEST_ASSERT_EQ(ept_2m_supported(), true);
2945 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
2946 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
2947 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
2948 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2949 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
2950 }
2951 
2952 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
2953 {
2954 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
2955 
2956 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
2957 
2958 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
2959 		return false;
2960 
2961 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
2962 		return false;
2963 
2964 	if (vpid >> 16)
2965 		return false;
2966 
2967 	if (type != INVVPID_ALL && !vpid)
2968 		return false;
2969 
2970 	if (type == INVVPID_ADDR && !is_canonical(gla))
2971 		return false;
2972 
2973 	return true;
2974 }
2975 
2976 static void try_invvpid(u64 type, u64 vpid, u64 gla)
2977 {
2978 	int rc;
2979 	bool valid = invvpid_valid(type, vpid, gla);
2980 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
2981 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
2982 	/*
2983 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
2984 	 * that we can tell if it is updated by INVVPID.
2985 	 */
2986 	vmcs_read(~0);
2987 	rc = invvpid(type, vpid, gla);
2988 	report("INVVPID type %ld VPID %lx GLA %lx %s",
2989 	       !rc == valid, type, vpid, gla,
2990 	       valid ? "passes" : "fails");
2991 	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
2992 	       vmcs_read(VMX_INST_ERROR) == expected,
2993 	       rc ? "failed" : "successful",
2994 	       expected, vmcs_read(VMX_INST_ERROR));
2995 }
2996 
2997 static void ds_invvpid(void *data)
2998 {
2999 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3000 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3001 
3002 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3003 	asm volatile("invvpid %0, %1"
3004 		     :
3005 		     : "m"(*(struct invvpid_operand *)data),
3006 		       "r"(type));
3007 }
3008 
3009 /*
3010  * The SS override is ignored in 64-bit mode, so we use an addressing
3011  * mode with %rsp as the base register to generate an implicit SS
3012  * reference.
3013  */
3014 static void ss_invvpid(void *data)
3015 {
3016 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3017 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3018 
3019 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3020 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3021 		     : "+r"(data)
3022 		     : "r"(type));
3023 }
3024 
3025 static void invvpid_test_gp(void)
3026 {
3027 	bool fault;
3028 
3029 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3030 				   (void *)NONCANONICAL);
3031 	report("INVVPID with non-canonical DS operand raises #GP", fault);
3032 }
3033 
3034 static void invvpid_test_ss(void)
3035 {
3036 	bool fault;
3037 
3038 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3039 				   (void *)NONCANONICAL);
3040 	report("INVVPID with non-canonical SS operand raises #SS", fault);
3041 }
3042 
3043 static void invvpid_test_pf(void)
3044 {
3045 	void *vpage = alloc_vpage();
3046 	bool fault;
3047 
3048 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3049 	report("INVVPID with unmapped operand raises #PF", fault);
3050 }
3051 
3052 static void try_compat_invvpid(void *unused)
3053 {
3054 	struct far_pointer32 fp = {
3055 		.offset = (uintptr_t)&&invvpid,
3056 		.selector = KERNEL_CS32,
3057 	};
3058 	register uintptr_t rsp asm("rsp");
3059 
3060 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3061 			"Code address too high.");
3062 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3063 
3064 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3065 	return;
3066 invvpid:
3067 	asm volatile (".code32;"
3068 		      "invvpid (%eax), %eax;"
3069 		      "lret;"
3070 		      ".code64");
3071 	__builtin_unreachable();
3072 }
3073 
3074 static void invvpid_test_compatibility_mode(void)
3075 {
3076 	bool fault;
3077 
3078 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3079 	report("Compatibility mode INVVPID raises #UD", fault);
3080 }
3081 
3082 static void invvpid_test_not_in_vmx_operation(void)
3083 {
3084 	bool fault;
3085 
3086 	TEST_ASSERT(!vmx_off());
3087 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3088 	report("INVVPID outside of VMX operation raises #UD", fault);
3089 	TEST_ASSERT(!vmx_on());
3090 }
3091 
3092 /*
3093  * This does not test real-address mode, virtual-8086 mode, protected mode,
3094  * or CPL > 0.
3095  */
3096 static void invvpid_test_v2(void)
3097 {
3098 	u64 msr;
3099 	int i;
3100 	unsigned types = 0;
3101 	unsigned type;
3102 
3103 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3104 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3105 		test_skip("VPID not supported");
3106 
3107 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3108 
3109 	if (!(msr & VPID_CAP_INVVPID))
3110 		test_skip("INVVPID not supported.\n");
3111 
3112 	if (msr & VPID_CAP_INVVPID_ADDR)
3113 		types |= 1u << INVVPID_ADDR;
3114 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3115 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3116 	if (msr & VPID_CAP_INVVPID_ALL)
3117 		types |= 1u << INVVPID_ALL;
3118 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3119 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3120 
3121 	if (!types)
3122 		test_skip("No INVVPID types supported.\n");
3123 
3124 	for (i = -127; i < 128; i++)
3125 		try_invvpid(i, 0xffff, 0);
3126 
3127 	/*
3128 	 * VPID must not be more than 16 bits.
3129 	 */
3130 	for (i = 0; i < 64; i++)
3131 		for (type = 0; type < 4; type++)
3132 			if (types & (1u << type))
3133 				try_invvpid(type, 1ul << i, 0);
3134 
3135 	/*
3136 	 * VPID must not be zero, except for "all contexts."
3137 	 */
3138 	for (type = 0; type < 4; type++)
3139 		if (types & (1u << type))
3140 			try_invvpid(type, 0, 0);
3141 
3142 	/*
3143 	 * The gla operand is only validated for single-address INVVPID.
3144 	 */
3145 	if (types & (1u << INVVPID_ADDR))
3146 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3147 
3148 	invvpid_test_gp();
3149 	invvpid_test_ss();
3150 	invvpid_test_pf();
3151 	invvpid_test_compatibility_mode();
3152 	invvpid_test_not_in_vmx_operation();
3153 }
3154 
3155 /*
3156  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3157  * at least as far as the guest-state checks. Returns false if the
3158  * VMLAUNCH fails early and execution falls through to the next
3159  * instruction.
3160  */
3161 static bool vmlaunch_succeeds(void)
3162 {
3163 	/*
3164 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3165 	 * unsupported VMCS component"). The caller can then check
3166 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3167 	 */
3168 	vmcs_write(~0u, 0);
3169 
3170 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3171 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3172 				   :
3173 				   : "r" ((u64)HOST_RSP)
3174 				   : "cc", "memory"
3175 				   : success);
3176 	return false;
3177 success:
3178 	TEST_ASSERT(vmcs_read(EXI_REASON) ==
3179 		    (VMX_FAIL_STATE | VMX_ENTRY_FAILURE));
3180 	return true;
3181 }
3182 
3183 /*
3184  * Try to launch the current VMCS.
3185  */
3186 static void test_vmx_controls(bool controls_valid, bool xfail)
3187 {
3188 	bool success = vmlaunch_succeeds();
3189 	u32 vmx_inst_err;
3190 
3191 	report_xfail("vmlaunch %s", xfail, success == controls_valid,
3192 		     controls_valid ? "succeeds" : "fails");
3193 	if (!success) {
3194 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3195 		report("VMX inst error is %d (actual %d)",
3196 		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
3197 		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
3198 	}
3199 }
3200 
3201 /*
3202  * Test a particular value of a VM-execution control bit, if the value
3203  * is required or if the value is zero.
3204  */
3205 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3206 				    enum Encoding encoding, unsigned bit,
3207 				    unsigned val)
3208 {
3209 	u32 mask = 1u << bit;
3210 	bool expected;
3211 	u32 controls;
3212 
3213 	if (msr.set & mask)
3214 		TEST_ASSERT(msr.clr & mask);
3215 
3216 	/*
3217 	 * We can't arbitrarily turn on a control bit, because it may
3218 	 * introduce dependencies on other VMCS fields. So, we only
3219 	 * test turning on bits that have a required setting.
3220 	 */
3221 	if (val && (msr.clr & mask) && !(msr.set & mask))
3222 		return;
3223 
3224 	report_prefix_pushf("%s %s bit %d",
3225 			    val ? "Set" : "Clear", name, bit);
3226 
3227 	controls = vmcs_read(encoding);
3228 	if (val) {
3229 		vmcs_write(encoding, msr.set | mask);
3230 		expected = (msr.clr & mask);
3231 	} else {
3232 		vmcs_write(encoding, msr.set & ~mask);
3233 		expected = !(msr.set & mask);
3234 	}
3235 	test_vmx_controls(expected, false);
3236 	vmcs_write(encoding, controls);
3237 	report_prefix_pop();
3238 }
3239 
3240 /*
3241  * Test reserved values of a VM-execution control bit, based on the
3242  * allowed bit settings from the corresponding VMX capability MSR.
3243  */
3244 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3245 			      enum Encoding encoding, unsigned bit)
3246 {
3247 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3248 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3249 }
3250 
3251 /*
3252  * Reserved bits in the pin-based VM-execution controls must be set
3253  * properly. Software may consult the VMX capability MSRs to determine
3254  * the proper settings.
3255  * [Intel SDM]
3256  */
3257 static void test_pin_based_ctls(void)
3258 {
3259 	unsigned bit;
3260 
3261 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3262 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3263 	for (bit = 0; bit < 32; bit++)
3264 		test_rsvd_ctl_bit("pin-based controls",
3265 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3266 }
3267 
3268 /*
3269  * Reserved bits in the primary processor-based VM-execution controls
3270  * must be set properly. Software may consult the VMX capability MSRs
3271  * to determine the proper settings.
3272  * [Intel SDM]
3273  */
3274 static void test_primary_processor_based_ctls(void)
3275 {
3276 	unsigned bit;
3277 
3278 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3279 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3280 	for (bit = 0; bit < 32; bit++)
3281 		test_rsvd_ctl_bit("primary processor-based controls",
3282 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3283 }
3284 
3285 /*
3286  * If the "activate secondary controls" primary processor-based
3287  * VM-execution control is 1, reserved bits in the secondary
3288  * processor-based VM-execution controls must be cleared. Software may
3289  * consult the VMX capability MSRs to determine which bits are
3290  * reserved.
3291  * If the "activate secondary controls" primary processor-based
3292  * VM-execution control is 0 (or if the processor does not support the
3293  * 1-setting of that control), no checks are performed on the
3294  * secondary processor-based VM-execution controls.
3295  * [Intel SDM]
3296  */
3297 static void test_secondary_processor_based_ctls(void)
3298 {
3299 	u32 primary;
3300 	u32 secondary;
3301 	unsigned bit;
3302 
3303 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3304 		return;
3305 
3306 	primary = vmcs_read(CPU_EXEC_CTRL0);
3307 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3308 
3309 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3310 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3311 	for (bit = 0; bit < 32; bit++)
3312 		test_rsvd_ctl_bit("secondary processor-based controls",
3313 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3314 
3315 	/*
3316 	 * When the "activate secondary controls" VM-execution control
3317 	 * is clear, there are no checks on the secondary controls.
3318 	 */
3319 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3320 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3321 	report("Secondary processor-based controls ignored",
3322 	       vmlaunch_succeeds());
3323 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3324 	vmcs_write(CPU_EXEC_CTRL0, primary);
3325 }
3326 
3327 static void try_cr3_target_count(unsigned i, unsigned max)
3328 {
3329 	report_prefix_pushf("CR3 target count 0x%x", i);
3330 	vmcs_write(CR3_TARGET_COUNT, i);
3331 	test_vmx_controls(i <= max, false);
3332 	report_prefix_pop();
3333 }
3334 
3335 /*
3336  * The CR3-target count must not be greater than 4. Future processors
3337  * may support a different number of CR3-target values. Software
3338  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3339  * number of values supported.
3340  * [Intel SDM]
3341  */
3342 static void test_cr3_targets(void)
3343 {
3344 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3345 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3346 	unsigned i;
3347 
3348 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3349 	TEST_ASSERT(supported_targets <= 256);
3350 
3351 	try_cr3_target_count(-1u, supported_targets);
3352 	try_cr3_target_count(0x80000000, supported_targets);
3353 	try_cr3_target_count(0x7fffffff, supported_targets);
3354 	for (i = 0; i <= supported_targets + 1; i++)
3355 		try_cr3_target_count(i, supported_targets);
3356 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3357 }
3358 
3359 /*
3360  * Test a particular address setting for a physical page reference in
3361  * the VMCS.
3362  */
3363 static void test_vmcs_page_addr(const char *name,
3364 				enum Encoding encoding,
3365 				bool ignored,
3366 				bool xfail_beyond_mapped_ram,
3367 				u64 addr)
3368 {
3369 	bool xfail =
3370 		(xfail_beyond_mapped_ram &&
3371 		 addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - PAGE_SIZE &&
3372 		 addr < (1ul << cpuid_maxphyaddr()));
3373 
3374 	report_prefix_pushf("%s = %lx", name, addr);
3375 	vmcs_write(encoding, addr);
3376 	test_vmx_controls(ignored || (IS_ALIGNED(addr, PAGE_SIZE) &&
3377 				  addr < (1ul << cpuid_maxphyaddr())),
3378 			  xfail);
3379 	report_prefix_pop();
3380 	xfail = false;
3381 }
3382 
3383 /*
3384  * Test interesting values for a physical page reference in the VMCS.
3385  */
3386 static void test_vmcs_page_values(const char *name,
3387 				  enum Encoding encoding,
3388 				  bool ignored,
3389 				  bool xfail_beyond_mapped_ram)
3390 {
3391 	unsigned i;
3392 	u64 orig_val = vmcs_read(encoding);
3393 
3394 	for (i = 0; i < 64; i++)
3395 		test_vmcs_page_addr(name, encoding, ignored,
3396 				    xfail_beyond_mapped_ram, 1ul << i);
3397 
3398 	test_vmcs_page_addr(name, encoding, ignored,
3399 			    xfail_beyond_mapped_ram, PAGE_SIZE - 1);
3400 	test_vmcs_page_addr(name, encoding, ignored,
3401 			    xfail_beyond_mapped_ram, PAGE_SIZE);
3402 	test_vmcs_page_addr(name, encoding, ignored,
3403 			    xfail_beyond_mapped_ram,
3404 			    (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3405 	test_vmcs_page_addr(name, encoding, ignored,
3406 			    xfail_beyond_mapped_ram,
3407 			    -1ul);
3408 
3409 	vmcs_write(encoding, orig_val);
3410 }
3411 
3412 /*
3413  * Test a physical page reference in the VMCS, when the corresponding
3414  * feature is enabled and when the corresponding feature is disabled.
3415  */
3416 static void test_vmcs_page_reference(u32 control_bit, enum Encoding field,
3417 				     const char *field_name,
3418 				     const char *control_name,
3419 				     bool xfail_beyond_mapped_ram)
3420 {
3421 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3422 	u64 page_addr;
3423 
3424 	if (!(ctrl_cpu_rev[0].clr & control_bit))
3425 		return;
3426 
3427 	page_addr = vmcs_read(field);
3428 
3429 	report_prefix_pushf("%s enabled", control_name);
3430 	vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3431 	test_vmcs_page_values(field_name, field, false, xfail_beyond_mapped_ram);
3432 	report_prefix_pop();
3433 
3434 	report_prefix_pushf("%s disabled", control_name);
3435 	vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3436 	test_vmcs_page_values(field_name, field, true, false);
3437 	report_prefix_pop();
3438 
3439 	vmcs_write(field, page_addr);
3440 	vmcs_write(CPU_EXEC_CTRL0, primary);
3441 }
3442 
3443 /*
3444  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3445  * each I/O-bitmap address must be 0. Neither address should set any
3446  * bits beyond the processor's physical-address width.
3447  * [Intel SDM]
3448  */
3449 static void test_io_bitmaps(void)
3450 {
3451 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3452 				 "I/O bitmap A", "Use I/O bitmaps", false);
3453 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3454 				 "I/O bitmap B", "Use I/O bitmaps", false);
3455 }
3456 
3457 /*
3458  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3459  * the MSR-bitmap address must be 0. The address should not set any
3460  * bits beyond the processor's physical-address width.
3461  * [Intel SDM]
3462  */
3463 static void test_msr_bitmap(void)
3464 {
3465 	test_vmcs_page_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3466 				 "MSR bitmap", "Use MSR bitmaps", false);
3467 }
3468 
3469 /*
3470  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3471  * address must satisfy the following checks:
3472  * - Bits 11:0 of the address must be 0.
3473  * - The address should not set any bits beyond the processor's
3474  *   physical-address width.
3475  * [Intel SDM]
3476  */
3477 static void test_apic_virt_addr(void)
3478 {
3479 	test_vmcs_page_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3480 				 "virtual-APIC address", "Use TPR shadow", true);
3481 }
3482 
3483 static void try_tpr_threshold(unsigned val)
3484 {
3485 	bool valid = true;
3486 
3487 	if ((vmcs_read(CPU_EXEC_CTRL0) & CPU_TPR_SHADOW) &&
3488 	    !((vmcs_read(CPU_EXEC_CTRL0) & CPU_SECONDARY) &&
3489 	      (vmcs_read(CPU_EXEC_CTRL1) & CPU_VINTD)))
3490 		valid = !(val >> 4);
3491 	report_prefix_pushf("TPR threshold 0x%x", val);
3492 	vmcs_write(TPR_THRESHOLD, val);
3493 	test_vmx_controls(valid, false);
3494 	report_prefix_pop();
3495 }
3496 
3497 /*
3498  * Test interesting TPR threshold values.
3499  */
3500 static void test_tpr_threshold_values(void)
3501 {
3502 	unsigned i;
3503 
3504 	for (i = 0; i < 0x10; i++)
3505 		try_tpr_threshold(i);
3506 	for (i = 4; i < 32; i++)
3507 		try_tpr_threshold(1u << i);
3508 	try_tpr_threshold(-1u);
3509 	try_tpr_threshold(0x7fffffff);
3510 }
3511 
3512 /*
3513  * If the "use TPR shadow" VM-execution control is 1 and the
3514  * "virtual-interrupt delivery" VM-execution control is 0, bits 31:4
3515  * of the TPR threshold VM-execution control field must be 0.
3516  * [Intel SDM]
3517  */
3518 static void test_tpr_threshold(void)
3519 {
3520 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3521 	void *virtual_apic_page;
3522 
3523 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
3524 		return;
3525 
3526 	virtual_apic_page = alloc_page();
3527 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
3528 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
3529 
3530 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
3531 	report_prefix_pushf("Use TPR shadow disabled");
3532 	test_tpr_threshold_values();
3533 	report_prefix_pop();
3534 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
3535 	report_prefix_pushf("Use TPR shadow enabled");
3536 	test_tpr_threshold_values();
3537 	report_prefix_pop();
3538 
3539 	if ((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
3540 	    (ctrl_cpu_rev[1].clr & CPU_VINTD)) {
3541 		u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3542 
3543 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
3544 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled");
3545 		test_tpr_threshold_values();
3546 		report_prefix_pop();
3547 		vmcs_write(CPU_EXEC_CTRL0,
3548 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
3549 		report_prefix_pushf("Use TPR shadow enabled; virtual-interrupt delivery enabled");
3550 		test_tpr_threshold_values();
3551 		report_prefix_pop();
3552 
3553 		vmcs_write(CPU_EXEC_CTRL1, secondary);
3554 	}
3555 
3556 	vmcs_write(CPU_EXEC_CTRL0, primary);
3557 }
3558 
3559 /*
3560  * Check that the virtual CPU checks all of the VMX controls as
3561  * documented in the Intel SDM.
3562  */
3563 static void vmx_controls_test(void)
3564 {
3565 	/*
3566 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
3567 	 * fail due to invalid guest state, should we make it that
3568 	 * far.
3569 	 */
3570 	vmcs_write(GUEST_RFLAGS, 0);
3571 
3572 	test_pin_based_ctls();
3573 	test_primary_processor_based_ctls();
3574 	test_secondary_processor_based_ctls();
3575 	test_cr3_targets();
3576 	test_io_bitmaps();
3577 	test_msr_bitmap();
3578 	test_apic_virt_addr();
3579 	test_tpr_threshold();
3580 }
3581 
3582 static bool valid_vmcs_for_vmentry(void)
3583 {
3584 	struct vmcs *current_vmcs = NULL;
3585 
3586 	if (vmcs_save(&current_vmcs))
3587 		return false;
3588 
3589 	return current_vmcs && !(current_vmcs->revision_id >> 31);
3590 }
3591 
3592 static void try_vmentry_in_movss_shadow(void)
3593 {
3594 	u32 vm_inst_err;
3595 	u32 flags;
3596 	bool early_failure = false;
3597 	u32 expected_flags = X86_EFLAGS_FIXED;
3598 	bool valid_vmcs = valid_vmcs_for_vmentry();
3599 
3600 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
3601 
3602 	/*
3603 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3604 	 * unsupported VMCS component").
3605 	 */
3606 	vmcs_write(~0u, 0);
3607 
3608 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
3609 			      "vmwrite %%rsp, %%rdx;"
3610 			      "mov 0f, %%rax;"
3611 			      "mov %[host_rip], %%edx;"
3612 			      "vmwrite %%rax, %%rdx;"
3613 			      "mov $-1, %%ah;"
3614 			      "sahf;"
3615 			      "mov %%ss, %%ax;"
3616 			      "mov %%ax, %%ss;"
3617 			      "vmlaunch;"
3618 			      "mov $1, %[early_failure];"
3619 			      "0: lahf;"
3620 			      "movzbl %%ah, %[flags]"
3621 			      : [early_failure] "+r" (early_failure),
3622 				[flags] "=&a" (flags)
3623 			      : [host_rsp] "i" (HOST_RSP),
3624 				[host_rip] "i" (HOST_RIP)
3625 			      : "rdx", "cc", "memory");
3626 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
3627 
3628 	report("Early VM-entry failure", early_failure);
3629 	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
3630 	       expected_flags, flags);
3631 	if (valid_vmcs)
3632 		report("VM-instruction error is %d (actual %d)",
3633 		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
3634 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
3635 }
3636 
3637 static void vmentry_movss_shadow_test(void)
3638 {
3639 	struct vmcs *orig_vmcs;
3640 
3641 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
3642 
3643 	/*
3644 	 * Set the launched flag on the current VMCS to verify the correct
3645 	 * error priority, below.
3646 	 */
3647 	test_set_guest(v2_null_test_guest);
3648 	enter_guest();
3649 
3650 	/*
3651 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
3652 	 * fail due to invalid guest state (if we make it that far).
3653 	 */
3654 	vmcs_write(GUEST_RFLAGS, 0);
3655 
3656 	/*
3657 	 * "VM entry with events blocked by MOV SS" takes precedence over
3658 	 * "VMLAUNCH with non-clear VMCS."
3659 	 */
3660 	report_prefix_push("valid current-VMCS");
3661 	try_vmentry_in_movss_shadow();
3662 	report_prefix_pop();
3663 
3664 	/*
3665 	 * VMfailInvalid takes precedence over "VM entry with events
3666 	 * blocked by MOV SS."
3667 	 */
3668 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
3669 	report_prefix_push("no current-VMCS");
3670 	try_vmentry_in_movss_shadow();
3671 	report_prefix_pop();
3672 
3673 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
3674 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
3675 }
3676 
3677 #define X86_FEATURE_PCID       (1 << 17)
3678 #define X86_FEATURE_MCE        (1 << 7)
3679 
3680 static int write_cr4_checking(unsigned long val)
3681 {
3682 	asm volatile(ASM_TRY("1f")
3683 		     "mov %0, %%cr4\n\t"
3684 		     "1:": : "r" (val));
3685 	return exception_vector();
3686 }
3687 
3688 static void vmx_cr_load_test(void)
3689 {
3690 	struct cpuid _cpuid = cpuid(1);
3691 	unsigned long cr4 = read_cr4(), cr3 = read_cr3();
3692 
3693 	if (!(_cpuid.c & X86_FEATURE_PCID)) {
3694 		report_skip("PCID not detected");
3695 		return;
3696 	}
3697 	if (!(_cpuid.d & X86_FEATURE_MCE)) {
3698 		report_skip("MCE not detected");
3699 		return;
3700 	}
3701 
3702 	TEST_ASSERT(!(cr4 & (X86_CR4_PCIDE | X86_CR4_MCE)));
3703 	TEST_ASSERT(!(cr3 & X86_CR3_PCID_MASK));
3704 
3705 	/* Enable PCID for L1. */
3706 	cr4 |= X86_CR4_PCIDE;
3707 	cr3 |= 0x1;
3708 	TEST_ASSERT(!write_cr4_checking(cr4));
3709 	write_cr3(cr3);
3710 
3711 	test_set_guest(v2_null_test_guest);
3712 	vmcs_write(HOST_CR4, cr4);
3713 	vmcs_write(HOST_CR3, cr3);
3714 	enter_guest();
3715 
3716 	/*
3717 	 * No exception is expected.
3718 	 *
3719 	 * NB. KVM loads the last guest write to CR4 into CR4 read
3720 	 *     shadow. In order to trigger an exit to KVM, we can set a
3721 	 *     bit that was zero in the above CR4 write and is owned by
3722 	 *     KVM. We choose to set CR4.MCE, which shall have no side
3723 	 *     effect because normally no guest MCE (e.g., as the result
3724 	 *     of bad memory) would happen during this test.
3725 	 */
3726 	TEST_ASSERT(!write_cr4_checking(cr4 | X86_CR4_MCE));
3727 
3728 	/* Cleanup L1 state: disable PCID. */
3729 	write_cr3(cr3 & ~X86_CR3_PCID_MASK);
3730 	TEST_ASSERT(!write_cr4_checking(cr4 & ~X86_CR4_PCIDE));
3731 }
3732 
3733 #define TEST(name) { #name, .v2 = name }
3734 
3735 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
3736 struct vmx_test vmx_tests[] = {
3737 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
3738 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
3739 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
3740 		preemption_timer_exit_handler, NULL, {0} },
3741 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
3742 		test_ctrl_pat_exit_handler, NULL, {0} },
3743 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
3744 		test_ctrl_efer_exit_handler, NULL, {0} },
3745 	{ "CR shadowing", NULL, cr_shadowing_main,
3746 		cr_shadowing_exit_handler, NULL, {0} },
3747 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
3748 		NULL, {0} },
3749 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
3750 		insn_intercept_exit_handler, NULL, {0} },
3751 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
3752 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
3753 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
3754 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
3755 	{ "interrupt", interrupt_init, interrupt_main,
3756 		interrupt_exit_handler, NULL, {0} },
3757 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
3758 		NULL, {0} },
3759 	{ "MSR switch", msr_switch_init, msr_switch_main,
3760 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
3761 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
3762 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
3763 		disable_rdtscp_exit_handler, NULL, {0} },
3764 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
3765 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
3766 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
3767 		exit_monitor_from_l2_handler, NULL, {0} },
3768 	/* Basic V2 tests. */
3769 	TEST(v2_null_test),
3770 	TEST(v2_multiple_entries_test),
3771 	TEST(fixture_test_case1),
3772 	TEST(fixture_test_case2),
3773 	/* EPT access tests. */
3774 	TEST(ept_access_test_not_present),
3775 	TEST(ept_access_test_read_only),
3776 	TEST(ept_access_test_write_only),
3777 	TEST(ept_access_test_read_write),
3778 	TEST(ept_access_test_execute_only),
3779 	TEST(ept_access_test_read_execute),
3780 	TEST(ept_access_test_write_execute),
3781 	TEST(ept_access_test_read_write_execute),
3782 	TEST(ept_access_test_reserved_bits),
3783 	TEST(ept_access_test_ignored_bits),
3784 	TEST(ept_access_test_paddr_not_present_ad_disabled),
3785 	TEST(ept_access_test_paddr_not_present_ad_enabled),
3786 	TEST(ept_access_test_paddr_read_only_ad_disabled),
3787 	TEST(ept_access_test_paddr_read_only_ad_enabled),
3788 	TEST(ept_access_test_paddr_read_write),
3789 	TEST(ept_access_test_paddr_read_write_execute),
3790 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
3791 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
3792 	TEST(ept_access_test_paddr_not_present_page_fault),
3793 	TEST(ept_access_test_force_2m_page),
3794 	/* Opcode tests. */
3795 	TEST(invvpid_test_v2),
3796 	/* VM-entry tests */
3797 	TEST(vmx_controls_test),
3798 	TEST(vmentry_movss_shadow_test),
3799 	/* Regression tests */
3800 	TEST(vmx_cr_load_test),
3801 	{ NULL, NULL, NULL, NULL, NULL, {0} },
3802 };
3803