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