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 
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  */
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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  */
466 static void kvm_seg_set_unusable(struct kvm_segment *segp)
467 {
468 	memset(segp, 0, sizeof(*segp));
469 	segp->unusable = true;
470 }
471 
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  */
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  */
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 
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 
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 
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 
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 void vm_vcpu_add_default(struct kvm_vm *vm, uint32_t vcpuid, void *guest_code)
654 {
655 	struct kvm_mp_state mp_state;
656 	struct kvm_regs regs;
657 	vm_vaddr_t stack_vaddr;
658 	stack_vaddr = vm_vaddr_alloc(vm, DEFAULT_STACK_PGS * getpagesize(),
659 				     DEFAULT_GUEST_STACK_VADDR_MIN);
660 
661 	/* Create VCPU */
662 	vm_vcpu_add(vm, vcpuid);
663 	vcpu_set_cpuid(vm, vcpuid, kvm_get_supported_cpuid());
664 	vcpu_setup(vm, vcpuid);
665 
666 	/* Setup guest general purpose registers */
667 	vcpu_regs_get(vm, vcpuid, &regs);
668 	regs.rflags = regs.rflags | 0x2;
669 	regs.rsp = stack_vaddr + (DEFAULT_STACK_PGS * getpagesize());
670 	regs.rip = (unsigned long) guest_code;
671 	vcpu_regs_set(vm, vcpuid, &regs);
672 
673 	/* Setup the MP state */
674 	mp_state.mp_state = 0;
675 	vcpu_set_mp_state(vm, vcpuid, &mp_state);
676 }
677 
678 /*
679  * Allocate an instance of struct kvm_cpuid2
680  *
681  * Input Args: None
682  *
683  * Output Args: None
684  *
685  * Return: A pointer to the allocated struct. The caller is responsible
686  * for freeing this struct.
687  *
688  * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
689  * array to be decided at allocation time, allocation is slightly
690  * complicated. This function uses a reasonable default length for
691  * the array and performs the appropriate allocation.
692  */
693 static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
694 {
695 	struct kvm_cpuid2 *cpuid;
696 	int nent = 100;
697 	size_t size;
698 
699 	size = sizeof(*cpuid);
700 	size += nent * sizeof(struct kvm_cpuid_entry2);
701 	cpuid = malloc(size);
702 	if (!cpuid) {
703 		perror("malloc");
704 		abort();
705 	}
706 
707 	cpuid->nent = nent;
708 
709 	return cpuid;
710 }
711 
712 /*
713  * KVM Supported CPUID Get
714  *
715  * Input Args: None
716  *
717  * Output Args:
718  *
719  * Return: The supported KVM CPUID
720  *
721  * Get the guest CPUID supported by KVM.
722  */
723 struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
724 {
725 	static struct kvm_cpuid2 *cpuid;
726 	int ret;
727 	int kvm_fd;
728 
729 	if (cpuid)
730 		return cpuid;
731 
732 	cpuid = allocate_kvm_cpuid2();
733 	kvm_fd = open_kvm_dev_path_or_exit();
734 
735 	ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
736 	TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
737 		    ret, errno);
738 
739 	close(kvm_fd);
740 	return cpuid;
741 }
742 
743 /*
744  * KVM Get MSR
745  *
746  * Input Args:
747  *   msr_index - Index of MSR
748  *
749  * Output Args: None
750  *
751  * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
752  *
753  * Get value of MSR for VCPU.
754  */
755 uint64_t kvm_get_feature_msr(uint64_t msr_index)
756 {
757 	struct {
758 		struct kvm_msrs header;
759 		struct kvm_msr_entry entry;
760 	} buffer = {};
761 	int r, kvm_fd;
762 
763 	buffer.header.nmsrs = 1;
764 	buffer.entry.index = msr_index;
765 	kvm_fd = open_kvm_dev_path_or_exit();
766 
767 	r = ioctl(kvm_fd, KVM_GET_MSRS, &buffer.header);
768 	TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
769 		"  rc: %i errno: %i", r, errno);
770 
771 	close(kvm_fd);
772 	return buffer.entry.data;
773 }
774 
775 /*
776  * VM VCPU CPUID Set
777  *
778  * Input Args:
779  *   vm - Virtual Machine
780  *   vcpuid - VCPU id
781  *
782  * Output Args: None
783  *
784  * Return: KVM CPUID (KVM_GET_CPUID2)
785  *
786  * Set the VCPU's CPUID.
787  */
788 struct kvm_cpuid2 *vcpu_get_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
789 {
790 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
791 	struct kvm_cpuid2 *cpuid;
792 	int max_ent;
793 	int rc = -1;
794 
795 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
796 
797 	cpuid = allocate_kvm_cpuid2();
798 	max_ent = cpuid->nent;
799 
800 	for (cpuid->nent = 1; cpuid->nent <= max_ent; cpuid->nent++) {
801 		rc = ioctl(vcpu->fd, KVM_GET_CPUID2, cpuid);
802 		if (!rc)
803 			break;
804 
805 		TEST_ASSERT(rc == -1 && errno == E2BIG,
806 			    "KVM_GET_CPUID2 should either succeed or give E2BIG: %d %d",
807 			    rc, errno);
808 	}
809 
810 	TEST_ASSERT(rc == 0, "KVM_GET_CPUID2 failed, rc: %i errno: %i",
811 		    rc, errno);
812 
813 	return cpuid;
814 }
815 
816 
817 
818 /*
819  * Locate a cpuid entry.
820  *
821  * Input Args:
822  *   function: The function of the cpuid entry to find.
823  *   index: The index of the cpuid entry.
824  *
825  * Output Args: None
826  *
827  * Return: A pointer to the cpuid entry. Never returns NULL.
828  */
829 struct kvm_cpuid_entry2 *
830 kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
831 {
832 	struct kvm_cpuid2 *cpuid;
833 	struct kvm_cpuid_entry2 *entry = NULL;
834 	int i;
835 
836 	cpuid = kvm_get_supported_cpuid();
837 	for (i = 0; i < cpuid->nent; i++) {
838 		if (cpuid->entries[i].function == function &&
839 		    cpuid->entries[i].index == index) {
840 			entry = &cpuid->entries[i];
841 			break;
842 		}
843 	}
844 
845 	TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
846 		    function, index);
847 	return entry;
848 }
849 
850 /*
851  * VM VCPU CPUID Set
852  *
853  * Input Args:
854  *   vm - Virtual Machine
855  *   vcpuid - VCPU id
856  *   cpuid - The CPUID values to set.
857  *
858  * Output Args: None
859  *
860  * Return: void
861  *
862  * Set the VCPU's CPUID.
863  */
864 void vcpu_set_cpuid(struct kvm_vm *vm,
865 		uint32_t vcpuid, struct kvm_cpuid2 *cpuid)
866 {
867 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
868 	int rc;
869 
870 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
871 
872 	rc = ioctl(vcpu->fd, KVM_SET_CPUID2, cpuid);
873 	TEST_ASSERT(rc == 0, "KVM_SET_CPUID2 failed, rc: %i errno: %i",
874 		    rc, errno);
875 
876 }
877 
878 /*
879  * VCPU Get MSR
880  *
881  * Input Args:
882  *   vm - Virtual Machine
883  *   vcpuid - VCPU ID
884  *   msr_index - Index of MSR
885  *
886  * Output Args: None
887  *
888  * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
889  *
890  * Get value of MSR for VCPU.
891  */
892 uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
893 {
894 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
895 	struct {
896 		struct kvm_msrs header;
897 		struct kvm_msr_entry entry;
898 	} buffer = {};
899 	int r;
900 
901 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
902 	buffer.header.nmsrs = 1;
903 	buffer.entry.index = msr_index;
904 	r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
905 	TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
906 		"  rc: %i errno: %i", r, errno);
907 
908 	return buffer.entry.data;
909 }
910 
911 /*
912  * _VCPU Set MSR
913  *
914  * Input Args:
915  *   vm - Virtual Machine
916  *   vcpuid - VCPU ID
917  *   msr_index - Index of MSR
918  *   msr_value - New value of MSR
919  *
920  * Output Args: None
921  *
922  * Return: The result of KVM_SET_MSRS.
923  *
924  * Sets the value of an MSR for the given VCPU.
925  */
926 int _vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
927 		  uint64_t msr_value)
928 {
929 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
930 	struct {
931 		struct kvm_msrs header;
932 		struct kvm_msr_entry entry;
933 	} buffer = {};
934 	int r;
935 
936 	TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
937 	memset(&buffer, 0, sizeof(buffer));
938 	buffer.header.nmsrs = 1;
939 	buffer.entry.index = msr_index;
940 	buffer.entry.data = msr_value;
941 	r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
942 	return r;
943 }
944 
945 /*
946  * VCPU Set MSR
947  *
948  * Input Args:
949  *   vm - Virtual Machine
950  *   vcpuid - VCPU ID
951  *   msr_index - Index of MSR
952  *   msr_value - New value of MSR
953  *
954  * Output Args: None
955  *
956  * Return: On success, nothing. On failure a TEST_ASSERT is produced.
957  *
958  * Set value of MSR for VCPU.
959  */
960 void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
961 	uint64_t msr_value)
962 {
963 	int r;
964 
965 	r = _vcpu_set_msr(vm, vcpuid, msr_index, msr_value);
966 	TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
967 		"  rc: %i errno: %i", r, errno);
968 }
969 
970 void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
971 {
972 	va_list ap;
973 	struct kvm_regs regs;
974 
975 	TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
976 		    "  num: %u\n",
977 		    num);
978 
979 	va_start(ap, num);
980 	vcpu_regs_get(vm, vcpuid, &regs);
981 
982 	if (num >= 1)
983 		regs.rdi = va_arg(ap, uint64_t);
984 
985 	if (num >= 2)
986 		regs.rsi = va_arg(ap, uint64_t);
987 
988 	if (num >= 3)
989 		regs.rdx = va_arg(ap, uint64_t);
990 
991 	if (num >= 4)
992 		regs.rcx = va_arg(ap, uint64_t);
993 
994 	if (num >= 5)
995 		regs.r8 = va_arg(ap, uint64_t);
996 
997 	if (num >= 6)
998 		regs.r9 = va_arg(ap, uint64_t);
999 
1000 	vcpu_regs_set(vm, vcpuid, &regs);
1001 	va_end(ap);
1002 }
1003 
1004 void vcpu_dump(FILE *stream, struct kvm_vm *vm, uint32_t vcpuid, uint8_t indent)
1005 {
1006 	struct kvm_regs regs;
1007 	struct kvm_sregs sregs;
1008 
1009 	fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
1010 
1011 	fprintf(stream, "%*sregs:\n", indent + 2, "");
1012 	vcpu_regs_get(vm, vcpuid, &regs);
1013 	regs_dump(stream, &regs, indent + 4);
1014 
1015 	fprintf(stream, "%*ssregs:\n", indent + 2, "");
1016 	vcpu_sregs_get(vm, vcpuid, &sregs);
1017 	sregs_dump(stream, &sregs, indent + 4);
1018 }
1019 
1020 struct kvm_x86_state {
1021 	struct kvm_vcpu_events events;
1022 	struct kvm_mp_state mp_state;
1023 	struct kvm_regs regs;
1024 	struct kvm_xsave xsave;
1025 	struct kvm_xcrs xcrs;
1026 	struct kvm_sregs sregs;
1027 	struct kvm_debugregs debugregs;
1028 	union {
1029 		struct kvm_nested_state nested;
1030 		char nested_[16384];
1031 	};
1032 	struct kvm_msrs msrs;
1033 };
1034 
1035 static int kvm_get_num_msrs_fd(int kvm_fd)
1036 {
1037 	struct kvm_msr_list nmsrs;
1038 	int r;
1039 
1040 	nmsrs.nmsrs = 0;
1041 	r = ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, &nmsrs);
1042 	TEST_ASSERT(r == -1 && errno == E2BIG, "Unexpected result from KVM_GET_MSR_INDEX_LIST probe, r: %i",
1043 		r);
1044 
1045 	return nmsrs.nmsrs;
1046 }
1047 
1048 static int kvm_get_num_msrs(struct kvm_vm *vm)
1049 {
1050 	return kvm_get_num_msrs_fd(vm->kvm_fd);
1051 }
1052 
1053 struct kvm_msr_list *kvm_get_msr_index_list(void)
1054 {
1055 	struct kvm_msr_list *list;
1056 	int nmsrs, r, kvm_fd;
1057 
1058 	kvm_fd = open_kvm_dev_path_or_exit();
1059 
1060 	nmsrs = kvm_get_num_msrs_fd(kvm_fd);
1061 	list = malloc(sizeof(*list) + nmsrs * sizeof(list->indices[0]));
1062 	list->nmsrs = nmsrs;
1063 	r = ioctl(kvm_fd, KVM_GET_MSR_INDEX_LIST, list);
1064 	close(kvm_fd);
1065 
1066 	TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MSR_INDEX_LIST, r: %i",
1067 		r);
1068 
1069 	return list;
1070 }
1071 
1072 struct kvm_x86_state *vcpu_save_state(struct kvm_vm *vm, uint32_t vcpuid)
1073 {
1074 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1075 	struct kvm_msr_list *list;
1076 	struct kvm_x86_state *state;
1077 	int nmsrs, r, i;
1078 	static int nested_size = -1;
1079 
1080 	if (nested_size == -1) {
1081 		nested_size = kvm_check_cap(KVM_CAP_NESTED_STATE);
1082 		TEST_ASSERT(nested_size <= sizeof(state->nested_),
1083 			    "Nested state size too big, %i > %zi",
1084 			    nested_size, sizeof(state->nested_));
1085 	}
1086 
1087 	/*
1088 	 * When KVM exits to userspace with KVM_EXIT_IO, KVM guarantees
1089 	 * guest state is consistent only after userspace re-enters the
1090 	 * kernel with KVM_RUN.  Complete IO prior to migrating state
1091 	 * to a new VM.
1092 	 */
1093 	vcpu_run_complete_io(vm, vcpuid);
1094 
1095 	nmsrs = kvm_get_num_msrs(vm);
1096 	list = malloc(sizeof(*list) + nmsrs * sizeof(list->indices[0]));
1097 	list->nmsrs = nmsrs;
1098 	r = ioctl(vm->kvm_fd, KVM_GET_MSR_INDEX_LIST, list);
1099         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MSR_INDEX_LIST, r: %i",
1100                 r);
1101 
1102 	state = malloc(sizeof(*state) + nmsrs * sizeof(state->msrs.entries[0]));
1103 	r = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, &state->events);
1104         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_VCPU_EVENTS, r: %i",
1105                 r);
1106 
1107 	r = ioctl(vcpu->fd, KVM_GET_MP_STATE, &state->mp_state);
1108         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_MP_STATE, r: %i",
1109                 r);
1110 
1111 	r = ioctl(vcpu->fd, KVM_GET_REGS, &state->regs);
1112         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_REGS, r: %i",
1113                 r);
1114 
1115 	r = ioctl(vcpu->fd, KVM_GET_XSAVE, &state->xsave);
1116         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_XSAVE, r: %i",
1117                 r);
1118 
1119 	if (kvm_check_cap(KVM_CAP_XCRS)) {
1120 		r = ioctl(vcpu->fd, KVM_GET_XCRS, &state->xcrs);
1121 		TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_XCRS, r: %i",
1122 			    r);
1123 	}
1124 
1125 	r = ioctl(vcpu->fd, KVM_GET_SREGS, &state->sregs);
1126         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_SREGS, r: %i",
1127                 r);
1128 
1129 	if (nested_size) {
1130 		state->nested.size = sizeof(state->nested_);
1131 		r = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, &state->nested);
1132 		TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_NESTED_STATE, r: %i",
1133 			r);
1134 		TEST_ASSERT(state->nested.size <= nested_size,
1135 			"Nested state size too big, %i (KVM_CHECK_CAP gave %i)",
1136 			state->nested.size, nested_size);
1137 	} else
1138 		state->nested.size = 0;
1139 
1140 	state->msrs.nmsrs = nmsrs;
1141 	for (i = 0; i < nmsrs; i++)
1142 		state->msrs.entries[i].index = list->indices[i];
1143 	r = ioctl(vcpu->fd, KVM_GET_MSRS, &state->msrs);
1144         TEST_ASSERT(r == nmsrs, "Unexpected result from KVM_GET_MSRS, r: %i (failed MSR was 0x%x)",
1145                 r, r == nmsrs ? -1 : list->indices[r]);
1146 
1147 	r = ioctl(vcpu->fd, KVM_GET_DEBUGREGS, &state->debugregs);
1148         TEST_ASSERT(r == 0, "Unexpected result from KVM_GET_DEBUGREGS, r: %i",
1149                 r);
1150 
1151 	free(list);
1152 	return state;
1153 }
1154 
1155 void vcpu_load_state(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_x86_state *state)
1156 {
1157 	struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1158 	int r;
1159 
1160 	r = ioctl(vcpu->fd, KVM_SET_XSAVE, &state->xsave);
1161         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_XSAVE, r: %i",
1162                 r);
1163 
1164 	if (kvm_check_cap(KVM_CAP_XCRS)) {
1165 		r = ioctl(vcpu->fd, KVM_SET_XCRS, &state->xcrs);
1166 		TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_XCRS, r: %i",
1167 			    r);
1168 	}
1169 
1170 	r = ioctl(vcpu->fd, KVM_SET_SREGS, &state->sregs);
1171         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_SREGS, r: %i",
1172                 r);
1173 
1174 	r = ioctl(vcpu->fd, KVM_SET_MSRS, &state->msrs);
1175         TEST_ASSERT(r == state->msrs.nmsrs, "Unexpected result from KVM_SET_MSRS, r: %i (failed at %x)",
1176                 r, r == state->msrs.nmsrs ? -1 : state->msrs.entries[r].index);
1177 
1178 	r = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, &state->events);
1179         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_VCPU_EVENTS, r: %i",
1180                 r);
1181 
1182 	r = ioctl(vcpu->fd, KVM_SET_MP_STATE, &state->mp_state);
1183         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_MP_STATE, r: %i",
1184                 r);
1185 
1186 	r = ioctl(vcpu->fd, KVM_SET_DEBUGREGS, &state->debugregs);
1187         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_DEBUGREGS, r: %i",
1188                 r);
1189 
1190 	r = ioctl(vcpu->fd, KVM_SET_REGS, &state->regs);
1191         TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_REGS, r: %i",
1192                 r);
1193 
1194 	if (state->nested.size) {
1195 		r = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, &state->nested);
1196 		TEST_ASSERT(r == 0, "Unexpected result from KVM_SET_NESTED_STATE, r: %i",
1197 			r);
1198 	}
1199 }
1200 
1201 bool is_intel_cpu(void)
1202 {
1203 	int eax, ebx, ecx, edx;
1204 	const uint32_t *chunk;
1205 	const int leaf = 0;
1206 
1207 	__asm__ __volatile__(
1208 		"cpuid"
1209 		: /* output */ "=a"(eax), "=b"(ebx),
1210 		  "=c"(ecx), "=d"(edx)
1211 		: /* input */ "0"(leaf), "2"(0));
1212 
1213 	chunk = (const uint32_t *)("GenuineIntel");
1214 	return (ebx == chunk[0] && edx == chunk[1] && ecx == chunk[2]);
1215 }
1216 
1217 uint32_t kvm_get_cpuid_max_basic(void)
1218 {
1219 	return kvm_get_supported_cpuid_entry(0)->eax;
1220 }
1221 
1222 uint32_t kvm_get_cpuid_max_extended(void)
1223 {
1224 	return kvm_get_supported_cpuid_entry(0x80000000)->eax;
1225 }
1226 
1227 void kvm_get_cpu_address_width(unsigned int *pa_bits, unsigned int *va_bits)
1228 {
1229 	struct kvm_cpuid_entry2 *entry;
1230 	bool pae;
1231 
1232 	/* SDM 4.1.4 */
1233 	if (kvm_get_cpuid_max_extended() < 0x80000008) {
1234 		pae = kvm_get_supported_cpuid_entry(1)->edx & (1 << 6);
1235 		*pa_bits = pae ? 36 : 32;
1236 		*va_bits = 32;
1237 	} else {
1238 		entry = kvm_get_supported_cpuid_entry(0x80000008);
1239 		*pa_bits = entry->eax & 0xff;
1240 		*va_bits = (entry->eax >> 8) & 0xff;
1241 	}
1242 }
1243 
1244 struct idt_entry {
1245 	uint16_t offset0;
1246 	uint16_t selector;
1247 	uint16_t ist : 3;
1248 	uint16_t : 5;
1249 	uint16_t type : 4;
1250 	uint16_t : 1;
1251 	uint16_t dpl : 2;
1252 	uint16_t p : 1;
1253 	uint16_t offset1;
1254 	uint32_t offset2; uint32_t reserved;
1255 };
1256 
1257 static void set_idt_entry(struct kvm_vm *vm, int vector, unsigned long addr,
1258 			  int dpl, unsigned short selector)
1259 {
1260 	struct idt_entry *base =
1261 		(struct idt_entry *)addr_gva2hva(vm, vm->idt);
1262 	struct idt_entry *e = &base[vector];
1263 
1264 	memset(e, 0, sizeof(*e));
1265 	e->offset0 = addr;
1266 	e->selector = selector;
1267 	e->ist = 0;
1268 	e->type = 14;
1269 	e->dpl = dpl;
1270 	e->p = 1;
1271 	e->offset1 = addr >> 16;
1272 	e->offset2 = addr >> 32;
1273 }
1274 
1275 void kvm_exit_unexpected_vector(uint32_t value)
1276 {
1277 	ucall(UCALL_UNHANDLED, 1, value);
1278 }
1279 
1280 void route_exception(struct ex_regs *regs)
1281 {
1282 	typedef void(*handler)(struct ex_regs *);
1283 	handler *handlers = (handler *)exception_handlers;
1284 
1285 	if (handlers && handlers[regs->vector]) {
1286 		handlers[regs->vector](regs);
1287 		return;
1288 	}
1289 
1290 	kvm_exit_unexpected_vector(regs->vector);
1291 }
1292 
1293 void vm_init_descriptor_tables(struct kvm_vm *vm)
1294 {
1295 	extern void *idt_handlers;
1296 	int i;
1297 
1298 	vm->idt = vm_vaddr_alloc_page(vm);
1299 	vm->handlers = vm_vaddr_alloc_page(vm);
1300 	/* Handlers have the same address in both address spaces.*/
1301 	for (i = 0; i < NUM_INTERRUPTS; i++)
1302 		set_idt_entry(vm, i, (unsigned long)(&idt_handlers)[i], 0,
1303 			DEFAULT_CODE_SELECTOR);
1304 }
1305 
1306 void vcpu_init_descriptor_tables(struct kvm_vm *vm, uint32_t vcpuid)
1307 {
1308 	struct kvm_sregs sregs;
1309 
1310 	vcpu_sregs_get(vm, vcpuid, &sregs);
1311 	sregs.idt.base = vm->idt;
1312 	sregs.idt.limit = NUM_INTERRUPTS * sizeof(struct idt_entry) - 1;
1313 	sregs.gdt.base = vm->gdt;
1314 	sregs.gdt.limit = getpagesize() - 1;
1315 	kvm_seg_set_kernel_data_64bit(NULL, DEFAULT_DATA_SELECTOR, &sregs.gs);
1316 	vcpu_sregs_set(vm, vcpuid, &sregs);
1317 	*(vm_vaddr_t *)addr_gva2hva(vm, (vm_vaddr_t)(&exception_handlers)) = vm->handlers;
1318 }
1319 
1320 void vm_install_exception_handler(struct kvm_vm *vm, int vector,
1321 			       void (*handler)(struct ex_regs *))
1322 {
1323 	vm_vaddr_t *handlers = (vm_vaddr_t *)addr_gva2hva(vm, vm->handlers);
1324 
1325 	handlers[vector] = (vm_vaddr_t)handler;
1326 }
1327 
1328 void assert_on_unhandled_exception(struct kvm_vm *vm, uint32_t vcpuid)
1329 {
1330 	struct ucall uc;
1331 
1332 	if (get_ucall(vm, vcpuid, &uc) == UCALL_UNHANDLED) {
1333 		uint64_t vector = uc.args[0];
1334 
1335 		TEST_FAIL("Unexpected vectored event in guest (vector:0x%lx)",
1336 			  vector);
1337 	}
1338 }
1339 
1340 bool set_cpuid(struct kvm_cpuid2 *cpuid,
1341 	       struct kvm_cpuid_entry2 *ent)
1342 {
1343 	int i;
1344 
1345 	for (i = 0; i < cpuid->nent; i++) {
1346 		struct kvm_cpuid_entry2 *cur = &cpuid->entries[i];
1347 
1348 		if (cur->function != ent->function || cur->index != ent->index)
1349 			continue;
1350 
1351 		memcpy(cur, ent, sizeof(struct kvm_cpuid_entry2));
1352 		return true;
1353 	}
1354 
1355 	return false;
1356 }
1357 
1358 uint64_t kvm_hypercall(uint64_t nr, uint64_t a0, uint64_t a1, uint64_t a2,
1359 		       uint64_t a3)
1360 {
1361 	uint64_t r;
1362 
1363 	asm volatile("vmcall"
1364 		     : "=a"(r)
1365 		     : "b"(a0), "c"(a1), "d"(a2), "S"(a3));
1366 	return r;
1367 }
1368 
1369 struct kvm_cpuid2 *kvm_get_supported_hv_cpuid(void)
1370 {
1371 	static struct kvm_cpuid2 *cpuid;
1372 	int ret;
1373 	int kvm_fd;
1374 
1375 	if (cpuid)
1376 		return cpuid;
1377 
1378 	cpuid = allocate_kvm_cpuid2();
1379 	kvm_fd = open_kvm_dev_path_or_exit();
1380 
1381 	ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1382 	TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_HV_CPUID failed %d %d\n",
1383 		    ret, errno);
1384 
1385 	close(kvm_fd);
1386 	return cpuid;
1387 }
1388 
1389 void vcpu_set_hv_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
1390 {
1391 	static struct kvm_cpuid2 *cpuid_full;
1392 	struct kvm_cpuid2 *cpuid_sys, *cpuid_hv;
1393 	int i, nent = 0;
1394 
1395 	if (!cpuid_full) {
1396 		cpuid_sys = kvm_get_supported_cpuid();
1397 		cpuid_hv = kvm_get_supported_hv_cpuid();
1398 
1399 		cpuid_full = malloc(sizeof(*cpuid_full) +
1400 				    (cpuid_sys->nent + cpuid_hv->nent) *
1401 				    sizeof(struct kvm_cpuid_entry2));
1402 		if (!cpuid_full) {
1403 			perror("malloc");
1404 			abort();
1405 		}
1406 
1407 		/* Need to skip KVM CPUID leaves 0x400000xx */
1408 		for (i = 0; i < cpuid_sys->nent; i++) {
1409 			if (cpuid_sys->entries[i].function >= 0x40000000 &&
1410 			    cpuid_sys->entries[i].function < 0x40000100)
1411 				continue;
1412 			cpuid_full->entries[nent] = cpuid_sys->entries[i];
1413 			nent++;
1414 		}
1415 
1416 		memcpy(&cpuid_full->entries[nent], cpuid_hv->entries,
1417 		       cpuid_hv->nent * sizeof(struct kvm_cpuid_entry2));
1418 		cpuid_full->nent = nent + cpuid_hv->nent;
1419 	}
1420 
1421 	vcpu_set_cpuid(vm, vcpuid, cpuid_full);
1422 }
1423 
1424 struct kvm_cpuid2 *vcpu_get_supported_hv_cpuid(struct kvm_vm *vm, uint32_t vcpuid)
1425 {
1426 	static struct kvm_cpuid2 *cpuid;
1427 
1428 	cpuid = allocate_kvm_cpuid2();
1429 
1430 	vcpu_ioctl(vm, vcpuid, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1431 
1432 	return cpuid;
1433 }
1434 
1435 #define X86EMUL_CPUID_VENDOR_AuthenticAMD_ebx 0x68747541
1436 #define X86EMUL_CPUID_VENDOR_AuthenticAMD_ecx 0x444d4163
1437 #define X86EMUL_CPUID_VENDOR_AuthenticAMD_edx 0x69746e65
1438 
1439 static inline unsigned x86_family(unsigned int eax)
1440 {
1441         unsigned int x86;
1442 
1443         x86 = (eax >> 8) & 0xf;
1444 
1445         if (x86 == 0xf)
1446                 x86 += (eax >> 20) & 0xff;
1447 
1448         return x86;
1449 }
1450 
1451 unsigned long vm_compute_max_gfn(struct kvm_vm *vm)
1452 {
1453 	const unsigned long num_ht_pages = 12 << (30 - vm->page_shift); /* 12 GiB */
1454 	unsigned long ht_gfn, max_gfn, max_pfn;
1455 	uint32_t eax, ebx, ecx, edx, max_ext_leaf;
1456 
1457 	max_gfn = (1ULL << (vm->pa_bits - vm->page_shift)) - 1;
1458 
1459 	/* Avoid reserved HyperTransport region on AMD processors.  */
1460 	eax = ecx = 0;
1461 	cpuid(&eax, &ebx, &ecx, &edx);
1462 	if (ebx != X86EMUL_CPUID_VENDOR_AuthenticAMD_ebx ||
1463 	    ecx != X86EMUL_CPUID_VENDOR_AuthenticAMD_ecx ||
1464 	    edx != X86EMUL_CPUID_VENDOR_AuthenticAMD_edx)
1465 		return max_gfn;
1466 
1467 	/* On parts with <40 physical address bits, the area is fully hidden */
1468 	if (vm->pa_bits < 40)
1469 		return max_gfn;
1470 
1471 	/* Before family 17h, the HyperTransport area is just below 1T.  */
1472 	ht_gfn = (1 << 28) - num_ht_pages;
1473 	eax = 1;
1474 	cpuid(&eax, &ebx, &ecx, &edx);
1475 	if (x86_family(eax) < 0x17)
1476 		goto done;
1477 
1478 	/*
1479 	 * Otherwise it's at the top of the physical address space, possibly
1480 	 * reduced due to SME by bits 11:6 of CPUID[0x8000001f].EBX.  Use
1481 	 * the old conservative value if MAXPHYADDR is not enumerated.
1482 	 */
1483 	eax = 0x80000000;
1484 	cpuid(&eax, &ebx, &ecx, &edx);
1485 	max_ext_leaf = eax;
1486 	if (max_ext_leaf < 0x80000008)
1487 		goto done;
1488 
1489 	eax = 0x80000008;
1490 	cpuid(&eax, &ebx, &ecx, &edx);
1491 	max_pfn = (1ULL << ((eax & 0xff) - vm->page_shift)) - 1;
1492 	if (max_ext_leaf >= 0x8000001f) {
1493 		eax = 0x8000001f;
1494 		cpuid(&eax, &ebx, &ecx, &edx);
1495 		max_pfn >>= (ebx >> 6) & 0x3f;
1496 	}
1497 
1498 	ht_gfn = max_pfn - num_ht_pages;
1499 done:
1500 	return min(max_gfn, ht_gfn - 1);
1501 }
1502