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 "processor.h"
11 
12 #ifndef NUM_INTERRUPTS
13 #define NUM_INTERRUPTS 256
14 #endif
15 
16 #define DEFAULT_CODE_SELECTOR 0x8
17 #define DEFAULT_DATA_SELECTOR 0x10
18 
19 #define MAX_NR_CPUID_ENTRIES 100
20 
21 vm_vaddr_t exception_handlers;
22 
23 static void regs_dump(FILE *stream, struct kvm_regs *regs, 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 static void segment_dump(FILE *stream, struct kvm_segment *segment,
47 			 uint8_t indent)
48 {
49 	fprintf(stream, "%*sbase: 0x%.16llx limit: 0x%.8x "
50 		"selector: 0x%.4x type: 0x%.2x\n",
51 		indent, "", segment->base, segment->limit,
52 		segment->selector, segment->type);
53 	fprintf(stream, "%*spresent: 0x%.2x dpl: 0x%.2x "
54 		"db: 0x%.2x s: 0x%.2x l: 0x%.2x\n",
55 		indent, "", segment->present, segment->dpl,
56 		segment->db, segment->s, segment->l);
57 	fprintf(stream, "%*sg: 0x%.2x avl: 0x%.2x "
58 		"unusable: 0x%.2x padding: 0x%.2x\n",
59 		indent, "", segment->g, segment->avl,
60 		segment->unusable, segment->padding);
61 }
62 
63 static void dtable_dump(FILE *stream, struct kvm_dtable *dtable,
64 			uint8_t indent)
65 {
66 	fprintf(stream, "%*sbase: 0x%.16llx limit: 0x%.4x "
67 		"padding: 0x%.4x 0x%.4x 0x%.4x\n",
68 		indent, "", dtable->base, dtable->limit,
69 		dtable->padding[0], dtable->padding[1], dtable->padding[2]);
70 }
71 
72 static void sregs_dump(FILE *stream, struct kvm_sregs *sregs, uint8_t indent)
73 {
74 	unsigned int i;
75 
76 	fprintf(stream, "%*scs:\n", indent, "");
77 	segment_dump(stream, &sregs->cs, indent + 2);
78 	fprintf(stream, "%*sds:\n", indent, "");
79 	segment_dump(stream, &sregs->ds, indent + 2);
80 	fprintf(stream, "%*ses:\n", indent, "");
81 	segment_dump(stream, &sregs->es, indent + 2);
82 	fprintf(stream, "%*sfs:\n", indent, "");
83 	segment_dump(stream, &sregs->fs, indent + 2);
84 	fprintf(stream, "%*sgs:\n", indent, "");
85 	segment_dump(stream, &sregs->gs, indent + 2);
86 	fprintf(stream, "%*sss:\n", indent, "");
87 	segment_dump(stream, &sregs->ss, indent + 2);
88 	fprintf(stream, "%*str:\n", indent, "");
89 	segment_dump(stream, &sregs->tr, indent + 2);
90 	fprintf(stream, "%*sldt:\n", indent, "");
91 	segment_dump(stream, &sregs->ldt, indent + 2);
92 
93 	fprintf(stream, "%*sgdt:\n", indent, "");
94 	dtable_dump(stream, &sregs->gdt, indent + 2);
95 	fprintf(stream, "%*sidt:\n", indent, "");
96 	dtable_dump(stream, &sregs->idt, indent + 2);
97 
98 	fprintf(stream, "%*scr0: 0x%.16llx cr2: 0x%.16llx "
99 		"cr3: 0x%.16llx cr4: 0x%.16llx\n",
100 		indent, "",
101 		sregs->cr0, sregs->cr2, sregs->cr3, sregs->cr4);
102 	fprintf(stream, "%*scr8: 0x%.16llx efer: 0x%.16llx "
103 		"apic_base: 0x%.16llx\n",
104 		indent, "",
105 		sregs->cr8, sregs->efer, sregs->apic_base);
106 
107 	fprintf(stream, "%*sinterrupt_bitmap:\n", indent, "");
108 	for (i = 0; i < (KVM_NR_INTERRUPTS + 63) / 64; i++) {
109 		fprintf(stream, "%*s%.16llx\n", indent + 2, "",
110 			sregs->interrupt_bitmap[i]);
111 	}
112 }
113 
114 bool kvm_is_tdp_enabled(void)
115 {
116 	if (is_intel_cpu())
117 		return get_kvm_intel_param_bool("ept");
118 	else
119 		return get_kvm_amd_param_bool("npt");
120 }
121 
122 void virt_arch_pgd_alloc(struct kvm_vm *vm)
123 {
124 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
125 		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
126 
127 	/* If needed, create page map l4 table. */
128 	if (!vm->pgd_created) {
129 		vm->pgd = vm_alloc_page_table(vm);
130 		vm->pgd_created = true;
131 	}
132 }
133 
134 static void *virt_get_pte(struct kvm_vm *vm, uint64_t *parent_pte,
135 			  uint64_t vaddr, int level)
136 {
137 	uint64_t pt_gpa = PTE_GET_PA(*parent_pte);
138 	uint64_t *page_table = addr_gpa2hva(vm, pt_gpa);
139 	int index = (vaddr >> PG_LEVEL_SHIFT(level)) & 0x1ffu;
140 
141 	TEST_ASSERT((*parent_pte & PTE_PRESENT_MASK) || parent_pte == &vm->pgd,
142 		    "Parent PTE (level %d) not PRESENT for gva: 0x%08lx",
143 		    level + 1, vaddr);
144 
145 	return &page_table[index];
146 }
147 
148 static uint64_t *virt_create_upper_pte(struct kvm_vm *vm,
149 				       uint64_t *parent_pte,
150 				       uint64_t vaddr,
151 				       uint64_t paddr,
152 				       int current_level,
153 				       int target_level)
154 {
155 	uint64_t *pte = virt_get_pte(vm, parent_pte, vaddr, current_level);
156 
157 	if (!(*pte & PTE_PRESENT_MASK)) {
158 		*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK;
159 		if (current_level == target_level)
160 			*pte |= PTE_LARGE_MASK | (paddr & PHYSICAL_PAGE_MASK);
161 		else
162 			*pte |= vm_alloc_page_table(vm) & PHYSICAL_PAGE_MASK;
163 	} else {
164 		/*
165 		 * Entry already present.  Assert that the caller doesn't want
166 		 * a hugepage at this level, and that there isn't a hugepage at
167 		 * this level.
168 		 */
169 		TEST_ASSERT(current_level != target_level,
170 			    "Cannot create hugepage at level: %u, vaddr: 0x%lx\n",
171 			    current_level, vaddr);
172 		TEST_ASSERT(!(*pte & PTE_LARGE_MASK),
173 			    "Cannot create page table at level: %u, vaddr: 0x%lx\n",
174 			    current_level, vaddr);
175 	}
176 	return pte;
177 }
178 
179 void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level)
180 {
181 	const uint64_t pg_size = PG_LEVEL_SIZE(level);
182 	uint64_t *pml4e, *pdpe, *pde;
183 	uint64_t *pte;
184 
185 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K,
186 		    "Unknown or unsupported guest mode, mode: 0x%x", vm->mode);
187 
188 	TEST_ASSERT((vaddr % pg_size) == 0,
189 		    "Virtual address not aligned,\n"
190 		    "vaddr: 0x%lx page size: 0x%lx", vaddr, pg_size);
191 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid, (vaddr >> vm->page_shift)),
192 		    "Invalid virtual address, vaddr: 0x%lx", vaddr);
193 	TEST_ASSERT((paddr % pg_size) == 0,
194 		    "Physical address not aligned,\n"
195 		    "  paddr: 0x%lx page size: 0x%lx", paddr, pg_size);
196 	TEST_ASSERT((paddr >> vm->page_shift) <= vm->max_gfn,
197 		    "Physical address beyond maximum supported,\n"
198 		    "  paddr: 0x%lx vm->max_gfn: 0x%lx vm->page_size: 0x%x",
199 		    paddr, vm->max_gfn, vm->page_size);
200 
201 	/*
202 	 * Allocate upper level page tables, if not already present.  Return
203 	 * early if a hugepage was created.
204 	 */
205 	pml4e = virt_create_upper_pte(vm, &vm->pgd, vaddr, paddr, PG_LEVEL_512G, level);
206 	if (*pml4e & PTE_LARGE_MASK)
207 		return;
208 
209 	pdpe = virt_create_upper_pte(vm, pml4e, vaddr, paddr, PG_LEVEL_1G, level);
210 	if (*pdpe & PTE_LARGE_MASK)
211 		return;
212 
213 	pde = virt_create_upper_pte(vm, pdpe, vaddr, paddr, PG_LEVEL_2M, level);
214 	if (*pde & PTE_LARGE_MASK)
215 		return;
216 
217 	/* Fill in page table entry. */
218 	pte = virt_get_pte(vm, pde, vaddr, PG_LEVEL_4K);
219 	TEST_ASSERT(!(*pte & PTE_PRESENT_MASK),
220 		    "PTE already present for 4k page at vaddr: 0x%lx\n", vaddr);
221 	*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK | (paddr & PHYSICAL_PAGE_MASK);
222 }
223 
224 void virt_arch_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr)
225 {
226 	__virt_pg_map(vm, vaddr, paddr, PG_LEVEL_4K);
227 }
228 
229 void virt_map_level(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
230 		    uint64_t nr_bytes, int level)
231 {
232 	uint64_t pg_size = PG_LEVEL_SIZE(level);
233 	uint64_t nr_pages = nr_bytes / pg_size;
234 	int i;
235 
236 	TEST_ASSERT(nr_bytes % pg_size == 0,
237 		    "Region size not aligned: nr_bytes: 0x%lx, page size: 0x%lx",
238 		    nr_bytes, pg_size);
239 
240 	for (i = 0; i < nr_pages; i++) {
241 		__virt_pg_map(vm, vaddr, paddr, level);
242 
243 		vaddr += pg_size;
244 		paddr += pg_size;
245 	}
246 }
247 
248 static bool vm_is_target_pte(uint64_t *pte, int *level, int current_level)
249 {
250 	if (*pte & PTE_LARGE_MASK) {
251 		TEST_ASSERT(*level == PG_LEVEL_NONE ||
252 			    *level == current_level,
253 			    "Unexpected hugepage at level %d\n", current_level);
254 		*level = current_level;
255 	}
256 
257 	return *level == current_level;
258 }
259 
260 uint64_t *__vm_get_page_table_entry(struct kvm_vm *vm, uint64_t vaddr,
261 				    int *level)
262 {
263 	uint64_t *pml4e, *pdpe, *pde;
264 
265 	TEST_ASSERT(*level >= PG_LEVEL_NONE && *level < PG_LEVEL_NUM,
266 		    "Invalid PG_LEVEL_* '%d'", *level);
267 
268 	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
269 		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
270 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid,
271 		(vaddr >> vm->page_shift)),
272 		"Invalid virtual address, vaddr: 0x%lx",
273 		vaddr);
274 	/*
275 	 * Based on the mode check above there are 48 bits in the vaddr, so
276 	 * shift 16 to sign extend the last bit (bit-47),
277 	 */
278 	TEST_ASSERT(vaddr == (((int64_t)vaddr << 16) >> 16),
279 		"Canonical check failed.  The virtual address is invalid.");
280 
281 	pml4e = virt_get_pte(vm, &vm->pgd, vaddr, PG_LEVEL_512G);
282 	if (vm_is_target_pte(pml4e, level, PG_LEVEL_512G))
283 		return pml4e;
284 
285 	pdpe = virt_get_pte(vm, pml4e, vaddr, PG_LEVEL_1G);
286 	if (vm_is_target_pte(pdpe, level, PG_LEVEL_1G))
287 		return pdpe;
288 
289 	pde = virt_get_pte(vm, pdpe, vaddr, PG_LEVEL_2M);
290 	if (vm_is_target_pte(pde, level, PG_LEVEL_2M))
291 		return pde;
292 
293 	return virt_get_pte(vm, pde, vaddr, PG_LEVEL_4K);
294 }
295 
296 uint64_t *vm_get_page_table_entry(struct kvm_vm *vm, uint64_t vaddr)
297 {
298 	int level = PG_LEVEL_4K;
299 
300 	return __vm_get_page_table_entry(vm, vaddr, &level);
301 }
302 
303 void virt_arch_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
304 {
305 	uint64_t *pml4e, *pml4e_start;
306 	uint64_t *pdpe, *pdpe_start;
307 	uint64_t *pde, *pde_start;
308 	uint64_t *pte, *pte_start;
309 
310 	if (!vm->pgd_created)
311 		return;
312 
313 	fprintf(stream, "%*s                                          "
314 		"                no\n", indent, "");
315 	fprintf(stream, "%*s      index hvaddr         gpaddr         "
316 		"addr         w exec dirty\n",
317 		indent, "");
318 	pml4e_start = (uint64_t *) addr_gpa2hva(vm, vm->pgd);
319 	for (uint16_t n1 = 0; n1 <= 0x1ffu; n1++) {
320 		pml4e = &pml4e_start[n1];
321 		if (!(*pml4e & PTE_PRESENT_MASK))
322 			continue;
323 		fprintf(stream, "%*spml4e 0x%-3zx %p 0x%-12lx 0x%-10llx %u "
324 			" %u\n",
325 			indent, "",
326 			pml4e - pml4e_start, pml4e,
327 			addr_hva2gpa(vm, pml4e), PTE_GET_PFN(*pml4e),
328 			!!(*pml4e & PTE_WRITABLE_MASK), !!(*pml4e & PTE_NX_MASK));
329 
330 		pdpe_start = addr_gpa2hva(vm, *pml4e & PHYSICAL_PAGE_MASK);
331 		for (uint16_t n2 = 0; n2 <= 0x1ffu; n2++) {
332 			pdpe = &pdpe_start[n2];
333 			if (!(*pdpe & PTE_PRESENT_MASK))
334 				continue;
335 			fprintf(stream, "%*spdpe  0x%-3zx %p 0x%-12lx 0x%-10llx "
336 				"%u  %u\n",
337 				indent, "",
338 				pdpe - pdpe_start, pdpe,
339 				addr_hva2gpa(vm, pdpe),
340 				PTE_GET_PFN(*pdpe), !!(*pdpe & PTE_WRITABLE_MASK),
341 				!!(*pdpe & PTE_NX_MASK));
342 
343 			pde_start = addr_gpa2hva(vm, *pdpe & PHYSICAL_PAGE_MASK);
344 			for (uint16_t n3 = 0; n3 <= 0x1ffu; n3++) {
345 				pde = &pde_start[n3];
346 				if (!(*pde & PTE_PRESENT_MASK))
347 					continue;
348 				fprintf(stream, "%*spde   0x%-3zx %p "
349 					"0x%-12lx 0x%-10llx %u  %u\n",
350 					indent, "", pde - pde_start, pde,
351 					addr_hva2gpa(vm, pde),
352 					PTE_GET_PFN(*pde), !!(*pde & PTE_WRITABLE_MASK),
353 					!!(*pde & PTE_NX_MASK));
354 
355 				pte_start = addr_gpa2hva(vm, *pde & PHYSICAL_PAGE_MASK);
356 				for (uint16_t n4 = 0; n4 <= 0x1ffu; n4++) {
357 					pte = &pte_start[n4];
358 					if (!(*pte & PTE_PRESENT_MASK))
359 						continue;
360 					fprintf(stream, "%*spte   0x%-3zx %p "
361 						"0x%-12lx 0x%-10llx %u  %u "
362 						"    %u    0x%-10lx\n",
363 						indent, "",
364 						pte - pte_start, pte,
365 						addr_hva2gpa(vm, pte),
366 						PTE_GET_PFN(*pte),
367 						!!(*pte & PTE_WRITABLE_MASK),
368 						!!(*pte & PTE_NX_MASK),
369 						!!(*pte & PTE_DIRTY_MASK),
370 						((uint64_t) n1 << 27)
371 							| ((uint64_t) n2 << 18)
372 							| ((uint64_t) n3 << 9)
373 							| ((uint64_t) n4));
374 				}
375 			}
376 		}
377 	}
378 }
379 
380 /*
381  * Set Unusable Segment
382  *
383  * Input Args: None
384  *
385  * Output Args:
386  *   segp - Pointer to segment register
387  *
388  * Return: None
389  *
390  * Sets the segment register pointed to by @segp to an unusable state.
391  */
392 static void kvm_seg_set_unusable(struct kvm_segment *segp)
393 {
394 	memset(segp, 0, sizeof(*segp));
395 	segp->unusable = true;
396 }
397 
398 static void kvm_seg_fill_gdt_64bit(struct kvm_vm *vm, struct kvm_segment *segp)
399 {
400 	void *gdt = addr_gva2hva(vm, vm->gdt);
401 	struct desc64 *desc = gdt + (segp->selector >> 3) * 8;
402 
403 	desc->limit0 = segp->limit & 0xFFFF;
404 	desc->base0 = segp->base & 0xFFFF;
405 	desc->base1 = segp->base >> 16;
406 	desc->type = segp->type;
407 	desc->s = segp->s;
408 	desc->dpl = segp->dpl;
409 	desc->p = segp->present;
410 	desc->limit1 = segp->limit >> 16;
411 	desc->avl = segp->avl;
412 	desc->l = segp->l;
413 	desc->db = segp->db;
414 	desc->g = segp->g;
415 	desc->base2 = segp->base >> 24;
416 	if (!segp->s)
417 		desc->base3 = segp->base >> 32;
418 }
419 
420 
421 /*
422  * Set Long Mode Flat Kernel Code Segment
423  *
424  * Input Args:
425  *   vm - VM whose GDT is being filled, or NULL to only write segp
426  *   selector - selector value
427  *
428  * Output Args:
429  *   segp - Pointer to KVM segment
430  *
431  * Return: None
432  *
433  * Sets up the KVM segment pointed to by @segp, to be a code segment
434  * with the selector value given by @selector.
435  */
436 static void kvm_seg_set_kernel_code_64bit(struct kvm_vm *vm, uint16_t selector,
437 	struct kvm_segment *segp)
438 {
439 	memset(segp, 0, sizeof(*segp));
440 	segp->selector = selector;
441 	segp->limit = 0xFFFFFFFFu;
442 	segp->s = 0x1; /* kTypeCodeData */
443 	segp->type = 0x08 | 0x01 | 0x02; /* kFlagCode | kFlagCodeAccessed
444 					  * | kFlagCodeReadable
445 					  */
446 	segp->g = true;
447 	segp->l = true;
448 	segp->present = 1;
449 	if (vm)
450 		kvm_seg_fill_gdt_64bit(vm, segp);
451 }
452 
453 /*
454  * Set Long Mode Flat Kernel Data Segment
455  *
456  * Input Args:
457  *   vm - VM whose GDT is being filled, or NULL to only write segp
458  *   selector - selector value
459  *
460  * Output Args:
461  *   segp - Pointer to KVM segment
462  *
463  * Return: None
464  *
465  * Sets up the KVM segment pointed to by @segp, to be a data segment
466  * with the selector value given by @selector.
467  */
468 static void kvm_seg_set_kernel_data_64bit(struct kvm_vm *vm, uint16_t selector,
469 	struct kvm_segment *segp)
470 {
471 	memset(segp, 0, sizeof(*segp));
472 	segp->selector = selector;
473 	segp->limit = 0xFFFFFFFFu;
474 	segp->s = 0x1; /* kTypeCodeData */
475 	segp->type = 0x00 | 0x01 | 0x02; /* kFlagData | kFlagDataAccessed
476 					  * | kFlagDataWritable
477 					  */
478 	segp->g = true;
479 	segp->present = true;
480 	if (vm)
481 		kvm_seg_fill_gdt_64bit(vm, segp);
482 }
483 
484 vm_paddr_t addr_arch_gva2gpa(struct kvm_vm *vm, vm_vaddr_t gva)
485 {
486 	int level = PG_LEVEL_NONE;
487 	uint64_t *pte = __vm_get_page_table_entry(vm, gva, &level);
488 
489 	TEST_ASSERT(*pte & PTE_PRESENT_MASK,
490 		    "Leaf PTE not PRESENT for gva: 0x%08lx", gva);
491 
492 	/*
493 	 * No need for a hugepage mask on the PTE, x86-64 requires the "unused"
494 	 * address bits to be zero.
495 	 */
496 	return PTE_GET_PA(*pte) | (gva & ~HUGEPAGE_MASK(level));
497 }
498 
499 static void kvm_setup_gdt(struct kvm_vm *vm, struct kvm_dtable *dt)
500 {
501 	if (!vm->gdt)
502 		vm->gdt = __vm_vaddr_alloc_page(vm, MEM_REGION_DATA);
503 
504 	dt->base = vm->gdt;
505 	dt->limit = getpagesize();
506 }
507 
508 static void kvm_setup_tss_64bit(struct kvm_vm *vm, struct kvm_segment *segp,
509 				int selector)
510 {
511 	if (!vm->tss)
512 		vm->tss = __vm_vaddr_alloc_page(vm, MEM_REGION_DATA);
513 
514 	memset(segp, 0, sizeof(*segp));
515 	segp->base = vm->tss;
516 	segp->limit = 0x67;
517 	segp->selector = selector;
518 	segp->type = 0xb;
519 	segp->present = 1;
520 	kvm_seg_fill_gdt_64bit(vm, segp);
521 }
522 
523 static void vcpu_setup(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
524 {
525 	struct kvm_sregs sregs;
526 
527 	/* Set mode specific system register values. */
528 	vcpu_sregs_get(vcpu, &sregs);
529 
530 	sregs.idt.limit = 0;
531 
532 	kvm_setup_gdt(vm, &sregs.gdt);
533 
534 	switch (vm->mode) {
535 	case VM_MODE_PXXV48_4K:
536 		sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
537 		sregs.cr4 |= X86_CR4_PAE | X86_CR4_OSFXSR;
538 		sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX);
539 
540 		kvm_seg_set_unusable(&sregs.ldt);
541 		kvm_seg_set_kernel_code_64bit(vm, DEFAULT_CODE_SELECTOR, &sregs.cs);
542 		kvm_seg_set_kernel_data_64bit(vm, DEFAULT_DATA_SELECTOR, &sregs.ds);
543 		kvm_seg_set_kernel_data_64bit(vm, DEFAULT_DATA_SELECTOR, &sregs.es);
544 		kvm_setup_tss_64bit(vm, &sregs.tr, 0x18);
545 		break;
546 
547 	default:
548 		TEST_FAIL("Unknown guest mode, mode: 0x%x", vm->mode);
549 	}
550 
551 	sregs.cr3 = vm->pgd;
552 	vcpu_sregs_set(vcpu, &sregs);
553 }
554 
555 void kvm_arch_vm_post_create(struct kvm_vm *vm)
556 {
557 	vm_create_irqchip(vm);
558 }
559 
560 struct kvm_vcpu *vm_arch_vcpu_add(struct kvm_vm *vm, uint32_t vcpu_id,
561 				  void *guest_code)
562 {
563 	struct kvm_mp_state mp_state;
564 	struct kvm_regs regs;
565 	vm_vaddr_t stack_vaddr;
566 	struct kvm_vcpu *vcpu;
567 
568 	stack_vaddr = __vm_vaddr_alloc(vm, DEFAULT_STACK_PGS * getpagesize(),
569 				       DEFAULT_GUEST_STACK_VADDR_MIN,
570 				       MEM_REGION_DATA);
571 
572 	vcpu = __vm_vcpu_add(vm, vcpu_id);
573 	vcpu_init_cpuid(vcpu, kvm_get_supported_cpuid());
574 	vcpu_setup(vm, vcpu);
575 
576 	/* Setup guest general purpose registers */
577 	vcpu_regs_get(vcpu, &regs);
578 	regs.rflags = regs.rflags | 0x2;
579 	regs.rsp = stack_vaddr + (DEFAULT_STACK_PGS * getpagesize());
580 	regs.rip = (unsigned long) guest_code;
581 	vcpu_regs_set(vcpu, &regs);
582 
583 	/* Setup the MP state */
584 	mp_state.mp_state = 0;
585 	vcpu_mp_state_set(vcpu, &mp_state);
586 
587 	return vcpu;
588 }
589 
590 struct kvm_vcpu *vm_arch_vcpu_recreate(struct kvm_vm *vm, uint32_t vcpu_id)
591 {
592 	struct kvm_vcpu *vcpu = __vm_vcpu_add(vm, vcpu_id);
593 
594 	vcpu_init_cpuid(vcpu, kvm_get_supported_cpuid());
595 
596 	return vcpu;
597 }
598 
599 void vcpu_arch_free(struct kvm_vcpu *vcpu)
600 {
601 	if (vcpu->cpuid)
602 		free(vcpu->cpuid);
603 }
604 
605 /* Do not use kvm_supported_cpuid directly except for validity checks. */
606 static void *kvm_supported_cpuid;
607 
608 const struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
609 {
610 	int kvm_fd;
611 
612 	if (kvm_supported_cpuid)
613 		return kvm_supported_cpuid;
614 
615 	kvm_supported_cpuid = allocate_kvm_cpuid2(MAX_NR_CPUID_ENTRIES);
616 	kvm_fd = open_kvm_dev_path_or_exit();
617 
618 	kvm_ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID,
619 		  (struct kvm_cpuid2 *)kvm_supported_cpuid);
620 
621 	close(kvm_fd);
622 	return kvm_supported_cpuid;
623 }
624 
625 static uint32_t __kvm_cpu_has(const struct kvm_cpuid2 *cpuid,
626 			      uint32_t function, uint32_t index,
627 			      uint8_t reg, uint8_t lo, uint8_t hi)
628 {
629 	const struct kvm_cpuid_entry2 *entry;
630 	int i;
631 
632 	for (i = 0; i < cpuid->nent; i++) {
633 		entry = &cpuid->entries[i];
634 
635 		/*
636 		 * The output registers in kvm_cpuid_entry2 are in alphabetical
637 		 * order, but kvm_x86_cpu_feature matches that mess, so yay
638 		 * pointer shenanigans!
639 		 */
640 		if (entry->function == function && entry->index == index)
641 			return ((&entry->eax)[reg] & GENMASK(hi, lo)) >> lo;
642 	}
643 
644 	return 0;
645 }
646 
647 bool kvm_cpuid_has(const struct kvm_cpuid2 *cpuid,
648 		   struct kvm_x86_cpu_feature feature)
649 {
650 	return __kvm_cpu_has(cpuid, feature.function, feature.index,
651 			     feature.reg, feature.bit, feature.bit);
652 }
653 
654 uint32_t kvm_cpuid_property(const struct kvm_cpuid2 *cpuid,
655 			    struct kvm_x86_cpu_property property)
656 {
657 	return __kvm_cpu_has(cpuid, property.function, property.index,
658 			     property.reg, property.lo_bit, property.hi_bit);
659 }
660 
661 uint64_t kvm_get_feature_msr(uint64_t msr_index)
662 {
663 	struct {
664 		struct kvm_msrs header;
665 		struct kvm_msr_entry entry;
666 	} buffer = {};
667 	int r, kvm_fd;
668 
669 	buffer.header.nmsrs = 1;
670 	buffer.entry.index = msr_index;
671 	kvm_fd = open_kvm_dev_path_or_exit();
672 
673 	r = __kvm_ioctl(kvm_fd, KVM_GET_MSRS, &buffer.header);
674 	TEST_ASSERT(r == 1, KVM_IOCTL_ERROR(KVM_GET_MSRS, r));
675 
676 	close(kvm_fd);
677 	return buffer.entry.data;
678 }
679 
680 void __vm_xsave_require_permission(int bit, const char *name)
681 {
682 	int kvm_fd;
683 	u64 bitmask;
684 	long rc;
685 	struct kvm_device_attr attr = {
686 		.group = 0,
687 		.attr = KVM_X86_XCOMP_GUEST_SUPP,
688 		.addr = (unsigned long) &bitmask
689 	};
690 
691 	TEST_ASSERT(!kvm_supported_cpuid,
692 		    "kvm_get_supported_cpuid() cannot be used before ARCH_REQ_XCOMP_GUEST_PERM");
693 
694 	kvm_fd = open_kvm_dev_path_or_exit();
695 	rc = __kvm_ioctl(kvm_fd, KVM_GET_DEVICE_ATTR, &attr);
696 	close(kvm_fd);
697 
698 	if (rc == -1 && (errno == ENXIO || errno == EINVAL))
699 		__TEST_REQUIRE(0, "KVM_X86_XCOMP_GUEST_SUPP not supported");
700 
701 	TEST_ASSERT(rc == 0, "KVM_GET_DEVICE_ATTR(0, KVM_X86_XCOMP_GUEST_SUPP) error: %ld", rc);
702 
703 	__TEST_REQUIRE(bitmask & (1ULL << bit),
704 		       "Required XSAVE feature '%s' not supported", name);
705 
706 	TEST_REQUIRE(!syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_GUEST_PERM, bit));
707 
708 	rc = syscall(SYS_arch_prctl, ARCH_GET_XCOMP_GUEST_PERM, &bitmask);
709 	TEST_ASSERT(rc == 0, "prctl(ARCH_GET_XCOMP_GUEST_PERM) error: %ld", rc);
710 	TEST_ASSERT(bitmask & (1ULL << bit),
711 		    "prctl(ARCH_REQ_XCOMP_GUEST_PERM) failure bitmask=0x%lx",
712 		    bitmask);
713 }
714 
715 void vcpu_init_cpuid(struct kvm_vcpu *vcpu, const struct kvm_cpuid2 *cpuid)
716 {
717 	TEST_ASSERT(cpuid != vcpu->cpuid, "@cpuid can't be the vCPU's CPUID");
718 
719 	/* Allow overriding the default CPUID. */
720 	if (vcpu->cpuid && vcpu->cpuid->nent < cpuid->nent) {
721 		free(vcpu->cpuid);
722 		vcpu->cpuid = NULL;
723 	}
724 
725 	if (!vcpu->cpuid)
726 		vcpu->cpuid = allocate_kvm_cpuid2(cpuid->nent);
727 
728 	memcpy(vcpu->cpuid, cpuid, kvm_cpuid2_size(cpuid->nent));
729 	vcpu_set_cpuid(vcpu);
730 }
731 
732 void vcpu_set_cpuid_maxphyaddr(struct kvm_vcpu *vcpu, uint8_t maxphyaddr)
733 {
734 	struct kvm_cpuid_entry2 *entry = vcpu_get_cpuid_entry(vcpu, 0x80000008);
735 
736 	entry->eax = (entry->eax & ~0xff) | maxphyaddr;
737 	vcpu_set_cpuid(vcpu);
738 }
739 
740 void vcpu_clear_cpuid_entry(struct kvm_vcpu *vcpu, uint32_t function)
741 {
742 	struct kvm_cpuid_entry2 *entry = vcpu_get_cpuid_entry(vcpu, function);
743 
744 	entry->eax = 0;
745 	entry->ebx = 0;
746 	entry->ecx = 0;
747 	entry->edx = 0;
748 	vcpu_set_cpuid(vcpu);
749 }
750 
751 void vcpu_set_or_clear_cpuid_feature(struct kvm_vcpu *vcpu,
752 				     struct kvm_x86_cpu_feature feature,
753 				     bool set)
754 {
755 	struct kvm_cpuid_entry2 *entry;
756 	u32 *reg;
757 
758 	entry = __vcpu_get_cpuid_entry(vcpu, feature.function, feature.index);
759 	reg = (&entry->eax) + feature.reg;
760 
761 	if (set)
762 		*reg |= BIT(feature.bit);
763 	else
764 		*reg &= ~BIT(feature.bit);
765 
766 	vcpu_set_cpuid(vcpu);
767 }
768 
769 uint64_t vcpu_get_msr(struct kvm_vcpu *vcpu, uint64_t msr_index)
770 {
771 	struct {
772 		struct kvm_msrs header;
773 		struct kvm_msr_entry entry;
774 	} buffer = {};
775 
776 	buffer.header.nmsrs = 1;
777 	buffer.entry.index = msr_index;
778 
779 	vcpu_msrs_get(vcpu, &buffer.header);
780 
781 	return buffer.entry.data;
782 }
783 
784 int _vcpu_set_msr(struct kvm_vcpu *vcpu, uint64_t msr_index, uint64_t msr_value)
785 {
786 	struct {
787 		struct kvm_msrs header;
788 		struct kvm_msr_entry entry;
789 	} buffer = {};
790 
791 	memset(&buffer, 0, sizeof(buffer));
792 	buffer.header.nmsrs = 1;
793 	buffer.entry.index = msr_index;
794 	buffer.entry.data = msr_value;
795 
796 	return __vcpu_ioctl(vcpu, KVM_SET_MSRS, &buffer.header);
797 }
798 
799 void vcpu_args_set(struct kvm_vcpu *vcpu, unsigned int num, ...)
800 {
801 	va_list ap;
802 	struct kvm_regs regs;
803 
804 	TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
805 		    "  num: %u\n",
806 		    num);
807 
808 	va_start(ap, num);
809 	vcpu_regs_get(vcpu, &regs);
810 
811 	if (num >= 1)
812 		regs.rdi = va_arg(ap, uint64_t);
813 
814 	if (num >= 2)
815 		regs.rsi = va_arg(ap, uint64_t);
816 
817 	if (num >= 3)
818 		regs.rdx = va_arg(ap, uint64_t);
819 
820 	if (num >= 4)
821 		regs.rcx = va_arg(ap, uint64_t);
822 
823 	if (num >= 5)
824 		regs.r8 = va_arg(ap, uint64_t);
825 
826 	if (num >= 6)
827 		regs.r9 = va_arg(ap, uint64_t);
828 
829 	vcpu_regs_set(vcpu, &regs);
830 	va_end(ap);
831 }
832 
833 void vcpu_arch_dump(FILE *stream, struct kvm_vcpu *vcpu, uint8_t indent)
834 {
835 	struct kvm_regs regs;
836 	struct kvm_sregs sregs;
837 
838 	fprintf(stream, "%*svCPU ID: %u\n", indent, "", vcpu->id);
839 
840 	fprintf(stream, "%*sregs:\n", indent + 2, "");
841 	vcpu_regs_get(vcpu, &regs);
842 	regs_dump(stream, &regs, indent + 4);
843 
844 	fprintf(stream, "%*ssregs:\n", indent + 2, "");
845 	vcpu_sregs_get(vcpu, &sregs);
846 	sregs_dump(stream, &sregs, indent + 4);
847 }
848 
849 static struct kvm_msr_list *__kvm_get_msr_index_list(bool feature_msrs)
850 {
851 	struct kvm_msr_list *list;
852 	struct kvm_msr_list nmsrs;
853 	int kvm_fd, r;
854 
855 	kvm_fd = open_kvm_dev_path_or_exit();
856 
857 	nmsrs.nmsrs = 0;
858 	if (!feature_msrs)
859 		r = __kvm_ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, &nmsrs);
860 	else
861 		r = __kvm_ioctl(kvm_fd, KVM_GET_MSR_FEATURE_INDEX_LIST, &nmsrs);
862 
863 	TEST_ASSERT(r == -1 && errno == E2BIG,
864 		    "Expected -E2BIG, got rc: %i errno: %i (%s)",
865 		    r, errno, strerror(errno));
866 
867 	list = malloc(sizeof(*list) + nmsrs.nmsrs * sizeof(list->indices[0]));
868 	TEST_ASSERT(list, "-ENOMEM when allocating MSR index list");
869 	list->nmsrs = nmsrs.nmsrs;
870 
871 	if (!feature_msrs)
872 		kvm_ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, list);
873 	else
874 		kvm_ioctl(kvm_fd, KVM_GET_MSR_FEATURE_INDEX_LIST, list);
875 	close(kvm_fd);
876 
877 	TEST_ASSERT(list->nmsrs == nmsrs.nmsrs,
878 		    "Number of MSRs in list changed, was %d, now %d",
879 		    nmsrs.nmsrs, list->nmsrs);
880 	return list;
881 }
882 
883 const struct kvm_msr_list *kvm_get_msr_index_list(void)
884 {
885 	static const struct kvm_msr_list *list;
886 
887 	if (!list)
888 		list = __kvm_get_msr_index_list(false);
889 	return list;
890 }
891 
892 
893 const struct kvm_msr_list *kvm_get_feature_msr_index_list(void)
894 {
895 	static const struct kvm_msr_list *list;
896 
897 	if (!list)
898 		list = __kvm_get_msr_index_list(true);
899 	return list;
900 }
901 
902 bool kvm_msr_is_in_save_restore_list(uint32_t msr_index)
903 {
904 	const struct kvm_msr_list *list = kvm_get_msr_index_list();
905 	int i;
906 
907 	for (i = 0; i < list->nmsrs; ++i) {
908 		if (list->indices[i] == msr_index)
909 			return true;
910 	}
911 
912 	return false;
913 }
914 
915 static void vcpu_save_xsave_state(struct kvm_vcpu *vcpu,
916 				  struct kvm_x86_state *state)
917 {
918 	int size = vm_check_cap(vcpu->vm, KVM_CAP_XSAVE2);
919 
920 	if (size) {
921 		state->xsave = malloc(size);
922 		vcpu_xsave2_get(vcpu, state->xsave);
923 	} else {
924 		state->xsave = malloc(sizeof(struct kvm_xsave));
925 		vcpu_xsave_get(vcpu, state->xsave);
926 	}
927 }
928 
929 struct kvm_x86_state *vcpu_save_state(struct kvm_vcpu *vcpu)
930 {
931 	const struct kvm_msr_list *msr_list = kvm_get_msr_index_list();
932 	struct kvm_x86_state *state;
933 	int i;
934 
935 	static int nested_size = -1;
936 
937 	if (nested_size == -1) {
938 		nested_size = kvm_check_cap(KVM_CAP_NESTED_STATE);
939 		TEST_ASSERT(nested_size <= sizeof(state->nested_),
940 			    "Nested state size too big, %i > %zi",
941 			    nested_size, sizeof(state->nested_));
942 	}
943 
944 	/*
945 	 * When KVM exits to userspace with KVM_EXIT_IO, KVM guarantees
946 	 * guest state is consistent only after userspace re-enters the
947 	 * kernel with KVM_RUN.  Complete IO prior to migrating state
948 	 * to a new VM.
949 	 */
950 	vcpu_run_complete_io(vcpu);
951 
952 	state = malloc(sizeof(*state) + msr_list->nmsrs * sizeof(state->msrs.entries[0]));
953 
954 	vcpu_events_get(vcpu, &state->events);
955 	vcpu_mp_state_get(vcpu, &state->mp_state);
956 	vcpu_regs_get(vcpu, &state->regs);
957 	vcpu_save_xsave_state(vcpu, state);
958 
959 	if (kvm_has_cap(KVM_CAP_XCRS))
960 		vcpu_xcrs_get(vcpu, &state->xcrs);
961 
962 	vcpu_sregs_get(vcpu, &state->sregs);
963 
964 	if (nested_size) {
965 		state->nested.size = sizeof(state->nested_);
966 
967 		vcpu_nested_state_get(vcpu, &state->nested);
968 		TEST_ASSERT(state->nested.size <= nested_size,
969 			    "Nested state size too big, %i (KVM_CHECK_CAP gave %i)",
970 			    state->nested.size, nested_size);
971 	} else {
972 		state->nested.size = 0;
973 	}
974 
975 	state->msrs.nmsrs = msr_list->nmsrs;
976 	for (i = 0; i < msr_list->nmsrs; i++)
977 		state->msrs.entries[i].index = msr_list->indices[i];
978 	vcpu_msrs_get(vcpu, &state->msrs);
979 
980 	vcpu_debugregs_get(vcpu, &state->debugregs);
981 
982 	return state;
983 }
984 
985 void vcpu_load_state(struct kvm_vcpu *vcpu, struct kvm_x86_state *state)
986 {
987 	vcpu_sregs_set(vcpu, &state->sregs);
988 	vcpu_msrs_set(vcpu, &state->msrs);
989 
990 	if (kvm_has_cap(KVM_CAP_XCRS))
991 		vcpu_xcrs_set(vcpu, &state->xcrs);
992 
993 	vcpu_xsave_set(vcpu,  state->xsave);
994 	vcpu_events_set(vcpu, &state->events);
995 	vcpu_mp_state_set(vcpu, &state->mp_state);
996 	vcpu_debugregs_set(vcpu, &state->debugregs);
997 	vcpu_regs_set(vcpu, &state->regs);
998 
999 	if (state->nested.size)
1000 		vcpu_nested_state_set(vcpu, &state->nested);
1001 }
1002 
1003 void kvm_x86_state_cleanup(struct kvm_x86_state *state)
1004 {
1005 	free(state->xsave);
1006 	free(state);
1007 }
1008 
1009 static bool cpu_vendor_string_is(const char *vendor)
1010 {
1011 	const uint32_t *chunk = (const uint32_t *)vendor;
1012 	uint32_t eax, ebx, ecx, edx;
1013 
1014 	cpuid(0, &eax, &ebx, &ecx, &edx);
1015 	return (ebx == chunk[0] && edx == chunk[1] && ecx == chunk[2]);
1016 }
1017 
1018 bool is_intel_cpu(void)
1019 {
1020 	return cpu_vendor_string_is("GenuineIntel");
1021 }
1022 
1023 /*
1024  * Exclude early K5 samples with a vendor string of "AMDisbetter!"
1025  */
1026 bool is_amd_cpu(void)
1027 {
1028 	return cpu_vendor_string_is("AuthenticAMD");
1029 }
1030 
1031 void kvm_get_cpu_address_width(unsigned int *pa_bits, unsigned int *va_bits)
1032 {
1033 	if (!kvm_cpu_has_p(X86_PROPERTY_MAX_PHY_ADDR)) {
1034 		*pa_bits = kvm_cpu_has(X86_FEATURE_PAE) ? 36 : 32;
1035 		*va_bits = 32;
1036 	} else {
1037 		*pa_bits = kvm_cpu_property(X86_PROPERTY_MAX_PHY_ADDR);
1038 		*va_bits = kvm_cpu_property(X86_PROPERTY_MAX_VIRT_ADDR);
1039 	}
1040 }
1041 
1042 static void set_idt_entry(struct kvm_vm *vm, int vector, unsigned long addr,
1043 			  int dpl, unsigned short selector)
1044 {
1045 	struct idt_entry *base =
1046 		(struct idt_entry *)addr_gva2hva(vm, vm->idt);
1047 	struct idt_entry *e = &base[vector];
1048 
1049 	memset(e, 0, sizeof(*e));
1050 	e->offset0 = addr;
1051 	e->selector = selector;
1052 	e->ist = 0;
1053 	e->type = 14;
1054 	e->dpl = dpl;
1055 	e->p = 1;
1056 	e->offset1 = addr >> 16;
1057 	e->offset2 = addr >> 32;
1058 }
1059 
1060 
1061 static bool kvm_fixup_exception(struct ex_regs *regs)
1062 {
1063 	if (regs->r9 != KVM_EXCEPTION_MAGIC || regs->rip != regs->r10)
1064 		return false;
1065 
1066 	if (regs->vector == DE_VECTOR)
1067 		return false;
1068 
1069 	regs->rip = regs->r11;
1070 	regs->r9 = regs->vector;
1071 	regs->r10 = regs->error_code;
1072 	return true;
1073 }
1074 
1075 void kvm_exit_unexpected_vector(uint32_t value)
1076 {
1077 	ucall(UCALL_UNHANDLED, 1, value);
1078 }
1079 
1080 void route_exception(struct ex_regs *regs)
1081 {
1082 	typedef void(*handler)(struct ex_regs *);
1083 	handler *handlers = (handler *)exception_handlers;
1084 
1085 	if (handlers && handlers[regs->vector]) {
1086 		handlers[regs->vector](regs);
1087 		return;
1088 	}
1089 
1090 	if (kvm_fixup_exception(regs))
1091 		return;
1092 
1093 	kvm_exit_unexpected_vector(regs->vector);
1094 }
1095 
1096 void vm_init_descriptor_tables(struct kvm_vm *vm)
1097 {
1098 	extern void *idt_handlers;
1099 	int i;
1100 
1101 	vm->idt = __vm_vaddr_alloc_page(vm, MEM_REGION_DATA);
1102 	vm->handlers = __vm_vaddr_alloc_page(vm, MEM_REGION_DATA);
1103 	/* Handlers have the same address in both address spaces.*/
1104 	for (i = 0; i < NUM_INTERRUPTS; i++)
1105 		set_idt_entry(vm, i, (unsigned long)(&idt_handlers)[i], 0,
1106 			DEFAULT_CODE_SELECTOR);
1107 }
1108 
1109 void vcpu_init_descriptor_tables(struct kvm_vcpu *vcpu)
1110 {
1111 	struct kvm_vm *vm = vcpu->vm;
1112 	struct kvm_sregs sregs;
1113 
1114 	vcpu_sregs_get(vcpu, &sregs);
1115 	sregs.idt.base = vm->idt;
1116 	sregs.idt.limit = NUM_INTERRUPTS * sizeof(struct idt_entry) - 1;
1117 	sregs.gdt.base = vm->gdt;
1118 	sregs.gdt.limit = getpagesize() - 1;
1119 	kvm_seg_set_kernel_data_64bit(NULL, DEFAULT_DATA_SELECTOR, &sregs.gs);
1120 	vcpu_sregs_set(vcpu, &sregs);
1121 	*(vm_vaddr_t *)addr_gva2hva(vm, (vm_vaddr_t)(&exception_handlers)) = vm->handlers;
1122 }
1123 
1124 void vm_install_exception_handler(struct kvm_vm *vm, int vector,
1125 			       void (*handler)(struct ex_regs *))
1126 {
1127 	vm_vaddr_t *handlers = (vm_vaddr_t *)addr_gva2hva(vm, vm->handlers);
1128 
1129 	handlers[vector] = (vm_vaddr_t)handler;
1130 }
1131 
1132 void assert_on_unhandled_exception(struct kvm_vcpu *vcpu)
1133 {
1134 	struct ucall uc;
1135 
1136 	if (get_ucall(vcpu, &uc) == UCALL_UNHANDLED) {
1137 		uint64_t vector = uc.args[0];
1138 
1139 		TEST_FAIL("Unexpected vectored event in guest (vector:0x%lx)",
1140 			  vector);
1141 	}
1142 }
1143 
1144 const struct kvm_cpuid_entry2 *get_cpuid_entry(const struct kvm_cpuid2 *cpuid,
1145 					       uint32_t function, uint32_t index)
1146 {
1147 	int i;
1148 
1149 	for (i = 0; i < cpuid->nent; i++) {
1150 		if (cpuid->entries[i].function == function &&
1151 		    cpuid->entries[i].index == index)
1152 			return &cpuid->entries[i];
1153 	}
1154 
1155 	TEST_FAIL("CPUID function 0x%x index 0x%x not found ", function, index);
1156 
1157 	return NULL;
1158 }
1159 
1160 uint64_t kvm_hypercall(uint64_t nr, uint64_t a0, uint64_t a1, uint64_t a2,
1161 		       uint64_t a3)
1162 {
1163 	uint64_t r;
1164 
1165 	asm volatile("vmcall"
1166 		     : "=a"(r)
1167 		     : "a"(nr), "b"(a0), "c"(a1), "d"(a2), "S"(a3));
1168 	return r;
1169 }
1170 
1171 const struct kvm_cpuid2 *kvm_get_supported_hv_cpuid(void)
1172 {
1173 	static struct kvm_cpuid2 *cpuid;
1174 	int kvm_fd;
1175 
1176 	if (cpuid)
1177 		return cpuid;
1178 
1179 	cpuid = allocate_kvm_cpuid2(MAX_NR_CPUID_ENTRIES);
1180 	kvm_fd = open_kvm_dev_path_or_exit();
1181 
1182 	kvm_ioctl(kvm_fd, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1183 
1184 	close(kvm_fd);
1185 	return cpuid;
1186 }
1187 
1188 void vcpu_set_hv_cpuid(struct kvm_vcpu *vcpu)
1189 {
1190 	static struct kvm_cpuid2 *cpuid_full;
1191 	const struct kvm_cpuid2 *cpuid_sys, *cpuid_hv;
1192 	int i, nent = 0;
1193 
1194 	if (!cpuid_full) {
1195 		cpuid_sys = kvm_get_supported_cpuid();
1196 		cpuid_hv = kvm_get_supported_hv_cpuid();
1197 
1198 		cpuid_full = allocate_kvm_cpuid2(cpuid_sys->nent + cpuid_hv->nent);
1199 		if (!cpuid_full) {
1200 			perror("malloc");
1201 			abort();
1202 		}
1203 
1204 		/* Need to skip KVM CPUID leaves 0x400000xx */
1205 		for (i = 0; i < cpuid_sys->nent; i++) {
1206 			if (cpuid_sys->entries[i].function >= 0x40000000 &&
1207 			    cpuid_sys->entries[i].function < 0x40000100)
1208 				continue;
1209 			cpuid_full->entries[nent] = cpuid_sys->entries[i];
1210 			nent++;
1211 		}
1212 
1213 		memcpy(&cpuid_full->entries[nent], cpuid_hv->entries,
1214 		       cpuid_hv->nent * sizeof(struct kvm_cpuid_entry2));
1215 		cpuid_full->nent = nent + cpuid_hv->nent;
1216 	}
1217 
1218 	vcpu_init_cpuid(vcpu, cpuid_full);
1219 }
1220 
1221 const struct kvm_cpuid2 *vcpu_get_supported_hv_cpuid(struct kvm_vcpu *vcpu)
1222 {
1223 	struct kvm_cpuid2 *cpuid = allocate_kvm_cpuid2(MAX_NR_CPUID_ENTRIES);
1224 
1225 	vcpu_ioctl(vcpu, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1226 
1227 	return cpuid;
1228 }
1229 
1230 unsigned long vm_compute_max_gfn(struct kvm_vm *vm)
1231 {
1232 	const unsigned long num_ht_pages = 12 << (30 - vm->page_shift); /* 12 GiB */
1233 	unsigned long ht_gfn, max_gfn, max_pfn;
1234 	uint8_t maxphyaddr;
1235 
1236 	max_gfn = (1ULL << (vm->pa_bits - vm->page_shift)) - 1;
1237 
1238 	/* Avoid reserved HyperTransport region on AMD processors.  */
1239 	if (!is_amd_cpu())
1240 		return max_gfn;
1241 
1242 	/* On parts with <40 physical address bits, the area is fully hidden */
1243 	if (vm->pa_bits < 40)
1244 		return max_gfn;
1245 
1246 	/* Before family 17h, the HyperTransport area is just below 1T.  */
1247 	ht_gfn = (1 << 28) - num_ht_pages;
1248 	if (this_cpu_family() < 0x17)
1249 		goto done;
1250 
1251 	/*
1252 	 * Otherwise it's at the top of the physical address space, possibly
1253 	 * reduced due to SME by bits 11:6 of CPUID[0x8000001f].EBX.  Use
1254 	 * the old conservative value if MAXPHYADDR is not enumerated.
1255 	 */
1256 	if (!this_cpu_has_p(X86_PROPERTY_MAX_PHY_ADDR))
1257 		goto done;
1258 
1259 	maxphyaddr = this_cpu_property(X86_PROPERTY_MAX_PHY_ADDR);
1260 	max_pfn = (1ULL << (maxphyaddr - vm->page_shift)) - 1;
1261 
1262 	if (this_cpu_has_p(X86_PROPERTY_PHYS_ADDR_REDUCTION))
1263 		max_pfn >>= this_cpu_property(X86_PROPERTY_PHYS_ADDR_REDUCTION);
1264 
1265 	ht_gfn = max_pfn - num_ht_pages;
1266 done:
1267 	return min(max_gfn, ht_gfn - 1);
1268 }
1269 
1270 /* Returns true if kvm_intel was loaded with unrestricted_guest=1. */
1271 bool vm_is_unrestricted_guest(struct kvm_vm *vm)
1272 {
1273 	/* Ensure that a KVM vendor-specific module is loaded. */
1274 	if (vm == NULL)
1275 		close(open_kvm_dev_path_or_exit());
1276 
1277 	return get_kvm_intel_param_bool("unrestricted_guest");
1278 }
1279