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