kvm_util.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. /*
  2. * tools/testing/selftests/kvm/lib/kvm_util.c
  3. *
  4. * Copyright (C) 2018, Google LLC.
  5. *
  6. * This work is licensed under the terms of the GNU GPL, version 2.
  7. */
  8. #include "test_util.h"
  9. #include "kvm_util.h"
  10. #include "kvm_util_internal.h"
  11. #include <assert.h>
  12. #include <sys/mman.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <linux/kernel.h>
  16. #define KVM_DEV_PATH "/dev/kvm"
  17. #define KVM_UTIL_PGS_PER_HUGEPG 512
  18. #define KVM_UTIL_MIN_PADDR 0x2000
  19. /* Aligns x up to the next multiple of size. Size must be a power of 2. */
  20. static void *align(void *x, size_t size)
  21. {
  22. size_t mask = size - 1;
  23. TEST_ASSERT(size != 0 && !(size & (size - 1)),
  24. "size not a power of 2: %lu", size);
  25. return (void *) (((size_t) x + mask) & ~mask);
  26. }
  27. /* Capability
  28. *
  29. * Input Args:
  30. * cap - Capability
  31. *
  32. * Output Args: None
  33. *
  34. * Return:
  35. * On success, the Value corresponding to the capability (KVM_CAP_*)
  36. * specified by the value of cap. On failure a TEST_ASSERT failure
  37. * is produced.
  38. *
  39. * Looks up and returns the value corresponding to the capability
  40. * (KVM_CAP_*) given by cap.
  41. */
  42. int kvm_check_cap(long cap)
  43. {
  44. int ret;
  45. int kvm_fd;
  46. kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
  47. if (kvm_fd < 0)
  48. exit(KSFT_SKIP);
  49. ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, cap);
  50. TEST_ASSERT(ret != -1, "KVM_CHECK_EXTENSION IOCTL failed,\n"
  51. " rc: %i errno: %i", ret, errno);
  52. close(kvm_fd);
  53. return ret;
  54. }
  55. /* VM Enable Capability
  56. *
  57. * Input Args:
  58. * vm - Virtual Machine
  59. * cap - Capability
  60. *
  61. * Output Args: None
  62. *
  63. * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
  64. *
  65. * Enables a capability (KVM_CAP_*) on the VM.
  66. */
  67. int vm_enable_cap(struct kvm_vm *vm, struct kvm_enable_cap *cap)
  68. {
  69. int ret;
  70. ret = ioctl(vm->fd, KVM_ENABLE_CAP, cap);
  71. TEST_ASSERT(ret == 0, "KVM_ENABLE_CAP IOCTL failed,\n"
  72. " rc: %i errno: %i", ret, errno);
  73. return ret;
  74. }
  75. static void vm_open(struct kvm_vm *vm, int perm)
  76. {
  77. vm->kvm_fd = open(KVM_DEV_PATH, perm);
  78. if (vm->kvm_fd < 0)
  79. exit(KSFT_SKIP);
  80. /* Create VM. */
  81. vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, NULL);
  82. TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
  83. "rc: %i errno: %i", vm->fd, errno);
  84. }
  85. /* VM Create
  86. *
  87. * Input Args:
  88. * mode - VM Mode (e.g. VM_MODE_FLAT48PG)
  89. * phy_pages - Physical memory pages
  90. * perm - permission
  91. *
  92. * Output Args: None
  93. *
  94. * Return:
  95. * Pointer to opaque structure that describes the created VM.
  96. *
  97. * Creates a VM with the mode specified by mode (e.g. VM_MODE_FLAT48PG).
  98. * When phy_pages is non-zero, a memory region of phy_pages physical pages
  99. * is created and mapped starting at guest physical address 0. The file
  100. * descriptor to control the created VM is created with the permissions
  101. * given by perm (e.g. O_RDWR).
  102. */
  103. struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
  104. {
  105. struct kvm_vm *vm;
  106. int kvm_fd;
  107. /* Allocate memory. */
  108. vm = calloc(1, sizeof(*vm));
  109. TEST_ASSERT(vm != NULL, "Insufficent Memory");
  110. vm->mode = mode;
  111. vm_open(vm, perm);
  112. /* Setup mode specific traits. */
  113. switch (vm->mode) {
  114. case VM_MODE_FLAT48PG:
  115. vm->page_size = 0x1000;
  116. vm->page_shift = 12;
  117. /* Limit to 48-bit canonical virtual addresses. */
  118. vm->vpages_valid = sparsebit_alloc();
  119. sparsebit_set_num(vm->vpages_valid,
  120. 0, (1ULL << (48 - 1)) >> vm->page_shift);
  121. sparsebit_set_num(vm->vpages_valid,
  122. (~((1ULL << (48 - 1)) - 1)) >> vm->page_shift,
  123. (1ULL << (48 - 1)) >> vm->page_shift);
  124. /* Limit physical addresses to 52-bits. */
  125. vm->max_gfn = ((1ULL << 52) >> vm->page_shift) - 1;
  126. break;
  127. default:
  128. TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
  129. }
  130. /* Allocate and setup memory for guest. */
  131. vm->vpages_mapped = sparsebit_alloc();
  132. if (phy_pages != 0)
  133. vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
  134. 0, 0, phy_pages, 0);
  135. return vm;
  136. }
  137. /* VM Restart
  138. *
  139. * Input Args:
  140. * vm - VM that has been released before
  141. * perm - permission
  142. *
  143. * Output Args: None
  144. *
  145. * Reopens the file descriptors associated to the VM and reinstates the
  146. * global state, such as the irqchip and the memory regions that are mapped
  147. * into the guest.
  148. */
  149. void kvm_vm_restart(struct kvm_vm *vmp, int perm)
  150. {
  151. struct userspace_mem_region *region;
  152. vm_open(vmp, perm);
  153. if (vmp->has_irqchip)
  154. vm_create_irqchip(vmp);
  155. for (region = vmp->userspace_mem_region_head; region;
  156. region = region->next) {
  157. int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
  158. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
  159. " rc: %i errno: %i\n"
  160. " slot: %u flags: 0x%x\n"
  161. " guest_phys_addr: 0x%lx size: 0x%lx",
  162. ret, errno, region->region.slot, region->region.flags,
  163. region->region.guest_phys_addr,
  164. region->region.memory_size);
  165. }
  166. }
  167. void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
  168. {
  169. struct kvm_dirty_log args = { .dirty_bitmap = log, .slot = slot };
  170. int ret;
  171. ret = ioctl(vm->fd, KVM_GET_DIRTY_LOG, &args);
  172. TEST_ASSERT(ret == 0, "%s: KVM_GET_DIRTY_LOG failed: %s",
  173. strerror(-ret));
  174. }
  175. /* Userspace Memory Region Find
  176. *
  177. * Input Args:
  178. * vm - Virtual Machine
  179. * start - Starting VM physical address
  180. * end - Ending VM physical address, inclusive.
  181. *
  182. * Output Args: None
  183. *
  184. * Return:
  185. * Pointer to overlapping region, NULL if no such region.
  186. *
  187. * Searches for a region with any physical memory that overlaps with
  188. * any portion of the guest physical addresses from start to end
  189. * inclusive. If multiple overlapping regions exist, a pointer to any
  190. * of the regions is returned. Null is returned only when no overlapping
  191. * region exists.
  192. */
  193. static struct userspace_mem_region *userspace_mem_region_find(
  194. struct kvm_vm *vm, uint64_t start, uint64_t end)
  195. {
  196. struct userspace_mem_region *region;
  197. for (region = vm->userspace_mem_region_head; region;
  198. region = region->next) {
  199. uint64_t existing_start = region->region.guest_phys_addr;
  200. uint64_t existing_end = region->region.guest_phys_addr
  201. + region->region.memory_size - 1;
  202. if (start <= existing_end && end >= existing_start)
  203. return region;
  204. }
  205. return NULL;
  206. }
  207. /* KVM Userspace Memory Region Find
  208. *
  209. * Input Args:
  210. * vm - Virtual Machine
  211. * start - Starting VM physical address
  212. * end - Ending VM physical address, inclusive.
  213. *
  214. * Output Args: None
  215. *
  216. * Return:
  217. * Pointer to overlapping region, NULL if no such region.
  218. *
  219. * Public interface to userspace_mem_region_find. Allows tests to look up
  220. * the memslot datastructure for a given range of guest physical memory.
  221. */
  222. struct kvm_userspace_memory_region *
  223. kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
  224. uint64_t end)
  225. {
  226. struct userspace_mem_region *region;
  227. region = userspace_mem_region_find(vm, start, end);
  228. if (!region)
  229. return NULL;
  230. return &region->region;
  231. }
  232. /* VCPU Find
  233. *
  234. * Input Args:
  235. * vm - Virtual Machine
  236. * vcpuid - VCPU ID
  237. *
  238. * Output Args: None
  239. *
  240. * Return:
  241. * Pointer to VCPU structure
  242. *
  243. * Locates a vcpu structure that describes the VCPU specified by vcpuid and
  244. * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU
  245. * for the specified vcpuid.
  246. */
  247. struct vcpu *vcpu_find(struct kvm_vm *vm,
  248. uint32_t vcpuid)
  249. {
  250. struct vcpu *vcpup;
  251. for (vcpup = vm->vcpu_head; vcpup; vcpup = vcpup->next) {
  252. if (vcpup->id == vcpuid)
  253. return vcpup;
  254. }
  255. return NULL;
  256. }
  257. /* VM VCPU Remove
  258. *
  259. * Input Args:
  260. * vm - Virtual Machine
  261. * vcpuid - VCPU ID
  262. *
  263. * Output Args: None
  264. *
  265. * Return: None, TEST_ASSERT failures for all error conditions
  266. *
  267. * Within the VM specified by vm, removes the VCPU given by vcpuid.
  268. */
  269. static void vm_vcpu_rm(struct kvm_vm *vm, uint32_t vcpuid)
  270. {
  271. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  272. int ret;
  273. ret = munmap(vcpu->state, sizeof(*vcpu->state));
  274. TEST_ASSERT(ret == 0, "munmap of VCPU fd failed, rc: %i "
  275. "errno: %i", ret, errno);
  276. close(vcpu->fd);
  277. TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
  278. "errno: %i", ret, errno);
  279. if (vcpu->next)
  280. vcpu->next->prev = vcpu->prev;
  281. if (vcpu->prev)
  282. vcpu->prev->next = vcpu->next;
  283. else
  284. vm->vcpu_head = vcpu->next;
  285. free(vcpu);
  286. }
  287. void kvm_vm_release(struct kvm_vm *vmp)
  288. {
  289. int ret;
  290. /* Free VCPUs. */
  291. while (vmp->vcpu_head)
  292. vm_vcpu_rm(vmp, vmp->vcpu_head->id);
  293. /* Close file descriptor for the VM. */
  294. ret = close(vmp->fd);
  295. TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
  296. " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
  297. close(vmp->kvm_fd);
  298. TEST_ASSERT(ret == 0, "Close of /dev/kvm fd failed,\n"
  299. " vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
  300. }
  301. /* Destroys and frees the VM pointed to by vmp.
  302. */
  303. void kvm_vm_free(struct kvm_vm *vmp)
  304. {
  305. int ret;
  306. if (vmp == NULL)
  307. return;
  308. /* Free userspace_mem_regions. */
  309. while (vmp->userspace_mem_region_head) {
  310. struct userspace_mem_region *region
  311. = vmp->userspace_mem_region_head;
  312. region->region.memory_size = 0;
  313. ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION,
  314. &region->region);
  315. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
  316. "rc: %i errno: %i", ret, errno);
  317. vmp->userspace_mem_region_head = region->next;
  318. sparsebit_free(&region->unused_phy_pages);
  319. ret = munmap(region->mmap_start, region->mmap_size);
  320. TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i",
  321. ret, errno);
  322. free(region);
  323. }
  324. /* Free sparsebit arrays. */
  325. sparsebit_free(&vmp->vpages_valid);
  326. sparsebit_free(&vmp->vpages_mapped);
  327. kvm_vm_release(vmp);
  328. /* Free the structure describing the VM. */
  329. free(vmp);
  330. }
  331. /* Memory Compare, host virtual to guest virtual
  332. *
  333. * Input Args:
  334. * hva - Starting host virtual address
  335. * vm - Virtual Machine
  336. * gva - Starting guest virtual address
  337. * len - number of bytes to compare
  338. *
  339. * Output Args: None
  340. *
  341. * Input/Output Args: None
  342. *
  343. * Return:
  344. * Returns 0 if the bytes starting at hva for a length of len
  345. * are equal the guest virtual bytes starting at gva. Returns
  346. * a value < 0, if bytes at hva are less than those at gva.
  347. * Otherwise a value > 0 is returned.
  348. *
  349. * Compares the bytes starting at the host virtual address hva, for
  350. * a length of len, to the guest bytes starting at the guest virtual
  351. * address given by gva.
  352. */
  353. int kvm_memcmp_hva_gva(void *hva,
  354. struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
  355. {
  356. size_t amt;
  357. /* Compare a batch of bytes until either a match is found
  358. * or all the bytes have been compared.
  359. */
  360. for (uintptr_t offset = 0; offset < len; offset += amt) {
  361. uintptr_t ptr1 = (uintptr_t)hva + offset;
  362. /* Determine host address for guest virtual address
  363. * at offset.
  364. */
  365. uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
  366. /* Determine amount to compare on this pass.
  367. * Don't allow the comparsion to cross a page boundary.
  368. */
  369. amt = len - offset;
  370. if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
  371. amt = vm->page_size - (ptr1 % vm->page_size);
  372. if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
  373. amt = vm->page_size - (ptr2 % vm->page_size);
  374. assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
  375. assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
  376. /* Perform the comparison. If there is a difference
  377. * return that result to the caller, otherwise need
  378. * to continue on looking for a mismatch.
  379. */
  380. int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
  381. if (ret != 0)
  382. return ret;
  383. }
  384. /* No mismatch found. Let the caller know the two memory
  385. * areas are equal.
  386. */
  387. return 0;
  388. }
  389. /* Allocate an instance of struct kvm_cpuid2
  390. *
  391. * Input Args: None
  392. *
  393. * Output Args: None
  394. *
  395. * Return: A pointer to the allocated struct. The caller is responsible
  396. * for freeing this struct.
  397. *
  398. * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
  399. * array to be decided at allocation time, allocation is slightly
  400. * complicated. This function uses a reasonable default length for
  401. * the array and performs the appropriate allocation.
  402. */
  403. static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
  404. {
  405. struct kvm_cpuid2 *cpuid;
  406. int nent = 100;
  407. size_t size;
  408. size = sizeof(*cpuid);
  409. size += nent * sizeof(struct kvm_cpuid_entry2);
  410. cpuid = malloc(size);
  411. if (!cpuid) {
  412. perror("malloc");
  413. abort();
  414. }
  415. cpuid->nent = nent;
  416. return cpuid;
  417. }
  418. /* KVM Supported CPUID Get
  419. *
  420. * Input Args: None
  421. *
  422. * Output Args:
  423. *
  424. * Return: The supported KVM CPUID
  425. *
  426. * Get the guest CPUID supported by KVM.
  427. */
  428. struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
  429. {
  430. static struct kvm_cpuid2 *cpuid;
  431. int ret;
  432. int kvm_fd;
  433. if (cpuid)
  434. return cpuid;
  435. cpuid = allocate_kvm_cpuid2();
  436. kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
  437. if (kvm_fd < 0)
  438. exit(KSFT_SKIP);
  439. ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
  440. TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
  441. ret, errno);
  442. close(kvm_fd);
  443. return cpuid;
  444. }
  445. /* Locate a cpuid entry.
  446. *
  447. * Input Args:
  448. * cpuid: The cpuid.
  449. * function: The function of the cpuid entry to find.
  450. *
  451. * Output Args: None
  452. *
  453. * Return: A pointer to the cpuid entry. Never returns NULL.
  454. */
  455. struct kvm_cpuid_entry2 *
  456. kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
  457. {
  458. struct kvm_cpuid2 *cpuid;
  459. struct kvm_cpuid_entry2 *entry = NULL;
  460. int i;
  461. cpuid = kvm_get_supported_cpuid();
  462. for (i = 0; i < cpuid->nent; i++) {
  463. if (cpuid->entries[i].function == function &&
  464. cpuid->entries[i].index == index) {
  465. entry = &cpuid->entries[i];
  466. break;
  467. }
  468. }
  469. TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
  470. function, index);
  471. return entry;
  472. }
  473. /* VM Userspace Memory Region Add
  474. *
  475. * Input Args:
  476. * vm - Virtual Machine
  477. * backing_src - Storage source for this region.
  478. * NULL to use anonymous memory.
  479. * guest_paddr - Starting guest physical address
  480. * slot - KVM region slot
  481. * npages - Number of physical pages
  482. * flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
  483. *
  484. * Output Args: None
  485. *
  486. * Return: None
  487. *
  488. * Allocates a memory area of the number of pages specified by npages
  489. * and maps it to the VM specified by vm, at a starting physical address
  490. * given by guest_paddr. The region is created with a KVM region slot
  491. * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM. The
  492. * region is created with the flags given by flags.
  493. */
  494. void vm_userspace_mem_region_add(struct kvm_vm *vm,
  495. enum vm_mem_backing_src_type src_type,
  496. uint64_t guest_paddr, uint32_t slot, uint64_t npages,
  497. uint32_t flags)
  498. {
  499. int ret;
  500. unsigned long pmem_size = 0;
  501. struct userspace_mem_region *region;
  502. size_t huge_page_size = KVM_UTIL_PGS_PER_HUGEPG * vm->page_size;
  503. TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
  504. "address not on a page boundary.\n"
  505. " guest_paddr: 0x%lx vm->page_size: 0x%x",
  506. guest_paddr, vm->page_size);
  507. TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
  508. <= vm->max_gfn, "Physical range beyond maximum "
  509. "supported physical address,\n"
  510. " guest_paddr: 0x%lx npages: 0x%lx\n"
  511. " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
  512. guest_paddr, npages, vm->max_gfn, vm->page_size);
  513. /* Confirm a mem region with an overlapping address doesn't
  514. * already exist.
  515. */
  516. region = (struct userspace_mem_region *) userspace_mem_region_find(
  517. vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1);
  518. if (region != NULL)
  519. TEST_ASSERT(false, "overlapping userspace_mem_region already "
  520. "exists\n"
  521. " requested guest_paddr: 0x%lx npages: 0x%lx "
  522. "page_size: 0x%x\n"
  523. " existing guest_paddr: 0x%lx size: 0x%lx",
  524. guest_paddr, npages, vm->page_size,
  525. (uint64_t) region->region.guest_phys_addr,
  526. (uint64_t) region->region.memory_size);
  527. /* Confirm no region with the requested slot already exists. */
  528. for (region = vm->userspace_mem_region_head; region;
  529. region = region->next) {
  530. if (region->region.slot == slot)
  531. break;
  532. }
  533. if (region != NULL)
  534. TEST_ASSERT(false, "A mem region with the requested slot "
  535. "already exists.\n"
  536. " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
  537. " existing slot: %u paddr: 0x%lx size: 0x%lx",
  538. slot, guest_paddr, npages,
  539. region->region.slot,
  540. (uint64_t) region->region.guest_phys_addr,
  541. (uint64_t) region->region.memory_size);
  542. /* Allocate and initialize new mem region structure. */
  543. region = calloc(1, sizeof(*region));
  544. TEST_ASSERT(region != NULL, "Insufficient Memory");
  545. region->mmap_size = npages * vm->page_size;
  546. /* Enough memory to align up to a huge page. */
  547. if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
  548. region->mmap_size += huge_page_size;
  549. region->mmap_start = mmap(NULL, region->mmap_size,
  550. PROT_READ | PROT_WRITE,
  551. MAP_PRIVATE | MAP_ANONYMOUS
  552. | (src_type == VM_MEM_SRC_ANONYMOUS_HUGETLB ? MAP_HUGETLB : 0),
  553. -1, 0);
  554. TEST_ASSERT(region->mmap_start != MAP_FAILED,
  555. "test_malloc failed, mmap_start: %p errno: %i",
  556. region->mmap_start, errno);
  557. /* Align THP allocation up to start of a huge page. */
  558. region->host_mem = align(region->mmap_start,
  559. src_type == VM_MEM_SRC_ANONYMOUS_THP ? huge_page_size : 1);
  560. /* As needed perform madvise */
  561. if (src_type == VM_MEM_SRC_ANONYMOUS || src_type == VM_MEM_SRC_ANONYMOUS_THP) {
  562. ret = madvise(region->host_mem, npages * vm->page_size,
  563. src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
  564. TEST_ASSERT(ret == 0, "madvise failed,\n"
  565. " addr: %p\n"
  566. " length: 0x%lx\n"
  567. " src_type: %x",
  568. region->host_mem, npages * vm->page_size, src_type);
  569. }
  570. region->unused_phy_pages = sparsebit_alloc();
  571. sparsebit_set_num(region->unused_phy_pages,
  572. guest_paddr >> vm->page_shift, npages);
  573. region->region.slot = slot;
  574. region->region.flags = flags;
  575. region->region.guest_phys_addr = guest_paddr;
  576. region->region.memory_size = npages * vm->page_size;
  577. region->region.userspace_addr = (uintptr_t) region->host_mem;
  578. ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
  579. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
  580. " rc: %i errno: %i\n"
  581. " slot: %u flags: 0x%x\n"
  582. " guest_phys_addr: 0x%lx size: 0x%lx",
  583. ret, errno, slot, flags,
  584. guest_paddr, (uint64_t) region->region.memory_size);
  585. /* Add to linked-list of memory regions. */
  586. if (vm->userspace_mem_region_head)
  587. vm->userspace_mem_region_head->prev = region;
  588. region->next = vm->userspace_mem_region_head;
  589. vm->userspace_mem_region_head = region;
  590. }
  591. /* Memslot to region
  592. *
  593. * Input Args:
  594. * vm - Virtual Machine
  595. * memslot - KVM memory slot ID
  596. *
  597. * Output Args: None
  598. *
  599. * Return:
  600. * Pointer to memory region structure that describe memory region
  601. * using kvm memory slot ID given by memslot. TEST_ASSERT failure
  602. * on error (e.g. currently no memory region using memslot as a KVM
  603. * memory slot ID).
  604. */
  605. static struct userspace_mem_region *memslot2region(struct kvm_vm *vm,
  606. uint32_t memslot)
  607. {
  608. struct userspace_mem_region *region;
  609. for (region = vm->userspace_mem_region_head; region;
  610. region = region->next) {
  611. if (region->region.slot == memslot)
  612. break;
  613. }
  614. if (region == NULL) {
  615. fprintf(stderr, "No mem region with the requested slot found,\n"
  616. " requested slot: %u\n", memslot);
  617. fputs("---- vm dump ----\n", stderr);
  618. vm_dump(stderr, vm, 2);
  619. TEST_ASSERT(false, "Mem region not found");
  620. }
  621. return region;
  622. }
  623. /* VM Memory Region Flags Set
  624. *
  625. * Input Args:
  626. * vm - Virtual Machine
  627. * flags - Starting guest physical address
  628. *
  629. * Output Args: None
  630. *
  631. * Return: None
  632. *
  633. * Sets the flags of the memory region specified by the value of slot,
  634. * to the values given by flags.
  635. */
  636. void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
  637. {
  638. int ret;
  639. struct userspace_mem_region *region;
  640. /* Locate memory region. */
  641. region = memslot2region(vm, slot);
  642. region->region.flags = flags;
  643. ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
  644. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
  645. " rc: %i errno: %i slot: %u flags: 0x%x",
  646. ret, errno, slot, flags);
  647. }
  648. /* VCPU mmap Size
  649. *
  650. * Input Args: None
  651. *
  652. * Output Args: None
  653. *
  654. * Return:
  655. * Size of VCPU state
  656. *
  657. * Returns the size of the structure pointed to by the return value
  658. * of vcpu_state().
  659. */
  660. static int vcpu_mmap_sz(void)
  661. {
  662. int dev_fd, ret;
  663. dev_fd = open(KVM_DEV_PATH, O_RDONLY);
  664. if (dev_fd < 0)
  665. exit(KSFT_SKIP);
  666. ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
  667. TEST_ASSERT(ret >= sizeof(struct kvm_run),
  668. "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
  669. __func__, ret, errno);
  670. close(dev_fd);
  671. return ret;
  672. }
  673. /* VM VCPU Add
  674. *
  675. * Input Args:
  676. * vm - Virtual Machine
  677. * vcpuid - VCPU ID
  678. *
  679. * Output Args: None
  680. *
  681. * Return: None
  682. *
  683. * Creates and adds to the VM specified by vm and virtual CPU with
  684. * the ID given by vcpuid.
  685. */
  686. void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_memslot)
  687. {
  688. struct vcpu *vcpu;
  689. /* Confirm a vcpu with the specified id doesn't already exist. */
  690. vcpu = vcpu_find(vm, vcpuid);
  691. if (vcpu != NULL)
  692. TEST_ASSERT(false, "vcpu with the specified id "
  693. "already exists,\n"
  694. " requested vcpuid: %u\n"
  695. " existing vcpuid: %u state: %p",
  696. vcpuid, vcpu->id, vcpu->state);
  697. /* Allocate and initialize new vcpu structure. */
  698. vcpu = calloc(1, sizeof(*vcpu));
  699. TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
  700. vcpu->id = vcpuid;
  701. vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
  702. TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
  703. vcpu->fd, errno);
  704. TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
  705. "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
  706. vcpu_mmap_sz(), sizeof(*vcpu->state));
  707. vcpu->state = (struct kvm_run *) mmap(NULL, sizeof(*vcpu->state),
  708. PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
  709. TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
  710. "vcpu id: %u errno: %i", vcpuid, errno);
  711. /* Add to linked-list of VCPUs. */
  712. if (vm->vcpu_head)
  713. vm->vcpu_head->prev = vcpu;
  714. vcpu->next = vm->vcpu_head;
  715. vm->vcpu_head = vcpu;
  716. vcpu_setup(vm, vcpuid, pgd_memslot, gdt_memslot);
  717. }
  718. /* VM Virtual Address Unused Gap
  719. *
  720. * Input Args:
  721. * vm - Virtual Machine
  722. * sz - Size (bytes)
  723. * vaddr_min - Minimum Virtual Address
  724. *
  725. * Output Args: None
  726. *
  727. * Return:
  728. * Lowest virtual address at or below vaddr_min, with at least
  729. * sz unused bytes. TEST_ASSERT failure if no area of at least
  730. * size sz is available.
  731. *
  732. * Within the VM specified by vm, locates the lowest starting virtual
  733. * address >= vaddr_min, that has at least sz unallocated bytes. A
  734. * TEST_ASSERT failure occurs for invalid input or no area of at least
  735. * sz unallocated bytes >= vaddr_min is available.
  736. */
  737. static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
  738. vm_vaddr_t vaddr_min)
  739. {
  740. uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
  741. /* Determine lowest permitted virtual page index. */
  742. uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
  743. if ((pgidx_start * vm->page_size) < vaddr_min)
  744. goto no_va_found;
  745. /* Loop over section with enough valid virtual page indexes. */
  746. if (!sparsebit_is_set_num(vm->vpages_valid,
  747. pgidx_start, pages))
  748. pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
  749. pgidx_start, pages);
  750. do {
  751. /*
  752. * Are there enough unused virtual pages available at
  753. * the currently proposed starting virtual page index.
  754. * If not, adjust proposed starting index to next
  755. * possible.
  756. */
  757. if (sparsebit_is_clear_num(vm->vpages_mapped,
  758. pgidx_start, pages))
  759. goto va_found;
  760. pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
  761. pgidx_start, pages);
  762. if (pgidx_start == 0)
  763. goto no_va_found;
  764. /*
  765. * If needed, adjust proposed starting virtual address,
  766. * to next range of valid virtual addresses.
  767. */
  768. if (!sparsebit_is_set_num(vm->vpages_valid,
  769. pgidx_start, pages)) {
  770. pgidx_start = sparsebit_next_set_num(
  771. vm->vpages_valid, pgidx_start, pages);
  772. if (pgidx_start == 0)
  773. goto no_va_found;
  774. }
  775. } while (pgidx_start != 0);
  776. no_va_found:
  777. TEST_ASSERT(false, "No vaddr of specified pages available, "
  778. "pages: 0x%lx", pages);
  779. /* NOT REACHED */
  780. return -1;
  781. va_found:
  782. TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
  783. pgidx_start, pages),
  784. "Unexpected, invalid virtual page index range,\n"
  785. " pgidx_start: 0x%lx\n"
  786. " pages: 0x%lx",
  787. pgidx_start, pages);
  788. TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
  789. pgidx_start, pages),
  790. "Unexpected, pages already mapped,\n"
  791. " pgidx_start: 0x%lx\n"
  792. " pages: 0x%lx",
  793. pgidx_start, pages);
  794. return pgidx_start * vm->page_size;
  795. }
  796. /* VM Virtual Address Allocate
  797. *
  798. * Input Args:
  799. * vm - Virtual Machine
  800. * sz - Size in bytes
  801. * vaddr_min - Minimum starting virtual address
  802. * data_memslot - Memory region slot for data pages
  803. * pgd_memslot - Memory region slot for new virtual translation tables
  804. *
  805. * Output Args: None
  806. *
  807. * Return:
  808. * Starting guest virtual address
  809. *
  810. * Allocates at least sz bytes within the virtual address space of the vm
  811. * given by vm. The allocated bytes are mapped to a virtual address >=
  812. * the address given by vaddr_min. Note that each allocation uses a
  813. * a unique set of pages, with the minimum real allocation being at least
  814. * a page.
  815. */
  816. vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
  817. uint32_t data_memslot, uint32_t pgd_memslot)
  818. {
  819. uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
  820. virt_pgd_alloc(vm, pgd_memslot);
  821. /* Find an unused range of virtual page addresses of at least
  822. * pages in length.
  823. */
  824. vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
  825. /* Map the virtual pages. */
  826. for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
  827. pages--, vaddr += vm->page_size) {
  828. vm_paddr_t paddr;
  829. paddr = vm_phy_page_alloc(vm, KVM_UTIL_MIN_PADDR, data_memslot);
  830. virt_pg_map(vm, vaddr, paddr, pgd_memslot);
  831. sparsebit_set(vm->vpages_mapped,
  832. vaddr >> vm->page_shift);
  833. }
  834. return vaddr_start;
  835. }
  836. /*
  837. * Map a range of VM virtual address to the VM's physical address
  838. *
  839. * Input Args:
  840. * vm - Virtual Machine
  841. * vaddr - Virtuall address to map
  842. * paddr - VM Physical Address
  843. * size - The size of the range to map
  844. * pgd_memslot - Memory region slot for new virtual translation tables
  845. *
  846. * Output Args: None
  847. *
  848. * Return: None
  849. *
  850. * Within the VM given by vm, creates a virtual translation for the
  851. * page range starting at vaddr to the page range starting at paddr.
  852. */
  853. void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
  854. size_t size, uint32_t pgd_memslot)
  855. {
  856. size_t page_size = vm->page_size;
  857. size_t npages = size / page_size;
  858. TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
  859. TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
  860. while (npages--) {
  861. virt_pg_map(vm, vaddr, paddr, pgd_memslot);
  862. vaddr += page_size;
  863. paddr += page_size;
  864. }
  865. }
  866. /* Address VM Physical to Host Virtual
  867. *
  868. * Input Args:
  869. * vm - Virtual Machine
  870. * gpa - VM physical address
  871. *
  872. * Output Args: None
  873. *
  874. * Return:
  875. * Equivalent host virtual address
  876. *
  877. * Locates the memory region containing the VM physical address given
  878. * by gpa, within the VM given by vm. When found, the host virtual
  879. * address providing the memory to the vm physical address is returned.
  880. * A TEST_ASSERT failure occurs if no region containing gpa exists.
  881. */
  882. void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
  883. {
  884. struct userspace_mem_region *region;
  885. for (region = vm->userspace_mem_region_head; region;
  886. region = region->next) {
  887. if ((gpa >= region->region.guest_phys_addr)
  888. && (gpa <= (region->region.guest_phys_addr
  889. + region->region.memory_size - 1)))
  890. return (void *) ((uintptr_t) region->host_mem
  891. + (gpa - region->region.guest_phys_addr));
  892. }
  893. TEST_ASSERT(false, "No vm physical memory at 0x%lx", gpa);
  894. return NULL;
  895. }
  896. /* Address Host Virtual to VM Physical
  897. *
  898. * Input Args:
  899. * vm - Virtual Machine
  900. * hva - Host virtual address
  901. *
  902. * Output Args: None
  903. *
  904. * Return:
  905. * Equivalent VM physical address
  906. *
  907. * Locates the memory region containing the host virtual address given
  908. * by hva, within the VM given by vm. When found, the equivalent
  909. * VM physical address is returned. A TEST_ASSERT failure occurs if no
  910. * region containing hva exists.
  911. */
  912. vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
  913. {
  914. struct userspace_mem_region *region;
  915. for (region = vm->userspace_mem_region_head; region;
  916. region = region->next) {
  917. if ((hva >= region->host_mem)
  918. && (hva <= (region->host_mem
  919. + region->region.memory_size - 1)))
  920. return (vm_paddr_t) ((uintptr_t)
  921. region->region.guest_phys_addr
  922. + (hva - (uintptr_t) region->host_mem));
  923. }
  924. TEST_ASSERT(false, "No mapping to a guest physical address, "
  925. "hva: %p", hva);
  926. return -1;
  927. }
  928. /* VM Create IRQ Chip
  929. *
  930. * Input Args:
  931. * vm - Virtual Machine
  932. *
  933. * Output Args: None
  934. *
  935. * Return: None
  936. *
  937. * Creates an interrupt controller chip for the VM specified by vm.
  938. */
  939. void vm_create_irqchip(struct kvm_vm *vm)
  940. {
  941. int ret;
  942. ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
  943. TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
  944. "rc: %i errno: %i", ret, errno);
  945. vm->has_irqchip = true;
  946. }
  947. /* VM VCPU State
  948. *
  949. * Input Args:
  950. * vm - Virtual Machine
  951. * vcpuid - VCPU ID
  952. *
  953. * Output Args: None
  954. *
  955. * Return:
  956. * Pointer to structure that describes the state of the VCPU.
  957. *
  958. * Locates and returns a pointer to a structure that describes the
  959. * state of the VCPU with the given vcpuid.
  960. */
  961. struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
  962. {
  963. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  964. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  965. return vcpu->state;
  966. }
  967. /* VM VCPU Run
  968. *
  969. * Input Args:
  970. * vm - Virtual Machine
  971. * vcpuid - VCPU ID
  972. *
  973. * Output Args: None
  974. *
  975. * Return: None
  976. *
  977. * Switch to executing the code for the VCPU given by vcpuid, within the VM
  978. * given by vm.
  979. */
  980. void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
  981. {
  982. int ret = _vcpu_run(vm, vcpuid);
  983. TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
  984. "rc: %i errno: %i", ret, errno);
  985. }
  986. int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
  987. {
  988. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  989. int rc;
  990. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  991. do {
  992. rc = ioctl(vcpu->fd, KVM_RUN, NULL);
  993. } while (rc == -1 && errno == EINTR);
  994. return rc;
  995. }
  996. /* VM VCPU Set MP State
  997. *
  998. * Input Args:
  999. * vm - Virtual Machine
  1000. * vcpuid - VCPU ID
  1001. * mp_state - mp_state to be set
  1002. *
  1003. * Output Args: None
  1004. *
  1005. * Return: None
  1006. *
  1007. * Sets the MP state of the VCPU given by vcpuid, to the state given
  1008. * by mp_state.
  1009. */
  1010. void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
  1011. struct kvm_mp_state *mp_state)
  1012. {
  1013. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1014. int ret;
  1015. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1016. ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
  1017. TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
  1018. "rc: %i errno: %i", ret, errno);
  1019. }
  1020. /* VM VCPU Regs Get
  1021. *
  1022. * Input Args:
  1023. * vm - Virtual Machine
  1024. * vcpuid - VCPU ID
  1025. *
  1026. * Output Args:
  1027. * regs - current state of VCPU regs
  1028. *
  1029. * Return: None
  1030. *
  1031. * Obtains the current register state for the VCPU specified by vcpuid
  1032. * and stores it at the location given by regs.
  1033. */
  1034. void vcpu_regs_get(struct kvm_vm *vm,
  1035. uint32_t vcpuid, struct kvm_regs *regs)
  1036. {
  1037. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1038. int ret;
  1039. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1040. /* Get the regs. */
  1041. ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
  1042. TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
  1043. ret, errno);
  1044. }
  1045. /* VM VCPU Regs Set
  1046. *
  1047. * Input Args:
  1048. * vm - Virtual Machine
  1049. * vcpuid - VCPU ID
  1050. * regs - Values to set VCPU regs to
  1051. *
  1052. * Output Args: None
  1053. *
  1054. * Return: None
  1055. *
  1056. * Sets the regs of the VCPU specified by vcpuid to the values
  1057. * given by regs.
  1058. */
  1059. void vcpu_regs_set(struct kvm_vm *vm,
  1060. uint32_t vcpuid, struct kvm_regs *regs)
  1061. {
  1062. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1063. int ret;
  1064. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1065. /* Set the regs. */
  1066. ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
  1067. TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
  1068. ret, errno);
  1069. }
  1070. void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
  1071. struct kvm_vcpu_events *events)
  1072. {
  1073. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1074. int ret;
  1075. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1076. /* Get the regs. */
  1077. ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
  1078. TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
  1079. ret, errno);
  1080. }
  1081. void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
  1082. struct kvm_vcpu_events *events)
  1083. {
  1084. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1085. int ret;
  1086. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1087. /* Set the regs. */
  1088. ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
  1089. TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
  1090. ret, errno);
  1091. }
  1092. /* VCPU Get MSR
  1093. *
  1094. * Input Args:
  1095. * vm - Virtual Machine
  1096. * vcpuid - VCPU ID
  1097. * msr_index - Index of MSR
  1098. *
  1099. * Output Args: None
  1100. *
  1101. * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
  1102. *
  1103. * Get value of MSR for VCPU.
  1104. */
  1105. uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
  1106. {
  1107. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1108. struct {
  1109. struct kvm_msrs header;
  1110. struct kvm_msr_entry entry;
  1111. } buffer = {};
  1112. int r;
  1113. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1114. buffer.header.nmsrs = 1;
  1115. buffer.entry.index = msr_index;
  1116. r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
  1117. TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
  1118. " rc: %i errno: %i", r, errno);
  1119. return buffer.entry.data;
  1120. }
  1121. /* VCPU Set MSR
  1122. *
  1123. * Input Args:
  1124. * vm - Virtual Machine
  1125. * vcpuid - VCPU ID
  1126. * msr_index - Index of MSR
  1127. * msr_value - New value of MSR
  1128. *
  1129. * Output Args: None
  1130. *
  1131. * Return: On success, nothing. On failure a TEST_ASSERT is produced.
  1132. *
  1133. * Set value of MSR for VCPU.
  1134. */
  1135. void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
  1136. uint64_t msr_value)
  1137. {
  1138. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1139. struct {
  1140. struct kvm_msrs header;
  1141. struct kvm_msr_entry entry;
  1142. } buffer = {};
  1143. int r;
  1144. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1145. memset(&buffer, 0, sizeof(buffer));
  1146. buffer.header.nmsrs = 1;
  1147. buffer.entry.index = msr_index;
  1148. buffer.entry.data = msr_value;
  1149. r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
  1150. TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
  1151. " rc: %i errno: %i", r, errno);
  1152. }
  1153. /* VM VCPU Args Set
  1154. *
  1155. * Input Args:
  1156. * vm - Virtual Machine
  1157. * vcpuid - VCPU ID
  1158. * num - number of arguments
  1159. * ... - arguments, each of type uint64_t
  1160. *
  1161. * Output Args: None
  1162. *
  1163. * Return: None
  1164. *
  1165. * Sets the first num function input arguments to the values
  1166. * given as variable args. Each of the variable args is expected to
  1167. * be of type uint64_t.
  1168. */
  1169. void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
  1170. {
  1171. va_list ap;
  1172. struct kvm_regs regs;
  1173. TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
  1174. " num: %u\n",
  1175. num);
  1176. va_start(ap, num);
  1177. vcpu_regs_get(vm, vcpuid, &regs);
  1178. if (num >= 1)
  1179. regs.rdi = va_arg(ap, uint64_t);
  1180. if (num >= 2)
  1181. regs.rsi = va_arg(ap, uint64_t);
  1182. if (num >= 3)
  1183. regs.rdx = va_arg(ap, uint64_t);
  1184. if (num >= 4)
  1185. regs.rcx = va_arg(ap, uint64_t);
  1186. if (num >= 5)
  1187. regs.r8 = va_arg(ap, uint64_t);
  1188. if (num >= 6)
  1189. regs.r9 = va_arg(ap, uint64_t);
  1190. vcpu_regs_set(vm, vcpuid, &regs);
  1191. va_end(ap);
  1192. }
  1193. /* VM VCPU System Regs Get
  1194. *
  1195. * Input Args:
  1196. * vm - Virtual Machine
  1197. * vcpuid - VCPU ID
  1198. *
  1199. * Output Args:
  1200. * sregs - current state of VCPU system regs
  1201. *
  1202. * Return: None
  1203. *
  1204. * Obtains the current system register state for the VCPU specified by
  1205. * vcpuid and stores it at the location given by sregs.
  1206. */
  1207. void vcpu_sregs_get(struct kvm_vm *vm,
  1208. uint32_t vcpuid, struct kvm_sregs *sregs)
  1209. {
  1210. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1211. int ret;
  1212. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1213. /* Get the regs. */
  1214. /* Get the regs. */
  1215. ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
  1216. TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
  1217. ret, errno);
  1218. }
  1219. /* VM VCPU System Regs Set
  1220. *
  1221. * Input Args:
  1222. * vm - Virtual Machine
  1223. * vcpuid - VCPU ID
  1224. * sregs - Values to set VCPU system regs to
  1225. *
  1226. * Output Args: None
  1227. *
  1228. * Return: None
  1229. *
  1230. * Sets the system regs of the VCPU specified by vcpuid to the values
  1231. * given by sregs.
  1232. */
  1233. void vcpu_sregs_set(struct kvm_vm *vm,
  1234. uint32_t vcpuid, struct kvm_sregs *sregs)
  1235. {
  1236. int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
  1237. TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
  1238. "rc: %i errno: %i", ret, errno);
  1239. }
  1240. int _vcpu_sregs_set(struct kvm_vm *vm,
  1241. uint32_t vcpuid, struct kvm_sregs *sregs)
  1242. {
  1243. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1244. int ret;
  1245. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1246. /* Get the regs. */
  1247. return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
  1248. }
  1249. /* VCPU Ioctl
  1250. *
  1251. * Input Args:
  1252. * vm - Virtual Machine
  1253. * vcpuid - VCPU ID
  1254. * cmd - Ioctl number
  1255. * arg - Argument to pass to the ioctl
  1256. *
  1257. * Return: None
  1258. *
  1259. * Issues an arbitrary ioctl on a VCPU fd.
  1260. */
  1261. void vcpu_ioctl(struct kvm_vm *vm,
  1262. uint32_t vcpuid, unsigned long cmd, void *arg)
  1263. {
  1264. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1265. int ret;
  1266. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1267. ret = ioctl(vcpu->fd, cmd, arg);
  1268. TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
  1269. cmd, ret, errno, strerror(errno));
  1270. }
  1271. /* VM Ioctl
  1272. *
  1273. * Input Args:
  1274. * vm - Virtual Machine
  1275. * cmd - Ioctl number
  1276. * arg - Argument to pass to the ioctl
  1277. *
  1278. * Return: None
  1279. *
  1280. * Issues an arbitrary ioctl on a VM fd.
  1281. */
  1282. void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
  1283. {
  1284. int ret;
  1285. ret = ioctl(vm->fd, cmd, arg);
  1286. TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
  1287. cmd, ret, errno, strerror(errno));
  1288. }
  1289. /* VM Dump
  1290. *
  1291. * Input Args:
  1292. * vm - Virtual Machine
  1293. * indent - Left margin indent amount
  1294. *
  1295. * Output Args:
  1296. * stream - Output FILE stream
  1297. *
  1298. * Return: None
  1299. *
  1300. * Dumps the current state of the VM given by vm, to the FILE stream
  1301. * given by stream.
  1302. */
  1303. void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
  1304. {
  1305. struct userspace_mem_region *region;
  1306. struct vcpu *vcpu;
  1307. fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
  1308. fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
  1309. fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
  1310. fprintf(stream, "%*sMem Regions:\n", indent, "");
  1311. for (region = vm->userspace_mem_region_head; region;
  1312. region = region->next) {
  1313. fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
  1314. "host_virt: %p\n", indent + 2, "",
  1315. (uint64_t) region->region.guest_phys_addr,
  1316. (uint64_t) region->region.memory_size,
  1317. region->host_mem);
  1318. fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
  1319. sparsebit_dump(stream, region->unused_phy_pages, 0);
  1320. }
  1321. fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
  1322. sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
  1323. fprintf(stream, "%*spgd_created: %u\n", indent, "",
  1324. vm->pgd_created);
  1325. if (vm->pgd_created) {
  1326. fprintf(stream, "%*sVirtual Translation Tables:\n",
  1327. indent + 2, "");
  1328. virt_dump(stream, vm, indent + 4);
  1329. }
  1330. fprintf(stream, "%*sVCPUs:\n", indent, "");
  1331. for (vcpu = vm->vcpu_head; vcpu; vcpu = vcpu->next)
  1332. vcpu_dump(stream, vm, vcpu->id, indent + 2);
  1333. }
  1334. /* VM VCPU Dump
  1335. *
  1336. * Input Args:
  1337. * vm - Virtual Machine
  1338. * vcpuid - VCPU ID
  1339. * indent - Left margin indent amount
  1340. *
  1341. * Output Args:
  1342. * stream - Output FILE stream
  1343. *
  1344. * Return: None
  1345. *
  1346. * Dumps the current state of the VCPU specified by vcpuid, within the VM
  1347. * given by vm, to the FILE stream given by stream.
  1348. */
  1349. void vcpu_dump(FILE *stream, struct kvm_vm *vm,
  1350. uint32_t vcpuid, uint8_t indent)
  1351. {
  1352. struct kvm_regs regs;
  1353. struct kvm_sregs sregs;
  1354. fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
  1355. fprintf(stream, "%*sregs:\n", indent + 2, "");
  1356. vcpu_regs_get(vm, vcpuid, &regs);
  1357. regs_dump(stream, &regs, indent + 4);
  1358. fprintf(stream, "%*ssregs:\n", indent + 2, "");
  1359. vcpu_sregs_get(vm, vcpuid, &sregs);
  1360. sregs_dump(stream, &sregs, indent + 4);
  1361. }
  1362. /* Known KVM exit reasons */
  1363. static struct exit_reason {
  1364. unsigned int reason;
  1365. const char *name;
  1366. } exit_reasons_known[] = {
  1367. {KVM_EXIT_UNKNOWN, "UNKNOWN"},
  1368. {KVM_EXIT_EXCEPTION, "EXCEPTION"},
  1369. {KVM_EXIT_IO, "IO"},
  1370. {KVM_EXIT_HYPERCALL, "HYPERCALL"},
  1371. {KVM_EXIT_DEBUG, "DEBUG"},
  1372. {KVM_EXIT_HLT, "HLT"},
  1373. {KVM_EXIT_MMIO, "MMIO"},
  1374. {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
  1375. {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
  1376. {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
  1377. {KVM_EXIT_INTR, "INTR"},
  1378. {KVM_EXIT_SET_TPR, "SET_TPR"},
  1379. {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
  1380. {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
  1381. {KVM_EXIT_S390_RESET, "S390_RESET"},
  1382. {KVM_EXIT_DCR, "DCR"},
  1383. {KVM_EXIT_NMI, "NMI"},
  1384. {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
  1385. {KVM_EXIT_OSI, "OSI"},
  1386. {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
  1387. #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
  1388. {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
  1389. #endif
  1390. };
  1391. /* Exit Reason String
  1392. *
  1393. * Input Args:
  1394. * exit_reason - Exit reason
  1395. *
  1396. * Output Args: None
  1397. *
  1398. * Return:
  1399. * Constant string pointer describing the exit reason.
  1400. *
  1401. * Locates and returns a constant string that describes the KVM exit
  1402. * reason given by exit_reason. If no such string is found, a constant
  1403. * string of "Unknown" is returned.
  1404. */
  1405. const char *exit_reason_str(unsigned int exit_reason)
  1406. {
  1407. unsigned int n1;
  1408. for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
  1409. if (exit_reason == exit_reasons_known[n1].reason)
  1410. return exit_reasons_known[n1].name;
  1411. }
  1412. return "Unknown";
  1413. }
  1414. /* Physical Page Allocate
  1415. *
  1416. * Input Args:
  1417. * vm - Virtual Machine
  1418. * paddr_min - Physical address minimum
  1419. * memslot - Memory region to allocate page from
  1420. *
  1421. * Output Args: None
  1422. *
  1423. * Return:
  1424. * Starting physical address
  1425. *
  1426. * Within the VM specified by vm, locates an available physical page
  1427. * at or above paddr_min. If found, the page is marked as in use
  1428. * and its address is returned. A TEST_ASSERT failure occurs if no
  1429. * page is available at or above paddr_min.
  1430. */
  1431. vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm,
  1432. vm_paddr_t paddr_min, uint32_t memslot)
  1433. {
  1434. struct userspace_mem_region *region;
  1435. sparsebit_idx_t pg;
  1436. TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
  1437. "not divisible by page size.\n"
  1438. " paddr_min: 0x%lx page_size: 0x%x",
  1439. paddr_min, vm->page_size);
  1440. /* Locate memory region. */
  1441. region = memslot2region(vm, memslot);
  1442. /* Locate next available physical page at or above paddr_min. */
  1443. pg = paddr_min >> vm->page_shift;
  1444. if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
  1445. pg = sparsebit_next_set(region->unused_phy_pages, pg);
  1446. if (pg == 0) {
  1447. fprintf(stderr, "No guest physical page available, "
  1448. "paddr_min: 0x%lx page_size: 0x%x memslot: %u",
  1449. paddr_min, vm->page_size, memslot);
  1450. fputs("---- vm dump ----\n", stderr);
  1451. vm_dump(stderr, vm, 2);
  1452. abort();
  1453. }
  1454. }
  1455. /* Specify page as in use and return its address. */
  1456. sparsebit_clear(region->unused_phy_pages, pg);
  1457. return pg * vm->page_size;
  1458. }
  1459. /* Address Guest Virtual to Host Virtual
  1460. *
  1461. * Input Args:
  1462. * vm - Virtual Machine
  1463. * gva - VM virtual address
  1464. *
  1465. * Output Args: None
  1466. *
  1467. * Return:
  1468. * Equivalent host virtual address
  1469. */
  1470. void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
  1471. {
  1472. return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
  1473. }
  1474. void guest_args_read(struct kvm_vm *vm, uint32_t vcpu_id,
  1475. struct guest_args *args)
  1476. {
  1477. struct kvm_run *run = vcpu_state(vm, vcpu_id);
  1478. struct kvm_regs regs;
  1479. memset(&regs, 0, sizeof(regs));
  1480. vcpu_regs_get(vm, vcpu_id, &regs);
  1481. args->port = run->io.port;
  1482. args->arg0 = regs.rdi;
  1483. args->arg1 = regs.rsi;
  1484. }