xref: /kvm-unit-tests/x86/vmx_tests.c (revision 1d371fd5ade2c52093fcffbed11c76d767626dd2)
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 	apic_write(APIC_TMICT, 0);
1589 	irq_enable();
1590 	timer_fired = false;
1591 	vmcall();
1592 	report("Inject an event to a halted guest", timer_fired);
1593 }
1594 
1595 static int interrupt_exit_handler(void)
1596 {
1597 	u64 guest_rip = vmcs_read(GUEST_RIP);
1598 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1599 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1600 
1601 	switch (reason) {
1602 	case VMX_VMCALL:
1603 		switch (vmx_get_test_stage()) {
1604 		case 0:
1605 		case 2:
1606 		case 5:
1607 			vmcs_write(PIN_CONTROLS,
1608 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1609 			break;
1610 		case 7:
1611 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1612 			vmcs_write(PIN_CONTROLS,
1613 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1614 			break;
1615 		case 1:
1616 		case 3:
1617 			vmcs_write(PIN_CONTROLS,
1618 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1619 			break;
1620 		case 4:
1621 		case 6:
1622 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1623 			break;
1624 
1625 		case 8:
1626 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1627 			vmcs_write(ENT_INTR_INFO,
1628 				   TIMER_VECTOR |
1629 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1630 				   INTR_INFO_VALID_MASK);
1631 			break;
1632 		}
1633 		vmx_inc_test_stage();
1634 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1635 		return VMX_TEST_RESUME;
1636 	case VMX_EXTINT:
1637 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1638 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1639 			handle_external_interrupt(vector);
1640 		} else {
1641 			irq_enable();
1642 			asm volatile ("nop");
1643 			irq_disable();
1644 		}
1645 		if (vmx_get_test_stage() >= 2)
1646 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1647 		return VMX_TEST_RESUME;
1648 	default:
1649 		report("Unknown exit reason, %ld", false, reason);
1650 		print_vmexit_info();
1651 	}
1652 
1653 	return VMX_TEST_VMEXIT;
1654 }
1655 
1656 static int dbgctls_init(struct vmcs *vmcs)
1657 {
1658 	u64 dr7 = 0x402;
1659 	u64 zero = 0;
1660 
1661 	msr_bmp_init();
1662 	asm volatile(
1663 		"mov %0,%%dr0\n\t"
1664 		"mov %0,%%dr1\n\t"
1665 		"mov %0,%%dr2\n\t"
1666 		"mov %1,%%dr7\n\t"
1667 		: : "r" (zero), "r" (dr7));
1668 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1669 	vmcs_write(GUEST_DR7, 0x404);
1670 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1671 
1672 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1673 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1674 
1675 	return VMX_TEST_START;
1676 }
1677 
1678 static void dbgctls_main(void)
1679 {
1680 	u64 dr7, debugctl;
1681 
1682 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1683 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1684 	/* Commented out: KVM does not support DEBUGCTL so far */
1685 	(void)debugctl;
1686 	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);
1687 
1688 	dr7 = 0x408;
1689 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1690 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1691 
1692 	vmx_set_test_stage(0);
1693 	vmcall();
1694 	report("Save debug controls", vmx_get_test_stage() == 1);
1695 
1696 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1697 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1698 		printf("\tDebug controls are always loaded/saved\n");
1699 		return;
1700 	}
1701 	vmx_set_test_stage(2);
1702 	vmcall();
1703 
1704 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1705 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1706 	/* Commented out: KVM does not support DEBUGCTL so far */
1707 	(void)debugctl;
1708 	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);
1709 
1710 	dr7 = 0x408;
1711 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1712 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1713 
1714 	vmx_set_test_stage(3);
1715 	vmcall();
1716 	report("Don't save debug controls", vmx_get_test_stage() == 4);
1717 }
1718 
1719 static int dbgctls_exit_handler(void)
1720 {
1721 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1722 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1723 	u64 guest_rip = vmcs_read(GUEST_RIP);
1724 	u64 dr7, debugctl;
1725 
1726 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1727 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1728 
1729 	switch (reason) {
1730 	case VMX_VMCALL:
1731 		switch (vmx_get_test_stage()) {
1732 		case 0:
1733 			if (dr7 == 0x400 && debugctl == 0 &&
1734 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1735 			    Commented out: KVM does not support DEBUGCTL so far
1736 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1737 				vmx_inc_test_stage();
1738 			break;
1739 		case 2:
1740 			dr7 = 0x402;
1741 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1742 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1743 			vmcs_write(GUEST_DR7, 0x404);
1744 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1745 
1746 			vmcs_write(ENT_CONTROLS,
1747 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1748 			vmcs_write(EXI_CONTROLS,
1749 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1750 			break;
1751 		case 3:
1752 			if (dr7 == 0x400 && debugctl == 0 &&
1753 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1754 			    Commented out: KVM does not support DEBUGCTL so far
1755 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1756 				vmx_inc_test_stage();
1757 			break;
1758 		}
1759 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1760 		return VMX_TEST_RESUME;
1761 	default:
1762 		report("Unknown exit reason, %d", false, reason);
1763 		print_vmexit_info();
1764 	}
1765 	return VMX_TEST_VMEXIT;
1766 }
1767 
1768 struct vmx_msr_entry {
1769 	u32 index;
1770 	u32 reserved;
1771 	u64 value;
1772 } __attribute__((packed));
1773 
1774 #define MSR_MAGIC 0x31415926
1775 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1776 
1777 static int msr_switch_init(struct vmcs *vmcs)
1778 {
1779 	msr_bmp_init();
1780 	exit_msr_store = alloc_page();
1781 	exit_msr_load = alloc_page();
1782 	entry_msr_load = alloc_page();
1783 	memset(exit_msr_store, 0, PAGE_SIZE);
1784 	memset(exit_msr_load, 0, PAGE_SIZE);
1785 	memset(entry_msr_load, 0, PAGE_SIZE);
1786 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1787 	entry_msr_load[0].value = MSR_MAGIC;
1788 
1789 	vmx_set_test_stage(1);
1790 	vmcs_write(ENT_MSR_LD_CNT, 1);
1791 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1792 	vmcs_write(EXI_MSR_ST_CNT, 1);
1793 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1794 	vmcs_write(EXI_MSR_LD_CNT, 1);
1795 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1796 	return VMX_TEST_START;
1797 }
1798 
1799 static void msr_switch_main()
1800 {
1801 	if (vmx_get_test_stage() == 1) {
1802 		report("VM entry MSR load",
1803 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
1804 		vmx_set_test_stage(2);
1805 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1806 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1807 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1808 		exit_msr_load[0].value = MSR_MAGIC + 2;
1809 	}
1810 	vmcall();
1811 }
1812 
1813 static int msr_switch_exit_handler()
1814 {
1815 	ulong reason;
1816 
1817 	reason = vmcs_read(EXI_REASON);
1818 	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
1819 		report("VM exit MSR store",
1820 			exit_msr_store[0].value == MSR_MAGIC + 1);
1821 		report("VM exit MSR load",
1822 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
1823 		vmx_set_test_stage(3);
1824 		entry_msr_load[0].index = MSR_FS_BASE;
1825 		return VMX_TEST_RESUME;
1826 	}
1827 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1828 		__func__, vmx_get_test_stage(), reason);
1829 	return VMX_TEST_EXIT;
1830 }
1831 
1832 static int msr_switch_entry_failure(struct vmentry_failure *failure)
1833 {
1834 	ulong reason;
1835 
1836 	if (failure->early) {
1837 		printf("ERROR %s: early exit\n", __func__);
1838 		return VMX_TEST_EXIT;
1839 	}
1840 
1841 	reason = vmcs_read(EXI_REASON);
1842 	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
1843 	    vmx_get_test_stage() == 3) {
1844 		report("VM entry MSR load: try to load FS_BASE",
1845 			vmcs_read(EXI_QUALIFICATION) == 1);
1846 		return VMX_TEST_VMEXIT;
1847 	}
1848 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1849 		__func__, vmx_get_test_stage(), reason);
1850 	return VMX_TEST_EXIT;
1851 }
1852 
1853 static int vmmcall_init(struct vmcs *vmcs	)
1854 {
1855 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1856 	return VMX_TEST_START;
1857 }
1858 
1859 static void vmmcall_main(void)
1860 {
1861 	asm volatile(
1862 		"mov $0xABCD, %%rax\n\t"
1863 		"vmmcall\n\t"
1864 		::: "rax");
1865 
1866 	report("VMMCALL", 0);
1867 }
1868 
1869 static int vmmcall_exit_handler()
1870 {
1871 	ulong reason;
1872 
1873 	reason = vmcs_read(EXI_REASON);
1874 	switch (reason) {
1875 	case VMX_VMCALL:
1876 		printf("here\n");
1877 		report("VMMCALL triggers #UD", 0);
1878 		break;
1879 	case VMX_EXC_NMI:
1880 		report("VMMCALL triggers #UD",
1881 		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
1882 		break;
1883 	default:
1884 		report("Unknown exit reason, %ld", false, reason);
1885 		print_vmexit_info();
1886 	}
1887 
1888 	return VMX_TEST_VMEXIT;
1889 }
1890 
1891 static int disable_rdtscp_init(struct vmcs *vmcs)
1892 {
1893 	u32 ctrl_cpu1;
1894 
1895 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
1896 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1897 		ctrl_cpu1 &= ~CPU_RDTSCP;
1898 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1899 	}
1900 
1901 	return VMX_TEST_START;
1902 }
1903 
1904 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
1905 {
1906 	switch (vmx_get_test_stage()) {
1907 	case 0:
1908 		report("RDTSCP triggers #UD", true);
1909 		vmx_inc_test_stage();
1910 		regs->rip += 3;
1911 		break;
1912 	case 2:
1913 		report("RDPID triggers #UD", true);
1914 		vmx_inc_test_stage();
1915 		regs->rip += 4;
1916 		break;
1917 	}
1918 	return;
1919 
1920 }
1921 
1922 static void disable_rdtscp_main(void)
1923 {
1924 	/* Test that #UD is properly injected in L2.  */
1925 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
1926 
1927 	vmx_set_test_stage(0);
1928 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
1929 	vmcall();
1930 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
1931 	vmcall();
1932 }
1933 
1934 static int disable_rdtscp_exit_handler(void)
1935 {
1936 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1937 
1938 	switch (reason) {
1939 	case VMX_VMCALL:
1940 		switch (vmx_get_test_stage()) {
1941 		case 0:
1942 			report("RDTSCP triggers #UD", false);
1943 			vmx_inc_test_stage();
1944 			/* fallthrough */
1945 		case 1:
1946 			vmx_inc_test_stage();
1947 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
1948 			return VMX_TEST_RESUME;
1949 		case 2:
1950 			report("RDPID triggers #UD", false);
1951 			break;
1952 		}
1953 		break;
1954 
1955 	default:
1956 		report("Unknown exit reason, %d", false, reason);
1957 		print_vmexit_info();
1958 	}
1959 	return VMX_TEST_VMEXIT;
1960 }
1961 
1962 int int3_init()
1963 {
1964 	vmcs_write(EXC_BITMAP, ~0u);
1965 	return VMX_TEST_START;
1966 }
1967 
1968 void int3_guest_main()
1969 {
1970 	asm volatile ("int3");
1971 }
1972 
1973 int int3_exit_handler()
1974 {
1975 	u32 reason = vmcs_read(EXI_REASON);
1976 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
1977 
1978 	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
1979 	       (intr_info & INTR_INFO_VALID_MASK) &&
1980 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
1981 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
1982 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
1983 
1984 	return VMX_TEST_VMEXIT;
1985 }
1986 
1987 int into_init()
1988 {
1989 	vmcs_write(EXC_BITMAP, ~0u);
1990 	return VMX_TEST_START;
1991 }
1992 
1993 void into_guest_main()
1994 {
1995 	struct far_pointer32 fp = {
1996 		.offset = (uintptr_t)&&into,
1997 		.selector = KERNEL_CS32,
1998 	};
1999 	register uintptr_t rsp asm("rsp");
2000 
2001 	if (fp.offset != (uintptr_t)&&into) {
2002 		printf("Code address too high.\n");
2003 		return;
2004 	}
2005 	if ((u32)rsp != rsp) {
2006 		printf("Stack address too high.\n");
2007 		return;
2008 	}
2009 
2010 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2011 	return;
2012 into:
2013 	asm volatile (".code32;"
2014 		      "movl $0x7fffffff, %eax;"
2015 		      "addl %eax, %eax;"
2016 		      "into;"
2017 		      "lret;"
2018 		      ".code64");
2019 	__builtin_unreachable();
2020 }
2021 
2022 int into_exit_handler()
2023 {
2024 	u32 reason = vmcs_read(EXI_REASON);
2025 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2026 
2027 	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
2028 	       (intr_info & INTR_INFO_VALID_MASK) &&
2029 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2030 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2031 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2032 
2033 	return VMX_TEST_VMEXIT;
2034 }
2035 
2036 static void exit_monitor_from_l2_main(void)
2037 {
2038 	printf("Calling exit(0) from l2...\n");
2039 	exit(0);
2040 }
2041 
2042 static int exit_monitor_from_l2_handler(void)
2043 {
2044 	report("The guest should have killed the VMM", false);
2045 	return VMX_TEST_EXIT;
2046 }
2047 
2048 static void assert_exit_reason(u64 expected)
2049 {
2050 	u64 actual = vmcs_read(EXI_REASON);
2051 
2052 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2053 			   exit_reason_description(expected),
2054 			   exit_reason_description(actual));
2055 }
2056 
2057 static void skip_exit_vmcall()
2058 {
2059 	u64 guest_rip = vmcs_read(GUEST_RIP);
2060 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2061 
2062 	assert_exit_reason(VMX_VMCALL);
2063 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2064 }
2065 
2066 static void v2_null_test_guest(void)
2067 {
2068 }
2069 
2070 static void v2_null_test(void)
2071 {
2072 	test_set_guest(v2_null_test_guest);
2073 	enter_guest();
2074 	report(__func__, 1);
2075 }
2076 
2077 static void v2_multiple_entries_test_guest(void)
2078 {
2079 	vmx_set_test_stage(1);
2080 	vmcall();
2081 	vmx_set_test_stage(2);
2082 }
2083 
2084 static void v2_multiple_entries_test(void)
2085 {
2086 	test_set_guest(v2_multiple_entries_test_guest);
2087 	enter_guest();
2088 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2089 	skip_exit_vmcall();
2090 	enter_guest();
2091 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2092 	report(__func__, 1);
2093 }
2094 
2095 static int fixture_test_data = 1;
2096 
2097 static void fixture_test_teardown(void *data)
2098 {
2099 	*((int *) data) = 1;
2100 }
2101 
2102 static void fixture_test_guest(void)
2103 {
2104 	fixture_test_data++;
2105 }
2106 
2107 
2108 static void fixture_test_setup(void)
2109 {
2110 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2111 			   "fixture_test_teardown didn't run?!");
2112 	fixture_test_data = 2;
2113 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2114 	test_set_guest(fixture_test_guest);
2115 }
2116 
2117 static void fixture_test_case1(void)
2118 {
2119 	fixture_test_setup();
2120 	TEST_ASSERT_EQ(2, fixture_test_data);
2121 	enter_guest();
2122 	TEST_ASSERT_EQ(3, fixture_test_data);
2123 	report(__func__, 1);
2124 }
2125 
2126 static void fixture_test_case2(void)
2127 {
2128 	fixture_test_setup();
2129 	TEST_ASSERT_EQ(2, fixture_test_data);
2130 	enter_guest();
2131 	TEST_ASSERT_EQ(3, fixture_test_data);
2132 	report(__func__, 1);
2133 }
2134 
2135 enum ept_access_op {
2136 	OP_READ,
2137 	OP_WRITE,
2138 	OP_EXEC,
2139 	OP_FLUSH_TLB,
2140 	OP_EXIT,
2141 };
2142 
2143 static struct ept_access_test_data {
2144 	unsigned long gpa;
2145 	unsigned long *gva;
2146 	unsigned long hpa;
2147 	unsigned long *hva;
2148 	enum ept_access_op op;
2149 } ept_access_test_data;
2150 
2151 extern unsigned char ret42_start;
2152 extern unsigned char ret42_end;
2153 
2154 /* Returns 42. */
2155 asm(
2156 	".align 64\n"
2157 	"ret42_start:\n"
2158 	"mov $42, %eax\n"
2159 	"ret\n"
2160 	"ret42_end:\n"
2161 );
2162 
2163 static void
2164 diagnose_ept_violation_qual(u64 expected, u64 actual)
2165 {
2166 
2167 #define DIAGNOSE(flag)							\
2168 do {									\
2169 	if ((expected & flag) != (actual & flag))			\
2170 		printf(#flag " %sexpected\n",				\
2171 		       (expected & flag) ? "" : "un");			\
2172 } while (0)
2173 
2174 	DIAGNOSE(EPT_VLT_RD);
2175 	DIAGNOSE(EPT_VLT_WR);
2176 	DIAGNOSE(EPT_VLT_FETCH);
2177 	DIAGNOSE(EPT_VLT_PERM_RD);
2178 	DIAGNOSE(EPT_VLT_PERM_WR);
2179 	DIAGNOSE(EPT_VLT_PERM_EX);
2180 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2181 	DIAGNOSE(EPT_VLT_PADDR);
2182 
2183 #undef DIAGNOSE
2184 }
2185 
2186 static void do_ept_access_op(enum ept_access_op op)
2187 {
2188 	ept_access_test_data.op = op;
2189 	enter_guest();
2190 }
2191 
2192 /*
2193  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2194  * needed by tests that modify guest PTEs.
2195  */
2196 static void ept_access_test_guest_flush_tlb(void)
2197 {
2198 	do_ept_access_op(OP_FLUSH_TLB);
2199 	skip_exit_vmcall();
2200 }
2201 
2202 /*
2203  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2204  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2205  * a huge page.
2206  */
2207 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2208 				 unsigned long clear, unsigned long set)
2209 {
2210 	struct ept_access_test_data *data = &ept_access_test_data;
2211 	unsigned long orig_pte;
2212 	unsigned long pte;
2213 
2214 	/* Screw with the mapping at the requested level. */
2215 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2216 	pte = orig_pte;
2217 	if (mkhuge)
2218 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2219 	else
2220 		pte = orig_pte;
2221 	pte = (pte & ~clear) | set;
2222 	set_ept_pte(pml4, gpa, level, pte);
2223 	ept_sync(INVEPT_SINGLE, eptp);
2224 
2225 	return orig_pte;
2226 }
2227 
2228 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2229 {
2230 	set_ept_pte(pml4, gpa, level, orig_pte);
2231 }
2232 
2233 static void do_ept_violation(bool leaf, enum ept_access_op op,
2234 			     u64 expected_qual, u64 expected_paddr)
2235 {
2236 	u64 qual;
2237 
2238 	/* Try the access and observe the violation. */
2239 	do_ept_access_op(op);
2240 
2241 	assert_exit_reason(VMX_EPT_VIOLATION);
2242 
2243 	qual = vmcs_read(EXI_QUALIFICATION);
2244 
2245 	diagnose_ept_violation_qual(expected_qual, qual);
2246 	TEST_EXPECT_EQ(expected_qual, qual);
2247 
2248 	#if 0
2249 	/* Disable for now otherwise every test will fail */
2250 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2251 		       (unsigned long) (
2252 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2253 	#endif
2254 	/*
2255 	 * TODO: tests that probe expected_paddr in pages other than the one at
2256 	 * the beginning of the 1g region.
2257 	 */
2258 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2259 }
2260 
2261 static void
2262 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2263 			      unsigned long set, enum ept_access_op op,
2264 			      u64 expected_qual)
2265 {
2266 	struct ept_access_test_data *data = &ept_access_test_data;
2267 	unsigned long orig_pte;
2268 
2269 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2270 
2271 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2272 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2273 					 data->gpa);
2274 
2275 	/* Fix the violation and resume the op loop. */
2276 	ept_untwiddle(data->gpa, level, orig_pte);
2277 	enter_guest();
2278 	skip_exit_vmcall();
2279 }
2280 
2281 static void
2282 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2283 		       enum ept_access_op op, u64 expected_qual)
2284 {
2285 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2286 				      expected_qual);
2287 	if (ept_huge_pages_supported(level))
2288 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2289 					      expected_qual);
2290 }
2291 
2292 static void ept_violation(unsigned long clear, unsigned long set,
2293 			  enum ept_access_op op, u64 expected_qual)
2294 {
2295 	ept_violation_at_level(1, clear, set, op, expected_qual);
2296 	ept_violation_at_level(2, clear, set, op, expected_qual);
2297 	ept_violation_at_level(3, clear, set, op, expected_qual);
2298 	ept_violation_at_level(4, clear, set, op, expected_qual);
2299 }
2300 
2301 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2302 				       u64 expected_qual)
2303 {
2304 	ept_violation(EPT_PRESENT, access, op,
2305 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2306 }
2307 
2308 /*
2309  * For translations that don't involve a GVA, that is physical address (paddr)
2310  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2311  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2312  * translations don't involve GVAs, such as when the hardware does the guest
2313  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2314  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2315  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2316  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2317  *
2318  * Note that paddr violations can also be triggered by loading PAE page tables
2319  * with wonky addresses. We don't test that yet.
2320  *
2321  * This function modifies the EPT entry that maps the GPA that the guest page
2322  * table entry mapping ept_access_data.gva resides on.
2323  *
2324  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2325  *
2326  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2327  *
2328  *	@op		Guest operation to perform with ept_access_data.gva.
2329  *
2330  *	@expect_violation
2331  *			Is a violation expected during the paddr access?
2332  *
2333  *	@expected_qual	Expected qualification for the EPT violation.
2334  *			EPT_VLT_PADDR should be clear.
2335  */
2336 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2337 			     enum ept_access_op op, bool expect_violation,
2338 			     u64 expected_qual)
2339 {
2340 	struct ept_access_test_data *data = &ept_access_test_data;
2341 	unsigned long *ptep;
2342 	unsigned long gpa;
2343 	unsigned long orig_epte;
2344 
2345 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2346 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2347 	TEST_ASSERT(ptep);
2348 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2349 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2350 	ept_access_test_guest_flush_tlb();
2351 
2352 	/*
2353 	 * Now modify the access bits on the EPT entry for the GPA that the
2354 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2355 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2356 	 * constructed our test such that those other 511 PTEs aren't used by
2357 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2358 	 * PTE we're modifying is at the beginning of a 4K page and the
2359 	 * following 511 entires are also under our control (and not touched by
2360 	 * the guest).
2361 	 */
2362 	gpa = virt_to_phys(ptep);
2363 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2364 	/*
2365 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2366 	 * otherwise our level=1 twiddling below will fail. We use the
2367 	 * identity map (gpa = gpa) since page tables are shared with the host.
2368 	 */
2369 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2370 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2371 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2372 
2373 	if (expect_violation) {
2374 		do_ept_violation(/*leaf=*/true, op,
2375 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2376 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2377 		do_ept_access_op(op);
2378 	} else {
2379 		do_ept_access_op(op);
2380 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2381 	}
2382 
2383 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2384 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2385 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2386 
2387 	skip_exit_vmcall();
2388 }
2389 
2390 static void ept_access_allowed_paddr(unsigned long ept_access,
2391 				     unsigned long pte_ad,
2392 				     enum ept_access_op op)
2393 {
2394 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2395 			 /*expected_qual=*/-1);
2396 }
2397 
2398 static void ept_access_violation_paddr(unsigned long ept_access,
2399 				       unsigned long pte_ad,
2400 				       enum ept_access_op op,
2401 				       u64 expected_qual)
2402 {
2403 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2404 			 expected_qual);
2405 }
2406 
2407 
2408 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2409 					unsigned long clear,
2410 					unsigned long set,
2411 					enum ept_access_op op)
2412 {
2413 	struct ept_access_test_data *data = &ept_access_test_data;
2414 	unsigned long orig_pte;
2415 
2416 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2417 
2418 	/* No violation. Should proceed to vmcall. */
2419 	do_ept_access_op(op);
2420 	skip_exit_vmcall();
2421 
2422 	ept_untwiddle(data->gpa, level, orig_pte);
2423 }
2424 
2425 static void ept_allowed_at_level(int level, unsigned long clear,
2426 				 unsigned long set, enum ept_access_op op)
2427 {
2428 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2429 	if (ept_huge_pages_supported(level))
2430 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2431 }
2432 
2433 static void ept_allowed(unsigned long clear, unsigned long set,
2434 			enum ept_access_op op)
2435 {
2436 	ept_allowed_at_level(1, clear, set, op);
2437 	ept_allowed_at_level(2, clear, set, op);
2438 	ept_allowed_at_level(3, clear, set, op);
2439 	ept_allowed_at_level(4, clear, set, op);
2440 }
2441 
2442 static void ept_ignored_bit(int bit)
2443 {
2444 	/* Set the bit. */
2445 	ept_allowed(0, 1ul << bit, OP_READ);
2446 	ept_allowed(0, 1ul << bit, OP_WRITE);
2447 	ept_allowed(0, 1ul << bit, OP_EXEC);
2448 
2449 	/* Clear the bit. */
2450 	ept_allowed(1ul << bit, 0, OP_READ);
2451 	ept_allowed(1ul << bit, 0, OP_WRITE);
2452 	ept_allowed(1ul << bit, 0, OP_EXEC);
2453 }
2454 
2455 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2456 {
2457 	ept_allowed(EPT_PRESENT, access, op);
2458 }
2459 
2460 
2461 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2462 					     unsigned long clear,
2463 					     unsigned long set,
2464 					     enum ept_access_op op)
2465 {
2466 	struct ept_access_test_data *data = &ept_access_test_data;
2467 	unsigned long orig_pte;
2468 
2469 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2470 
2471 	do_ept_access_op(op);
2472 	assert_exit_reason(VMX_EPT_MISCONFIG);
2473 
2474 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2475 	#if 0
2476 	/* broken: */
2477 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2478 	#endif
2479 	#if 0
2480 	/*
2481 	 * broken:
2482 	 * According to description of exit qual for EPT violation,
2483 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2484 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2485 	 * to be set for msiconfig.
2486 	 */
2487 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2488 		       (unsigned long) (
2489 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2490 	#endif
2491 
2492 	/* Fix the violation and resume the op loop. */
2493 	ept_untwiddle(data->gpa, level, orig_pte);
2494 	enter_guest();
2495 	skip_exit_vmcall();
2496 }
2497 
2498 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2499 					  unsigned long clear,
2500 					  unsigned long set)
2501 {
2502 	/* The op shouldn't matter (read, write, exec), so try them all! */
2503 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2504 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2505 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2506 }
2507 
2508 static void ept_misconfig_at_level(int level, unsigned long clear,
2509 				   unsigned long set)
2510 {
2511 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2512 	if (ept_huge_pages_supported(level))
2513 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2514 }
2515 
2516 static void ept_misconfig(unsigned long clear, unsigned long set)
2517 {
2518 	ept_misconfig_at_level(1, clear, set);
2519 	ept_misconfig_at_level(2, clear, set);
2520 	ept_misconfig_at_level(3, clear, set);
2521 	ept_misconfig_at_level(4, clear, set);
2522 }
2523 
2524 static void ept_access_misconfig(unsigned long access)
2525 {
2526 	ept_misconfig(EPT_PRESENT, access);
2527 }
2528 
2529 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2530 {
2531 	/* Setting the bit causes a misconfig. */
2532 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2533 
2534 	/* Making the entry non-present turns reserved bits into ignored. */
2535 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2536 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2537 }
2538 
2539 static void ept_reserved_bit_at_level_huge(int level, int bit)
2540 {
2541 	/* Setting the bit causes a misconfig. */
2542 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2543 
2544 	/* Making the entry non-present turns reserved bits into ignored. */
2545 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2546 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2547 }
2548 
2549 static void ept_reserved_bit_at_level(int level, int bit)
2550 {
2551 	/* Setting the bit causes a misconfig. */
2552 	ept_misconfig_at_level(level, 0, 1ul << bit);
2553 
2554 	/* Making the entry non-present turns reserved bits into ignored. */
2555 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2556 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2557 }
2558 
2559 static void ept_reserved_bit(int bit)
2560 {
2561 	ept_reserved_bit_at_level(1, bit);
2562 	ept_reserved_bit_at_level(2, bit);
2563 	ept_reserved_bit_at_level(3, bit);
2564 	ept_reserved_bit_at_level(4, bit);
2565 }
2566 
2567 #define PAGE_2M_ORDER 9
2568 #define PAGE_1G_ORDER 18
2569 
2570 static void *get_1g_page(void)
2571 {
2572 	static void *alloc;
2573 
2574 	if (!alloc)
2575 		alloc = alloc_pages(PAGE_1G_ORDER);
2576 	return alloc;
2577 }
2578 
2579 static void ept_access_test_teardown(void *unused)
2580 {
2581 	/* Exit the guest cleanly. */
2582 	do_ept_access_op(OP_EXIT);
2583 }
2584 
2585 static void ept_access_test_guest(void)
2586 {
2587 	struct ept_access_test_data *data = &ept_access_test_data;
2588 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2589 
2590 	while (true) {
2591 		switch (data->op) {
2592 		case OP_READ:
2593 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2594 			break;
2595 		case OP_WRITE:
2596 			*data->gva = MAGIC_VAL_2;
2597 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2598 			*data->gva = MAGIC_VAL_1;
2599 			break;
2600 		case OP_EXEC:
2601 			TEST_ASSERT_EQ(42, code());
2602 			break;
2603 		case OP_FLUSH_TLB:
2604 			write_cr3(read_cr3());
2605 			break;
2606 		case OP_EXIT:
2607 			return;
2608 		default:
2609 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2610 		}
2611 		vmcall();
2612 	}
2613 }
2614 
2615 static void ept_access_test_setup(void)
2616 {
2617 	struct ept_access_test_data *data = &ept_access_test_data;
2618 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2619 	unsigned long size = npages * PAGE_SIZE;
2620 	unsigned long *page_table = current_page_table();
2621 	unsigned long pte;
2622 
2623 	if (setup_ept(false))
2624 		test_skip("EPT not supported");
2625 
2626 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2627 	if (cpuid_maxphyaddr() < 40)
2628 		test_skip("Test needs MAXPHYADDR >= 40");
2629 
2630 	test_set_guest(ept_access_test_guest);
2631 	test_add_teardown(ept_access_test_teardown, NULL);
2632 
2633 	data->hva = get_1g_page();
2634 	TEST_ASSERT(data->hva);
2635 	data->hpa = virt_to_phys(data->hva);
2636 
2637 	data->gpa = 1ul << 39;
2638 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2639 				   size);
2640 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2641 	install_pages(page_table, data->gpa, size, data->gva);
2642 
2643 	/*
2644 	 * Make sure nothing's mapped here so the tests that screw with the
2645 	 * pml4 entry don't inadvertently break something.
2646 	 */
2647 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2648 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2649 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2650 
2651 	data->hva[0] = MAGIC_VAL_1;
2652 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2653 }
2654 
2655 static void ept_access_test_not_present(void)
2656 {
2657 	ept_access_test_setup();
2658 	/* --- */
2659 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2660 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2661 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2662 }
2663 
2664 static void ept_access_test_read_only(void)
2665 {
2666 	ept_access_test_setup();
2667 
2668 	/* r-- */
2669 	ept_access_allowed(EPT_RA, OP_READ);
2670 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2671 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2672 }
2673 
2674 static void ept_access_test_write_only(void)
2675 {
2676 	ept_access_test_setup();
2677 	/* -w- */
2678 	ept_access_misconfig(EPT_WA);
2679 }
2680 
2681 static void ept_access_test_read_write(void)
2682 {
2683 	ept_access_test_setup();
2684 	/* rw- */
2685 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2686 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2687 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2688 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2689 }
2690 
2691 
2692 static void ept_access_test_execute_only(void)
2693 {
2694 	ept_access_test_setup();
2695 	/* --x */
2696 	if (ept_execute_only_supported()) {
2697 		ept_access_violation(EPT_EA, OP_READ,
2698 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2699 		ept_access_violation(EPT_EA, OP_WRITE,
2700 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2701 		ept_access_allowed(EPT_EA, OP_EXEC);
2702 	} else {
2703 		ept_access_misconfig(EPT_EA);
2704 	}
2705 }
2706 
2707 static void ept_access_test_read_execute(void)
2708 {
2709 	ept_access_test_setup();
2710 	/* r-x */
2711 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2712 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2713 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2714 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2715 }
2716 
2717 static void ept_access_test_write_execute(void)
2718 {
2719 	ept_access_test_setup();
2720 	/* -wx */
2721 	ept_access_misconfig(EPT_WA | EPT_EA);
2722 }
2723 
2724 static void ept_access_test_read_write_execute(void)
2725 {
2726 	ept_access_test_setup();
2727 	/* rwx */
2728 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2729 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2730 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2731 }
2732 
2733 static void ept_access_test_reserved_bits(void)
2734 {
2735 	int i;
2736 	int maxphyaddr;
2737 
2738 	ept_access_test_setup();
2739 
2740 	/* Reserved bits above maxphyaddr. */
2741 	maxphyaddr = cpuid_maxphyaddr();
2742 	for (i = maxphyaddr; i <= 51; i++) {
2743 		report_prefix_pushf("reserved_bit=%d", i);
2744 		ept_reserved_bit(i);
2745 		report_prefix_pop();
2746 	}
2747 
2748 	/* Level-specific reserved bits. */
2749 	ept_reserved_bit_at_level_nohuge(2, 3);
2750 	ept_reserved_bit_at_level_nohuge(2, 4);
2751 	ept_reserved_bit_at_level_nohuge(2, 5);
2752 	ept_reserved_bit_at_level_nohuge(2, 6);
2753 	/* 2M alignment. */
2754 	for (i = 12; i < 20; i++) {
2755 		report_prefix_pushf("reserved_bit=%d", i);
2756 		ept_reserved_bit_at_level_huge(2, i);
2757 		report_prefix_pop();
2758 	}
2759 	ept_reserved_bit_at_level_nohuge(3, 3);
2760 	ept_reserved_bit_at_level_nohuge(3, 4);
2761 	ept_reserved_bit_at_level_nohuge(3, 5);
2762 	ept_reserved_bit_at_level_nohuge(3, 6);
2763 	/* 1G alignment. */
2764 	for (i = 12; i < 29; i++) {
2765 		report_prefix_pushf("reserved_bit=%d", i);
2766 		ept_reserved_bit_at_level_huge(3, i);
2767 		report_prefix_pop();
2768 	}
2769 	ept_reserved_bit_at_level(4, 3);
2770 	ept_reserved_bit_at_level(4, 4);
2771 	ept_reserved_bit_at_level(4, 5);
2772 	ept_reserved_bit_at_level(4, 6);
2773 	ept_reserved_bit_at_level(4, 7);
2774 }
2775 
2776 static void ept_access_test_ignored_bits(void)
2777 {
2778 	ept_access_test_setup();
2779 	/*
2780 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2781 	 * far as translation is concerned even if AD bits are enabled in the
2782 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2783 	 * control is 0.
2784 	 */
2785 	ept_ignored_bit(8);
2786 	ept_ignored_bit(9);
2787 	ept_ignored_bit(10);
2788 	ept_ignored_bit(11);
2789 	ept_ignored_bit(52);
2790 	ept_ignored_bit(53);
2791 	ept_ignored_bit(54);
2792 	ept_ignored_bit(55);
2793 	ept_ignored_bit(56);
2794 	ept_ignored_bit(57);
2795 	ept_ignored_bit(58);
2796 	ept_ignored_bit(59);
2797 	ept_ignored_bit(60);
2798 	ept_ignored_bit(61);
2799 	ept_ignored_bit(62);
2800 	ept_ignored_bit(63);
2801 }
2802 
2803 static void ept_access_test_paddr_not_present_ad_disabled(void)
2804 {
2805 	ept_access_test_setup();
2806 	ept_disable_ad_bits();
2807 
2808 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2809 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2810 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2811 }
2812 
2813 static void ept_access_test_paddr_not_present_ad_enabled(void)
2814 {
2815 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2816 
2817 	ept_access_test_setup();
2818 	ept_enable_ad_bits_or_skip_test();
2819 
2820 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2821 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2822 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2823 }
2824 
2825 static void ept_access_test_paddr_read_only_ad_disabled(void)
2826 {
2827 	/*
2828 	 * When EPT AD bits are disabled, all accesses to guest paging
2829 	 * structures are reported separately as a read and (after
2830 	 * translation of the GPA to host physical address) a read+write
2831 	 * if the A/D bits have to be set.
2832 	 */
2833 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2834 
2835 	ept_access_test_setup();
2836 	ept_disable_ad_bits();
2837 
2838 	/* Can't update A bit, so all accesses fail. */
2839 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2840 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2841 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2842 	/* AD bits disabled, so only writes try to update the D bit. */
2843 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
2844 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2845 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
2846 	/* Both A and D already set, so read-only is OK. */
2847 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
2848 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
2849 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
2850 }
2851 
2852 static void ept_access_test_paddr_read_only_ad_enabled(void)
2853 {
2854 	/*
2855 	 * When EPT AD bits are enabled, all accesses to guest paging
2856 	 * structures are considered writes as far as EPT translation
2857 	 * is concerned.
2858 	 */
2859 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2860 
2861 	ept_access_test_setup();
2862 	ept_enable_ad_bits_or_skip_test();
2863 
2864 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2865 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2866 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2867 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
2868 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2869 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
2870 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
2871 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
2872 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
2873 }
2874 
2875 static void ept_access_test_paddr_read_write(void)
2876 {
2877 	ept_access_test_setup();
2878 	/* Read-write access to paging structure. */
2879 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
2880 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
2881 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
2882 }
2883 
2884 static void ept_access_test_paddr_read_write_execute(void)
2885 {
2886 	ept_access_test_setup();
2887 	/* RWX access to paging structure. */
2888 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
2889 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
2890 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
2891 }
2892 
2893 static void ept_access_test_paddr_read_execute_ad_disabled(void)
2894 {
2895   	/*
2896 	 * When EPT AD bits are disabled, all accesses to guest paging
2897 	 * structures are reported separately as a read and (after
2898 	 * translation of the GPA to host physical address) a read+write
2899 	 * if the A/D bits have to be set.
2900 	 */
2901 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2902 
2903 	ept_access_test_setup();
2904 	ept_disable_ad_bits();
2905 
2906 	/* Can't update A bit, so all accesses fail. */
2907 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2908 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2909 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2910 	/* AD bits disabled, so only writes try to update the D bit. */
2911 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
2912 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2913 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
2914 	/* Both A and D already set, so read-only is OK. */
2915 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
2916 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
2917 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
2918 }
2919 
2920 static void ept_access_test_paddr_read_execute_ad_enabled(void)
2921 {
2922 	/*
2923 	 * When EPT AD bits are enabled, all accesses to guest paging
2924 	 * structures are considered writes as far as EPT translation
2925 	 * is concerned.
2926 	 */
2927 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2928 
2929 	ept_access_test_setup();
2930 	ept_enable_ad_bits_or_skip_test();
2931 
2932 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2933 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2934 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2935 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
2936 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2937 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
2938 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
2939 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
2940 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
2941 }
2942 
2943 static void ept_access_test_paddr_not_present_page_fault(void)
2944 {
2945 	ept_access_test_setup();
2946 	/*
2947 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
2948 	 * page is read-only in EPT but GVA is also mapped read only in PT.
2949 	 * Thus guest page fault before host takes EPT violation for trying to
2950 	 * update A bit.
2951 	 */
2952 }
2953 
2954 static void ept_access_test_force_2m_page(void)
2955 {
2956 	ept_access_test_setup();
2957 
2958 	TEST_ASSERT_EQ(ept_2m_supported(), true);
2959 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
2960 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
2961 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
2962 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2963 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
2964 }
2965 
2966 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
2967 {
2968 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
2969 
2970 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
2971 
2972 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
2973 		return false;
2974 
2975 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
2976 		return false;
2977 
2978 	if (vpid >> 16)
2979 		return false;
2980 
2981 	if (type != INVVPID_ALL && !vpid)
2982 		return false;
2983 
2984 	if (type == INVVPID_ADDR && !is_canonical(gla))
2985 		return false;
2986 
2987 	return true;
2988 }
2989 
2990 static void try_invvpid(u64 type, u64 vpid, u64 gla)
2991 {
2992 	int rc;
2993 	bool valid = invvpid_valid(type, vpid, gla);
2994 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
2995 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
2996 	/*
2997 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
2998 	 * that we can tell if it is updated by INVVPID.
2999 	 */
3000 	vmcs_read(~0);
3001 	rc = invvpid(type, vpid, gla);
3002 	report("INVVPID type %ld VPID %lx GLA %lx %s",
3003 	       !rc == valid, type, vpid, gla,
3004 	       valid ? "passes" : "fails");
3005 	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3006 	       vmcs_read(VMX_INST_ERROR) == expected,
3007 	       rc ? "failed" : "successful",
3008 	       expected, vmcs_read(VMX_INST_ERROR));
3009 }
3010 
3011 static void ds_invvpid(void *data)
3012 {
3013 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3014 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3015 
3016 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3017 	asm volatile("invvpid %0, %1"
3018 		     :
3019 		     : "m"(*(struct invvpid_operand *)data),
3020 		       "r"(type));
3021 }
3022 
3023 /*
3024  * The SS override is ignored in 64-bit mode, so we use an addressing
3025  * mode with %rsp as the base register to generate an implicit SS
3026  * reference.
3027  */
3028 static void ss_invvpid(void *data)
3029 {
3030 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3031 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3032 
3033 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3034 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3035 		     : "+r"(data)
3036 		     : "r"(type));
3037 }
3038 
3039 static void invvpid_test_gp(void)
3040 {
3041 	bool fault;
3042 
3043 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3044 				   (void *)NONCANONICAL);
3045 	report("INVVPID with non-canonical DS operand raises #GP", fault);
3046 }
3047 
3048 static void invvpid_test_ss(void)
3049 {
3050 	bool fault;
3051 
3052 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3053 				   (void *)NONCANONICAL);
3054 	report("INVVPID with non-canonical SS operand raises #SS", fault);
3055 }
3056 
3057 static void invvpid_test_pf(void)
3058 {
3059 	void *vpage = alloc_vpage();
3060 	bool fault;
3061 
3062 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3063 	report("INVVPID with unmapped operand raises #PF", fault);
3064 }
3065 
3066 static void try_compat_invvpid(void *unused)
3067 {
3068 	struct far_pointer32 fp = {
3069 		.offset = (uintptr_t)&&invvpid,
3070 		.selector = KERNEL_CS32,
3071 	};
3072 	register uintptr_t rsp asm("rsp");
3073 
3074 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3075 			"Code address too high.");
3076 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3077 
3078 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3079 	return;
3080 invvpid:
3081 	asm volatile (".code32;"
3082 		      "invvpid (%eax), %eax;"
3083 		      "lret;"
3084 		      ".code64");
3085 	__builtin_unreachable();
3086 }
3087 
3088 static void invvpid_test_compatibility_mode(void)
3089 {
3090 	bool fault;
3091 
3092 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3093 	report("Compatibility mode INVVPID raises #UD", fault);
3094 }
3095 
3096 static void invvpid_test_not_in_vmx_operation(void)
3097 {
3098 	bool fault;
3099 
3100 	TEST_ASSERT(!vmx_off());
3101 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3102 	report("INVVPID outside of VMX operation raises #UD", fault);
3103 	TEST_ASSERT(!vmx_on());
3104 }
3105 
3106 /*
3107  * This does not test real-address mode, virtual-8086 mode, protected mode,
3108  * or CPL > 0.
3109  */
3110 static void invvpid_test_v2(void)
3111 {
3112 	u64 msr;
3113 	int i;
3114 	unsigned types = 0;
3115 	unsigned type;
3116 
3117 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3118 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3119 		test_skip("VPID not supported");
3120 
3121 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3122 
3123 	if (!(msr & VPID_CAP_INVVPID))
3124 		test_skip("INVVPID not supported.\n");
3125 
3126 	if (msr & VPID_CAP_INVVPID_ADDR)
3127 		types |= 1u << INVVPID_ADDR;
3128 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3129 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3130 	if (msr & VPID_CAP_INVVPID_ALL)
3131 		types |= 1u << INVVPID_ALL;
3132 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3133 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3134 
3135 	if (!types)
3136 		test_skip("No INVVPID types supported.\n");
3137 
3138 	for (i = -127; i < 128; i++)
3139 		try_invvpid(i, 0xffff, 0);
3140 
3141 	/*
3142 	 * VPID must not be more than 16 bits.
3143 	 */
3144 	for (i = 0; i < 64; i++)
3145 		for (type = 0; type < 4; type++)
3146 			if (types & (1u << type))
3147 				try_invvpid(type, 1ul << i, 0);
3148 
3149 	/*
3150 	 * VPID must not be zero, except for "all contexts."
3151 	 */
3152 	for (type = 0; type < 4; type++)
3153 		if (types & (1u << type))
3154 			try_invvpid(type, 0, 0);
3155 
3156 	/*
3157 	 * The gla operand is only validated for single-address INVVPID.
3158 	 */
3159 	if (types & (1u << INVVPID_ADDR))
3160 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3161 
3162 	invvpid_test_gp();
3163 	invvpid_test_ss();
3164 	invvpid_test_pf();
3165 	invvpid_test_compatibility_mode();
3166 	invvpid_test_not_in_vmx_operation();
3167 }
3168 
3169 /*
3170  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3171  * at least as far as the guest-state checks. Returns false if the
3172  * VMLAUNCH fails early and execution falls through to the next
3173  * instruction.
3174  */
3175 static bool vmlaunch_succeeds(void)
3176 {
3177 	/*
3178 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3179 	 * unsupported VMCS component"). The caller can then check
3180 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3181 	 */
3182 	vmcs_write(~0u, 0);
3183 
3184 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3185 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3186 				   :
3187 				   : "r" ((u64)HOST_RSP)
3188 				   : "cc", "memory"
3189 				   : success);
3190 	return false;
3191 success:
3192 	TEST_ASSERT(vmcs_read(EXI_REASON) ==
3193 		    (VMX_FAIL_STATE | VMX_ENTRY_FAILURE));
3194 	return true;
3195 }
3196 
3197 /*
3198  * Try to launch the current VMCS.
3199  */
3200 static void test_vmx_controls(bool controls_valid, bool xfail)
3201 {
3202 	bool success = vmlaunch_succeeds();
3203 	u32 vmx_inst_err;
3204 
3205 	report_xfail("vmlaunch %s", xfail, success == controls_valid,
3206 		     controls_valid ? "succeeds" : "fails");
3207 	if (!success) {
3208 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3209 		report("VMX inst error is %d (actual %d)",
3210 		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
3211 		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
3212 	}
3213 }
3214 
3215 /*
3216  * Test a particular value of a VM-execution control bit, if the value
3217  * is required or if the value is zero.
3218  */
3219 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3220 				    enum Encoding encoding, unsigned bit,
3221 				    unsigned val)
3222 {
3223 	u32 mask = 1u << bit;
3224 	bool expected;
3225 	u32 controls;
3226 
3227 	if (msr.set & mask)
3228 		TEST_ASSERT(msr.clr & mask);
3229 
3230 	/*
3231 	 * We can't arbitrarily turn on a control bit, because it may
3232 	 * introduce dependencies on other VMCS fields. So, we only
3233 	 * test turning on bits that have a required setting.
3234 	 */
3235 	if (val && (msr.clr & mask) && !(msr.set & mask))
3236 		return;
3237 
3238 	report_prefix_pushf("%s %s bit %d",
3239 			    val ? "Set" : "Clear", name, bit);
3240 
3241 	controls = vmcs_read(encoding);
3242 	if (val) {
3243 		vmcs_write(encoding, msr.set | mask);
3244 		expected = (msr.clr & mask);
3245 	} else {
3246 		vmcs_write(encoding, msr.set & ~mask);
3247 		expected = !(msr.set & mask);
3248 	}
3249 	test_vmx_controls(expected, false);
3250 	vmcs_write(encoding, controls);
3251 	report_prefix_pop();
3252 }
3253 
3254 /*
3255  * Test reserved values of a VM-execution control bit, based on the
3256  * allowed bit settings from the corresponding VMX capability MSR.
3257  */
3258 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3259 			      enum Encoding encoding, unsigned bit)
3260 {
3261 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3262 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3263 }
3264 
3265 /*
3266  * Reserved bits in the pin-based VM-execution controls must be set
3267  * properly. Software may consult the VMX capability MSRs to determine
3268  * the proper settings.
3269  * [Intel SDM]
3270  */
3271 static void test_pin_based_ctls(void)
3272 {
3273 	unsigned bit;
3274 
3275 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3276 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3277 	for (bit = 0; bit < 32; bit++)
3278 		test_rsvd_ctl_bit("pin-based controls",
3279 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3280 }
3281 
3282 /*
3283  * Reserved bits in the primary processor-based VM-execution controls
3284  * must be set properly. Software may consult the VMX capability MSRs
3285  * to determine the proper settings.
3286  * [Intel SDM]
3287  */
3288 static void test_primary_processor_based_ctls(void)
3289 {
3290 	unsigned bit;
3291 
3292 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3293 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3294 	for (bit = 0; bit < 32; bit++)
3295 		test_rsvd_ctl_bit("primary processor-based controls",
3296 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3297 }
3298 
3299 /*
3300  * If the "activate secondary controls" primary processor-based
3301  * VM-execution control is 1, reserved bits in the secondary
3302  * processor-based VM-execution controls must be cleared. Software may
3303  * consult the VMX capability MSRs to determine which bits are
3304  * reserved.
3305  * If the "activate secondary controls" primary processor-based
3306  * VM-execution control is 0 (or if the processor does not support the
3307  * 1-setting of that control), no checks are performed on the
3308  * secondary processor-based VM-execution controls.
3309  * [Intel SDM]
3310  */
3311 static void test_secondary_processor_based_ctls(void)
3312 {
3313 	u32 primary;
3314 	u32 secondary;
3315 	unsigned bit;
3316 
3317 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3318 		return;
3319 
3320 	primary = vmcs_read(CPU_EXEC_CTRL0);
3321 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3322 
3323 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3324 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3325 	for (bit = 0; bit < 32; bit++)
3326 		test_rsvd_ctl_bit("secondary processor-based controls",
3327 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3328 
3329 	/*
3330 	 * When the "activate secondary controls" VM-execution control
3331 	 * is clear, there are no checks on the secondary controls.
3332 	 */
3333 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3334 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3335 	report("Secondary processor-based controls ignored",
3336 	       vmlaunch_succeeds());
3337 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3338 	vmcs_write(CPU_EXEC_CTRL0, primary);
3339 }
3340 
3341 static void try_cr3_target_count(unsigned i, unsigned max)
3342 {
3343 	report_prefix_pushf("CR3 target count 0x%x", i);
3344 	vmcs_write(CR3_TARGET_COUNT, i);
3345 	test_vmx_controls(i <= max, false);
3346 	report_prefix_pop();
3347 }
3348 
3349 /*
3350  * The CR3-target count must not be greater than 4. Future processors
3351  * may support a different number of CR3-target values. Software
3352  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3353  * number of values supported.
3354  * [Intel SDM]
3355  */
3356 static void test_cr3_targets(void)
3357 {
3358 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3359 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3360 	unsigned i;
3361 
3362 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3363 	TEST_ASSERT(supported_targets <= 256);
3364 
3365 	try_cr3_target_count(-1u, supported_targets);
3366 	try_cr3_target_count(0x80000000, supported_targets);
3367 	try_cr3_target_count(0x7fffffff, supported_targets);
3368 	for (i = 0; i <= supported_targets + 1; i++)
3369 		try_cr3_target_count(i, supported_targets);
3370 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3371 }
3372 
3373 /*
3374  * Test a particular address setting for a physical page reference in
3375  * the VMCS.
3376  */
3377 static void test_vmcs_page_addr(const char *name,
3378 				enum Encoding encoding,
3379 				bool ignored,
3380 				bool xfail_beyond_mapped_ram,
3381 				u64 addr)
3382 {
3383 	bool xfail =
3384 		(xfail_beyond_mapped_ram &&
3385 		 addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - PAGE_SIZE &&
3386 		 addr < (1ul << cpuid_maxphyaddr()));
3387 
3388 	report_prefix_pushf("%s = %lx", name, addr);
3389 	vmcs_write(encoding, addr);
3390 	test_vmx_controls(ignored || (IS_ALIGNED(addr, PAGE_SIZE) &&
3391 				  addr < (1ul << cpuid_maxphyaddr())),
3392 			  xfail);
3393 	report_prefix_pop();
3394 	xfail = false;
3395 }
3396 
3397 /*
3398  * Test interesting values for a physical page reference in the VMCS.
3399  */
3400 static void test_vmcs_page_values(const char *name,
3401 				  enum Encoding encoding,
3402 				  bool ignored,
3403 				  bool xfail_beyond_mapped_ram)
3404 {
3405 	unsigned i;
3406 	u64 orig_val = vmcs_read(encoding);
3407 
3408 	for (i = 0; i < 64; i++)
3409 		test_vmcs_page_addr(name, encoding, ignored,
3410 				    xfail_beyond_mapped_ram, 1ul << i);
3411 
3412 	test_vmcs_page_addr(name, encoding, ignored,
3413 			    xfail_beyond_mapped_ram, PAGE_SIZE - 1);
3414 	test_vmcs_page_addr(name, encoding, ignored,
3415 			    xfail_beyond_mapped_ram, PAGE_SIZE);
3416 	test_vmcs_page_addr(name, encoding, ignored,
3417 			    xfail_beyond_mapped_ram,
3418 			    (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3419 	test_vmcs_page_addr(name, encoding, ignored,
3420 			    xfail_beyond_mapped_ram,
3421 			    -1ul);
3422 
3423 	vmcs_write(encoding, orig_val);
3424 }
3425 
3426 /*
3427  * Test a physical page reference in the VMCS, when the corresponding
3428  * feature is enabled and when the corresponding feature is disabled.
3429  */
3430 static void test_vmcs_page_reference(u32 control_bit, enum Encoding field,
3431 				     const char *field_name,
3432 				     const char *control_name,
3433 				     bool xfail_beyond_mapped_ram)
3434 {
3435 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3436 	u64 page_addr;
3437 
3438 	if (!(ctrl_cpu_rev[0].clr & control_bit))
3439 		return;
3440 
3441 	page_addr = vmcs_read(field);
3442 
3443 	report_prefix_pushf("%s enabled", control_name);
3444 	vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3445 	test_vmcs_page_values(field_name, field, false, xfail_beyond_mapped_ram);
3446 	report_prefix_pop();
3447 
3448 	report_prefix_pushf("%s disabled", control_name);
3449 	vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3450 	test_vmcs_page_values(field_name, field, true, false);
3451 	report_prefix_pop();
3452 
3453 	vmcs_write(field, page_addr);
3454 	vmcs_write(CPU_EXEC_CTRL0, primary);
3455 }
3456 
3457 /*
3458  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3459  * each I/O-bitmap address must be 0. Neither address should set any
3460  * bits beyond the processor's physical-address width.
3461  * [Intel SDM]
3462  */
3463 static void test_io_bitmaps(void)
3464 {
3465 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3466 				 "I/O bitmap A", "Use I/O bitmaps", false);
3467 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3468 				 "I/O bitmap B", "Use I/O bitmaps", false);
3469 }
3470 
3471 /*
3472  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3473  * the MSR-bitmap address must be 0. The address should not set any
3474  * bits beyond the processor's physical-address width.
3475  * [Intel SDM]
3476  */
3477 static void test_msr_bitmap(void)
3478 {
3479 	test_vmcs_page_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3480 				 "MSR bitmap", "Use MSR bitmaps", false);
3481 }
3482 
3483 /*
3484  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3485  * address must satisfy the following checks:
3486  * - Bits 11:0 of the address must be 0.
3487  * - The address should not set any bits beyond the processor's
3488  *   physical-address width.
3489  * [Intel SDM]
3490  */
3491 static void test_apic_virt_addr(void)
3492 {
3493 	test_vmcs_page_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3494 				 "virtual-APIC address", "Use TPR shadow", true);
3495 }
3496 
3497 static void set_vtpr(unsigned vtpr)
3498 {
3499 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
3500 }
3501 
3502 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
3503 {
3504 	bool valid = true;
3505 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3506 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3507 
3508 	if ((primary & CPU_TPR_SHADOW) &&
3509 	    (!(primary & CPU_SECONDARY) ||
3510 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
3511 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
3512 
3513 	set_vtpr(vtpr);
3514 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
3515 	    threshold, (vtpr >> 4) & 0xf);
3516 	test_vmx_controls(valid, false);
3517 	report_prefix_pop();
3518 }
3519 
3520 /*
3521  * Test interesting vTPR values for a given TPR threshold.
3522  */
3523 static void test_vtpr_values(unsigned threshold)
3524 {
3525 	try_tpr_threshold_and_vtpr(threshold, threshold - 1);
3526 	try_tpr_threshold_and_vtpr(threshold, threshold);
3527 	try_tpr_threshold_and_vtpr(threshold, threshold + 1);
3528 }
3529 
3530 static void try_tpr_threshold(unsigned threshold)
3531 {
3532 	bool valid = true;
3533 
3534 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3535 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3536 
3537 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
3538 	    (secondary & CPU_VINTD)))
3539 		valid = !(threshold >> 4);
3540 
3541 	set_vtpr(-1);
3542 	vmcs_write(TPR_THRESHOLD, threshold);
3543 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
3544 	test_vmx_controls(valid, false);
3545 	report_prefix_pop();
3546 
3547 	if (valid)
3548 		test_vtpr_values(threshold);
3549 }
3550 
3551 /*
3552  * Test interesting TPR threshold values.
3553  */
3554 static void test_tpr_threshold_values(void)
3555 {
3556 	unsigned i;
3557 
3558 	for (i = 0; i < 0x10; i++)
3559 		try_tpr_threshold(i);
3560 	for (i = 4; i < 32; i++)
3561 		try_tpr_threshold(1u << i);
3562 	try_tpr_threshold(-1u);
3563 	try_tpr_threshold(0x7fffffff);
3564 }
3565 
3566 /*
3567  * This test covers the following two VM entry checks:
3568  *
3569  *      i) If the "use TPR shadow" VM-execution control is 1 and the
3570  *         "virtual-interrupt delivery" VM-execution control is 0, bits
3571  *         31:4 of the TPR threshold VM-execution control field must
3572 	   be 0.
3573  *         [Intel SDM]
3574  *
3575  *      ii) If the "use TPR shadow" VM-execution control is 1, the
3576  *          "virtual-interrupt delivery" VM-execution control is 0
3577  *          and the "virtualize APIC accesses" VM-execution control
3578  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
3579  *          control field must not be greater than the value of bits
3580  *          7:4 of VTPR.
3581  *          [Intel SDM]
3582  */
3583 static void test_tpr_threshold(void)
3584 {
3585 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3586 	void *virtual_apic_page;
3587 
3588 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
3589 		return;
3590 
3591 	virtual_apic_page = alloc_page();
3592 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
3593 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
3594 
3595 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
3596 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
3597 	test_tpr_threshold_values();
3598 	report_prefix_pop();
3599 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
3600 	report_prefix_pushf("Use TPR shadow enabled");
3601 	test_tpr_threshold_values();
3602 	report_prefix_pop();
3603 
3604 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
3605 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES))))
3606 		return;
3607 
3608 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3609 
3610 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
3611 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
3612 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
3613 		test_tpr_threshold_values();
3614 		report_prefix_pop();
3615 
3616 		vmcs_write(CPU_EXEC_CTRL0,
3617 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
3618 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
3619 		test_tpr_threshold_values();
3620 		report_prefix_pop();
3621 	}
3622 
3623 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
3624 		vmcs_write(CPU_EXEC_CTRL0,
3625 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
3626 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
3627 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
3628 		test_tpr_threshold_values();
3629 		report_prefix_pop();
3630 
3631 		vmcs_write(CPU_EXEC_CTRL0,
3632 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
3633 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
3634 		test_tpr_threshold_values();
3635 		report_prefix_pop();
3636 	}
3637 
3638 	if ((ctrl_cpu_rev[1].clr &
3639 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
3640 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
3641 		vmcs_write(CPU_EXEC_CTRL0,
3642 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
3643 		vmcs_write(CPU_EXEC_CTRL1,
3644 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
3645 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
3646 		test_tpr_threshold_values();
3647 		report_prefix_pop();
3648 
3649 		vmcs_write(CPU_EXEC_CTRL0,
3650 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
3651 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
3652 		test_tpr_threshold_values();
3653 		report_prefix_pop();
3654 	}
3655 
3656 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3657 	vmcs_write(CPU_EXEC_CTRL0, primary);
3658 }
3659 
3660 /*
3661  * Check that the virtual CPU checks all of the VMX controls as
3662  * documented in the Intel SDM.
3663  */
3664 static void vmx_controls_test(void)
3665 {
3666 	/*
3667 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
3668 	 * fail due to invalid guest state, should we make it that
3669 	 * far.
3670 	 */
3671 	vmcs_write(GUEST_RFLAGS, 0);
3672 
3673 	test_pin_based_ctls();
3674 	test_primary_processor_based_ctls();
3675 	test_secondary_processor_based_ctls();
3676 	test_cr3_targets();
3677 	test_io_bitmaps();
3678 	test_msr_bitmap();
3679 	test_apic_virt_addr();
3680 	test_tpr_threshold();
3681 }
3682 
3683 static bool valid_vmcs_for_vmentry(void)
3684 {
3685 	struct vmcs *current_vmcs = NULL;
3686 
3687 	if (vmcs_save(&current_vmcs))
3688 		return false;
3689 
3690 	return current_vmcs && !(current_vmcs->revision_id >> 31);
3691 }
3692 
3693 static void try_vmentry_in_movss_shadow(void)
3694 {
3695 	u32 vm_inst_err;
3696 	u32 flags;
3697 	bool early_failure = false;
3698 	u32 expected_flags = X86_EFLAGS_FIXED;
3699 	bool valid_vmcs = valid_vmcs_for_vmentry();
3700 
3701 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
3702 
3703 	/*
3704 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3705 	 * unsupported VMCS component").
3706 	 */
3707 	vmcs_write(~0u, 0);
3708 
3709 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
3710 			      "vmwrite %%rsp, %%rdx;"
3711 			      "mov 0f, %%rax;"
3712 			      "mov %[host_rip], %%edx;"
3713 			      "vmwrite %%rax, %%rdx;"
3714 			      "mov $-1, %%ah;"
3715 			      "sahf;"
3716 			      "mov %%ss, %%ax;"
3717 			      "mov %%ax, %%ss;"
3718 			      "vmlaunch;"
3719 			      "mov $1, %[early_failure];"
3720 			      "0: lahf;"
3721 			      "movzbl %%ah, %[flags]"
3722 			      : [early_failure] "+r" (early_failure),
3723 				[flags] "=&a" (flags)
3724 			      : [host_rsp] "i" (HOST_RSP),
3725 				[host_rip] "i" (HOST_RIP)
3726 			      : "rdx", "cc", "memory");
3727 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
3728 
3729 	report("Early VM-entry failure", early_failure);
3730 	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
3731 	       expected_flags, flags);
3732 	if (valid_vmcs)
3733 		report("VM-instruction error is %d (actual %d)",
3734 		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
3735 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
3736 }
3737 
3738 static void vmentry_movss_shadow_test(void)
3739 {
3740 	struct vmcs *orig_vmcs;
3741 
3742 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
3743 
3744 	/*
3745 	 * Set the launched flag on the current VMCS to verify the correct
3746 	 * error priority, below.
3747 	 */
3748 	test_set_guest(v2_null_test_guest);
3749 	enter_guest();
3750 
3751 	/*
3752 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
3753 	 * fail due to invalid guest state (if we make it that far).
3754 	 */
3755 	vmcs_write(GUEST_RFLAGS, 0);
3756 
3757 	/*
3758 	 * "VM entry with events blocked by MOV SS" takes precedence over
3759 	 * "VMLAUNCH with non-clear VMCS."
3760 	 */
3761 	report_prefix_push("valid current-VMCS");
3762 	try_vmentry_in_movss_shadow();
3763 	report_prefix_pop();
3764 
3765 	/*
3766 	 * VMfailInvalid takes precedence over "VM entry with events
3767 	 * blocked by MOV SS."
3768 	 */
3769 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
3770 	report_prefix_push("no current-VMCS");
3771 	try_vmentry_in_movss_shadow();
3772 	report_prefix_pop();
3773 
3774 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
3775 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
3776 }
3777 
3778 #define X86_FEATURE_PCID       (1 << 17)
3779 #define X86_FEATURE_MCE        (1 << 7)
3780 
3781 static int write_cr4_checking(unsigned long val)
3782 {
3783 	asm volatile(ASM_TRY("1f")
3784 		     "mov %0, %%cr4\n\t"
3785 		     "1:": : "r" (val));
3786 	return exception_vector();
3787 }
3788 
3789 static void vmx_cr_load_test(void)
3790 {
3791 	struct cpuid _cpuid = cpuid(1);
3792 	unsigned long cr4 = read_cr4(), cr3 = read_cr3();
3793 
3794 	if (!(_cpuid.c & X86_FEATURE_PCID)) {
3795 		report_skip("PCID not detected");
3796 		return;
3797 	}
3798 	if (!(_cpuid.d & X86_FEATURE_MCE)) {
3799 		report_skip("MCE not detected");
3800 		return;
3801 	}
3802 
3803 	TEST_ASSERT(!(cr4 & (X86_CR4_PCIDE | X86_CR4_MCE)));
3804 	TEST_ASSERT(!(cr3 & X86_CR3_PCID_MASK));
3805 
3806 	/* Enable PCID for L1. */
3807 	cr4 |= X86_CR4_PCIDE;
3808 	cr3 |= 0x1;
3809 	TEST_ASSERT(!write_cr4_checking(cr4));
3810 	write_cr3(cr3);
3811 
3812 	test_set_guest(v2_null_test_guest);
3813 	vmcs_write(HOST_CR4, cr4);
3814 	vmcs_write(HOST_CR3, cr3);
3815 	enter_guest();
3816 
3817 	/*
3818 	 * No exception is expected.
3819 	 *
3820 	 * NB. KVM loads the last guest write to CR4 into CR4 read
3821 	 *     shadow. In order to trigger an exit to KVM, we can set a
3822 	 *     bit that was zero in the above CR4 write and is owned by
3823 	 *     KVM. We choose to set CR4.MCE, which shall have no side
3824 	 *     effect because normally no guest MCE (e.g., as the result
3825 	 *     of bad memory) would happen during this test.
3826 	 */
3827 	TEST_ASSERT(!write_cr4_checking(cr4 | X86_CR4_MCE));
3828 
3829 	/* Cleanup L1 state: disable PCID. */
3830 	write_cr3(cr3 & ~X86_CR3_PCID_MASK);
3831 	TEST_ASSERT(!write_cr4_checking(cr4 & ~X86_CR4_PCIDE));
3832 }
3833 
3834 #define TEST(name) { #name, .v2 = name }
3835 
3836 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
3837 struct vmx_test vmx_tests[] = {
3838 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
3839 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
3840 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
3841 		preemption_timer_exit_handler, NULL, {0} },
3842 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
3843 		test_ctrl_pat_exit_handler, NULL, {0} },
3844 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
3845 		test_ctrl_efer_exit_handler, NULL, {0} },
3846 	{ "CR shadowing", NULL, cr_shadowing_main,
3847 		cr_shadowing_exit_handler, NULL, {0} },
3848 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
3849 		NULL, {0} },
3850 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
3851 		insn_intercept_exit_handler, NULL, {0} },
3852 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
3853 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
3854 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
3855 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
3856 	{ "interrupt", interrupt_init, interrupt_main,
3857 		interrupt_exit_handler, NULL, {0} },
3858 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
3859 		NULL, {0} },
3860 	{ "MSR switch", msr_switch_init, msr_switch_main,
3861 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
3862 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
3863 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
3864 		disable_rdtscp_exit_handler, NULL, {0} },
3865 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
3866 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
3867 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
3868 		exit_monitor_from_l2_handler, NULL, {0} },
3869 	/* Basic V2 tests. */
3870 	TEST(v2_null_test),
3871 	TEST(v2_multiple_entries_test),
3872 	TEST(fixture_test_case1),
3873 	TEST(fixture_test_case2),
3874 	/* EPT access tests. */
3875 	TEST(ept_access_test_not_present),
3876 	TEST(ept_access_test_read_only),
3877 	TEST(ept_access_test_write_only),
3878 	TEST(ept_access_test_read_write),
3879 	TEST(ept_access_test_execute_only),
3880 	TEST(ept_access_test_read_execute),
3881 	TEST(ept_access_test_write_execute),
3882 	TEST(ept_access_test_read_write_execute),
3883 	TEST(ept_access_test_reserved_bits),
3884 	TEST(ept_access_test_ignored_bits),
3885 	TEST(ept_access_test_paddr_not_present_ad_disabled),
3886 	TEST(ept_access_test_paddr_not_present_ad_enabled),
3887 	TEST(ept_access_test_paddr_read_only_ad_disabled),
3888 	TEST(ept_access_test_paddr_read_only_ad_enabled),
3889 	TEST(ept_access_test_paddr_read_write),
3890 	TEST(ept_access_test_paddr_read_write_execute),
3891 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
3892 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
3893 	TEST(ept_access_test_paddr_not_present_page_fault),
3894 	TEST(ept_access_test_force_2m_page),
3895 	/* Opcode tests. */
3896 	TEST(invvpid_test_v2),
3897 	/* VM-entry tests */
3898 	TEST(vmx_controls_test),
3899 	TEST(vmentry_movss_shadow_test),
3900 	/* Regression tests */
3901 	TEST(vmx_cr_load_test),
3902 	{ NULL, NULL, NULL, NULL, NULL, {0} },
3903 };
3904