kvm_util.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  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);
  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. if ((guest_paddr <= (region->region.guest_phys_addr
  533. + region->region.memory_size))
  534. && ((guest_paddr + npages * vm->page_size)
  535. >= region->region.guest_phys_addr))
  536. break;
  537. }
  538. if (region != NULL)
  539. TEST_ASSERT(false, "A mem region with the requested slot "
  540. "or overlapping physical memory range already exists.\n"
  541. " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
  542. " existing slot: %u paddr: 0x%lx size: 0x%lx",
  543. slot, guest_paddr, npages,
  544. region->region.slot,
  545. (uint64_t) region->region.guest_phys_addr,
  546. (uint64_t) region->region.memory_size);
  547. /* Allocate and initialize new mem region structure. */
  548. region = calloc(1, sizeof(*region));
  549. TEST_ASSERT(region != NULL, "Insufficient Memory");
  550. region->mmap_size = npages * vm->page_size;
  551. /* Enough memory to align up to a huge page. */
  552. if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
  553. region->mmap_size += huge_page_size;
  554. region->mmap_start = mmap(NULL, region->mmap_size,
  555. PROT_READ | PROT_WRITE,
  556. MAP_PRIVATE | MAP_ANONYMOUS
  557. | (src_type == VM_MEM_SRC_ANONYMOUS_HUGETLB ? MAP_HUGETLB : 0),
  558. -1, 0);
  559. TEST_ASSERT(region->mmap_start != MAP_FAILED,
  560. "test_malloc failed, mmap_start: %p errno: %i",
  561. region->mmap_start, errno);
  562. /* Align THP allocation up to start of a huge page. */
  563. region->host_mem = align(region->mmap_start,
  564. src_type == VM_MEM_SRC_ANONYMOUS_THP ? huge_page_size : 1);
  565. /* As needed perform madvise */
  566. if (src_type == VM_MEM_SRC_ANONYMOUS || src_type == VM_MEM_SRC_ANONYMOUS_THP) {
  567. ret = madvise(region->host_mem, npages * vm->page_size,
  568. src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
  569. TEST_ASSERT(ret == 0, "madvise failed,\n"
  570. " addr: %p\n"
  571. " length: 0x%lx\n"
  572. " src_type: %x",
  573. region->host_mem, npages * vm->page_size, src_type);
  574. }
  575. region->unused_phy_pages = sparsebit_alloc();
  576. sparsebit_set_num(region->unused_phy_pages,
  577. guest_paddr >> vm->page_shift, npages);
  578. region->region.slot = slot;
  579. region->region.flags = flags;
  580. region->region.guest_phys_addr = guest_paddr;
  581. region->region.memory_size = npages * vm->page_size;
  582. region->region.userspace_addr = (uintptr_t) region->host_mem;
  583. ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
  584. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
  585. " rc: %i errno: %i\n"
  586. " slot: %u flags: 0x%x\n"
  587. " guest_phys_addr: 0x%lx size: 0x%lx",
  588. ret, errno, slot, flags,
  589. guest_paddr, (uint64_t) region->region.memory_size);
  590. /* Add to linked-list of memory regions. */
  591. if (vm->userspace_mem_region_head)
  592. vm->userspace_mem_region_head->prev = region;
  593. region->next = vm->userspace_mem_region_head;
  594. vm->userspace_mem_region_head = region;
  595. }
  596. /* Memslot to region
  597. *
  598. * Input Args:
  599. * vm - Virtual Machine
  600. * memslot - KVM memory slot ID
  601. *
  602. * Output Args: None
  603. *
  604. * Return:
  605. * Pointer to memory region structure that describe memory region
  606. * using kvm memory slot ID given by memslot. TEST_ASSERT failure
  607. * on error (e.g. currently no memory region using memslot as a KVM
  608. * memory slot ID).
  609. */
  610. static struct userspace_mem_region *memslot2region(struct kvm_vm *vm,
  611. uint32_t memslot)
  612. {
  613. struct userspace_mem_region *region;
  614. for (region = vm->userspace_mem_region_head; region;
  615. region = region->next) {
  616. if (region->region.slot == memslot)
  617. break;
  618. }
  619. if (region == NULL) {
  620. fprintf(stderr, "No mem region with the requested slot found,\n"
  621. " requested slot: %u\n", memslot);
  622. fputs("---- vm dump ----\n", stderr);
  623. vm_dump(stderr, vm, 2);
  624. TEST_ASSERT(false, "Mem region not found");
  625. }
  626. return region;
  627. }
  628. /* VM Memory Region Flags Set
  629. *
  630. * Input Args:
  631. * vm - Virtual Machine
  632. * flags - Starting guest physical address
  633. *
  634. * Output Args: None
  635. *
  636. * Return: None
  637. *
  638. * Sets the flags of the memory region specified by the value of slot,
  639. * to the values given by flags.
  640. */
  641. void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
  642. {
  643. int ret;
  644. struct userspace_mem_region *region;
  645. /* Locate memory region. */
  646. region = memslot2region(vm, slot);
  647. region->region.flags = flags;
  648. ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
  649. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
  650. " rc: %i errno: %i slot: %u flags: 0x%x",
  651. ret, errno, slot, flags);
  652. }
  653. /* VCPU mmap Size
  654. *
  655. * Input Args: None
  656. *
  657. * Output Args: None
  658. *
  659. * Return:
  660. * Size of VCPU state
  661. *
  662. * Returns the size of the structure pointed to by the return value
  663. * of vcpu_state().
  664. */
  665. static int vcpu_mmap_sz(void)
  666. {
  667. int dev_fd, ret;
  668. dev_fd = open(KVM_DEV_PATH, O_RDONLY);
  669. if (dev_fd < 0)
  670. exit(KSFT_SKIP);
  671. ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
  672. TEST_ASSERT(ret >= sizeof(struct kvm_run),
  673. "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
  674. __func__, ret, errno);
  675. close(dev_fd);
  676. return ret;
  677. }
  678. /* VM VCPU Add
  679. *
  680. * Input Args:
  681. * vm - Virtual Machine
  682. * vcpuid - VCPU ID
  683. *
  684. * Output Args: None
  685. *
  686. * Return: None
  687. *
  688. * Creates and adds to the VM specified by vm and virtual CPU with
  689. * the ID given by vcpuid.
  690. */
  691. void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_memslot)
  692. {
  693. struct vcpu *vcpu;
  694. /* Confirm a vcpu with the specified id doesn't already exist. */
  695. vcpu = vcpu_find(vm, vcpuid);
  696. if (vcpu != NULL)
  697. TEST_ASSERT(false, "vcpu with the specified id "
  698. "already exists,\n"
  699. " requested vcpuid: %u\n"
  700. " existing vcpuid: %u state: %p",
  701. vcpuid, vcpu->id, vcpu->state);
  702. /* Allocate and initialize new vcpu structure. */
  703. vcpu = calloc(1, sizeof(*vcpu));
  704. TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
  705. vcpu->id = vcpuid;
  706. vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
  707. TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
  708. vcpu->fd, errno);
  709. TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
  710. "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
  711. vcpu_mmap_sz(), sizeof(*vcpu->state));
  712. vcpu->state = (struct kvm_run *) mmap(NULL, sizeof(*vcpu->state),
  713. PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
  714. TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
  715. "vcpu id: %u errno: %i", vcpuid, errno);
  716. /* Add to linked-list of VCPUs. */
  717. if (vm->vcpu_head)
  718. vm->vcpu_head->prev = vcpu;
  719. vcpu->next = vm->vcpu_head;
  720. vm->vcpu_head = vcpu;
  721. vcpu_setup(vm, vcpuid, pgd_memslot, gdt_memslot);
  722. }
  723. /* VM Virtual Address Unused Gap
  724. *
  725. * Input Args:
  726. * vm - Virtual Machine
  727. * sz - Size (bytes)
  728. * vaddr_min - Minimum Virtual Address
  729. *
  730. * Output Args: None
  731. *
  732. * Return:
  733. * Lowest virtual address at or below vaddr_min, with at least
  734. * sz unused bytes. TEST_ASSERT failure if no area of at least
  735. * size sz is available.
  736. *
  737. * Within the VM specified by vm, locates the lowest starting virtual
  738. * address >= vaddr_min, that has at least sz unallocated bytes. A
  739. * TEST_ASSERT failure occurs for invalid input or no area of at least
  740. * sz unallocated bytes >= vaddr_min is available.
  741. */
  742. static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
  743. vm_vaddr_t vaddr_min)
  744. {
  745. uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
  746. /* Determine lowest permitted virtual page index. */
  747. uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
  748. if ((pgidx_start * vm->page_size) < vaddr_min)
  749. goto no_va_found;
  750. /* Loop over section with enough valid virtual page indexes. */
  751. if (!sparsebit_is_set_num(vm->vpages_valid,
  752. pgidx_start, pages))
  753. pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
  754. pgidx_start, pages);
  755. do {
  756. /*
  757. * Are there enough unused virtual pages available at
  758. * the currently proposed starting virtual page index.
  759. * If not, adjust proposed starting index to next
  760. * possible.
  761. */
  762. if (sparsebit_is_clear_num(vm->vpages_mapped,
  763. pgidx_start, pages))
  764. goto va_found;
  765. pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
  766. pgidx_start, pages);
  767. if (pgidx_start == 0)
  768. goto no_va_found;
  769. /*
  770. * If needed, adjust proposed starting virtual address,
  771. * to next range of valid virtual addresses.
  772. */
  773. if (!sparsebit_is_set_num(vm->vpages_valid,
  774. pgidx_start, pages)) {
  775. pgidx_start = sparsebit_next_set_num(
  776. vm->vpages_valid, pgidx_start, pages);
  777. if (pgidx_start == 0)
  778. goto no_va_found;
  779. }
  780. } while (pgidx_start != 0);
  781. no_va_found:
  782. TEST_ASSERT(false, "No vaddr of specified pages available, "
  783. "pages: 0x%lx", pages);
  784. /* NOT REACHED */
  785. return -1;
  786. va_found:
  787. TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
  788. pgidx_start, pages),
  789. "Unexpected, invalid virtual page index range,\n"
  790. " pgidx_start: 0x%lx\n"
  791. " pages: 0x%lx",
  792. pgidx_start, pages);
  793. TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
  794. pgidx_start, pages),
  795. "Unexpected, pages already mapped,\n"
  796. " pgidx_start: 0x%lx\n"
  797. " pages: 0x%lx",
  798. pgidx_start, pages);
  799. return pgidx_start * vm->page_size;
  800. }
  801. /* VM Virtual Address Allocate
  802. *
  803. * Input Args:
  804. * vm - Virtual Machine
  805. * sz - Size in bytes
  806. * vaddr_min - Minimum starting virtual address
  807. * data_memslot - Memory region slot for data pages
  808. * pgd_memslot - Memory region slot for new virtual translation tables
  809. *
  810. * Output Args: None
  811. *
  812. * Return:
  813. * Starting guest virtual address
  814. *
  815. * Allocates at least sz bytes within the virtual address space of the vm
  816. * given by vm. The allocated bytes are mapped to a virtual address >=
  817. * the address given by vaddr_min. Note that each allocation uses a
  818. * a unique set of pages, with the minimum real allocation being at least
  819. * a page.
  820. */
  821. vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
  822. uint32_t data_memslot, uint32_t pgd_memslot)
  823. {
  824. uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
  825. virt_pgd_alloc(vm, pgd_memslot);
  826. /* Find an unused range of virtual page addresses of at least
  827. * pages in length.
  828. */
  829. vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
  830. /* Map the virtual pages. */
  831. for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
  832. pages--, vaddr += vm->page_size) {
  833. vm_paddr_t paddr;
  834. paddr = vm_phy_page_alloc(vm, KVM_UTIL_MIN_PADDR, data_memslot);
  835. virt_pg_map(vm, vaddr, paddr, pgd_memslot);
  836. sparsebit_set(vm->vpages_mapped,
  837. vaddr >> vm->page_shift);
  838. }
  839. return vaddr_start;
  840. }
  841. /*
  842. * Map a range of VM virtual address to the VM's physical address
  843. *
  844. * Input Args:
  845. * vm - Virtual Machine
  846. * vaddr - Virtuall address to map
  847. * paddr - VM Physical Address
  848. * size - The size of the range to map
  849. * pgd_memslot - Memory region slot for new virtual translation tables
  850. *
  851. * Output Args: None
  852. *
  853. * Return: None
  854. *
  855. * Within the VM given by vm, creates a virtual translation for the
  856. * page range starting at vaddr to the page range starting at paddr.
  857. */
  858. void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
  859. size_t size, uint32_t pgd_memslot)
  860. {
  861. size_t page_size = vm->page_size;
  862. size_t npages = size / page_size;
  863. TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
  864. TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
  865. while (npages--) {
  866. virt_pg_map(vm, vaddr, paddr, pgd_memslot);
  867. vaddr += page_size;
  868. paddr += page_size;
  869. }
  870. }
  871. /* Address VM Physical to Host Virtual
  872. *
  873. * Input Args:
  874. * vm - Virtual Machine
  875. * gpa - VM physical address
  876. *
  877. * Output Args: None
  878. *
  879. * Return:
  880. * Equivalent host virtual address
  881. *
  882. * Locates the memory region containing the VM physical address given
  883. * by gpa, within the VM given by vm. When found, the host virtual
  884. * address providing the memory to the vm physical address is returned.
  885. * A TEST_ASSERT failure occurs if no region containing gpa exists.
  886. */
  887. void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
  888. {
  889. struct userspace_mem_region *region;
  890. for (region = vm->userspace_mem_region_head; region;
  891. region = region->next) {
  892. if ((gpa >= region->region.guest_phys_addr)
  893. && (gpa <= (region->region.guest_phys_addr
  894. + region->region.memory_size - 1)))
  895. return (void *) ((uintptr_t) region->host_mem
  896. + (gpa - region->region.guest_phys_addr));
  897. }
  898. TEST_ASSERT(false, "No vm physical memory at 0x%lx", gpa);
  899. return NULL;
  900. }
  901. /* Address Host Virtual to VM Physical
  902. *
  903. * Input Args:
  904. * vm - Virtual Machine
  905. * hva - Host virtual address
  906. *
  907. * Output Args: None
  908. *
  909. * Return:
  910. * Equivalent VM physical address
  911. *
  912. * Locates the memory region containing the host virtual address given
  913. * by hva, within the VM given by vm. When found, the equivalent
  914. * VM physical address is returned. A TEST_ASSERT failure occurs if no
  915. * region containing hva exists.
  916. */
  917. vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
  918. {
  919. struct userspace_mem_region *region;
  920. for (region = vm->userspace_mem_region_head; region;
  921. region = region->next) {
  922. if ((hva >= region->host_mem)
  923. && (hva <= (region->host_mem
  924. + region->region.memory_size - 1)))
  925. return (vm_paddr_t) ((uintptr_t)
  926. region->region.guest_phys_addr
  927. + (hva - (uintptr_t) region->host_mem));
  928. }
  929. TEST_ASSERT(false, "No mapping to a guest physical address, "
  930. "hva: %p", hva);
  931. return -1;
  932. }
  933. /* VM Create IRQ Chip
  934. *
  935. * Input Args:
  936. * vm - Virtual Machine
  937. *
  938. * Output Args: None
  939. *
  940. * Return: None
  941. *
  942. * Creates an interrupt controller chip for the VM specified by vm.
  943. */
  944. void vm_create_irqchip(struct kvm_vm *vm)
  945. {
  946. int ret;
  947. ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
  948. TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
  949. "rc: %i errno: %i", ret, errno);
  950. vm->has_irqchip = true;
  951. }
  952. /* VM VCPU State
  953. *
  954. * Input Args:
  955. * vm - Virtual Machine
  956. * vcpuid - VCPU ID
  957. *
  958. * Output Args: None
  959. *
  960. * Return:
  961. * Pointer to structure that describes the state of the VCPU.
  962. *
  963. * Locates and returns a pointer to a structure that describes the
  964. * state of the VCPU with the given vcpuid.
  965. */
  966. struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
  967. {
  968. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  969. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  970. return vcpu->state;
  971. }
  972. /* VM VCPU Run
  973. *
  974. * Input Args:
  975. * vm - Virtual Machine
  976. * vcpuid - VCPU ID
  977. *
  978. * Output Args: None
  979. *
  980. * Return: None
  981. *
  982. * Switch to executing the code for the VCPU given by vcpuid, within the VM
  983. * given by vm.
  984. */
  985. void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
  986. {
  987. int ret = _vcpu_run(vm, vcpuid);
  988. TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
  989. "rc: %i errno: %i", ret, errno);
  990. }
  991. int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
  992. {
  993. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  994. int rc;
  995. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  996. do {
  997. rc = ioctl(vcpu->fd, KVM_RUN, NULL);
  998. } while (rc == -1 && errno == EINTR);
  999. return rc;
  1000. }
  1001. /* VM VCPU Set MP State
  1002. *
  1003. * Input Args:
  1004. * vm - Virtual Machine
  1005. * vcpuid - VCPU ID
  1006. * mp_state - mp_state to be set
  1007. *
  1008. * Output Args: None
  1009. *
  1010. * Return: None
  1011. *
  1012. * Sets the MP state of the VCPU given by vcpuid, to the state given
  1013. * by mp_state.
  1014. */
  1015. void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
  1016. struct kvm_mp_state *mp_state)
  1017. {
  1018. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1019. int ret;
  1020. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1021. ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
  1022. TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
  1023. "rc: %i errno: %i", ret, errno);
  1024. }
  1025. /* VM VCPU Regs Get
  1026. *
  1027. * Input Args:
  1028. * vm - Virtual Machine
  1029. * vcpuid - VCPU ID
  1030. *
  1031. * Output Args:
  1032. * regs - current state of VCPU regs
  1033. *
  1034. * Return: None
  1035. *
  1036. * Obtains the current register state for the VCPU specified by vcpuid
  1037. * and stores it at the location given by regs.
  1038. */
  1039. void vcpu_regs_get(struct kvm_vm *vm,
  1040. uint32_t vcpuid, struct kvm_regs *regs)
  1041. {
  1042. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1043. int ret;
  1044. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1045. /* Get the regs. */
  1046. ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
  1047. TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
  1048. ret, errno);
  1049. }
  1050. /* VM VCPU Regs Set
  1051. *
  1052. * Input Args:
  1053. * vm - Virtual Machine
  1054. * vcpuid - VCPU ID
  1055. * regs - Values to set VCPU regs to
  1056. *
  1057. * Output Args: None
  1058. *
  1059. * Return: None
  1060. *
  1061. * Sets the regs of the VCPU specified by vcpuid to the values
  1062. * given by regs.
  1063. */
  1064. void vcpu_regs_set(struct kvm_vm *vm,
  1065. uint32_t vcpuid, struct kvm_regs *regs)
  1066. {
  1067. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1068. int ret;
  1069. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1070. /* Set the regs. */
  1071. ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
  1072. TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
  1073. ret, errno);
  1074. }
  1075. void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
  1076. struct kvm_vcpu_events *events)
  1077. {
  1078. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1079. int ret;
  1080. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1081. /* Get the regs. */
  1082. ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
  1083. TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
  1084. ret, errno);
  1085. }
  1086. void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
  1087. struct kvm_vcpu_events *events)
  1088. {
  1089. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1090. int ret;
  1091. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1092. /* Set the regs. */
  1093. ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
  1094. TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
  1095. ret, errno);
  1096. }
  1097. /* VCPU Get MSR
  1098. *
  1099. * Input Args:
  1100. * vm - Virtual Machine
  1101. * vcpuid - VCPU ID
  1102. * msr_index - Index of MSR
  1103. *
  1104. * Output Args: None
  1105. *
  1106. * Return: On success, value of the MSR. On failure a TEST_ASSERT is produced.
  1107. *
  1108. * Get value of MSR for VCPU.
  1109. */
  1110. uint64_t vcpu_get_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index)
  1111. {
  1112. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1113. struct {
  1114. struct kvm_msrs header;
  1115. struct kvm_msr_entry entry;
  1116. } buffer = {};
  1117. int r;
  1118. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1119. buffer.header.nmsrs = 1;
  1120. buffer.entry.index = msr_index;
  1121. r = ioctl(vcpu->fd, KVM_GET_MSRS, &buffer.header);
  1122. TEST_ASSERT(r == 1, "KVM_GET_MSRS IOCTL failed,\n"
  1123. " rc: %i errno: %i", r, errno);
  1124. return buffer.entry.data;
  1125. }
  1126. /* VCPU Set MSR
  1127. *
  1128. * Input Args:
  1129. * vm - Virtual Machine
  1130. * vcpuid - VCPU ID
  1131. * msr_index - Index of MSR
  1132. * msr_value - New value of MSR
  1133. *
  1134. * Output Args: None
  1135. *
  1136. * Return: On success, nothing. On failure a TEST_ASSERT is produced.
  1137. *
  1138. * Set value of MSR for VCPU.
  1139. */
  1140. void vcpu_set_msr(struct kvm_vm *vm, uint32_t vcpuid, uint64_t msr_index,
  1141. uint64_t msr_value)
  1142. {
  1143. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1144. struct {
  1145. struct kvm_msrs header;
  1146. struct kvm_msr_entry entry;
  1147. } buffer = {};
  1148. int r;
  1149. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1150. memset(&buffer, 0, sizeof(buffer));
  1151. buffer.header.nmsrs = 1;
  1152. buffer.entry.index = msr_index;
  1153. buffer.entry.data = msr_value;
  1154. r = ioctl(vcpu->fd, KVM_SET_MSRS, &buffer.header);
  1155. TEST_ASSERT(r == 1, "KVM_SET_MSRS IOCTL failed,\n"
  1156. " rc: %i errno: %i", r, errno);
  1157. }
  1158. /* VM VCPU Args Set
  1159. *
  1160. * Input Args:
  1161. * vm - Virtual Machine
  1162. * vcpuid - VCPU ID
  1163. * num - number of arguments
  1164. * ... - arguments, each of type uint64_t
  1165. *
  1166. * Output Args: None
  1167. *
  1168. * Return: None
  1169. *
  1170. * Sets the first num function input arguments to the values
  1171. * given as variable args. Each of the variable args is expected to
  1172. * be of type uint64_t.
  1173. */
  1174. void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
  1175. {
  1176. va_list ap;
  1177. struct kvm_regs regs;
  1178. TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
  1179. " num: %u\n",
  1180. num);
  1181. va_start(ap, num);
  1182. vcpu_regs_get(vm, vcpuid, &regs);
  1183. if (num >= 1)
  1184. regs.rdi = va_arg(ap, uint64_t);
  1185. if (num >= 2)
  1186. regs.rsi = va_arg(ap, uint64_t);
  1187. if (num >= 3)
  1188. regs.rdx = va_arg(ap, uint64_t);
  1189. if (num >= 4)
  1190. regs.rcx = va_arg(ap, uint64_t);
  1191. if (num >= 5)
  1192. regs.r8 = va_arg(ap, uint64_t);
  1193. if (num >= 6)
  1194. regs.r9 = va_arg(ap, uint64_t);
  1195. vcpu_regs_set(vm, vcpuid, &regs);
  1196. va_end(ap);
  1197. }
  1198. /* VM VCPU System Regs Get
  1199. *
  1200. * Input Args:
  1201. * vm - Virtual Machine
  1202. * vcpuid - VCPU ID
  1203. *
  1204. * Output Args:
  1205. * sregs - current state of VCPU system regs
  1206. *
  1207. * Return: None
  1208. *
  1209. * Obtains the current system register state for the VCPU specified by
  1210. * vcpuid and stores it at the location given by sregs.
  1211. */
  1212. void vcpu_sregs_get(struct kvm_vm *vm,
  1213. uint32_t vcpuid, struct kvm_sregs *sregs)
  1214. {
  1215. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1216. int ret;
  1217. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1218. /* Get the regs. */
  1219. /* Get the regs. */
  1220. ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
  1221. TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
  1222. ret, errno);
  1223. }
  1224. /* VM VCPU System Regs Set
  1225. *
  1226. * Input Args:
  1227. * vm - Virtual Machine
  1228. * vcpuid - VCPU ID
  1229. * sregs - Values to set VCPU system regs to
  1230. *
  1231. * Output Args: None
  1232. *
  1233. * Return: None
  1234. *
  1235. * Sets the system regs of the VCPU specified by vcpuid to the values
  1236. * given by sregs.
  1237. */
  1238. void vcpu_sregs_set(struct kvm_vm *vm,
  1239. uint32_t vcpuid, struct kvm_sregs *sregs)
  1240. {
  1241. int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
  1242. TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
  1243. "rc: %i errno: %i", ret, errno);
  1244. }
  1245. int _vcpu_sregs_set(struct kvm_vm *vm,
  1246. uint32_t vcpuid, struct kvm_sregs *sregs)
  1247. {
  1248. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1249. int ret;
  1250. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1251. /* Get the regs. */
  1252. return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
  1253. }
  1254. /* VCPU Ioctl
  1255. *
  1256. * Input Args:
  1257. * vm - Virtual Machine
  1258. * vcpuid - VCPU ID
  1259. * cmd - Ioctl number
  1260. * arg - Argument to pass to the ioctl
  1261. *
  1262. * Return: None
  1263. *
  1264. * Issues an arbitrary ioctl on a VCPU fd.
  1265. */
  1266. void vcpu_ioctl(struct kvm_vm *vm,
  1267. uint32_t vcpuid, unsigned long cmd, void *arg)
  1268. {
  1269. struct vcpu *vcpu = vcpu_find(vm, vcpuid);
  1270. int ret;
  1271. TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
  1272. ret = ioctl(vcpu->fd, cmd, arg);
  1273. TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
  1274. cmd, ret, errno, strerror(errno));
  1275. }
  1276. /* VM Ioctl
  1277. *
  1278. * Input Args:
  1279. * vm - Virtual Machine
  1280. * cmd - Ioctl number
  1281. * arg - Argument to pass to the ioctl
  1282. *
  1283. * Return: None
  1284. *
  1285. * Issues an arbitrary ioctl on a VM fd.
  1286. */
  1287. void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
  1288. {
  1289. int ret;
  1290. ret = ioctl(vm->fd, cmd, arg);
  1291. TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
  1292. cmd, ret, errno, strerror(errno));
  1293. }
  1294. /* VM Dump
  1295. *
  1296. * Input Args:
  1297. * vm - Virtual Machine
  1298. * indent - Left margin indent amount
  1299. *
  1300. * Output Args:
  1301. * stream - Output FILE stream
  1302. *
  1303. * Return: None
  1304. *
  1305. * Dumps the current state of the VM given by vm, to the FILE stream
  1306. * given by stream.
  1307. */
  1308. void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
  1309. {
  1310. struct userspace_mem_region *region;
  1311. struct vcpu *vcpu;
  1312. fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
  1313. fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
  1314. fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
  1315. fprintf(stream, "%*sMem Regions:\n", indent, "");
  1316. for (region = vm->userspace_mem_region_head; region;
  1317. region = region->next) {
  1318. fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
  1319. "host_virt: %p\n", indent + 2, "",
  1320. (uint64_t) region->region.guest_phys_addr,
  1321. (uint64_t) region->region.memory_size,
  1322. region->host_mem);
  1323. fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
  1324. sparsebit_dump(stream, region->unused_phy_pages, 0);
  1325. }
  1326. fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
  1327. sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
  1328. fprintf(stream, "%*spgd_created: %u\n", indent, "",
  1329. vm->pgd_created);
  1330. if (vm->pgd_created) {
  1331. fprintf(stream, "%*sVirtual Translation Tables:\n",
  1332. indent + 2, "");
  1333. virt_dump(stream, vm, indent + 4);
  1334. }
  1335. fprintf(stream, "%*sVCPUs:\n", indent, "");
  1336. for (vcpu = vm->vcpu_head; vcpu; vcpu = vcpu->next)
  1337. vcpu_dump(stream, vm, vcpu->id, indent + 2);
  1338. }
  1339. /* VM VCPU Dump
  1340. *
  1341. * Input Args:
  1342. * vm - Virtual Machine
  1343. * vcpuid - VCPU ID
  1344. * indent - Left margin indent amount
  1345. *
  1346. * Output Args:
  1347. * stream - Output FILE stream
  1348. *
  1349. * Return: None
  1350. *
  1351. * Dumps the current state of the VCPU specified by vcpuid, within the VM
  1352. * given by vm, to the FILE stream given by stream.
  1353. */
  1354. void vcpu_dump(FILE *stream, struct kvm_vm *vm,
  1355. uint32_t vcpuid, uint8_t indent)
  1356. {
  1357. struct kvm_regs regs;
  1358. struct kvm_sregs sregs;
  1359. fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
  1360. fprintf(stream, "%*sregs:\n", indent + 2, "");
  1361. vcpu_regs_get(vm, vcpuid, &regs);
  1362. regs_dump(stream, &regs, indent + 4);
  1363. fprintf(stream, "%*ssregs:\n", indent + 2, "");
  1364. vcpu_sregs_get(vm, vcpuid, &sregs);
  1365. sregs_dump(stream, &sregs, indent + 4);
  1366. }
  1367. /* Known KVM exit reasons */
  1368. static struct exit_reason {
  1369. unsigned int reason;
  1370. const char *name;
  1371. } exit_reasons_known[] = {
  1372. {KVM_EXIT_UNKNOWN, "UNKNOWN"},
  1373. {KVM_EXIT_EXCEPTION, "EXCEPTION"},
  1374. {KVM_EXIT_IO, "IO"},
  1375. {KVM_EXIT_HYPERCALL, "HYPERCALL"},
  1376. {KVM_EXIT_DEBUG, "DEBUG"},
  1377. {KVM_EXIT_HLT, "HLT"},
  1378. {KVM_EXIT_MMIO, "MMIO"},
  1379. {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
  1380. {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
  1381. {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
  1382. {KVM_EXIT_INTR, "INTR"},
  1383. {KVM_EXIT_SET_TPR, "SET_TPR"},
  1384. {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
  1385. {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
  1386. {KVM_EXIT_S390_RESET, "S390_RESET"},
  1387. {KVM_EXIT_DCR, "DCR"},
  1388. {KVM_EXIT_NMI, "NMI"},
  1389. {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
  1390. {KVM_EXIT_OSI, "OSI"},
  1391. {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
  1392. #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
  1393. {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
  1394. #endif
  1395. };
  1396. /* Exit Reason String
  1397. *
  1398. * Input Args:
  1399. * exit_reason - Exit reason
  1400. *
  1401. * Output Args: None
  1402. *
  1403. * Return:
  1404. * Constant string pointer describing the exit reason.
  1405. *
  1406. * Locates and returns a constant string that describes the KVM exit
  1407. * reason given by exit_reason. If no such string is found, a constant
  1408. * string of "Unknown" is returned.
  1409. */
  1410. const char *exit_reason_str(unsigned int exit_reason)
  1411. {
  1412. unsigned int n1;
  1413. for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
  1414. if (exit_reason == exit_reasons_known[n1].reason)
  1415. return exit_reasons_known[n1].name;
  1416. }
  1417. return "Unknown";
  1418. }
  1419. /* Physical Page Allocate
  1420. *
  1421. * Input Args:
  1422. * vm - Virtual Machine
  1423. * paddr_min - Physical address minimum
  1424. * memslot - Memory region to allocate page from
  1425. *
  1426. * Output Args: None
  1427. *
  1428. * Return:
  1429. * Starting physical address
  1430. *
  1431. * Within the VM specified by vm, locates an available physical page
  1432. * at or above paddr_min. If found, the page is marked as in use
  1433. * and its address is returned. A TEST_ASSERT failure occurs if no
  1434. * page is available at or above paddr_min.
  1435. */
  1436. vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm,
  1437. vm_paddr_t paddr_min, uint32_t memslot)
  1438. {
  1439. struct userspace_mem_region *region;
  1440. sparsebit_idx_t pg;
  1441. TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
  1442. "not divisible by page size.\n"
  1443. " paddr_min: 0x%lx page_size: 0x%x",
  1444. paddr_min, vm->page_size);
  1445. /* Locate memory region. */
  1446. region = memslot2region(vm, memslot);
  1447. /* Locate next available physical page at or above paddr_min. */
  1448. pg = paddr_min >> vm->page_shift;
  1449. if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
  1450. pg = sparsebit_next_set(region->unused_phy_pages, pg);
  1451. if (pg == 0) {
  1452. fprintf(stderr, "No guest physical page available, "
  1453. "paddr_min: 0x%lx page_size: 0x%x memslot: %u",
  1454. paddr_min, vm->page_size, memslot);
  1455. fputs("---- vm dump ----\n", stderr);
  1456. vm_dump(stderr, vm, 2);
  1457. abort();
  1458. }
  1459. }
  1460. /* Specify page as in use and return its address. */
  1461. sparsebit_clear(region->unused_phy_pages, pg);
  1462. return pg * vm->page_size;
  1463. }
  1464. /* Address Guest Virtual to Host Virtual
  1465. *
  1466. * Input Args:
  1467. * vm - Virtual Machine
  1468. * gva - VM virtual address
  1469. *
  1470. * Output Args: None
  1471. *
  1472. * Return:
  1473. * Equivalent host virtual address
  1474. */
  1475. void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
  1476. {
  1477. return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
  1478. }
  1479. void guest_args_read(struct kvm_vm *vm, uint32_t vcpu_id,
  1480. struct guest_args *args)
  1481. {
  1482. struct kvm_run *run = vcpu_state(vm, vcpu_id);
  1483. struct kvm_regs regs;
  1484. memset(&regs, 0, sizeof(regs));
  1485. vcpu_regs_get(vm, vcpu_id, &regs);
  1486. args->port = run->io.port;
  1487. args->arg0 = regs.rdi;
  1488. args->arg1 = regs.rsi;
  1489. }