kvm_util.c 49.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7
/*
 * tools/testing/selftests/kvm/lib/kvm_util.c
 *
 * Copyright (C) 2018, Google LLC.
 */

8
#define _GNU_SOURCE /* for program_invocation_name */
9 10
#include "test_util.h"
#include "kvm_util.h"
11
#include "processor.h"
12 13 14 15 16

#include <assert.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
17
#include <unistd.h>
18
#include <linux/kernel.h>
19

20
#define KVM_UTIL_MIN_PFN	2
21

22 23
static int vcpu_mmap_sz(void);

24 25 26 27 28
int open_path_or_exit(const char *path, int flags)
{
	int fd;

	fd = open(path, flags);
29
	__TEST_REQUIRE(fd >= 0, "%s not available (errno: %d)", path, errno);
30 31 32 33

	return fd;
}

34 35 36 37 38 39 40 41 42 43 44
/*
 * Open KVM_DEV_PATH if available, otherwise exit the entire program.
 *
 * Input Args:
 *   flags - The flags to pass when opening KVM_DEV_PATH.
 *
 * Return:
 *   The opened file descriptor of /dev/kvm.
 */
static int _open_kvm_dev_path_or_exit(int flags)
{
45
	return open_path_or_exit(KVM_DEV_PATH, flags);
46 47 48 49 50 51 52
}

int open_kvm_dev_path_or_exit(void)
{
	return _open_kvm_dev_path_or_exit(O_RDONLY);
}

A
Andrew Jones 已提交
53 54
/*
 * Capability
55 56 57 58 59 60 61 62 63 64 65 66 67 68
 *
 * Input Args:
 *   cap - Capability
 *
 * Output Args: None
 *
 * Return:
 *   On success, the Value corresponding to the capability (KVM_CAP_*)
 *   specified by the value of cap.  On failure a TEST_ASSERT failure
 *   is produced.
 *
 * Looks up and returns the value corresponding to the capability
 * (KVM_CAP_*) given by cap.
 */
69
unsigned int kvm_check_cap(long cap)
70 71 72 73
{
	int ret;
	int kvm_fd;

74
	kvm_fd = open_kvm_dev_path_or_exit();
75
	ret = __kvm_ioctl(kvm_fd, KVM_CHECK_EXTENSION, (void *)cap);
76
	TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_CHECK_EXTENSION, ret));
77 78 79

	close(kvm_fd);

80
	return (unsigned int)ret;
81 82
}

83 84
void vm_enable_dirty_ring(struct kvm_vm *vm, uint32_t ring_size)
{
85
	vm_enable_cap(vm, KVM_CAP_DIRTY_LOG_RING, ring_size);
86 87 88
	vm->dirty_ring_size = ring_size;
}

89
static void vm_open(struct kvm_vm *vm)
90
{
91
	vm->kvm_fd = _open_kvm_dev_path_or_exit(O_RDWR);
92

93
	TEST_REQUIRE(kvm_has_cap(KVM_CAP_IMMEDIATE_EXIT));
94

95
	vm->fd = __kvm_ioctl(vm->kvm_fd, KVM_CREATE_VM, (void *)vm->type);
96
	TEST_ASSERT(vm->fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_VM, vm->fd));
97 98
}

99 100 101 102 103 104
const char *vm_guest_mode_string(uint32_t i)
{
	static const char * const strings[] = {
		[VM_MODE_P52V48_4K]	= "PA-bits:52,  VA-bits:48,  4K pages",
		[VM_MODE_P52V48_64K]	= "PA-bits:52,  VA-bits:48, 64K pages",
		[VM_MODE_P48V48_4K]	= "PA-bits:48,  VA-bits:48,  4K pages",
105
		[VM_MODE_P48V48_16K]	= "PA-bits:48,  VA-bits:48, 16K pages",
106 107
		[VM_MODE_P48V48_64K]	= "PA-bits:48,  VA-bits:48, 64K pages",
		[VM_MODE_P40V48_4K]	= "PA-bits:40,  VA-bits:48,  4K pages",
108
		[VM_MODE_P40V48_16K]	= "PA-bits:40,  VA-bits:48, 16K pages",
109 110
		[VM_MODE_P40V48_64K]	= "PA-bits:40,  VA-bits:48, 64K pages",
		[VM_MODE_PXXV48_4K]	= "PA-bits:ANY, VA-bits:48,  4K pages",
111
		[VM_MODE_P47V64_4K]	= "PA-bits:47,  VA-bits:64,  4K pages",
112
		[VM_MODE_P44V64_4K]	= "PA-bits:44,  VA-bits:64,  4K pages",
113
		[VM_MODE_P36V48_4K]	= "PA-bits:36,  VA-bits:48,  4K pages",
114
		[VM_MODE_P36V48_16K]	= "PA-bits:36,  VA-bits:48, 16K pages",
115
		[VM_MODE_P36V48_64K]	= "PA-bits:36,  VA-bits:48, 64K pages",
116
		[VM_MODE_P36V47_16K]	= "PA-bits:36,  VA-bits:47, 16K pages",
117 118 119 120 121 122 123 124
	};
	_Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES,
		       "Missing new mode strings?");

	TEST_ASSERT(i < NUM_VM_MODES, "Guest mode ID %d too big", i);

	return strings[i];
}
125

126
const struct vm_guest_mode_params vm_guest_mode_params[] = {
127 128 129
	[VM_MODE_P52V48_4K]	= { 52, 48,  0x1000, 12 },
	[VM_MODE_P52V48_64K]	= { 52, 48, 0x10000, 16 },
	[VM_MODE_P48V48_4K]	= { 48, 48,  0x1000, 12 },
130
	[VM_MODE_P48V48_16K]	= { 48, 48,  0x4000, 14 },
131 132
	[VM_MODE_P48V48_64K]	= { 48, 48, 0x10000, 16 },
	[VM_MODE_P40V48_4K]	= { 40, 48,  0x1000, 12 },
133
	[VM_MODE_P40V48_16K]	= { 40, 48,  0x4000, 14 },
134 135 136 137
	[VM_MODE_P40V48_64K]	= { 40, 48, 0x10000, 16 },
	[VM_MODE_PXXV48_4K]	= {  0,  0,  0x1000, 12 },
	[VM_MODE_P47V64_4K]	= { 47, 64,  0x1000, 12 },
	[VM_MODE_P44V64_4K]	= { 44, 64,  0x1000, 12 },
138
	[VM_MODE_P36V48_4K]	= { 36, 48,  0x1000, 12 },
139
	[VM_MODE_P36V48_16K]	= { 36, 48,  0x4000, 14 },
140
	[VM_MODE_P36V48_64K]	= { 36, 48, 0x10000, 16 },
141
	[VM_MODE_P36V47_16K]	= { 36, 47,  0x4000, 14 },
142 143 144 145
};
_Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
	       "Missing new mode params?");

146
struct kvm_vm *____vm_create(enum vm_guest_mode mode, uint64_t nr_pages)
147 148 149
{
	struct kvm_vm *vm;

150
	pr_debug("%s: mode='%s' pages='%ld'\n", __func__,
151
		 vm_guest_mode_string(mode), nr_pages);
152

153
	vm = calloc(1, sizeof(*vm));
154
	TEST_ASSERT(vm != NULL, "Insufficient Memory");
155

156
	INIT_LIST_HEAD(&vm->vcpus);
157 158 159
	vm->regions.gpa_tree = RB_ROOT;
	vm->regions.hva_tree = RB_ROOT;
	hash_init(vm->regions.slot_hash);
160

161
	vm->mode = mode;
162
	vm->type = 0;
163

164 165 166 167 168
	vm->pa_bits = vm_guest_mode_params[mode].pa_bits;
	vm->va_bits = vm_guest_mode_params[mode].va_bits;
	vm->page_size = vm_guest_mode_params[mode].page_size;
	vm->page_shift = vm_guest_mode_params[mode].page_shift;

169 170
	/* Setup mode specific traits. */
	switch (vm->mode) {
171
	case VM_MODE_P52V48_4K:
172
		vm->pgtable_levels = 4;
173
		break;
174 175
	case VM_MODE_P52V48_64K:
		vm->pgtable_levels = 3;
176 177 178 179 180 181
		break;
	case VM_MODE_P48V48_4K:
		vm->pgtable_levels = 4;
		break;
	case VM_MODE_P48V48_64K:
		vm->pgtable_levels = 3;
182
		break;
183
	case VM_MODE_P40V48_4K:
184
	case VM_MODE_P36V48_4K:
185 186 187
		vm->pgtable_levels = 4;
		break;
	case VM_MODE_P40V48_64K:
188
	case VM_MODE_P36V48_64K:
189 190
		vm->pgtable_levels = 3;
		break;
191 192 193 194 195 196
	case VM_MODE_P48V48_16K:
	case VM_MODE_P40V48_16K:
	case VM_MODE_P36V48_16K:
		vm->pgtable_levels = 4;
		break;
	case VM_MODE_P36V47_16K:
197 198
		vm->pgtable_levels = 3;
		break;
199 200 201
	case VM_MODE_PXXV48_4K:
#ifdef __x86_64__
		kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
202 203 204 205 206 207 208 209
		/*
		 * Ignore KVM support for 5-level paging (vm->va_bits == 57),
		 * it doesn't take effect unless a CR4.LA57 is set, which it
		 * isn't for this VM_MODE.
		 */
		TEST_ASSERT(vm->va_bits == 48 || vm->va_bits == 57,
			    "Linear address width (%d bits) not supported",
			    vm->va_bits);
210 211
		pr_debug("Guest physical address width detected: %d\n",
			 vm->pa_bits);
212
		vm->pgtable_levels = 4;
213
		vm->va_bits = 48;
214
#else
215
		TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms");
216 217
#endif
		break;
218 219 220
	case VM_MODE_P47V64_4K:
		vm->pgtable_levels = 5;
		break;
221 222 223
	case VM_MODE_P44V64_4K:
		vm->pgtable_levels = 5;
		break;
224
	default:
225
		TEST_FAIL("Unknown guest mode, mode: 0x%x", mode);
226 227
	}

228 229 230 231 232
#ifdef __aarch64__
	if (vm->pa_bits != 40)
		vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits);
#endif

233
	vm_open(vm);
234

235 236 237 238 239 240 241 242 243
	/* Limit to VA-bit canonical virtual addresses. */
	vm->vpages_valid = sparsebit_alloc();
	sparsebit_set_num(vm->vpages_valid,
		0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
	sparsebit_set_num(vm->vpages_valid,
		(~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
		(1ULL << (vm->va_bits - 1)) >> vm->page_shift);

	/* Limit physical addresses to PA-bits. */
244
	vm->max_gfn = vm_compute_max_gfn(vm);
245

246 247
	/* Allocate and setup memory for guest. */
	vm->vpages_mapped = sparsebit_alloc();
248
	if (nr_pages != 0)
249
		vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
250
					    0, 0, nr_pages, 0);
251 252 253 254

	return vm;
}

255 256 257
static uint64_t vm_nr_pages_required(enum vm_guest_mode mode,
				     uint32_t nr_runnable_vcpus,
				     uint64_t extra_mem_pages)
258
{
259 260 261 262 263 264 265 266 267
	uint64_t nr_pages;

	TEST_ASSERT(nr_runnable_vcpus,
		    "Use vm_create_barebones() for VMs that _never_ have vCPUs\n");

	TEST_ASSERT(nr_runnable_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS),
		    "nr_vcpus = %d too large for host, max-vcpus = %d",
		    nr_runnable_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS));

268 269 270 271 272 273 274
	/*
	 * Arbitrarily allocate 512 pages (2mb when page size is 4kb) for the
	 * test code and other per-VM assets that will be loaded into memslot0.
	 */
	nr_pages = 512;

	/* Account for the per-vCPU stacks on behalf of the test. */
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
	nr_pages += nr_runnable_vcpus * DEFAULT_STACK_PGS;

	/*
	 * Account for the number of pages needed for the page tables.  The
	 * maximum page table size for a memory region will be when the
	 * smallest page size is used. Considering each page contains x page
	 * table descriptors, the total extra size for page tables (for extra
	 * N pages) will be: N/x+N/x^2+N/x^3+... which is definitely smaller
	 * than N/x*2.
	 */
	nr_pages += (nr_pages + extra_mem_pages) / PTES_PER_MIN_PAGE * 2;

	TEST_ASSERT(nr_runnable_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS),
		    "Host doesn't support %d vCPUs, max-vcpus = %d",
		    nr_runnable_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS));
290

291 292 293 294 295 296 297 298 299
	return vm_adjust_num_guest_pages(mode, nr_pages);
}

struct kvm_vm *__vm_create(enum vm_guest_mode mode, uint32_t nr_runnable_vcpus,
			   uint64_t nr_extra_pages)
{
	uint64_t nr_pages = vm_nr_pages_required(mode, nr_runnable_vcpus,
						 nr_extra_pages);
	struct kvm_vm *vm;
300

301
	vm = ____vm_create(mode, nr_pages);
302 303 304 305 306 307 308 309 310

	kvm_vm_elf_load(vm, program_invocation_name);

#ifdef __x86_64__
	vm_create_irqchip(vm);
#endif
	return vm;
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
/*
 * VM Create with customized parameters
 *
 * Input Args:
 *   mode - VM Mode (e.g. VM_MODE_P52V48_4K)
 *   nr_vcpus - VCPU count
 *   extra_mem_pages - Non-slot0 physical memory total size
 *   guest_code - Guest entry point
 *   vcpuids - VCPU IDs
 *
 * Output Args: None
 *
 * Return:
 *   Pointer to opaque structure that describes the created VM.
 *
326
 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
327 328 329
 * extra_mem_pages is only used to calculate the maximum page table size,
 * no real memory allocation for non-slot0 memory in this function.
 */
330
struct kvm_vm *__vm_create_with_vcpus(enum vm_guest_mode mode, uint32_t nr_vcpus,
331
				      uint64_t extra_mem_pages,
332
				      void *guest_code, struct kvm_vcpu *vcpus[])
333
{
334 335 336
	struct kvm_vm *vm;
	int i;

337 338
	TEST_ASSERT(!nr_vcpus || vcpus, "Must provide vCPU array");

339
	vm = __vm_create(mode, nr_vcpus, extra_mem_pages);
340

341 342
	for (i = 0; i < nr_vcpus; ++i)
		vcpus[i] = vm_vcpu_add(vm, i, guest_code);
343 344 345 346

	return vm;
}

347
struct kvm_vm *__vm_create_with_one_vcpu(struct kvm_vcpu **vcpu,
348 349 350
					 uint64_t extra_mem_pages,
					 void *guest_code)
{
351 352 353
	struct kvm_vcpu *vcpus[1];
	struct kvm_vm *vm;

354
	vm = __vm_create_with_vcpus(VM_MODE_DEFAULT, 1, extra_mem_pages,
355
				    guest_code, vcpus);
356

357
	*vcpu = vcpus[0];
358 359 360
	return vm;
}

A
Andrew Jones 已提交
361 362
/*
 * VM Restart
363 364 365 366 367 368 369 370 371 372
 *
 * Input Args:
 *   vm - VM that has been released before
 *
 * Output Args: None
 *
 * Reopens the file descriptors associated to the VM and reinstates the
 * global state, such as the irqchip and the memory regions that are mapped
 * into the guest.
 */
373
void kvm_vm_restart(struct kvm_vm *vmp)
374
{
375
	int ctr;
376 377
	struct userspace_mem_region *region;

378
	vm_open(vmp);
379 380 381
	if (vmp->has_irqchip)
		vm_create_irqchip(vmp);

382
	hash_for_each(vmp->regions.slot_hash, ctr, region, slot_node) {
383 384 385 386
		int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
		TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
			    "  rc: %i errno: %i\n"
			    "  slot: %u flags: 0x%x\n"
387
			    "  guest_phys_addr: 0x%llx size: 0x%llx",
A
Andrew Jones 已提交
388 389
			    ret, errno, region->region.slot,
			    region->region.flags,
390 391 392 393 394
			    region->region.guest_phys_addr,
			    region->region.memory_size);
	}
}

395
struct kvm_vcpu *vm_recreate_with_one_vcpu(struct kvm_vm *vm)
396 397 398
{
	kvm_vm_restart(vm);

399
	return __vm_vcpu_add(vm, 0);
400 401
}

A
Andrew Jones 已提交
402 403
/*
 * Userspace Memory Region Find
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
 *
 * Input Args:
 *   vm - Virtual Machine
 *   start - Starting VM physical address
 *   end - Ending VM physical address, inclusive.
 *
 * Output Args: None
 *
 * Return:
 *   Pointer to overlapping region, NULL if no such region.
 *
 * Searches for a region with any physical memory that overlaps with
 * any portion of the guest physical addresses from start to end
 * inclusive.  If multiple overlapping regions exist, a pointer to any
 * of the regions is returned.  Null is returned only when no overlapping
 * region exists.
 */
A
Andrew Jones 已提交
421 422
static struct userspace_mem_region *
userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
423
{
424
	struct rb_node *node;
425

426 427 428
	for (node = vm->regions.gpa_tree.rb_node; node; ) {
		struct userspace_mem_region *region =
			container_of(node, struct userspace_mem_region, gpa_node);
429 430 431 432 433
		uint64_t existing_start = region->region.guest_phys_addr;
		uint64_t existing_end = region->region.guest_phys_addr
			+ region->region.memory_size - 1;
		if (start <= existing_end && end >= existing_start)
			return region;
434 435 436 437 438

		if (start < existing_start)
			node = node->rb_left;
		else
			node = node->rb_right;
439 440 441 442 443
	}

	return NULL;
}

A
Andrew Jones 已提交
444 445
/*
 * KVM Userspace Memory Region Find
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
 *
 * Input Args:
 *   vm - Virtual Machine
 *   start - Starting VM physical address
 *   end - Ending VM physical address, inclusive.
 *
 * Output Args: None
 *
 * Return:
 *   Pointer to overlapping region, NULL if no such region.
 *
 * Public interface to userspace_mem_region_find. Allows tests to look up
 * the memslot datastructure for a given range of guest physical memory.
 */
struct kvm_userspace_memory_region *
kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
				 uint64_t end)
{
	struct userspace_mem_region *region;

	region = userspace_mem_region_find(vm, start, end);
	if (!region)
		return NULL;

	return &region->region;
}

A
Andrew Jones 已提交
473 474
/*
 * VM VCPU Remove
475 476
 *
 * Input Args:
477
 *   vcpu - VCPU to remove
478 479 480 481 482
 *
 * Output Args: None
 *
 * Return: None, TEST_ASSERT failures for all error conditions
 *
483
 * Removes a vCPU from a VM and frees its resources.
484
 */
485
static void vm_vcpu_rm(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
486
{
487
	int ret;
488

489 490
	if (vcpu->dirty_gfns) {
		ret = munmap(vcpu->dirty_gfns, vm->dirty_ring_size);
491
		TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret));
492 493 494
		vcpu->dirty_gfns = NULL;
	}

495
	ret = munmap(vcpu->run, vcpu_mmap_sz());
496 497
	TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret));

498
	ret = close(vcpu->fd);
499
	TEST_ASSERT(!ret,  __KVM_SYSCALL_ERROR("close()", ret));
500

501
	list_del(&vcpu->list);
502 503 504
	free(vcpu);
}

505 506
void kvm_vm_release(struct kvm_vm *vmp)
{
507
	struct kvm_vcpu *vcpu, *tmp;
508 509
	int ret;

510
	list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list)
511
		vm_vcpu_rm(vmp, vcpu);
512 513

	ret = close(vmp->fd);
514
	TEST_ASSERT(!ret,  __KVM_SYSCALL_ERROR("close()", ret));
515

516
	ret = close(vmp->kvm_fd);
517
	TEST_ASSERT(!ret,  __KVM_SYSCALL_ERROR("close()", ret));
518
}
519

520
static void __vm_mem_region_delete(struct kvm_vm *vm,
521 522
				   struct userspace_mem_region *region,
				   bool unlink)
523 524 525
{
	int ret;

526 527 528 529 530
	if (unlink) {
		rb_erase(&region->gpa_node, &vm->regions.gpa_tree);
		rb_erase(&region->hva_node, &vm->regions.hva_tree);
		hash_del(&region->slot_node);
	}
531 532

	region->region.memory_size = 0;
533
	vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION, &region->region);
534 535 536

	sparsebit_free(&region->unused_phy_pages);
	ret = munmap(region->mmap_start, region->mmap_size);
537
	TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret));
538 539 540 541

	free(region);
}

A
Andrew Jones 已提交
542 543
/*
 * Destroys and frees the VM pointed to by vmp.
544 545 546
 */
void kvm_vm_free(struct kvm_vm *vmp)
{
547 548 549
	int ctr;
	struct hlist_node *node;
	struct userspace_mem_region *region;
550 551 552 553 554

	if (vmp == NULL)
		return;

	/* Free userspace_mem_regions. */
555 556
	hash_for_each_safe(vmp->regions.slot_hash, ctr, node, region, slot_node)
		__vm_mem_region_delete(vmp, region, false);
557 558 559 560 561

	/* Free sparsebit arrays. */
	sparsebit_free(&vmp->vpages_valid);
	sparsebit_free(&vmp->vpages_mapped);

562
	kvm_vm_release(vmp);
563 564 565 566 567

	/* Free the structure describing the VM. */
	free(vmp);
}

568 569 570 571 572 573 574 575 576
int kvm_memfd_alloc(size_t size, bool hugepages)
{
	int memfd_flags = MFD_CLOEXEC;
	int fd, r;

	if (hugepages)
		memfd_flags |= MFD_HUGETLB;

	fd = memfd_create("kvm_selftest", memfd_flags);
577
	TEST_ASSERT(fd != -1, __KVM_SYSCALL_ERROR("memfd_create()", fd));
578 579

	r = ftruncate(fd, size);
580
	TEST_ASSERT(!r, __KVM_SYSCALL_ERROR("ftruncate()", r));
581 582

	r = fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, size);
583
	TEST_ASSERT(!r, __KVM_SYSCALL_ERROR("fallocate()", r));
584 585 586 587

	return fd;
}

A
Andrew Jones 已提交
588 589
/*
 * Memory Compare, host virtual to guest virtual
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
 *
 * Input Args:
 *   hva - Starting host virtual address
 *   vm - Virtual Machine
 *   gva - Starting guest virtual address
 *   len - number of bytes to compare
 *
 * Output Args: None
 *
 * Input/Output Args: None
 *
 * Return:
 *   Returns 0 if the bytes starting at hva for a length of len
 *   are equal the guest virtual bytes starting at gva.  Returns
 *   a value < 0, if bytes at hva are less than those at gva.
 *   Otherwise a value > 0 is returned.
 *
 * Compares the bytes starting at the host virtual address hva, for
 * a length of len, to the guest bytes starting at the guest virtual
 * address given by gva.
 */
A
Andrew Jones 已提交
611
int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
612 613 614
{
	size_t amt;

A
Andrew Jones 已提交
615 616
	/*
	 * Compare a batch of bytes until either a match is found
617 618 619 620 621
	 * or all the bytes have been compared.
	 */
	for (uintptr_t offset = 0; offset < len; offset += amt) {
		uintptr_t ptr1 = (uintptr_t)hva + offset;

A
Andrew Jones 已提交
622 623
		/*
		 * Determine host address for guest virtual address
624 625 626 627
		 * at offset.
		 */
		uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);

A
Andrew Jones 已提交
628 629
		/*
		 * Determine amount to compare on this pass.
630 631 632 633 634 635 636 637 638 639 640
		 * Don't allow the comparsion to cross a page boundary.
		 */
		amt = len - offset;
		if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
			amt = vm->page_size - (ptr1 % vm->page_size);
		if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
			amt = vm->page_size - (ptr2 % vm->page_size);

		assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
		assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));

A
Andrew Jones 已提交
641 642
		/*
		 * Perform the comparison.  If there is a difference
643 644 645 646 647 648 649 650
		 * return that result to the caller, otherwise need
		 * to continue on looking for a mismatch.
		 */
		int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
		if (ret != 0)
			return ret;
	}

A
Andrew Jones 已提交
651 652
	/*
	 * No mismatch found.  Let the caller know the two memory
653 654 655 656 657
	 * areas are equal.
	 */
	return 0;
}

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
static void vm_userspace_mem_region_gpa_insert(struct rb_root *gpa_tree,
					       struct userspace_mem_region *region)
{
	struct rb_node **cur, *parent;

	for (cur = &gpa_tree->rb_node, parent = NULL; *cur; ) {
		struct userspace_mem_region *cregion;

		cregion = container_of(*cur, typeof(*cregion), gpa_node);
		parent = *cur;
		if (region->region.guest_phys_addr <
		    cregion->region.guest_phys_addr)
			cur = &(*cur)->rb_left;
		else {
			TEST_ASSERT(region->region.guest_phys_addr !=
				    cregion->region.guest_phys_addr,
				    "Duplicate GPA in region tree");

			cur = &(*cur)->rb_right;
		}
	}

	rb_link_node(&region->gpa_node, parent, cur);
	rb_insert_color(&region->gpa_node, gpa_tree);
}

static void vm_userspace_mem_region_hva_insert(struct rb_root *hva_tree,
					       struct userspace_mem_region *region)
{
	struct rb_node **cur, *parent;

	for (cur = &hva_tree->rb_node, parent = NULL; *cur; ) {
		struct userspace_mem_region *cregion;

		cregion = container_of(*cur, typeof(*cregion), hva_node);
		parent = *cur;
		if (region->host_mem < cregion->host_mem)
			cur = &(*cur)->rb_left;
		else {
			TEST_ASSERT(region->host_mem !=
				    cregion->host_mem,
				    "Duplicate HVA in region tree");

			cur = &(*cur)->rb_right;
		}
	}

	rb_link_node(&region->hva_node, parent, cur);
	rb_insert_color(&region->hva_node, hva_tree);
}

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

int __vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
				uint64_t gpa, uint64_t size, void *hva)
{
	struct kvm_userspace_memory_region region = {
		.slot = slot,
		.flags = flags,
		.guest_phys_addr = gpa,
		.memory_size = size,
		.userspace_addr = (uintptr_t)hva,
	};

	return ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region);
}

void vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
			       uint64_t gpa, uint64_t size, void *hva)
{
	int ret = __vm_set_user_memory_region(vm, slot, flags, gpa, size, hva);

	TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed, errno = %d (%s)",
		    errno, strerror(errno));
}

A
Andrew Jones 已提交
733 734
/*
 * VM Userspace Memory Region Add
735 736 737
 *
 * Input Args:
 *   vm - Virtual Machine
738 739
 *   src_type - Storage source for this region.
 *              NULL to use anonymous memory.
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
 *   guest_paddr - Starting guest physical address
 *   slot - KVM region slot
 *   npages - Number of physical pages
 *   flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
 *
 * Output Args: None
 *
 * Return: None
 *
 * Allocates a memory area of the number of pages specified by npages
 * and maps it to the VM specified by vm, at a starting physical address
 * given by guest_paddr.  The region is created with a KVM region slot
 * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM.  The
 * region is created with the flags given by flags.
 */
void vm_userspace_mem_region_add(struct kvm_vm *vm,
	enum vm_mem_backing_src_type src_type,
	uint64_t guest_paddr, uint32_t slot, uint64_t npages,
	uint32_t flags)
{
	int ret;
	struct userspace_mem_region *region;
762
	size_t backing_src_pagesz = get_backing_src_pagesz(src_type);
763
	size_t alignment;
764

765 766 767 768
	TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages,
		"Number of guest pages is not compatible with the host. "
		"Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages));

769 770 771 772 773 774 775 776 777 778 779
	TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
		"address not on a page boundary.\n"
		"  guest_paddr: 0x%lx vm->page_size: 0x%x",
		guest_paddr, vm->page_size);
	TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
		<= vm->max_gfn, "Physical range beyond maximum "
		"supported physical address,\n"
		"  guest_paddr: 0x%lx npages: 0x%lx\n"
		"  vm->max_gfn: 0x%lx vm->page_size: 0x%x",
		guest_paddr, npages, vm->max_gfn, vm->page_size);

A
Andrew Jones 已提交
780 781
	/*
	 * Confirm a mem region with an overlapping address doesn't
782 783 784
	 * already exist.
	 */
	region = (struct userspace_mem_region *) userspace_mem_region_find(
785
		vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1);
786
	if (region != NULL)
787
		TEST_FAIL("overlapping userspace_mem_region already "
788 789 790 791 792 793 794 795 796
			"exists\n"
			"  requested guest_paddr: 0x%lx npages: 0x%lx "
			"page_size: 0x%x\n"
			"  existing guest_paddr: 0x%lx size: 0x%lx",
			guest_paddr, npages, vm->page_size,
			(uint64_t) region->region.guest_phys_addr,
			(uint64_t) region->region.memory_size);

	/* Confirm no region with the requested slot already exists. */
797 798
	hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
			       slot) {
799 800 801
		if (region->region.slot != slot)
			continue;

802
		TEST_FAIL("A mem region with the requested slot "
803
			"already exists.\n"
804 805 806 807 808 809
			"  requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
			"  existing slot: %u paddr: 0x%lx size: 0x%lx",
			slot, guest_paddr, npages,
			region->region.slot,
			(uint64_t) region->region.guest_phys_addr,
			(uint64_t) region->region.memory_size);
810
	}
811 812 813 814 815 816

	/* Allocate and initialize new mem region structure. */
	region = calloc(1, sizeof(*region));
	TEST_ASSERT(region != NULL, "Insufficient Memory");
	region->mmap_size = npages * vm->page_size;

817 818 819 820 821 822 823
#ifdef __s390x__
	/* On s390x, the host address must be aligned to 1M (due to PGSTEs) */
	alignment = 0x100000;
#else
	alignment = 1;
#endif

824 825 826 827 828 829
	/*
	 * When using THP mmap is not guaranteed to returned a hugepage aligned
	 * address so we have to pad the mmap. Padding is not needed for HugeTLB
	 * because mmap will always return an address aligned to the HugeTLB
	 * page size.
	 */
830
	if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
831
		alignment = max(backing_src_pagesz, alignment);
832

833 834
	ASSERT_EQ(guest_paddr, align_up(guest_paddr, backing_src_pagesz));

835 836 837 838
	/* Add enough memory to align up if necessary */
	if (alignment > 1)
		region->mmap_size += alignment;

839
	region->fd = -1;
840 841 842
	if (backing_src_is_shared(src_type))
		region->fd = kvm_memfd_alloc(region->mmap_size,
					     src_type == VM_MEM_SRC_SHARED_HUGETLB);
843

844 845
	region->mmap_start = mmap(NULL, region->mmap_size,
				  PROT_READ | PROT_WRITE,
846
				  vm_mem_backing_src_alias(src_type)->flag,
847
				  region->fd, 0);
848
	TEST_ASSERT(region->mmap_start != MAP_FAILED,
849
		    __KVM_SYSCALL_ERROR("mmap()", (int)(unsigned long)MAP_FAILED));
850

851 852 853 854 855
	TEST_ASSERT(!is_backing_src_hugetlb(src_type) ||
		    region->mmap_start == align_ptr_up(region->mmap_start, backing_src_pagesz),
		    "mmap_start %p is not aligned to HugeTLB page size 0x%lx",
		    region->mmap_start, backing_src_pagesz);

856
	/* Align host address */
857
	region->host_mem = align_ptr_up(region->mmap_start, alignment);
858 859

	/* As needed perform madvise */
860 861 862 863 864 865 866
	if ((src_type == VM_MEM_SRC_ANONYMOUS ||
	     src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) {
		ret = madvise(region->host_mem, npages * vm->page_size,
			      src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
		TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s",
			    region->host_mem, npages * vm->page_size,
			    vm_mem_backing_src_alias(src_type)->name);
867 868 869 870 871 872 873 874 875 876
	}

	region->unused_phy_pages = sparsebit_alloc();
	sparsebit_set_num(region->unused_phy_pages,
		guest_paddr >> vm->page_shift, npages);
	region->region.slot = slot;
	region->region.flags = flags;
	region->region.guest_phys_addr = guest_paddr;
	region->region.memory_size = npages * vm->page_size;
	region->region.userspace_addr = (uintptr_t) region->host_mem;
877
	ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION, &region->region);
878 879 880 881 882 883 884
	TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
		"  rc: %i errno: %i\n"
		"  slot: %u flags: 0x%x\n"
		"  guest_phys_addr: 0x%lx size: 0x%lx",
		ret, errno, slot, flags,
		guest_paddr, (uint64_t) region->region.memory_size);

885 886 887 888
	/* Add to quick lookup data structures */
	vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region);
	vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region);
	hash_add(vm->regions.slot_hash, &region->slot_node, slot);
889 890 891 892 893 894 895 896

	/* If shared memory, create an alias. */
	if (region->fd >= 0) {
		region->mmap_alias = mmap(NULL, region->mmap_size,
					  PROT_READ | PROT_WRITE,
					  vm_mem_backing_src_alias(src_type)->flag,
					  region->fd, 0);
		TEST_ASSERT(region->mmap_alias != MAP_FAILED,
897
			    __KVM_SYSCALL_ERROR("mmap()",  (int)(unsigned long)MAP_FAILED));
898 899

		/* Align host alias address */
900
		region->host_alias = align_ptr_up(region->mmap_alias, alignment);
901
	}
902 903
}

A
Andrew Jones 已提交
904 905
/*
 * Memslot to region
906 907 908 909 910 911 912 913 914 915 916 917 918
 *
 * Input Args:
 *   vm - Virtual Machine
 *   memslot - KVM memory slot ID
 *
 * Output Args: None
 *
 * Return:
 *   Pointer to memory region structure that describe memory region
 *   using kvm memory slot ID given by memslot.  TEST_ASSERT failure
 *   on error (e.g. currently no memory region using memslot as a KVM
 *   memory slot ID).
 */
919
struct userspace_mem_region *
A
Andrew Jones 已提交
920
memslot2region(struct kvm_vm *vm, uint32_t memslot)
921 922 923
{
	struct userspace_mem_region *region;

924 925
	hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
			       memslot)
926
		if (region->region.slot == memslot)
927
			return region;
928

929 930 931 932 933 934
	fprintf(stderr, "No mem region with the requested slot found,\n"
		"  requested slot: %u\n", memslot);
	fputs("---- vm dump ----\n", stderr);
	vm_dump(stderr, vm, 2);
	TEST_FAIL("Mem region not found");
	return NULL;
935 936
}

A
Andrew Jones 已提交
937 938
/*
 * VM Memory Region Flags Set
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
 *
 * Input Args:
 *   vm - Virtual Machine
 *   flags - Starting guest physical address
 *
 * Output Args: None
 *
 * Return: None
 *
 * Sets the flags of the memory region specified by the value of slot,
 * to the values given by flags.
 */
void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
{
	int ret;
	struct userspace_mem_region *region;

	region = memslot2region(vm, slot);

	region->region.flags = flags;

960
	ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION, &region->region);
961 962 963 964 965 966

	TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
		"  rc: %i errno: %i slot: %u flags: 0x%x",
		ret, errno, slot, flags);
}

967 968 969 970 971 972
/*
 * VM Memory Region Move
 *
 * Input Args:
 *   vm - Virtual Machine
 *   slot - Slot of the memory region to move
973
 *   new_gpa - Starting guest physical address
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
 *
 * Output Args: None
 *
 * Return: None
 *
 * Change the gpa of a memory region.
 */
void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
{
	struct userspace_mem_region *region;
	int ret;

	region = memslot2region(vm, slot);

	region->region.guest_phys_addr = new_gpa;

990
	ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION, &region->region);
991 992

	TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed\n"
993
		    "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
994 995 996
		    ret, errno, slot, new_gpa);
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
/*
 * VM Memory Region Delete
 *
 * Input Args:
 *   vm - Virtual Machine
 *   slot - Slot of the memory region to delete
 *
 * Output Args: None
 *
 * Return: None
 *
 * Delete a memory region.
 */
void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
{
1012
	__vm_mem_region_delete(vm, memslot2region(vm, slot), true);
1013 1014
}

1015
/* Returns the size of a vCPU's kvm_run structure. */
1016 1017 1018 1019
static int vcpu_mmap_sz(void)
{
	int dev_fd, ret;

1020
	dev_fd = open_kvm_dev_path_or_exit();
1021 1022 1023

	ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
	TEST_ASSERT(ret >= sizeof(struct kvm_run),
1024
		    KVM_IOCTL_ERROR(KVM_GET_VCPU_MMAP_SIZE, ret));
1025 1026 1027 1028 1029 1030

	close(dev_fd);

	return ret;
}

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
static bool vcpu_exists(struct kvm_vm *vm, uint32_t vcpu_id)
{
	struct kvm_vcpu *vcpu;

	list_for_each_entry(vcpu, &vm->vcpus, list) {
		if (vcpu->id == vcpu_id)
			return true;
	}

	return false;
}

A
Andrew Jones 已提交
1043
/*
1044 1045
 * Adds a virtual CPU to the VM specified by vm with the ID given by vcpu_id.
 * No additional vCPU setup is done.  Returns the vCPU.
1046
 */
1047
struct kvm_vcpu *__vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpu_id)
1048
{
1049
	struct kvm_vcpu *vcpu;
1050 1051

	/* Confirm a vcpu with the specified id doesn't already exist. */
1052
	TEST_ASSERT(!vcpu_exists(vm, vcpu_id), "vCPU%d already exists\n", vcpu_id);
1053 1054 1055 1056

	/* Allocate and initialize new vcpu structure. */
	vcpu = calloc(1, sizeof(*vcpu));
	TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
1057

1058
	vcpu->vm = vm;
1059 1060
	vcpu->id = vcpu_id;
	vcpu->fd = __vm_ioctl(vm, KVM_CREATE_VCPU, (void *)(unsigned long)vcpu_id);
1061
	TEST_ASSERT(vcpu->fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_VCPU, vcpu->fd));
1062

1063
	TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->run), "vcpu mmap size "
1064
		"smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
1065 1066
		vcpu_mmap_sz(), sizeof(*vcpu->run));
	vcpu->run = (struct kvm_run *) mmap(NULL, vcpu_mmap_sz(),
1067
		PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
1068
	TEST_ASSERT(vcpu->run != MAP_FAILED,
1069
		    __KVM_SYSCALL_ERROR("mmap()", (int)(unsigned long)MAP_FAILED));
1070 1071

	/* Add to linked-list of VCPUs. */
1072
	list_add(&vcpu->list, &vm->vcpus);
1073 1074

	return vcpu;
1075 1076
}

A
Andrew Jones 已提交
1077 1078
/*
 * VM Virtual Address Unused Gap
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
 *
 * Input Args:
 *   vm - Virtual Machine
 *   sz - Size (bytes)
 *   vaddr_min - Minimum Virtual Address
 *
 * Output Args: None
 *
 * Return:
 *   Lowest virtual address at or below vaddr_min, with at least
 *   sz unused bytes.  TEST_ASSERT failure if no area of at least
 *   size sz is available.
 *
 * Within the VM specified by vm, locates the lowest starting virtual
 * address >= vaddr_min, that has at least sz unallocated bytes.  A
 * TEST_ASSERT failure occurs for invalid input or no area of at least
 * sz unallocated bytes >= vaddr_min is available.
 */
static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
A
Andrew Jones 已提交
1098
				      vm_vaddr_t vaddr_min)
1099 1100 1101 1102 1103 1104
{
	uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;

	/* Determine lowest permitted virtual page index. */
	uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
	if ((pgidx_start * vm->page_size) < vaddr_min)
A
Andrew Jones 已提交
1105
		goto no_va_found;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

	/* Loop over section with enough valid virtual page indexes. */
	if (!sparsebit_is_set_num(vm->vpages_valid,
		pgidx_start, pages))
		pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
			pgidx_start, pages);
	do {
		/*
		 * Are there enough unused virtual pages available at
		 * the currently proposed starting virtual page index.
		 * If not, adjust proposed starting index to next
		 * possible.
		 */
		if (sparsebit_is_clear_num(vm->vpages_mapped,
			pgidx_start, pages))
			goto va_found;
		pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
			pgidx_start, pages);
		if (pgidx_start == 0)
			goto no_va_found;

		/*
		 * If needed, adjust proposed starting virtual address,
		 * to next range of valid virtual addresses.
		 */
		if (!sparsebit_is_set_num(vm->vpages_valid,
			pgidx_start, pages)) {
			pgidx_start = sparsebit_next_set_num(
				vm->vpages_valid, pgidx_start, pages);
			if (pgidx_start == 0)
				goto no_va_found;
		}
	} while (pgidx_start != 0);

no_va_found:
1141
	TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

	/* NOT REACHED */
	return -1;

va_found:
	TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
		pgidx_start, pages),
		"Unexpected, invalid virtual page index range,\n"
		"  pgidx_start: 0x%lx\n"
		"  pages: 0x%lx",
		pgidx_start, pages);
	TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
		pgidx_start, pages),
		"Unexpected, pages already mapped,\n"
		"  pgidx_start: 0x%lx\n"
		"  pages: 0x%lx",
		pgidx_start, pages);

	return pgidx_start * vm->page_size;
}

A
Andrew Jones 已提交
1163 1164
/*
 * VM Virtual Address Allocate
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
 *
 * Input Args:
 *   vm - Virtual Machine
 *   sz - Size in bytes
 *   vaddr_min - Minimum starting virtual address
 *   data_memslot - Memory region slot for data pages
 *   pgd_memslot - Memory region slot for new virtual translation tables
 *
 * Output Args: None
 *
 * Return:
 *   Starting guest virtual address
 *
 * Allocates at least sz bytes within the virtual address space of the vm
 * given by vm.  The allocated bytes are mapped to a virtual address >=
 * the address given by vaddr_min.  Note that each allocation uses a
 * a unique set of pages, with the minimum real allocation being at least
 * a page.
 */
1184
vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min)
1185 1186 1187
{
	uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);

1188
	virt_pgd_alloc(vm);
1189
	vm_paddr_t paddr = vm_phy_pages_alloc(vm, pages,
1190
					      KVM_UTIL_MIN_PFN * vm->page_size, 0);
1191

A
Andrew Jones 已提交
1192 1193
	/*
	 * Find an unused range of virtual page addresses of at least
1194 1195 1196 1197 1198 1199
	 * pages in length.
	 */
	vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);

	/* Map the virtual pages. */
	for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
1200
		pages--, vaddr += vm->page_size, paddr += vm->page_size) {
1201

1202
		virt_pg_map(vm, vaddr, paddr);
1203 1204 1205 1206 1207 1208 1209 1210

		sparsebit_set(vm->vpages_mapped,
			vaddr >> vm->page_shift);
	}

	return vaddr_start;
}

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
/*
 * VM Virtual Address Allocate Pages
 *
 * Input Args:
 *   vm - Virtual Machine
 *
 * Output Args: None
 *
 * Return:
 *   Starting guest virtual address
 *
 * Allocates at least N system pages worth of bytes within the virtual address
 * space of the vm.
 */
vm_vaddr_t vm_vaddr_alloc_pages(struct kvm_vm *vm, int nr_pages)
{
1227
	return vm_vaddr_alloc(vm, nr_pages * getpagesize(), KVM_UTIL_MIN_VADDR);
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
}

/*
 * VM Virtual Address Allocate Page
 *
 * Input Args:
 *   vm - Virtual Machine
 *
 * Output Args: None
 *
 * Return:
 *   Starting guest virtual address
 *
 * Allocates at least one system page worth of bytes within the virtual address
 * space of the vm.
 */
vm_vaddr_t vm_vaddr_alloc_page(struct kvm_vm *vm)
{
	return vm_vaddr_alloc_pages(vm, 1);
}

P
Peter Xu 已提交
1249 1250 1251 1252 1253 1254 1255
/*
 * Map a range of VM virtual address to the VM's physical address
 *
 * Input Args:
 *   vm - Virtual Machine
 *   vaddr - Virtuall address to map
 *   paddr - VM Physical Address
1256
 *   npages - The number of pages to map
P
Peter Xu 已提交
1257 1258 1259 1260 1261 1262
 *   pgd_memslot - Memory region slot for new virtual translation tables
 *
 * Output Args: None
 *
 * Return: None
 *
1263 1264
 * Within the VM given by @vm, creates a virtual translation for
 * @npages starting at @vaddr to the page range starting at @paddr.
P
Peter Xu 已提交
1265 1266
 */
void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1267
	      unsigned int npages)
P
Peter Xu 已提交
1268 1269
{
	size_t page_size = vm->page_size;
1270
	size_t size = npages * page_size;
P
Peter Xu 已提交
1271 1272 1273 1274 1275

	TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
	TEST_ASSERT(paddr + size > paddr, "Paddr overflow");

	while (npages--) {
1276
		virt_pg_map(vm, vaddr, paddr);
P
Peter Xu 已提交
1277 1278 1279 1280 1281
		vaddr += page_size;
		paddr += page_size;
	}
}

A
Andrew Jones 已提交
1282 1283
/*
 * Address VM Physical to Host Virtual
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
 *
 * Input Args:
 *   vm - Virtual Machine
 *   gpa - VM physical address
 *
 * Output Args: None
 *
 * Return:
 *   Equivalent host virtual address
 *
 * Locates the memory region containing the VM physical address given
 * by gpa, within the VM given by vm.  When found, the host virtual
 * address providing the memory to the vm physical address is returned.
 * A TEST_ASSERT failure occurs if no region containing gpa exists.
 */
void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
{
	struct userspace_mem_region *region;
1302

1303 1304 1305 1306
	region = userspace_mem_region_find(vm, gpa, gpa);
	if (!region) {
		TEST_FAIL("No vm physical memory at 0x%lx", gpa);
		return NULL;
1307 1308
	}

1309 1310
	return (void *)((uintptr_t)region->host_mem
		+ (gpa - region->region.guest_phys_addr));
1311 1312
}

A
Andrew Jones 已提交
1313 1314
/*
 * Address Host Virtual to VM Physical
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
 *
 * Input Args:
 *   vm - Virtual Machine
 *   hva - Host virtual address
 *
 * Output Args: None
 *
 * Return:
 *   Equivalent VM physical address
 *
 * Locates the memory region containing the host virtual address given
 * by hva, within the VM given by vm.  When found, the equivalent
 * VM physical address is returned. A TEST_ASSERT failure occurs if no
 * region containing hva exists.
 */
vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
{
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
	struct rb_node *node;

	for (node = vm->regions.hva_tree.rb_node; node; ) {
		struct userspace_mem_region *region =
			container_of(node, struct userspace_mem_region, hva_node);

		if (hva >= region->host_mem) {
			if (hva <= (region->host_mem
				+ region->region.memory_size - 1))
				return (vm_paddr_t)((uintptr_t)
					region->region.guest_phys_addr
					+ (hva - (uintptr_t)region->host_mem));
1344

1345 1346 1347
			node = node->rb_right;
		} else
			node = node->rb_left;
1348 1349
	}

1350
	TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
1351 1352 1353
	return -1;
}

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
/*
 * Address VM physical to Host Virtual *alias*.
 *
 * Input Args:
 *   vm - Virtual Machine
 *   gpa - VM physical address
 *
 * Output Args: None
 *
 * Return:
 *   Equivalent address within the host virtual *alias* area, or NULL
 *   (without failing the test) if the guest memory is not shared (so
 *   no alias exists).
 *
1368 1369 1370 1371
 * Create a writable, shared virtual=>physical alias for the specific GPA.
 * The primary use case is to allow the host selftest to manipulate guest
 * memory without mapping said memory in the guest's address space. And, for
 * userfaultfd-based demand paging, to do so without triggering userfaults.
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
 */
void *addr_gpa2alias(struct kvm_vm *vm, vm_paddr_t gpa)
{
	struct userspace_mem_region *region;
	uintptr_t offset;

	region = userspace_mem_region_find(vm, gpa, gpa);
	if (!region)
		return NULL;

	if (!region->host_alias)
		return NULL;

	offset = gpa - region->region.guest_phys_addr;
	return (void *) ((uintptr_t) region->host_alias + offset);
}

1389
/* Create an interrupt controller chip for the specified VM. */
1390 1391
void vm_create_irqchip(struct kvm_vm *vm)
{
1392
	vm_ioctl(vm, KVM_CREATE_IRQCHIP, NULL);
1393 1394

	vm->has_irqchip = true;
1395
}
1396

1397
int _vcpu_run(struct kvm_vcpu *vcpu)
1398 1399 1400
{
	int rc;

A
Andrew Jones 已提交
1401
	do {
1402
		rc = __vcpu_run(vcpu);
1403
	} while (rc == -1 && errno == EINTR);
1404

1405
	assert_on_unhandled_exception(vcpu);
1406

1407 1408 1409
	return rc;
}

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
/*
 * Invoke KVM_RUN on a vCPU until KVM returns something other than -EINTR.
 * Assert if the KVM returns an error (other than -EINTR).
 */
void vcpu_run(struct kvm_vcpu *vcpu)
{
	int ret = _vcpu_run(vcpu);

	TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_RUN, ret));
}

void vcpu_run_complete_io(struct kvm_vcpu *vcpu)
1422 1423 1424
{
	int ret;

1425
	vcpu->run->immediate_exit = 1;
1426
	ret = __vcpu_run(vcpu);
1427
	vcpu->run->immediate_exit = 0;
1428 1429 1430 1431 1432 1433

	TEST_ASSERT(ret == -1 && errno == EINTR,
		    "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
		    ret, errno);
}

1434 1435
/*
 * Get the list of guest registers which are supported for
1436
 * KVM_GET_ONE_REG/KVM_SET_ONE_REG ioctls.  Returns a kvm_reg_list pointer,
1437
 * it is the caller's responsibility to free the list.
1438
 */
1439
struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vcpu *vcpu)
1440 1441 1442 1443
{
	struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list;
	int ret;

1444
	ret = __vcpu_ioctl(vcpu, KVM_GET_REG_LIST, &reg_list_n);
1445
	TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0");
1446

1447 1448
	reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64));
	reg_list->n = reg_list_n.n;
1449
	vcpu_ioctl(vcpu, KVM_GET_REG_LIST, reg_list);
1450 1451 1452
	return reg_list;
}

1453
void *vcpu_map_dirty_ring(struct kvm_vcpu *vcpu)
1454
{
1455 1456
	uint32_t page_size = vcpu->vm->page_size;
	uint32_t size = vcpu->vm->dirty_ring_size;
1457 1458 1459 1460 1461 1462

	TEST_ASSERT(size > 0, "Should enable dirty ring first");

	if (!vcpu->dirty_gfns) {
		void *addr;

1463 1464
		addr = mmap(NULL, size, PROT_READ, MAP_PRIVATE, vcpu->fd,
			    page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1465 1466
		TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private");

1467 1468
		addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE, vcpu->fd,
			    page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1469 1470
		TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec");

1471 1472
		addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd,
			    page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1473 1474 1475 1476 1477 1478 1479 1480 1481
		TEST_ASSERT(addr != MAP_FAILED, "Dirty ring map failed");

		vcpu->dirty_gfns = addr;
		vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn);
	}

	return vcpu->dirty_gfns;
}

1482 1483 1484 1485
/*
 * Device Ioctl
 */

1486
int __kvm_has_device_attr(int dev_fd, uint32_t group, uint64_t attr)
1487 1488 1489 1490 1491 1492 1493
{
	struct kvm_device_attr attribute = {
		.group = group,
		.attr = attr,
		.flags = 0,
	};

1494
	return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute);
1495 1496
}

1497
int __kvm_test_create_device(struct kvm_vm *vm, uint64_t type)
1498
{
1499 1500 1501 1502 1503 1504 1505 1506
	struct kvm_create_device create_dev = {
		.type = type,
		.flags = KVM_CREATE_DEVICE_TEST,
	};

	return __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev);
}

1507
int __kvm_create_device(struct kvm_vm *vm, uint64_t type)
1508 1509 1510 1511 1512 1513
{
	struct kvm_create_device create_dev = {
		.type = type,
		.fd = -1,
		.flags = 0,
	};
1514
	int err;
1515

1516 1517 1518
	err = __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev);
	TEST_ASSERT(err <= 0, "KVM_CREATE_DEVICE shouldn't return a positive value");
	return err ? : create_dev.fd;
1519 1520
}

1521
int __kvm_device_attr_get(int dev_fd, uint32_t group, uint64_t attr, void *val)
1522
{
1523 1524 1525 1526 1527 1528
	struct kvm_device_attr kvmattr = {
		.group = group,
		.attr = attr,
		.flags = 0,
		.addr = (uintptr_t)val,
	};
1529

1530
	return __kvm_ioctl(dev_fd, KVM_GET_DEVICE_ATTR, &kvmattr);
1531 1532
}

1533
int __kvm_device_attr_set(int dev_fd, uint32_t group, uint64_t attr, void *val)
1534 1535 1536 1537 1538 1539 1540 1541
{
	struct kvm_device_attr kvmattr = {
		.group = group,
		.attr = attr,
		.flags = 0,
		.addr = (uintptr_t)val,
	};

1542
	return __kvm_ioctl(dev_fd, KVM_SET_DEVICE_ATTR, &kvmattr);
1543 1544
}

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
/*
 * IRQ related functions.
 */

int _kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
{
	struct kvm_irq_level irq_level = {
		.irq    = irq,
		.level  = level,
	};

1556
	return __vm_ioctl(vm, KVM_IRQ_LINE, &irq_level);
1557 1558 1559 1560 1561 1562
}

void kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
{
	int ret = _kvm_irq_line(vm, irq, level);

1563
	TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_IRQ_LINE, ret));
1564 1565
}

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
struct kvm_irq_routing *kvm_gsi_routing_create(void)
{
	struct kvm_irq_routing *routing;
	size_t size;

	size = sizeof(struct kvm_irq_routing);
	/* Allocate space for the max number of entries: this wastes 196 KBs. */
	size += KVM_MAX_IRQ_ROUTES * sizeof(struct kvm_irq_routing_entry);
	routing = calloc(1, size);
	assert(routing);

	return routing;
}

void kvm_gsi_routing_irqchip_add(struct kvm_irq_routing *routing,
		uint32_t gsi, uint32_t pin)
{
	int i;

	assert(routing);
	assert(routing->nr < KVM_MAX_IRQ_ROUTES);

	i = routing->nr;
	routing->entries[i].gsi = gsi;
	routing->entries[i].type = KVM_IRQ_ROUTING_IRQCHIP;
	routing->entries[i].flags = 0;
	routing->entries[i].u.irqchip.irqchip = 0;
	routing->entries[i].u.irqchip.pin = pin;
	routing->nr++;
}

int _kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
{
	int ret;

	assert(routing);
1602
	ret = __vm_ioctl(vm, KVM_SET_GSI_ROUTING, routing);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
	free(routing);

	return ret;
}

void kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
{
	int ret;

	ret = _kvm_gsi_routing_write(vm, routing);
1613
	TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_SET_GSI_ROUTING, ret));
1614 1615
}

A
Andrew Jones 已提交
1616 1617
/*
 * VM Dump
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
 *
 * Input Args:
 *   vm - Virtual Machine
 *   indent - Left margin indent amount
 *
 * Output Args:
 *   stream - Output FILE stream
 *
 * Return: None
 *
 * Dumps the current state of the VM given by vm, to the FILE stream
 * given by stream.
 */
void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
{
1633
	int ctr;
1634
	struct userspace_mem_region *region;
1635
	struct kvm_vcpu *vcpu;
1636 1637 1638 1639 1640

	fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
	fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
	fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
	fprintf(stream, "%*sMem Regions:\n", indent, "");
1641
	hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) {
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
		fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
			"host_virt: %p\n", indent + 2, "",
			(uint64_t) region->region.guest_phys_addr,
			(uint64_t) region->region.memory_size,
			region->host_mem);
		fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
		sparsebit_dump(stream, region->unused_phy_pages, 0);
	}
	fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
	sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
	fprintf(stream, "%*spgd_created: %u\n", indent, "",
		vm->pgd_created);
	if (vm->pgd_created) {
		fprintf(stream, "%*sVirtual Translation Tables:\n",
			indent + 2, "");
		virt_dump(stream, vm, indent + 4);
	}
	fprintf(stream, "%*sVCPUs:\n", indent, "");
1660

1661
	list_for_each_entry(vcpu, &vm->vcpus, list)
1662
		vcpu_dump(stream, vcpu, indent + 2);
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
}

/* Known KVM exit reasons */
static struct exit_reason {
	unsigned int reason;
	const char *name;
} exit_reasons_known[] = {
	{KVM_EXIT_UNKNOWN, "UNKNOWN"},
	{KVM_EXIT_EXCEPTION, "EXCEPTION"},
	{KVM_EXIT_IO, "IO"},
	{KVM_EXIT_HYPERCALL, "HYPERCALL"},
	{KVM_EXIT_DEBUG, "DEBUG"},
	{KVM_EXIT_HLT, "HLT"},
	{KVM_EXIT_MMIO, "MMIO"},
	{KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
	{KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
	{KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
	{KVM_EXIT_INTR, "INTR"},
	{KVM_EXIT_SET_TPR, "SET_TPR"},
	{KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
	{KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
	{KVM_EXIT_S390_RESET, "S390_RESET"},
	{KVM_EXIT_DCR, "DCR"},
	{KVM_EXIT_NMI, "NMI"},
	{KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
	{KVM_EXIT_OSI, "OSI"},
	{KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
1690
	{KVM_EXIT_DIRTY_RING_FULL, "DIRTY_RING_FULL"},
1691 1692
	{KVM_EXIT_X86_RDMSR, "RDMSR"},
	{KVM_EXIT_X86_WRMSR, "WRMSR"},
1693
	{KVM_EXIT_XEN, "XEN"},
1694 1695 1696 1697 1698
#ifdef KVM_EXIT_MEMORY_NOT_PRESENT
	{KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
#endif
};

A
Andrew Jones 已提交
1699 1700
/*
 * Exit Reason String
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
 *
 * Input Args:
 *   exit_reason - Exit reason
 *
 * Output Args: None
 *
 * Return:
 *   Constant string pointer describing the exit reason.
 *
 * Locates and returns a constant string that describes the KVM exit
 * reason given by exit_reason.  If no such string is found, a constant
 * string of "Unknown" is returned.
 */
const char *exit_reason_str(unsigned int exit_reason)
{
	unsigned int n1;

	for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
		if (exit_reason == exit_reasons_known[n1].reason)
			return exit_reasons_known[n1].name;
	}

	return "Unknown";
}

A
Andrew Jones 已提交
1726
/*
1727
 * Physical Contiguous Page Allocator
1728 1729 1730
 *
 * Input Args:
 *   vm - Virtual Machine
1731
 *   num - number of pages
1732 1733 1734 1735 1736 1737 1738 1739
 *   paddr_min - Physical address minimum
 *   memslot - Memory region to allocate page from
 *
 * Output Args: None
 *
 * Return:
 *   Starting physical address
 *
1740 1741
 * Within the VM specified by vm, locates a range of available physical
 * pages at or above paddr_min. If found, the pages are marked as in use
1742
 * and their base address is returned. A TEST_ASSERT failure occurs if
1743
 * not enough pages are available at or above paddr_min.
1744
 */
1745 1746
vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
			      vm_paddr_t paddr_min, uint32_t memslot)
1747 1748
{
	struct userspace_mem_region *region;
1749 1750 1751
	sparsebit_idx_t pg, base;

	TEST_ASSERT(num > 0, "Must allocate at least one page");
1752 1753

	TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
1754
		"not divisible by page size.\n"
1755 1756 1757 1758
		"  paddr_min: 0x%lx page_size: 0x%x",
		paddr_min, vm->page_size);

	region = memslot2region(vm, memslot);
1759 1760 1761 1762 1763 1764 1765 1766
	base = pg = paddr_min >> vm->page_shift;

	do {
		for (; pg < base + num; ++pg) {
			if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
				base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
				break;
			}
1767
		}
1768 1769 1770 1771 1772 1773 1774 1775 1776
	} while (pg && pg != base + num);

	if (pg == 0) {
		fprintf(stderr, "No guest physical page available, "
			"paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
			paddr_min, vm->page_size, memslot);
		fputs("---- vm dump ----\n", stderr);
		vm_dump(stderr, vm, 2);
		abort();
1777 1778
	}

1779 1780 1781 1782 1783
	for (pg = base; pg < base + num; ++pg)
		sparsebit_clear(region->unused_phy_pages, pg);

	return base * vm->page_size;
}
1784

1785 1786 1787 1788
vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
			     uint32_t memslot)
{
	return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
1789 1790
}

1791 1792 1793 1794 1795 1796 1797 1798
/* Arbitrary minimum physical address used for virtual translation tables. */
#define KVM_GUEST_PAGE_TABLE_MIN_PADDR 0x180000

vm_paddr_t vm_alloc_page_table(struct kvm_vm *vm)
{
	return vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, 0);
}

A
Andrew Jones 已提交
1799 1800
/*
 * Address Guest Virtual to Host Virtual
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
 *
 * Input Args:
 *   vm - Virtual Machine
 *   gva - VM virtual address
 *
 * Output Args: None
 *
 * Return:
 *   Equivalent host virtual address
 */
void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
{
	return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
}
1815

1816 1817 1818 1819 1820
unsigned long __attribute__((weak)) vm_compute_max_gfn(struct kvm_vm *vm)
{
	return ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
}

1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
static unsigned int vm_calc_num_pages(unsigned int num_pages,
				      unsigned int page_shift,
				      unsigned int new_page_shift,
				      bool ceil)
{
	unsigned int n = 1 << (new_page_shift - page_shift);

	if (page_shift >= new_page_shift)
		return num_pages * (1 << (page_shift - new_page_shift));

	return num_pages / n + !!(ceil && num_pages % n);
}

static inline int getpageshift(void)
{
	return __builtin_ffs(getpagesize()) - 1;
}

unsigned int
vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
{
	return vm_calc_num_pages(num_guest_pages,
				 vm_guest_mode_params[mode].page_shift,
				 getpageshift(), true);
}

unsigned int
vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
{
	return vm_calc_num_pages(num_host_pages, getpageshift(),
				 vm_guest_mode_params[mode].page_shift, false);
}
1853 1854 1855 1856 1857 1858 1859

unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
{
	unsigned int n;
	n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
	return vm_adjust_num_guest_pages(mode, n);
}