1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * tools/testing/selftests/kvm/lib/x86_64/processor.c
4  *
5  * Copyright (C) 2018, Google LLC.
6  */
7 
8 #include "test_util.h"
9 #include "kvm_util.h"
10 #include "../kvm_util_internal.h"
11 #include "processor.h"
12 
13 #ifndef NUM_INTERRUPTS
14 #define NUM_INTERRUPTS 256
15 #endif
16 
17 #define DEFAULT_CODE_SELECTOR 0x8
18 #define DEFAULT_DATA_SELECTOR 0x10
19 
20 vm_vaddr_t exception_handlers;
21 
22 void regs_dump(FILE *stream, struct kvm_regs *regs,
23 	       uint8_t indent)
24 {
25 	fprintf(stream, "%*srax: 0x%.16llx rbx: 0x%.16llx "
26 		"rcx: 0x%.16llx rdx: 0x%.16llx\n",
27 		indent, "",
28 		regs->rax, regs->rbx, regs->rcx, regs->rdx);
29 	fprintf(stream, "%*srsi: 0x%.16llx rdi: 0x%.16llx "
30 		"rsp: 0x%.16llx rbp: 0x%.16llx\n",
31 		indent, "",
32 		regs->rsi, regs->rdi, regs->rsp, regs->rbp);
33 	fprintf(stream, "%*sr8:  0x%.16llx r9:  0x%.16llx "
34 		"r10: 0x%.16llx r11: 0x%.16llx\n",
35 		indent, "",
36 		regs->r8, regs->r9, regs->r10, regs->r11);
37 	fprintf(stream, "%*sr12: 0x%.16llx r13: 0x%.16llx "
38 		"r14: 0x%.16llx r15: 0x%.16llx\n",
39 		indent, "",
40 		regs->r12, regs->r13, regs->r14, regs->r15);
41 	fprintf(stream, "%*srip: 0x%.16llx rfl: 0x%.16llx\n",
42 		indent, "",
43 		regs->rip, regs->rflags);
44 }
45 
46 /*
47  * Segment Dump
48  *
49  * Input Args:
50  *   stream  - Output FILE stream
51  *   segment - KVM segment
52  *   indent  - Left margin indent amount
53  *
54  * Output Args: None
55  *
56  * Return: None
57  *
58  * Dumps the state of the KVM segment given by @segment, to the FILE stream
59  * given by @stream.
60  */
61 static void segment_dump(FILE *stream, struct kvm_segment *segment,
62 			 uint8_t indent)
63 {
64 	fprintf(stream, "%*sbase: 0x%.16llx limit: 0x%.8x "
65 		"selector: 0x%.4x type: 0x%.2x\n",
66 		indent, "", segment->base, segment->limit,
67 		segment->selector, segment->type);
68 	fprintf(stream, "%*spresent: 0x%.2x dpl: 0x%.2x "
69 		"db: 0x%.2x s: 0x%.2x l: 0x%.2x\n",
70 		indent, "", segment->present, segment->dpl,
71 		segment->db, segment->s, segment->l);
72 	fprintf(stream, "%*sg: 0x%.2x avl: 0x%.2x "
73 		"unusable: 0x%.2x padding: 0x%.2x\n",
74 		indent, "", segment->g, segment->avl,
75 		segment->unusable, segment->padding);
76 }
77 
78 /*
79  * dtable Dump
80  *
81  * Input Args:
82  *   stream - Output FILE stream
83  *   dtable - KVM dtable
84  *   indent - Left margin indent amount
85  *
86  * Output Args: None
87  *
88  * Return: None
89  *
90  * Dumps the state of the KVM dtable given by @dtable, to the FILE stream
91  * given by @stream.
92  */
93 static void dtable_dump(FILE *stream, struct kvm_dtable *dtable,
94 			uint8_t indent)
95 {
96 	fprintf(stream, "%*sbase: 0x%.16llx limit: 0x%.4x "
97 		"padding: 0x%.4x 0x%.4x 0x%.4x\n",
98 		indent, "", dtable->base, dtable->limit,
99 		dtable->padding[0], dtable->padding[1], dtable->padding[2]);
100 }
101 
102 void sregs_dump(FILE *stream, struct kvm_sregs *sregs,
103 		uint8_t indent)
104 {
105 	unsigned int i;
106 
107 	fprintf(stream, "%*scs:\n", indent, "");
108 	segment_dump(stream, &sregs->cs, indent + 2);
109 	fprintf(stream, "%*sds:\n", indent, "");
110 	segment_dump(stream, &sregs->ds, indent + 2);
111 	fprintf(stream, "%*ses:\n", indent, "");
112 	segment_dump(stream, &sregs->es, indent + 2);
113 	fprintf(stream, "%*sfs:\n", indent, "");
114 	segment_dump(stream, &sregs->fs, indent + 2);
115 	fprintf(stream, "%*sgs:\n", indent, "");
116 	segment_dump(stream, &sregs->gs, indent + 2);
117 	fprintf(stream, "%*sss:\n", indent, "");
118 	segment_dump(stream, &sregs->ss, indent + 2);
119 	fprintf(stream, "%*str:\n", indent, "");
120 	segment_dump(stream, &sregs->tr, indent + 2);
121 	fprintf(stream, "%*sldt:\n", indent, "");
122 	segment_dump(stream, &sregs->ldt, indent + 2);
123 
124 	fprintf(stream, "%*sgdt:\n", indent, "");
125 	dtable_dump(stream, &sregs->gdt, indent + 2);
126 	fprintf(stream, "%*sidt:\n", indent, "");
127 	dtable_dump(stream, &sregs->idt, indent + 2);
128 
129 	fprintf(stream, "%*scr0: 0x%.16llx cr2: 0x%.16llx "
130 		"cr3: 0x%.16llx cr4: 0x%.16llx\n",
131 		indent, "",
132 		sregs->cr0, sregs->cr2, sregs->cr3, sregs->cr4);
133 	fprintf(stream, "%*scr8: 0x%.16llx efer: 0x%.16llx "
134 		"apic_base: 0x%.16llx\n",
135 		indent, "",
136 		sregs->cr8, sregs->efer, sregs->apic_base);
137 
138 	fprintf(stream, "%*sinterrupt_bitmap:\n", indent, "");
139 	for (i = 0; i < (KVM_NR_INTERRUPTS + 63) / 64; i++) {
140 		fprintf(stream, "%*s%.16llx\n", indent + 2, "",
141 			sregs->interrupt_bitmap[i]);
142 	}
143 }
144 
145 void virt_pgd_alloc(struct kvm_vm *vm)
146 {
147 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
148 		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
149 
150 	/* If needed, create page map l4 table. */
151 	if (!vm->pgd_created) {
152 		vm->pgd = vm_alloc_page_table(vm);
153 		vm->pgd_created = true;
154 	}
155 }
156 
157 static void *virt_get_pte(struct kvm_vm *vm, uint64_t pt_pfn, uint64_t vaddr,
158 			  int level)
159 {
160 	uint64_t *page_table = addr_gpa2hva(vm, pt_pfn << vm->page_shift);
161 	int index = vaddr >> (vm->page_shift + level * 9) & 0x1ffu;
162 
163 	return &page_table[index];
164 }
165 
166 static uint64_t *virt_create_upper_pte(struct kvm_vm *vm,
167 				       uint64_t pt_pfn,
168 				       uint64_t vaddr,
169 				       uint64_t paddr,
170 				       int level,
171 				       enum x86_page_size page_size)
172 {
173 	uint64_t *pte = virt_get_pte(vm, pt_pfn, vaddr, level);
174 
175 	if (!(*pte & PTE_PRESENT_MASK)) {
176 		*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK;
177 		if (level == page_size)
178 			*pte |= PTE_LARGE_MASK | (paddr & PHYSICAL_PAGE_MASK);
179 		else
180 			*pte |= vm_alloc_page_table(vm) & PHYSICAL_PAGE_MASK;
181 	} else {
182 		/*
183 		 * Entry already present.  Assert that the caller doesn't want
184 		 * a hugepage at this level, and that there isn't a hugepage at
185 		 * this level.
186 		 */
187 		TEST_ASSERT(level != page_size,
188 			    "Cannot create hugepage at level: %u, vaddr: 0x%lx\n",
189 			    page_size, vaddr);
190 		TEST_ASSERT(!(*pte & PTE_LARGE_MASK),
191 			    "Cannot create page table at level: %u, vaddr: 0x%lx\n",
192 			    level, vaddr);
193 	}
194 	return pte;
195 }
196 
197 void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
198 		   enum x86_page_size page_size)
199 {
200 	const uint64_t pg_size = 1ull << ((page_size * 9) + 12);
201 	uint64_t *pml4e, *pdpe, *pde;
202 	uint64_t *pte;
203 
204 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K,
205 		    "Unknown or unsupported guest mode, mode: 0x%x", vm->mode);
206 
207 	TEST_ASSERT((vaddr % pg_size) == 0,
208 		    "Virtual address not aligned,\n"
209 		    "vaddr: 0x%lx page size: 0x%lx", vaddr, pg_size);
210 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid, (vaddr >> vm->page_shift)),
211 		    "Invalid virtual address, vaddr: 0x%lx", vaddr);
212 	TEST_ASSERT((paddr % pg_size) == 0,
213 		    "Physical address not aligned,\n"
214 		    "  paddr: 0x%lx page size: 0x%lx", paddr, pg_size);
215 	TEST_ASSERT((paddr >> vm->page_shift) <= vm->max_gfn,
216 		    "Physical address beyond maximum supported,\n"
217 		    "  paddr: 0x%lx vm->max_gfn: 0x%lx vm->page_size: 0x%x",
218 		    paddr, vm->max_gfn, vm->page_size);
219 
220 	/*
221 	 * Allocate upper level page tables, if not already present.  Return
222 	 * early if a hugepage was created.
223 	 */
224 	pml4e = virt_create_upper_pte(vm, vm->pgd >> vm->page_shift,
225 				      vaddr, paddr, 3, page_size);
226 	if (*pml4e & PTE_LARGE_MASK)
227 		return;
228 
229 	pdpe = virt_create_upper_pte(vm, PTE_GET_PFN(*pml4e), vaddr, paddr, 2, page_size);
230 	if (*pdpe & PTE_LARGE_MASK)
231 		return;
232 
233 	pde = virt_create_upper_pte(vm, PTE_GET_PFN(*pdpe), vaddr, paddr, 1, page_size);
234 	if (*pde & PTE_LARGE_MASK)
235 		return;
236 
237 	/* Fill in page table entry. */
238 	pte = virt_get_pte(vm, PTE_GET_PFN(*pde), vaddr, 0);
239 	TEST_ASSERT(!(*pte & PTE_PRESENT_MASK),
240 		    "PTE already present for 4k page at vaddr: 0x%lx\n", vaddr);
241 	*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK | (paddr & PHYSICAL_PAGE_MASK);
242 }
243 
244 void virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr)
245 {
246 	__virt_pg_map(vm, vaddr, paddr, X86_PAGE_SIZE_4K);
247 }
248 
249 static uint64_t *_vm_get_page_table_entry(struct kvm_vm *vm, int vcpuid,
250 						       uint64_t vaddr)
251 {
252 	uint16_t index[4];
253 	uint64_t *pml4e, *pdpe, *pde;
254 	uint64_t *pte;
255 	struct kvm_cpuid_entry2 *entry;
256 	struct kvm_sregs sregs;
257 	int max_phy_addr;
258 	uint64_t rsvd_mask = 0;
259 
260 	entry = kvm_get_supported_cpuid_index(0x80000008, 0);
261 	max_phy_addr = entry->eax & 0x000000ff;
262 	/* Set the high bits in the reserved mask. */
263 	if (max_phy_addr < 52)
264 		rsvd_mask = GENMASK_ULL(51, max_phy_addr);
265 
266 	/*
267 	 * SDM vol 3, fig 4-11 "Formats of CR3 and Paging-Structure Entries
268 	 * with 4-Level Paging and 5-Level Paging".
269 	 * If IA32_EFER.NXE = 0 and the P flag of a paging-structure entry is 1,
270 	 * the XD flag (bit 63) is reserved.
271 	 */
272 	vcpu_sregs_get(vm, vcpuid, &sregs);
273 	if ((sregs.efer & EFER_NX) == 0) {
274 		rsvd_mask |= PTE_NX_MASK;
275 	}
276 
277 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
278 		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
279 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid,
280 		(vaddr >> vm->page_shift)),
281 		"Invalid virtual address, vaddr: 0x%lx",
282 		vaddr);
283 	/*
284 	 * Based on the mode check above there are 48 bits in the vaddr, so
285 	 * shift 16 to sign extend the last bit (bit-47),
286 	 */
287 	TEST_ASSERT(vaddr == (((int64_t)vaddr << 16) >> 16),
288 		"Canonical check failed.  The virtual address is invalid.");
289 
290 	index[0] = (vaddr >> 12) & 0x1ffu;
291 	index[1] = (vaddr >> 21) & 0x1ffu;
292 	index[2] = (vaddr >> 30) & 0x1ffu;
293 	index[3] = (vaddr >> 39) & 0x1ffu;
294 
295 	pml4e = addr_gpa2hva(vm, vm->pgd);
296 	TEST_ASSERT(pml4e[index[3]] & PTE_PRESENT_MASK,
297 		"Expected pml4e to be present for gva: 0x%08lx", vaddr);
298 	TEST_ASSERT((pml4e[index[3]] & (rsvd_mask | PTE_LARGE_MASK)) == 0,
299 		"Unexpected reserved bits set.");
300 
301 	pdpe = addr_gpa2hva(vm, PTE_GET_PFN(pml4e[index[3]]) * vm->page_size);
302 	TEST_ASSERT(pdpe[index[2]] & PTE_PRESENT_MASK,
303 		"Expected pdpe to be present for gva: 0x%08lx", vaddr);
304 	TEST_ASSERT(!(pdpe[index[2]] & PTE_LARGE_MASK),
305 		"Expected pdpe to map a pde not a 1-GByte page.");
306 	TEST_ASSERT((pdpe[index[2]] & rsvd_mask) == 0,
307 		"Unexpected reserved bits set.");
308 
309 	pde = addr_gpa2hva(vm, PTE_GET_PFN(pdpe[index[2]]) * vm->page_size);
310 	TEST_ASSERT(pde[index[1]] & PTE_PRESENT_MASK,
311 		"Expected pde to be present for gva: 0x%08lx", vaddr);
312 	TEST_ASSERT(!(pde[index[1]] & PTE_LARGE_MASK),
313 		"Expected pde to map a pte not a 2-MByte page.");
314 	TEST_ASSERT((pde[index[1]] & rsvd_mask) == 0,
315 		"Unexpected reserved bits set.");
316 
317 	pte = addr_gpa2hva(vm, PTE_GET_PFN(pde[index[1]]) * vm->page_size);
318 	TEST_ASSERT(pte[index[0]] & PTE_PRESENT_MASK,
319 		"Expected pte to be present for gva: 0x%08lx", vaddr);
320 
321 	return &pte[index[0]];
322 }
323 
324 uint64_t vm_get_page_table_entry(struct kvm_vm *vm, int vcpuid, uint64_t vaddr)
325 {
326 	uint64_t *pte = _vm_get_page_table_entry(vm, vcpuid, vaddr);
327 
328 	return *(uint64_t *)pte;
329 }
330 
331 void vm_set_page_table_entry(struct kvm_vm *vm, int vcpuid, uint64_t vaddr,
332 			     uint64_t pte)
333 {
334 	uint64_t *new_pte = _vm_get_page_table_entry(vm, vcpuid, vaddr);
335 
336 	*(uint64_t *)new_pte = pte;
337 }
338 
339 void virt_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
340 {
341 	uint64_t *pml4e, *pml4e_start;
342 	uint64_t *pdpe, *pdpe_start;
343 	uint64_t *pde, *pde_start;
344 	uint64_t *pte, *pte_start;
345 
346 	if (!vm->pgd_created)
347 		return;
348 
349 	fprintf(stream, "%*s                                          "
350 		"                no\n", indent, "");
351 	fprintf(stream, "%*s      index hvaddr         gpaddr         "
352 		"addr         w exec dirty\n",
353 		indent, "");
354 	pml4e_start = (uint64_t *) addr_gpa2hva(vm, vm->pgd);
355 	for (uint16_t n1 = 0; n1 <= 0x1ffu; n1++) {
356 		pml4e = &pml4e_start[n1];
357 		if (!(*pml4e & PTE_PRESENT_MASK))
358 			continue;
359 		fprintf(stream, "%*spml4e 0x%-3zx %p 0x%-12lx 0x%-10llx %u "
360 			" %u\n",
361 			indent, "",
362 			pml4e - pml4e_start, pml4e,
363 			addr_hva2gpa(vm, pml4e), PTE_GET_PFN(*pml4e),
364 			!!(*pml4e & PTE_WRITABLE_MASK), !!(*pml4e & PTE_NX_MASK));
365 
366 		pdpe_start = addr_gpa2hva(vm, *pml4e & PHYSICAL_PAGE_MASK);
367 		for (uint16_t n2 = 0; n2 <= 0x1ffu; n2++) {
368 			pdpe = &pdpe_start[n2];
369 			if (!(*pdpe & PTE_PRESENT_MASK))
370 				continue;
371 			fprintf(stream, "%*spdpe  0x%-3zx %p 0x%-12lx 0x%-10llx "
372 				"%u  %u\n",
373 				indent, "",
374 				pdpe - pdpe_start, pdpe,
375 				addr_hva2gpa(vm, pdpe),
376 				PTE_GET_PFN(*pdpe), !!(*pdpe & PTE_WRITABLE_MASK),
377 				!!(*pdpe & PTE_NX_MASK));
378 
379 			pde_start = addr_gpa2hva(vm, *pdpe & PHYSICAL_PAGE_MASK);
380 			for (uint16_t n3 = 0; n3 <= 0x1ffu; n3++) {
381 				pde = &pde_start[n3];
382 				if (!(*pde & PTE_PRESENT_MASK))
383 					continue;
384 				fprintf(stream, "%*spde   0x%-3zx %p "
385 					"0x%-12lx 0x%-10llx %u  %u\n",
386 					indent, "", pde - pde_start, pde,
387 					addr_hva2gpa(vm, pde),
388 					PTE_GET_PFN(*pde), !!(*pde & PTE_WRITABLE_MASK),
389 					!!(*pde & PTE_NX_MASK));
390 
391 				pte_start = addr_gpa2hva(vm, *pde & PHYSICAL_PAGE_MASK);
392 				for (uint16_t n4 = 0; n4 <= 0x1ffu; n4++) {
393 					pte = &pte_start[n4];
394 					if (!(*pte & PTE_PRESENT_MASK))
395 						continue;
396 					fprintf(stream, "%*spte   0x%-3zx %p "
397 						"0x%-12lx 0x%-10llx %u  %u "
398 						"    %u    0x%-10lx\n",
399 						indent, "",
400 						pte - pte_start, pte,
401 						addr_hva2gpa(vm, pte),
402 						PTE_GET_PFN(*pte),
403 						!!(*pte & PTE_WRITABLE_MASK),
404 						!!(*pte & PTE_NX_MASK),
405 						!!(*pte & PTE_DIRTY_MASK),
406 						((uint64_t) n1 << 27)
407 							| ((uint64_t) n2 << 18)
408 							| ((uint64_t) n3 << 9)
409 							| ((uint64_t) n4));
410 				}
411 			}
412 		}
413 	}
414 }
415 
416 /*
417  * Set Unusable Segment
418  *
419  * Input Args: None
420  *
421  * Output Args:
422  *   segp - Pointer to segment register
423  *
424  * Return: None
425  *
426  * Sets the segment register pointed to by @segp to an unusable state.
427  */
428 static void kvm_seg_set_unusable(struct kvm_segment *segp)
429 {
430 	memset(segp, 0, sizeof(*segp));
431 	segp->unusable = true;
432 }
433 
434 static void kvm_seg_fill_gdt_64bit(struct kvm_vm *vm, struct kvm_segment *segp)
435 {
436 	void *gdt = addr_gva2hva(vm, vm->gdt);
437 	struct desc64 *desc = gdt + (segp->selector >> 3) * 8;
438 
439 	desc->limit0 = segp->limit & 0xFFFF;
440 	desc->base0 = segp->base & 0xFFFF;
441 	desc->base1 = segp->base >> 16;
442 	desc->type = segp->type;
443 	desc->s = segp->s;
444 	desc->dpl = segp->dpl;
445 	desc->p = segp->present;
446 	desc->limit1 = segp->limit >> 16;
447 	desc->avl = segp->avl;
448 	desc->l = segp->l;
449 	desc->db = segp->db;
450 	desc->g = segp->g;
451 	desc->base2 = segp->base >> 24;
452 	if (!segp->s)
453 		desc->base3 = segp->base >> 32;
454 }
455 
456 
457 /*
458  * Set Long Mode Flat Kernel Code Segment
459  *
460  * Input Args:
461  *   vm - VM whose GDT is being filled, or NULL to only write segp
462  *   selector - selector value
463  *
464  * Output Args:
465  *   segp - Pointer to KVM segment
466  *
467  * Return: None
468  *
469  * Sets up the KVM segment pointed to by @segp, to be a code segment
470  * with the selector value given by @selector.
471  */
472 static void kvm_seg_set_kernel_code_64bit(struct kvm_vm *vm, uint16_t selector,
473 	struct kvm_segment *segp)
474 {
475 	memset(segp, 0, sizeof(*segp));
476 	segp->selector = selector;
477 	segp->limit = 0xFFFFFFFFu;
478 	segp->s = 0x1; /* kTypeCodeData */
479 	segp->type = 0x08 | 0x01 | 0x02; /* kFlagCode | kFlagCodeAccessed
480 					  * | kFlagCodeReadable
481 					  */
482 	segp->g = true;
483 	segp->l = true;
484 	segp->present = 1;
485 	if (vm)
486 		kvm_seg_fill_gdt_64bit(vm, segp);
487 }
488 
489 /*
490  * Set Long Mode Flat Kernel Data Segment
491  *
492  * Input Args:
493  *   vm - VM whose GDT is being filled, or NULL to only write segp
494  *   selector - selector value
495  *
496  * Output Args:
497  *   segp - Pointer to KVM segment
498  *
499  * Return: None
500  *
501  * Sets up the KVM segment pointed to by @segp, to be a data segment
502  * with the selector value given by @selector.
503  */
504 static void kvm_seg_set_kernel_data_64bit(struct kvm_vm *vm, uint16_t selector,
505 	struct kvm_segment *segp)
506 {
507 	memset(segp, 0, sizeof(*segp));
508 	segp->selector = selector;
509 	segp->limit = 0xFFFFFFFFu;
510 	segp->s = 0x1; /* kTypeCodeData */
511 	segp->type = 0x00 | 0x01 | 0x02; /* kFlagData | kFlagDataAccessed
512 					  * | kFlagDataWritable
513 					  */
514 	segp->g = true;
515 	segp->present = true;
516 	if (vm)
517 		kvm_seg_fill_gdt_64bit(vm, segp);
518 }
519 
520 vm_paddr_t addr_gva2gpa(struct kvm_vm *vm, vm_vaddr_t gva)
521 {
522 	uint16_t index[4];
523 	uint64_t *pml4e, *pdpe, *pde;
524 	uint64_t *pte;
525 
526 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
527 		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
528 
529 	index[0] = (gva >> 12) & 0x1ffu;
530 	index[1] = (gva >> 21) & 0x1ffu;
531 	index[2] = (gva >> 30) & 0x1ffu;
532 	index[3] = (gva >> 39) & 0x1ffu;
533 
534 	if (!vm->pgd_created)
535 		goto unmapped_gva;
536 	pml4e = addr_gpa2hva(vm, vm->pgd);
537 	if (!(pml4e[index[3]] & PTE_PRESENT_MASK))
538 		goto unmapped_gva;
539 
540 	pdpe = addr_gpa2hva(vm, PTE_GET_PFN(pml4e[index[3]]) * vm->page_size);
541 	if (!(pdpe[index[2]] & PTE_PRESENT_MASK))
542 		goto unmapped_gva;
543 
544 	pde = addr_gpa2hva(vm, PTE_GET_PFN(pdpe[index[2]]) * vm->page_size);
545 	if (!(pde[index[1]] & PTE_PRESENT_MASK))
546 		goto unmapped_gva;
547 
548 	pte = addr_gpa2hva(vm, PTE_GET_PFN(pde[index[1]]) * vm->page_size);
549 	if (!(pte[index[0]] & PTE_PRESENT_MASK))
550 		goto unmapped_gva;
551 
552 	return (PTE_GET_PFN(pte[index[0]]) * vm->page_size) + (gva & ~PAGE_MASK);
553 
554 unmapped_gva:
555 	TEST_FAIL("No mapping for vm virtual address, gva: 0x%lx", gva);
556 	exit(EXIT_FAILURE);
557 }
558 
559 static void kvm_setup_gdt(struct kvm_vm *vm, struct kvm_dtable *dt)
560 {
561 	if (!vm->gdt)
562 		vm->gdt = vm_vaddr_alloc_page(vm);
563 
564 	dt->base = vm->gdt;
565 	dt->limit = getpagesize();
566 }
567 
568 static void kvm_setup_tss_64bit(struct kvm_vm *vm, struct kvm_segment *segp,
569 				int selector)
570 {
571 	if (!vm->tss)
572 		vm->tss = vm_vaddr_alloc_page(vm);
573 
574 	memset(segp, 0, sizeof(*segp));
575 	segp->base = vm->tss;
576 	segp->limit = 0x67;
577 	segp->selector = selector;
578 	segp->type = 0xb;
579 	segp->present = 1;
580 	kvm_seg_fill_gdt_64bit(vm, segp);
581 }
582 
583 static void vcpu_setup(struct kvm_vm *vm, int vcpuid)
584 {
585 	struct kvm_sregs sregs;
586 
587 	/* Set mode specific system register values. */
588 	vcpu_sregs_get(vm, vcpuid, &sregs);
589 
590 	sregs.idt.limit = 0;
591 
592 	kvm_setup_gdt(vm, &sregs.gdt);
593 
594 	switch (vm->mode) {
595 	case VM_MODE_PXXV48_4K:
596 		sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
597 		sregs.cr4 |= X86_CR4_PAE | X86_CR4_OSFXSR;
598 		sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX);
599 
600 		kvm_seg_set_unusable(&sregs.ldt);
601 		kvm_seg_set_kernel_code_64bit(vm, DEFAULT_CODE_SELECTOR, &sregs.cs);
602 		kvm_seg_set_kernel_data_64bit(vm, DEFAULT_DATA_SELECTOR, &sregs.ds);
603 		kvm_seg_set_kernel_data_64bit(vm, DEFAULT_DATA_SELECTOR, &sregs.es);
604 		kvm_setup_tss_64bit(vm, &sregs.tr, 0x18);
605 		break;
606 
607 	default:
608 		TEST_FAIL("Unknown guest mode, mode: 0x%x", vm->mode);
609 	}
610 
611 	sregs.cr3 = vm->pgd;
612 	vcpu_sregs_set(vm, vcpuid, &sregs);
613 }
614 
615 #define CPUID_XFD_BIT (1 << 4)
616 static bool is_xfd_supported(void)
617 {
618 	int eax, ebx, ecx, edx;
619 	const int leaf = 0xd, subleaf = 0x1;
620 
621 	__asm__ __volatile__(
622 		"cpuid"
623 		: /* output */ "=a"(eax), "=b"(ebx),
624 		  "=c"(ecx), "=d"(edx)
625 		: /* input */ "0"(leaf), "2"(subleaf));
626 
627 	return !!(eax & CPUID_XFD_BIT);
628 }
629 
630 void vm_xsave_req_perm(int bit)
631 {
632 	int kvm_fd;
633 	u64 bitmask;
634 	long rc;
635 	struct kvm_device_attr attr = {
636 		.group = 0,
637 		.attr = KVM_X86_XCOMP_GUEST_SUPP,
638 		.addr = (unsigned long) &bitmask
639 	};
640 
641 	kvm_fd = open_kvm_dev_path_or_exit();
642 	rc = ioctl(kvm_fd, KVM_GET_DEVICE_ATTR, &attr);
643 	close(kvm_fd);
644 	if (rc == -1 && (errno == ENXIO || errno == EINVAL))
645 		exit(KSFT_SKIP);
646 	TEST_ASSERT(rc == 0, "KVM_GET_DEVICE_ATTR(0, KVM_X86_XCOMP_GUEST_SUPP) error: %ld", rc);
647 	if (!(bitmask & (1ULL << bit)))
648 		exit(KSFT_SKIP);
649 
650 	if (!is_xfd_supported())
651 		exit(KSFT_SKIP);
652 
653 	rc = syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit);
654 
655 	/*
656 	 * The older kernel version(<5.15) can't support
657 	 * ARCH_REQ_XCOMP_GUEST_PERM and directly return.
658 	 */
659 	if (rc)
660 		return;
661 
662 	rc = syscall(SYS_arch_prctl, ARCH_GET_XCOMP_GUEST_PERM, &bitmask);
663 	TEST_ASSERT(rc == 0, "prctl(ARCH_GET_XCOMP_GUEST_PERM) error: %ld", rc);
664 	TEST_ASSERT(bitmask & (1ULL << bit),
665 		    "prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure bitmask=0x%lx",
666 		    bitmask);
667 }
668 
669 void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code)
670 {
671 	struct kvm_mp_state mp_state;
672 	struct kvm_regs regs;
673 	vm_vaddr_t stack_vaddr;
674 	stack_vaddr = vm_vaddr_alloc(vm, DEFAULT_STACK_PGS * getpagesize(),
675 				     DEFAULT_GUEST_STACK_VADDR_MIN);
676 
677 	/* Create VCPU */
678 	vm_vcpu_add(vm, vcpuid);
679 	vcpu_set_cpuid(vm, vcpuid, kvm_get_supported_cpuid());
680 	vcpu_setup(vm, vcpuid);
681 
682 	/* Setup guest general purpose registers */
683 	vcpu_regs_get(vm, vcpuid, &regs);
684 	regs.rflags = regs.rflags | 0x2;
685 	regs.rsp = stack_vaddr + (DEFAULT_STACK_PGS * getpagesize());
686 	regs.rip = (unsigned long) guest_code;
687 	vcpu_regs_set(vm, vcpuid, &regs);
688 
689 	/* Setup the MP state */
690 	mp_state.mp_state = 0;
691 	vcpu_set_mp_state(vm, vcpuid, &mp_state);
692 }
693 
694 /*
695  * Allocate an instance of struct kvm_cpuid2
696  *
697  * Input Args: None
698  *
699  * Output Args: None
700  *
701  * Return: A pointer to the allocated struct. The caller is responsible
702  * for freeing this struct.
703  *
704  * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
705  * array to be decided at allocation time, allocation is slightly
706  * complicated. This function uses a reasonable default length for
707  * the array and performs the appropriate allocation.
708  */
709 static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
710 {
711 	struct kvm_cpuid2 *cpuid;
712 	int nent = 100;
713 	size_t size;
714 
715 	size = sizeof(*cpuid);
716 	size += nent * sizeof(struct kvm_cpuid_entry2);
717 	cpuid = malloc(size);
718 	if (!cpuid) {
719 		perror("malloc");
720 		abort();
721 	}
722 
723 	cpuid->nent = nent;
724 
725 	return cpuid;
726 }
727 
728 /*
729  * KVM Supported CPUID Get
730  *
731  * Input Args: None
732  *
733  * Output Args:
734  *
735  * Return: The supported KVM CPUID
736  *
737  * Get the guest CPUID supported by KVM.
738  */
739 struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
740 {
741 	static struct kvm_cpuid2 *cpuid;
742 	int ret;
743 	int kvm_fd;
744 
745 	if (cpuid)
746 		return cpuid;
747 
748 	cpuid = allocate_kvm_cpuid2();
749 	kvm_fd = open_kvm_dev_path_or_exit();
750 
751 	ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
752 	TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
753 		    ret, errno);
754 
755 	close(kvm_fd);
756 	return cpuid;
757 }
758 
759 /*
760  * KVM Get MSR
761  *
762  * Input Args:
763  *   msr_index - Index of MSR
764  *
765  * Output Args: None
766  *
767  * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
768  *
769  * Get value of MSR for VCPU.
770  */
771 uint64_t kvm_get_feature_msr(uint64_t msr_index)
772 {
773 	struct {
774 		struct kvm_msrs header;
775 		struct kvm_msr_entry entry;
776 	} buffer = {};
777 	int r, kvm_fd;
778 
779 	buffer.header.nmsrs = 1;
780 	buffer.entry.index = msr_index;
781 	kvm_fd = open_kvm_dev_path_or_exit();
782 
783 	r = ioctl(kvm_fd, KVM_GET_MSRS, &buffer.header);
784 	TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
785 		"  rc: %i errno: %i", r, errno);
786 
787 	close(kvm_fd);
788 	return buffer.entry.data;
789 }
790 
791 /*
792  * VM VCPU CPUID Set
793  *
794  * Input Args:
795  *   vm - Virtual Machine
796  *   vcpuid - VCPU id
797  *
798  * Output Args: None
799  *
800  * Return: KVM CPUID (KVM_GET_CPUID2)
801  *
802  * Set the VCPU's CPUID.
803  */
804 struct kvm_cpuid2 *vcpu_get_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
805 {
806 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
807 	struct kvm_cpuid2 *cpuid;
808 	int max_ent;
809 	int rc = -1;
810 
811 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
812 
813 	cpuid = allocate_kvm_cpuid2();
814 	max_ent = cpuid->nent;
815 
816 	for (cpuid->nent = 1; cpuid->nent <= max_ent; cpuid->nent++) {
817 		rc = ioctl(vcpu->fd, KVM_GET_CPUID2, cpuid);
818 		if (!rc)
819 			break;
820 
821 		TEST_ASSERT(rc == -1 && errno == E2BIG,
822 			    "KVM_GET_CPUID2 should either succeed or give E2BIG: %d %d",
823 			    rc, errno);
824 	}
825 
826 	TEST_ASSERT(rc == 0, "KVM_GET_CPUID2 failed, rc: %i errno: %i",
827 		    rc, errno);
828 
829 	return cpuid;
830 }
831 
832 
833 
834 /*
835  * Locate a cpuid entry.
836  *
837  * Input Args:
838  *   function: The function of the cpuid entry to find.
839  *   index: The index of the cpuid entry.
840  *
841  * Output Args: None
842  *
843  * Return: A pointer to the cpuid entry. Never returns NULL.
844  */
845 struct kvm_cpuid_entry2 *
846 kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
847 {
848 	struct kvm_cpuid2 *cpuid;
849 	struct kvm_cpuid_entry2 *entry = NULL;
850 	int i;
851 
852 	cpuid = kvm_get_supported_cpuid();
853 	for (i = 0; i < cpuid->nent; i++) {
854 		if (cpuid->entries[i].function == function &&
855 		    cpuid->entries[i].index == index) {
856 			entry = &cpuid->entries[i];
857 			break;
858 		}
859 	}
860 
861 	TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
862 		    function, index);
863 	return entry;
864 }
865 
866 
867 int __vcpu_set_cpuid(struct kvm_vm *vm, uint32_t vcpuid,
868 		     struct kvm_cpuid2 *cpuid)
869 {
870 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
871 
872 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
873 
874 	return ioctl(vcpu->fd, KVM_SET_CPUID2, cpuid);
875 }
876 
877 /*
878  * VM VCPU CPUID Set
879  *
880  * Input Args:
881  *   vm - Virtual Machine
882  *   vcpuid - VCPU id
883  *   cpuid - The CPUID values to set.
884  *
885  * Output Args: None
886  *
887  * Return: void
888  *
889  * Set the VCPU's CPUID.
890  */
891 void vcpu_set_cpuid(struct kvm_vm *vm,
892 		uint32_t vcpuid, struct kvm_cpuid2 *cpuid)
893 {
894 	int rc;
895 
896 	rc = __vcpu_set_cpuid(vm, vcpuid, cpuid);
897 	TEST_ASSERT(rc == 0, "KVM_SET_CPUID2 failed, rc: %i errno: %i",
898 		    rc, errno);
899 
900 }
901 
902 /*
903  * VCPU Get MSR
904  *
905  * Input Args:
906  *   vm - Virtual Machine
907  *   vcpuid - VCPU ID
908  *   msr_index - Index of MSR
909  *
910  * Output Args: None
911  *
912  * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
913  *
914  * Get value of MSR for VCPU.
915  */
916 uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
917 {
918 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
919 	struct {
920 		struct kvm_msrs header;
921 		struct kvm_msr_entry entry;
922 	} buffer = {};
923 	int r;
924 
925 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
926 	buffer.header.nmsrs = 1;
927 	buffer.entry.index = msr_index;
928 	r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
929 	TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
930 		"  rc: %i errno: %i", r, errno);
931 
932 	return buffer.entry.data;
933 }
934 
935 /*
936  * _VCPU Set MSR
937  *
938  * Input Args:
939  *   vm - Virtual Machine
940  *   vcpuid - VCPU ID
941  *   msr_index - Index of MSR
942  *   msr_value - New value of MSR
943  *
944  * Output Args: None
945  *
946  * Return: The result of KVM_SET_MSRS.
947  *
948  * Sets the value of an MSR for the given VCPU.
949  */
950 int _vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
951 		  uint64_t msr_value)
952 {
953 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
954 	struct {
955 		struct kvm_msrs header;
956 		struct kvm_msr_entry entry;
957 	} buffer = {};
958 	int r;
959 
960 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
961 	memset(&buffer, 0, sizeof(buffer));
962 	buffer.header.nmsrs = 1;
963 	buffer.entry.index = msr_index;
964 	buffer.entry.data = msr_value;
965 	r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
966 	return r;
967 }
968 
969 /*
970  * VCPU Set MSR
971  *
972  * Input Args:
973  *   vm - Virtual Machine
974  *   vcpuid - VCPU ID
975  *   msr_index - Index of MSR
976  *   msr_value - New value of MSR
977  *
978  * Output Args: None
979  *
980  * Return: On success, nothing. On failure a TEST_ASSERT is produced.
981  *
982  * Set value of MSR for VCPU.
983  */
984 void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
985 	uint64_t msr_value)
986 {
987 	int r;
988 
989 	r = _vcpu_set_msr(vm, vcpuid, msr_index, msr_value);
990 	TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
991 		"  rc: %i errno: %i", r, errno);
992 }
993 
994 void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
995 {
996 	va_list ap;
997 	struct kvm_regs regs;
998 
999 	TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
1000 		    "  num: %u\n",
1001 		    num);
1002 
1003 	va_start(ap, num);
1004 	vcpu_regs_get(vm, vcpuid, &regs);
1005 
1006 	if (num >= 1)
1007 		regs.rdi = va_arg(ap, uint64_t);
1008 
1009 	if (num >= 2)
1010 		regs.rsi = va_arg(ap, uint64_t);
1011 
1012 	if (num >= 3)
1013 		regs.rdx = va_arg(ap, uint64_t);
1014 
1015 	if (num >= 4)
1016 		regs.rcx = va_arg(ap, uint64_t);
1017 
1018 	if (num >= 5)
1019 		regs.r8 = va_arg(ap, uint64_t);
1020 
1021 	if (num >= 6)
1022 		regs.r9 = va_arg(ap, uint64_t);
1023 
1024 	vcpu_regs_set(vm, vcpuid, &regs);
1025 	va_end(ap);
1026 }
1027 
1028 void vcpu_dump(FILE *stream, struct kvm_vm *vm, uint32_t vcpuid, uint8_t indent)
1029 {
1030 	struct kvm_regs regs;
1031 	struct kvm_sregs sregs;
1032 
1033 	fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
1034 
1035 	fprintf(stream, "%*sregs:\n", indent + 2, "");
1036 	vcpu_regs_get(vm, vcpuid, &regs);
1037 	regs_dump(stream, &regs, indent + 4);
1038 
1039 	fprintf(stream, "%*ssregs:\n", indent + 2, "");
1040 	vcpu_sregs_get(vm, vcpuid, &sregs);
1041 	sregs_dump(stream, &sregs, indent + 4);
1042 }
1043 
1044 static int kvm_get_num_msrs_fd(int kvm_fd)
1045 {
1046 	struct kvm_msr_list nmsrs;
1047 	int r;
1048 
1049 	nmsrs.nmsrs = 0;
1050 	r = ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, &nmsrs);
1051 	TEST_ASSERT(r == -1 && errno == E2BIG, "Unexpected result from KVM_GET_MSR_INDEX_LIST probe, r: %i",
1052 		r);
1053 
1054 	return nmsrs.nmsrs;
1055 }
1056 
1057 static int kvm_get_num_msrs(struct kvm_vm *vm)
1058 {
1059 	return kvm_get_num_msrs_fd(vm->kvm_fd);
1060 }
1061 
1062 struct kvm_msr_list *kvm_get_msr_index_list(void)
1063 {
1064 	struct kvm_msr_list *list;
1065 	int nmsrs, r, kvm_fd;
1066 
1067 	kvm_fd = open_kvm_dev_path_or_exit();
1068 
1069 	nmsrs = kvm_get_num_msrs_fd(kvm_fd);
1070 	list = malloc(sizeof(*list) + nmsrs * sizeof(list->indices[0]));
1071 	list->nmsrs = nmsrs;
1072 	r = ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, list);
1073 	close(kvm_fd);
1074 
1075 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MSR_INDEX_LIST, r: %i",
1076 		r);
1077 
1078 	return list;
1079 }
1080 
1081 static int vcpu_save_xsave_state(struct kvm_vm *vm, struct vcpu *vcpu,
1082 				 struct kvm_x86_state *state)
1083 {
1084 	int size;
1085 
1086 	size = vm_check_cap(vm, KVM_CAP_XSAVE2);
1087 	if (!size)
1088 		size = sizeof(struct kvm_xsave);
1089 
1090 	state->xsave = malloc(size);
1091 	if (size == sizeof(struct kvm_xsave))
1092 		return ioctl(vcpu->fd, KVM_GET_XSAVE, state->xsave);
1093 	else
1094 		return ioctl(vcpu->fd, KVM_GET_XSAVE2, state->xsave);
1095 }
1096 
1097 struct kvm_x86_state *vcpu_save_state(struct kvm_vm *vm, uint32_t vcpuid)
1098 {
1099 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1100 	struct kvm_msr_list *list;
1101 	struct kvm_x86_state *state;
1102 	int nmsrs, r, i;
1103 	static int nested_size = -1;
1104 
1105 	if (nested_size == -1) {
1106 		nested_size = kvm_check_cap(KVM_CAP_NESTED_STATE);
1107 		TEST_ASSERT(nested_size <= sizeof(state->nested_),
1108 			    "Nested state size too big, %i > %zi",
1109 			    nested_size, sizeof(state->nested_));
1110 	}
1111 
1112 	/*
1113 	 * When KVM exits to userspace with KVM_EXIT_IO, KVM guarantees
1114 	 * guest state is consistent only after userspace re-enters the
1115 	 * kernel with KVM_RUN.  Complete IO prior to migrating state
1116 	 * to a new VM.
1117 	 */
1118 	vcpu_run_complete_io(vm, vcpuid);
1119 
1120 	nmsrs = kvm_get_num_msrs(vm);
1121 	list = malloc(sizeof(*list) + nmsrs * sizeof(list->indices[0]));
1122 	list->nmsrs = nmsrs;
1123 	r = ioctl(vm->kvm_fd, KVM_GET_MSR_INDEX_LIST, list);
1124 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MSR_INDEX_LIST, r: %i",
1125 		    r);
1126 
1127 	state = malloc(sizeof(*state) + nmsrs * sizeof(state->msrs.entries[0]));
1128 	r = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, &state->events);
1129 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_VCPU_EVENTS, r: %i",
1130 		    r);
1131 
1132 	r = ioctl(vcpu->fd, KVM_GET_MP_STATE, &state->mp_state);
1133 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MP_STATE, r: %i",
1134 		    r);
1135 
1136 	r = ioctl(vcpu->fd, KVM_GET_REGS, &state->regs);
1137 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_REGS, r: %i",
1138 		    r);
1139 
1140 	r = vcpu_save_xsave_state(vm, vcpu, state);
1141 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_XSAVE, r: %i",
1142 		    r);
1143 
1144 	if (kvm_check_cap(KVM_CAP_XCRS)) {
1145 		r = ioctl(vcpu->fd, KVM_GET_XCRS, &state->xcrs);
1146 		TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_XCRS, r: %i",
1147 			    r);
1148 	}
1149 
1150 	r = ioctl(vcpu->fd, KVM_GET_SREGS, &state->sregs);
1151 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_SREGS, r: %i",
1152 		    r);
1153 
1154 	if (nested_size) {
1155 		state->nested.size = sizeof(state->nested_);
1156 		r = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, &state->nested);
1157 		TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_NESTED_STATE, r: %i",
1158 			    r);
1159 		TEST_ASSERT(state->nested.size <= nested_size,
1160 			    "Nested state size too big, %i (KVM_CHECK_CAP gave %i)",
1161 			    state->nested.size, nested_size);
1162 	} else
1163 		state->nested.size = 0;
1164 
1165 	state->msrs.nmsrs = nmsrs;
1166 	for (i = 0; i < nmsrs; i++)
1167 		state->msrs.entries[i].index = list->indices[i];
1168 	r = ioctl(vcpu->fd, KVM_GET_MSRS, &state->msrs);
1169 	TEST_ASSERT(r == nmsrs, "Unexpected result from KVM_GET_MSRS, r: %i (failed MSR was 0x%x)",
1170 		    r, r == nmsrs ? -1 : list->indices[r]);
1171 
1172 	r = ioctl(vcpu->fd, KVM_GET_DEBUGREGS, &state->debugregs);
1173 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_DEBUGREGS, r: %i",
1174 		    r);
1175 
1176 	free(list);
1177 	return state;
1178 }
1179 
1180 void vcpu_load_state(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_x86_state *state)
1181 {
1182 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1183 	int r;
1184 
1185 	r = ioctl(vcpu->fd, KVM_SET_SREGS, &state->sregs);
1186 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_SREGS, r: %i",
1187 		    r);
1188 
1189 	r = ioctl(vcpu->fd, KVM_SET_MSRS, &state->msrs);
1190 	TEST_ASSERT(r == state->msrs.nmsrs,
1191 		"Unexpected result from KVM_SET_MSRS, r: %i (failed at %x)",
1192 		r, r == state->msrs.nmsrs ? -1 : state->msrs.entries[r].index);
1193 
1194 	if (kvm_check_cap(KVM_CAP_XCRS)) {
1195 		r = ioctl(vcpu->fd, KVM_SET_XCRS, &state->xcrs);
1196 		TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_XCRS, r: %i",
1197 			    r);
1198 	}
1199 
1200 	r = ioctl(vcpu->fd, KVM_SET_XSAVE, state->xsave);
1201 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_XSAVE, r: %i",
1202 		    r);
1203 
1204 	r = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, &state->events);
1205 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_VCPU_EVENTS, r: %i",
1206 		    r);
1207 
1208 	r = ioctl(vcpu->fd, KVM_SET_MP_STATE, &state->mp_state);
1209 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_MP_STATE, r: %i",
1210 		    r);
1211 
1212 	r = ioctl(vcpu->fd, KVM_SET_DEBUGREGS, &state->debugregs);
1213 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_DEBUGREGS, r: %i",
1214 		    r);
1215 
1216 	r = ioctl(vcpu->fd, KVM_SET_REGS, &state->regs);
1217 	TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_REGS, r: %i",
1218 		    r);
1219 
1220 	if (state->nested.size) {
1221 		r = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, &state->nested);
1222 		TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_NESTED_STATE, r: %i",
1223 			    r);
1224 	}
1225 }
1226 
1227 void kvm_x86_state_cleanup(struct kvm_x86_state *state)
1228 {
1229 	free(state->xsave);
1230 	free(state);
1231 }
1232 
1233 static bool cpu_vendor_string_is(const char *vendor)
1234 {
1235 	const uint32_t *chunk = (const uint32_t *)vendor;
1236 	int eax, ebx, ecx, edx;
1237 	const int leaf = 0;
1238 
1239 	__asm__ __volatile__(
1240 		"cpuid"
1241 		: /* output */ "=a"(eax), "=b"(ebx),
1242 		  "=c"(ecx), "=d"(edx)
1243 		: /* input */ "0"(leaf), "2"(0));
1244 
1245 	return (ebx == chunk[0] && edx == chunk[1] && ecx == chunk[2]);
1246 }
1247 
1248 bool is_intel_cpu(void)
1249 {
1250 	return cpu_vendor_string_is("GenuineIntel");
1251 }
1252 
1253 /*
1254  * Exclude early K5 samples with a vendor string of "AMDisbetter!"
1255  */
1256 bool is_amd_cpu(void)
1257 {
1258 	return cpu_vendor_string_is("AuthenticAMD");
1259 }
1260 
1261 uint32_t kvm_get_cpuid_max_basic(void)
1262 {
1263 	return kvm_get_supported_cpuid_entry(0)->eax;
1264 }
1265 
1266 uint32_t kvm_get_cpuid_max_extended(void)
1267 {
1268 	return kvm_get_supported_cpuid_entry(0x80000000)->eax;
1269 }
1270 
1271 void kvm_get_cpu_address_width(unsigned int *pa_bits, unsigned int *va_bits)
1272 {
1273 	struct kvm_cpuid_entry2 *entry;
1274 	bool pae;
1275 
1276 	/* SDM 4.1.4 */
1277 	if (kvm_get_cpuid_max_extended() < 0x80000008) {
1278 		pae = kvm_get_supported_cpuid_entry(1)->edx & (1 << 6);
1279 		*pa_bits = pae ? 36 : 32;
1280 		*va_bits = 32;
1281 	} else {
1282 		entry = kvm_get_supported_cpuid_entry(0x80000008);
1283 		*pa_bits = entry->eax & 0xff;
1284 		*va_bits = (entry->eax >> 8) & 0xff;
1285 	}
1286 }
1287 
1288 struct idt_entry {
1289 	uint16_t offset0;
1290 	uint16_t selector;
1291 	uint16_t ist : 3;
1292 	uint16_t : 5;
1293 	uint16_t type : 4;
1294 	uint16_t : 1;
1295 	uint16_t dpl : 2;
1296 	uint16_t p : 1;
1297 	uint16_t offset1;
1298 	uint32_t offset2; uint32_t reserved;
1299 };
1300 
1301 static void set_idt_entry(struct kvm_vm *vm, int vector, unsigned long addr,
1302 			  int dpl, unsigned short selector)
1303 {
1304 	struct idt_entry *base =
1305 		(struct idt_entry *)addr_gva2hva(vm, vm->idt);
1306 	struct idt_entry *e = &base[vector];
1307 
1308 	memset(e, 0, sizeof(*e));
1309 	e->offset0 = addr;
1310 	e->selector = selector;
1311 	e->ist = 0;
1312 	e->type = 14;
1313 	e->dpl = dpl;
1314 	e->p = 1;
1315 	e->offset1 = addr >> 16;
1316 	e->offset2 = addr >> 32;
1317 }
1318 
1319 void kvm_exit_unexpected_vector(uint32_t value)
1320 {
1321 	ucall(UCALL_UNHANDLED, 1, value);
1322 }
1323 
1324 void route_exception(struct ex_regs *regs)
1325 {
1326 	typedef void(*handler)(struct ex_regs *);
1327 	handler *handlers = (handler *)exception_handlers;
1328 
1329 	if (handlers && handlers[regs->vector]) {
1330 		handlers[regs->vector](regs);
1331 		return;
1332 	}
1333 
1334 	kvm_exit_unexpected_vector(regs->vector);
1335 }
1336 
1337 void vm_init_descriptor_tables(struct kvm_vm *vm)
1338 {
1339 	extern void *idt_handlers;
1340 	int i;
1341 
1342 	vm->idt = vm_vaddr_alloc_page(vm);
1343 	vm->handlers = vm_vaddr_alloc_page(vm);
1344 	/* Handlers have the same address in both address spaces.*/
1345 	for (i = 0; i < NUM_INTERRUPTS; i++)
1346 		set_idt_entry(vm, i, (unsigned long)(&idt_handlers)[i], 0,
1347 			DEFAULT_CODE_SELECTOR);
1348 }
1349 
1350 void vcpu_init_descriptor_tables(struct kvm_vm *vm, uint32_t vcpuid)
1351 {
1352 	struct kvm_sregs sregs;
1353 
1354 	vcpu_sregs_get(vm, vcpuid, &sregs);
1355 	sregs.idt.base = vm->idt;
1356 	sregs.idt.limit = NUM_INTERRUPTS * sizeof(struct idt_entry) - 1;
1357 	sregs.gdt.base = vm->gdt;
1358 	sregs.gdt.limit = getpagesize() - 1;
1359 	kvm_seg_set_kernel_data_64bit(NULL, DEFAULT_DATA_SELECTOR, &sregs.gs);
1360 	vcpu_sregs_set(vm, vcpuid, &sregs);
1361 	*(vm_vaddr_t *)addr_gva2hva(vm, (vm_vaddr_t)(&exception_handlers)) = vm->handlers;
1362 }
1363 
1364 void vm_install_exception_handler(struct kvm_vm *vm, int vector,
1365 			       void (*handler)(struct ex_regs *))
1366 {
1367 	vm_vaddr_t *handlers = (vm_vaddr_t *)addr_gva2hva(vm, vm->handlers);
1368 
1369 	handlers[vector] = (vm_vaddr_t)handler;
1370 }
1371 
1372 void assert_on_unhandled_exception(struct kvm_vm *vm, uint32_t vcpuid)
1373 {
1374 	struct ucall uc;
1375 
1376 	if (get_ucall(vm, vcpuid, &uc) == UCALL_UNHANDLED) {
1377 		uint64_t vector = uc.args[0];
1378 
1379 		TEST_FAIL("Unexpected vectored event in guest (vector:0x%lx)",
1380 			  vector);
1381 	}
1382 }
1383 
1384 struct kvm_cpuid_entry2 *get_cpuid(struct kvm_cpuid2 *cpuid, uint32_t function,
1385 				   uint32_t index)
1386 {
1387 	int i;
1388 
1389 	for (i = 0; i < cpuid->nent; i++) {
1390 		struct kvm_cpuid_entry2 *cur = &cpuid->entries[i];
1391 
1392 		if (cur->function == function && cur->index == index)
1393 			return cur;
1394 	}
1395 
1396 	TEST_FAIL("CPUID function 0x%x index 0x%x not found ", function, index);
1397 
1398 	return NULL;
1399 }
1400 
1401 bool set_cpuid(struct kvm_cpuid2 *cpuid,
1402 	       struct kvm_cpuid_entry2 *ent)
1403 {
1404 	int i;
1405 
1406 	for (i = 0; i < cpuid->nent; i++) {
1407 		struct kvm_cpuid_entry2 *cur = &cpuid->entries[i];
1408 
1409 		if (cur->function != ent->function || cur->index != ent->index)
1410 			continue;
1411 
1412 		memcpy(cur, ent, sizeof(struct kvm_cpuid_entry2));
1413 		return true;
1414 	}
1415 
1416 	return false;
1417 }
1418 
1419 uint64_t kvm_hypercall(uint64_t nr, uint64_t a0, uint64_t a1, uint64_t a2,
1420 		       uint64_t a3)
1421 {
1422 	uint64_t r;
1423 
1424 	asm volatile("vmcall"
1425 		     : "=a"(r)
1426 		     : "b"(a0), "c"(a1), "d"(a2), "S"(a3));
1427 	return r;
1428 }
1429 
1430 struct kvm_cpuid2 *kvm_get_supported_hv_cpuid(void)
1431 {
1432 	static struct kvm_cpuid2 *cpuid;
1433 	int ret;
1434 	int kvm_fd;
1435 
1436 	if (cpuid)
1437 		return cpuid;
1438 
1439 	cpuid = allocate_kvm_cpuid2();
1440 	kvm_fd = open_kvm_dev_path_or_exit();
1441 
1442 	ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1443 	TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_HV_CPUID failed %d %d\n",
1444 		    ret, errno);
1445 
1446 	close(kvm_fd);
1447 	return cpuid;
1448 }
1449 
1450 void vcpu_set_hv_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
1451 {
1452 	static struct kvm_cpuid2 *cpuid_full;
1453 	struct kvm_cpuid2 *cpuid_sys, *cpuid_hv;
1454 	int i, nent = 0;
1455 
1456 	if (!cpuid_full) {
1457 		cpuid_sys = kvm_get_supported_cpuid();
1458 		cpuid_hv = kvm_get_supported_hv_cpuid();
1459 
1460 		cpuid_full = malloc(sizeof(*cpuid_full) +
1461 				    (cpuid_sys->nent + cpuid_hv->nent) *
1462 				    sizeof(struct kvm_cpuid_entry2));
1463 		if (!cpuid_full) {
1464 			perror("malloc");
1465 			abort();
1466 		}
1467 
1468 		/* Need to skip KVM CPUID leaves 0x400000xx */
1469 		for (i = 0; i < cpuid_sys->nent; i++) {
1470 			if (cpuid_sys->entries[i].function >= 0x40000000 &&
1471 			    cpuid_sys->entries[i].function < 0x40000100)
1472 				continue;
1473 			cpuid_full->entries[nent] = cpuid_sys->entries[i];
1474 			nent++;
1475 		}
1476 
1477 		memcpy(&cpuid_full->entries[nent], cpuid_hv->entries,
1478 		       cpuid_hv->nent * sizeof(struct kvm_cpuid_entry2));
1479 		cpuid_full->nent = nent + cpuid_hv->nent;
1480 	}
1481 
1482 	vcpu_set_cpuid(vm, vcpuid, cpuid_full);
1483 }
1484 
1485 struct kvm_cpuid2 *vcpu_get_supported_hv_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
1486 {
1487 	static struct kvm_cpuid2 *cpuid;
1488 
1489 	cpuid = allocate_kvm_cpuid2();
1490 
1491 	vcpu_ioctl(vm, vcpuid, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1492 
1493 	return cpuid;
1494 }
1495 
1496 unsigned long vm_compute_max_gfn(struct kvm_vm *vm)
1497 {
1498 	const unsigned long num_ht_pages = 12 << (30 - vm->page_shift); /* 12 GiB */
1499 	unsigned long ht_gfn, max_gfn, max_pfn;
1500 	uint32_t eax, ebx, ecx, edx, max_ext_leaf;
1501 
1502 	max_gfn = (1ULL << (vm->pa_bits - vm->page_shift)) - 1;
1503 
1504 	/* Avoid reserved HyperTransport region on AMD processors.  */
1505 	if (!is_amd_cpu())
1506 		return max_gfn;
1507 
1508 	/* On parts with <40 physical address bits, the area is fully hidden */
1509 	if (vm->pa_bits < 40)
1510 		return max_gfn;
1511 
1512 	/* Before family 17h, the HyperTransport area is just below 1T.  */
1513 	ht_gfn = (1 << 28) - num_ht_pages;
1514 	eax = 1;
1515 	ecx = 0;
1516 	cpuid(&eax, &ebx, &ecx, &edx);
1517 	if (x86_family(eax) < 0x17)
1518 		goto done;
1519 
1520 	/*
1521 	 * Otherwise it's at the top of the physical address space, possibly
1522 	 * reduced due to SME by bits 11:6 of CPUID[0x8000001f].EBX.  Use
1523 	 * the old conservative value if MAXPHYADDR is not enumerated.
1524 	 */
1525 	eax = 0x80000000;
1526 	cpuid(&eax, &ebx, &ecx, &edx);
1527 	max_ext_leaf = eax;
1528 	if (max_ext_leaf < 0x80000008)
1529 		goto done;
1530 
1531 	eax = 0x80000008;
1532 	cpuid(&eax, &ebx, &ecx, &edx);
1533 	max_pfn = (1ULL << ((eax & 0xff) - vm->page_shift)) - 1;
1534 	if (max_ext_leaf >= 0x8000001f) {
1535 		eax = 0x8000001f;
1536 		cpuid(&eax, &ebx, &ecx, &edx);
1537 		max_pfn >>= (ebx >> 6) & 0x3f;
1538 	}
1539 
1540 	ht_gfn = max_pfn - num_ht_pages;
1541 done:
1542 	return min(max_gfn, ht_gfn - 1);
1543 }
1544