kvm_util.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * tools/testing/selftests/kvm/lib/kvm_util.c
  4. *
  5. * Copyright (C) 2018, Google LLC.
  6. */
  7. #include "test_util.h"
  8. #include "kvm_util.h"
  9. #include "processor.h"
  10. #include "ucall_common.h"
  11. #include <assert.h>
  12. #include <sched.h>
  13. #include <sys/mman.h>
  14. #include <sys/resource.h>
  15. #include <sys/types.h>
  16. #include <sys/stat.h>
  17. #include <unistd.h>
  18. #include <linux/kernel.h>
  19. #define KVM_UTIL_MIN_PFN 2
  20. uint32_t guest_random_seed;
  21. struct guest_random_state guest_rng;
  22. static uint32_t last_guest_seed;
  23. static size_t vcpu_mmap_sz(void);
  24. int __open_path_or_exit(const char *path, int flags, const char *enoent_help)
  25. {
  26. int fd;
  27. fd = open(path, flags);
  28. if (fd < 0)
  29. goto error;
  30. return fd;
  31. error:
  32. if (errno == EACCES || errno == ENOENT)
  33. ksft_exit_skip("- Cannot open '%s': %s. %s\n",
  34. path, strerror(errno),
  35. errno == EACCES ? "Root required?" : enoent_help);
  36. TEST_FAIL("Failed to open '%s'", path);
  37. }
  38. int open_path_or_exit(const char *path, int flags)
  39. {
  40. return __open_path_or_exit(path, flags, "");
  41. }
  42. /*
  43. * Open KVM_DEV_PATH if available, otherwise exit the entire program.
  44. *
  45. * Input Args:
  46. * flags - The flags to pass when opening KVM_DEV_PATH.
  47. *
  48. * Return:
  49. * The opened file descriptor of /dev/kvm.
  50. */
  51. static int _open_kvm_dev_path_or_exit(int flags)
  52. {
  53. return __open_path_or_exit(KVM_DEV_PATH, flags, "Is KVM loaded and enabled?");
  54. }
  55. int open_kvm_dev_path_or_exit(void)
  56. {
  57. return _open_kvm_dev_path_or_exit(O_RDONLY);
  58. }
  59. static ssize_t get_module_param(const char *module_name, const char *param,
  60. void *buffer, size_t buffer_size)
  61. {
  62. const int path_size = 128;
  63. char path[path_size];
  64. ssize_t bytes_read;
  65. int fd, r;
  66. /* Verify KVM is loaded, to provide a more helpful SKIP message. */
  67. close(open_kvm_dev_path_or_exit());
  68. r = snprintf(path, path_size, "/sys/module/%s/parameters/%s",
  69. module_name, param);
  70. TEST_ASSERT(r < path_size,
  71. "Failed to construct sysfs path in %d bytes.", path_size);
  72. fd = open_path_or_exit(path, O_RDONLY);
  73. bytes_read = read(fd, buffer, buffer_size);
  74. TEST_ASSERT(bytes_read > 0, "read(%s) returned %ld, wanted %ld bytes",
  75. path, bytes_read, buffer_size);
  76. r = close(fd);
  77. TEST_ASSERT(!r, "close(%s) failed", path);
  78. return bytes_read;
  79. }
  80. int kvm_get_module_param_integer(const char *module_name, const char *param)
  81. {
  82. /*
  83. * 16 bytes to hold a 64-bit value (1 byte per char), 1 byte for the
  84. * NUL char, and 1 byte because the kernel sucks and inserts a newline
  85. * at the end.
  86. */
  87. char value[16 + 1 + 1];
  88. ssize_t r;
  89. memset(value, '\0', sizeof(value));
  90. r = get_module_param(module_name, param, value, sizeof(value));
  91. TEST_ASSERT(value[r - 1] == '\n',
  92. "Expected trailing newline, got char '%c'", value[r - 1]);
  93. /*
  94. * Squash the newline, otherwise atoi_paranoid() will complain about
  95. * trailing non-NUL characters in the string.
  96. */
  97. value[r - 1] = '\0';
  98. return atoi_paranoid(value);
  99. }
  100. bool kvm_get_module_param_bool(const char *module_name, const char *param)
  101. {
  102. char value;
  103. ssize_t r;
  104. r = get_module_param(module_name, param, &value, sizeof(value));
  105. TEST_ASSERT_EQ(r, 1);
  106. if (value == 'Y')
  107. return true;
  108. else if (value == 'N')
  109. return false;
  110. TEST_FAIL("Unrecognized value '%c' for boolean module param", value);
  111. }
  112. /*
  113. * Capability
  114. *
  115. * Input Args:
  116. * cap - Capability
  117. *
  118. * Output Args: None
  119. *
  120. * Return:
  121. * On success, the Value corresponding to the capability (KVM_CAP_*)
  122. * specified by the value of cap. On failure a TEST_ASSERT failure
  123. * is produced.
  124. *
  125. * Looks up and returns the value corresponding to the capability
  126. * (KVM_CAP_*) given by cap.
  127. */
  128. unsigned int kvm_check_cap(long cap)
  129. {
  130. int ret;
  131. int kvm_fd;
  132. kvm_fd = open_kvm_dev_path_or_exit();
  133. ret = __kvm_ioctl(kvm_fd, KVM_CHECK_EXTENSION, (void *)cap);
  134. TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_CHECK_EXTENSION, ret));
  135. close(kvm_fd);
  136. return (unsigned int)ret;
  137. }
  138. void vm_enable_dirty_ring(struct kvm_vm *vm, uint32_t ring_size)
  139. {
  140. if (vm_check_cap(vm, KVM_CAP_DIRTY_LOG_RING_ACQ_REL))
  141. vm_enable_cap(vm, KVM_CAP_DIRTY_LOG_RING_ACQ_REL, ring_size);
  142. else
  143. vm_enable_cap(vm, KVM_CAP_DIRTY_LOG_RING, ring_size);
  144. vm->dirty_ring_size = ring_size;
  145. }
  146. static void vm_open(struct kvm_vm *vm)
  147. {
  148. vm->kvm_fd = _open_kvm_dev_path_or_exit(O_RDWR);
  149. TEST_REQUIRE(kvm_has_cap(KVM_CAP_IMMEDIATE_EXIT));
  150. vm->fd = __kvm_ioctl(vm->kvm_fd, KVM_CREATE_VM, (void *)vm->type);
  151. TEST_ASSERT(vm->fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_VM, vm->fd));
  152. if (kvm_has_cap(KVM_CAP_BINARY_STATS_FD))
  153. vm->stats.fd = vm_get_stats_fd(vm);
  154. else
  155. vm->stats.fd = -1;
  156. }
  157. const char *vm_guest_mode_string(uint32_t i)
  158. {
  159. static const char * const strings[] = {
  160. [VM_MODE_P52V48_4K] = "PA-bits:52, VA-bits:48, 4K pages",
  161. [VM_MODE_P52V48_16K] = "PA-bits:52, VA-bits:48, 16K pages",
  162. [VM_MODE_P52V48_64K] = "PA-bits:52, VA-bits:48, 64K pages",
  163. [VM_MODE_P48V48_4K] = "PA-bits:48, VA-bits:48, 4K pages",
  164. [VM_MODE_P48V48_16K] = "PA-bits:48, VA-bits:48, 16K pages",
  165. [VM_MODE_P48V48_64K] = "PA-bits:48, VA-bits:48, 64K pages",
  166. [VM_MODE_P40V48_4K] = "PA-bits:40, VA-bits:48, 4K pages",
  167. [VM_MODE_P40V48_16K] = "PA-bits:40, VA-bits:48, 16K pages",
  168. [VM_MODE_P40V48_64K] = "PA-bits:40, VA-bits:48, 64K pages",
  169. [VM_MODE_PXXVYY_4K] = "PA-bits:ANY, VA-bits:48 or 57, 4K pages",
  170. [VM_MODE_P47V64_4K] = "PA-bits:47, VA-bits:64, 4K pages",
  171. [VM_MODE_P44V64_4K] = "PA-bits:44, VA-bits:64, 4K pages",
  172. [VM_MODE_P36V48_4K] = "PA-bits:36, VA-bits:48, 4K pages",
  173. [VM_MODE_P36V48_16K] = "PA-bits:36, VA-bits:48, 16K pages",
  174. [VM_MODE_P36V48_64K] = "PA-bits:36, VA-bits:48, 64K pages",
  175. [VM_MODE_P47V47_16K] = "PA-bits:47, VA-bits:47, 16K pages",
  176. [VM_MODE_P36V47_16K] = "PA-bits:36, VA-bits:47, 16K pages",
  177. [VM_MODE_P56V57_4K] = "PA-bits:56, VA-bits:57, 4K pages",
  178. [VM_MODE_P56V48_4K] = "PA-bits:56, VA-bits:48, 4K pages",
  179. [VM_MODE_P56V39_4K] = "PA-bits:56, VA-bits:39, 4K pages",
  180. [VM_MODE_P50V57_4K] = "PA-bits:50, VA-bits:57, 4K pages",
  181. [VM_MODE_P50V48_4K] = "PA-bits:50, VA-bits:48, 4K pages",
  182. [VM_MODE_P50V39_4K] = "PA-bits:50, VA-bits:39, 4K pages",
  183. [VM_MODE_P41V57_4K] = "PA-bits:41, VA-bits:57, 4K pages",
  184. [VM_MODE_P41V48_4K] = "PA-bits:41, VA-bits:48, 4K pages",
  185. [VM_MODE_P41V39_4K] = "PA-bits:41, VA-bits:39, 4K pages",
  186. };
  187. _Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES,
  188. "Missing new mode strings?");
  189. TEST_ASSERT(i < NUM_VM_MODES, "Guest mode ID %d too big", i);
  190. return strings[i];
  191. }
  192. const struct vm_guest_mode_params vm_guest_mode_params[] = {
  193. [VM_MODE_P52V48_4K] = { 52, 48, 0x1000, 12 },
  194. [VM_MODE_P52V48_16K] = { 52, 48, 0x4000, 14 },
  195. [VM_MODE_P52V48_64K] = { 52, 48, 0x10000, 16 },
  196. [VM_MODE_P48V48_4K] = { 48, 48, 0x1000, 12 },
  197. [VM_MODE_P48V48_16K] = { 48, 48, 0x4000, 14 },
  198. [VM_MODE_P48V48_64K] = { 48, 48, 0x10000, 16 },
  199. [VM_MODE_P40V48_4K] = { 40, 48, 0x1000, 12 },
  200. [VM_MODE_P40V48_16K] = { 40, 48, 0x4000, 14 },
  201. [VM_MODE_P40V48_64K] = { 40, 48, 0x10000, 16 },
  202. [VM_MODE_PXXVYY_4K] = { 0, 0, 0x1000, 12 },
  203. [VM_MODE_P47V64_4K] = { 47, 64, 0x1000, 12 },
  204. [VM_MODE_P44V64_4K] = { 44, 64, 0x1000, 12 },
  205. [VM_MODE_P36V48_4K] = { 36, 48, 0x1000, 12 },
  206. [VM_MODE_P36V48_16K] = { 36, 48, 0x4000, 14 },
  207. [VM_MODE_P36V48_64K] = { 36, 48, 0x10000, 16 },
  208. [VM_MODE_P47V47_16K] = { 47, 47, 0x4000, 14 },
  209. [VM_MODE_P36V47_16K] = { 36, 47, 0x4000, 14 },
  210. [VM_MODE_P56V57_4K] = { 56, 57, 0x1000, 12 },
  211. [VM_MODE_P56V48_4K] = { 56, 48, 0x1000, 12 },
  212. [VM_MODE_P56V39_4K] = { 56, 39, 0x1000, 12 },
  213. [VM_MODE_P50V57_4K] = { 50, 57, 0x1000, 12 },
  214. [VM_MODE_P50V48_4K] = { 50, 48, 0x1000, 12 },
  215. [VM_MODE_P50V39_4K] = { 50, 39, 0x1000, 12 },
  216. [VM_MODE_P41V57_4K] = { 41, 57, 0x1000, 12 },
  217. [VM_MODE_P41V48_4K] = { 41, 48, 0x1000, 12 },
  218. [VM_MODE_P41V39_4K] = { 41, 39, 0x1000, 12 },
  219. };
  220. _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
  221. "Missing new mode params?");
  222. /*
  223. * Initializes vm->vpages_valid to match the canonical VA space of the
  224. * architecture.
  225. *
  226. * The default implementation is valid for architectures which split the
  227. * range addressed by a single page table into a low and high region
  228. * based on the MSB of the VA. On architectures with this behavior
  229. * the VA region spans [0, 2^(va_bits - 1)), [-(2^(va_bits - 1), -1].
  230. */
  231. __weak void vm_vaddr_populate_bitmap(struct kvm_vm *vm)
  232. {
  233. sparsebit_set_num(vm->vpages_valid,
  234. 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
  235. sparsebit_set_num(vm->vpages_valid,
  236. (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
  237. (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
  238. }
  239. struct kvm_vm *____vm_create(struct vm_shape shape)
  240. {
  241. struct kvm_vm *vm;
  242. vm = calloc(1, sizeof(*vm));
  243. TEST_ASSERT(vm != NULL, "Insufficient Memory");
  244. INIT_LIST_HEAD(&vm->vcpus);
  245. vm->regions.gpa_tree = RB_ROOT;
  246. vm->regions.hva_tree = RB_ROOT;
  247. hash_init(vm->regions.slot_hash);
  248. vm->mode = shape.mode;
  249. vm->type = shape.type;
  250. vm->pa_bits = vm_guest_mode_params[vm->mode].pa_bits;
  251. vm->va_bits = vm_guest_mode_params[vm->mode].va_bits;
  252. vm->page_size = vm_guest_mode_params[vm->mode].page_size;
  253. vm->page_shift = vm_guest_mode_params[vm->mode].page_shift;
  254. /* Setup mode specific traits. */
  255. switch (vm->mode) {
  256. case VM_MODE_P52V48_4K:
  257. vm->mmu.pgtable_levels = 4;
  258. break;
  259. case VM_MODE_P52V48_64K:
  260. vm->mmu.pgtable_levels = 3;
  261. break;
  262. case VM_MODE_P48V48_4K:
  263. vm->mmu.pgtable_levels = 4;
  264. break;
  265. case VM_MODE_P48V48_64K:
  266. vm->mmu.pgtable_levels = 3;
  267. break;
  268. case VM_MODE_P40V48_4K:
  269. case VM_MODE_P36V48_4K:
  270. vm->mmu.pgtable_levels = 4;
  271. break;
  272. case VM_MODE_P40V48_64K:
  273. case VM_MODE_P36V48_64K:
  274. vm->mmu.pgtable_levels = 3;
  275. break;
  276. case VM_MODE_P52V48_16K:
  277. case VM_MODE_P48V48_16K:
  278. case VM_MODE_P40V48_16K:
  279. case VM_MODE_P36V48_16K:
  280. vm->mmu.pgtable_levels = 4;
  281. break;
  282. case VM_MODE_P47V47_16K:
  283. case VM_MODE_P36V47_16K:
  284. vm->mmu.pgtable_levels = 3;
  285. break;
  286. case VM_MODE_PXXVYY_4K:
  287. #ifdef __x86_64__
  288. kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
  289. kvm_init_vm_address_properties(vm);
  290. pr_debug("Guest physical address width detected: %d\n",
  291. vm->pa_bits);
  292. pr_debug("Guest virtual address width detected: %d\n",
  293. vm->va_bits);
  294. if (vm->va_bits == 57) {
  295. vm->mmu.pgtable_levels = 5;
  296. } else {
  297. TEST_ASSERT(vm->va_bits == 48,
  298. "Unexpected guest virtual address width: %d",
  299. vm->va_bits);
  300. vm->mmu.pgtable_levels = 4;
  301. }
  302. #else
  303. TEST_FAIL("VM_MODE_PXXVYY_4K not supported on non-x86 platforms");
  304. #endif
  305. break;
  306. case VM_MODE_P47V64_4K:
  307. vm->mmu.pgtable_levels = 5;
  308. break;
  309. case VM_MODE_P44V64_4K:
  310. vm->mmu.pgtable_levels = 5;
  311. break;
  312. case VM_MODE_P56V57_4K:
  313. case VM_MODE_P50V57_4K:
  314. case VM_MODE_P41V57_4K:
  315. vm->mmu.pgtable_levels = 5;
  316. break;
  317. case VM_MODE_P56V48_4K:
  318. case VM_MODE_P50V48_4K:
  319. case VM_MODE_P41V48_4K:
  320. vm->mmu.pgtable_levels = 4;
  321. break;
  322. case VM_MODE_P56V39_4K:
  323. case VM_MODE_P50V39_4K:
  324. case VM_MODE_P41V39_4K:
  325. vm->mmu.pgtable_levels = 3;
  326. break;
  327. default:
  328. TEST_FAIL("Unknown guest mode: 0x%x", vm->mode);
  329. }
  330. #ifdef __aarch64__
  331. TEST_ASSERT(!vm->type, "ARM doesn't support test-provided types");
  332. if (vm->pa_bits != 40)
  333. vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits);
  334. #endif
  335. vm_open(vm);
  336. /* Limit to VA-bit canonical virtual addresses. */
  337. vm->vpages_valid = sparsebit_alloc();
  338. vm_vaddr_populate_bitmap(vm);
  339. /* Limit physical addresses to PA-bits. */
  340. vm->max_gfn = vm_compute_max_gfn(vm);
  341. /* Allocate and setup memory for guest. */
  342. vm->vpages_mapped = sparsebit_alloc();
  343. return vm;
  344. }
  345. static uint64_t vm_nr_pages_required(enum vm_guest_mode mode,
  346. uint32_t nr_runnable_vcpus,
  347. uint64_t extra_mem_pages)
  348. {
  349. uint64_t page_size = vm_guest_mode_params[mode].page_size;
  350. uint64_t nr_pages;
  351. TEST_ASSERT(nr_runnable_vcpus,
  352. "Use vm_create_barebones() for VMs that _never_ have vCPUs");
  353. TEST_ASSERT(nr_runnable_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS),
  354. "nr_vcpus = %d too large for host, max-vcpus = %d",
  355. nr_runnable_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS));
  356. /*
  357. * Arbitrarily allocate 512 pages (2mb when page size is 4kb) for the
  358. * test code and other per-VM assets that will be loaded into memslot0.
  359. */
  360. nr_pages = 512;
  361. /* Account for the per-vCPU stacks on behalf of the test. */
  362. nr_pages += nr_runnable_vcpus * DEFAULT_STACK_PGS;
  363. /*
  364. * Account for the number of pages needed for the page tables. The
  365. * maximum page table size for a memory region will be when the
  366. * smallest page size is used. Considering each page contains x page
  367. * table descriptors, the total extra size for page tables (for extra
  368. * N pages) will be: N/x+N/x^2+N/x^3+... which is definitely smaller
  369. * than N/x*2.
  370. */
  371. nr_pages += (nr_pages + extra_mem_pages) / PTES_PER_MIN_PAGE * 2;
  372. /* Account for the number of pages needed by ucall. */
  373. nr_pages += ucall_nr_pages_required(page_size);
  374. return vm_adjust_num_guest_pages(mode, nr_pages);
  375. }
  376. void kvm_set_files_rlimit(uint32_t nr_vcpus)
  377. {
  378. /*
  379. * Each vCPU will open two file descriptors: the vCPU itself and the
  380. * vCPU's binary stats file descriptor. Add an arbitrary amount of
  381. * buffer for all other files a test may open.
  382. */
  383. int nr_fds_wanted = nr_vcpus * 2 + 100;
  384. struct rlimit rl;
  385. /*
  386. * Check that we're allowed to open nr_fds_wanted file descriptors and
  387. * try raising the limits if needed.
  388. */
  389. TEST_ASSERT(!getrlimit(RLIMIT_NOFILE, &rl), "getrlimit() failed!");
  390. if (rl.rlim_cur < nr_fds_wanted) {
  391. rl.rlim_cur = nr_fds_wanted;
  392. if (rl.rlim_max < nr_fds_wanted) {
  393. int old_rlim_max = rl.rlim_max;
  394. rl.rlim_max = nr_fds_wanted;
  395. __TEST_REQUIRE(setrlimit(RLIMIT_NOFILE, &rl) >= 0,
  396. "RLIMIT_NOFILE hard limit is too low (%d, wanted %d)",
  397. old_rlim_max, nr_fds_wanted);
  398. } else {
  399. TEST_ASSERT(!setrlimit(RLIMIT_NOFILE, &rl), "setrlimit() failed!");
  400. }
  401. }
  402. }
  403. static bool is_guest_memfd_required(struct vm_shape shape)
  404. {
  405. #ifdef __x86_64__
  406. return shape.type == KVM_X86_SNP_VM;
  407. #else
  408. return false;
  409. #endif
  410. }
  411. struct kvm_vm *__vm_create(struct vm_shape shape, uint32_t nr_runnable_vcpus,
  412. uint64_t nr_extra_pages)
  413. {
  414. uint64_t nr_pages = vm_nr_pages_required(shape.mode, nr_runnable_vcpus,
  415. nr_extra_pages);
  416. struct userspace_mem_region *slot0;
  417. struct kvm_vm *vm;
  418. int i, flags;
  419. kvm_set_files_rlimit(nr_runnable_vcpus);
  420. pr_debug("%s: mode='%s' type='%d', pages='%ld'\n", __func__,
  421. vm_guest_mode_string(shape.mode), shape.type, nr_pages);
  422. vm = ____vm_create(shape);
  423. /*
  424. * Force GUEST_MEMFD for the primary memory region if necessary, e.g.
  425. * for CoCo VMs that require GUEST_MEMFD backed private memory.
  426. */
  427. flags = 0;
  428. if (is_guest_memfd_required(shape))
  429. flags |= KVM_MEM_GUEST_MEMFD;
  430. vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, 0, 0, nr_pages, flags);
  431. for (i = 0; i < NR_MEM_REGIONS; i++)
  432. vm->memslots[i] = 0;
  433. kvm_vm_elf_load(vm, program_invocation_name);
  434. /*
  435. * TODO: Add proper defines to protect the library's memslots, and then
  436. * carve out memslot1 for the ucall MMIO address. KVM treats writes to
  437. * read-only memslots as MMIO, and creating a read-only memslot for the
  438. * MMIO region would prevent silently clobbering the MMIO region.
  439. */
  440. slot0 = memslot2region(vm, 0);
  441. ucall_init(vm, slot0->region.guest_phys_addr + slot0->region.memory_size);
  442. if (guest_random_seed != last_guest_seed) {
  443. pr_info("Random seed: 0x%x\n", guest_random_seed);
  444. last_guest_seed = guest_random_seed;
  445. }
  446. guest_rng = new_guest_random_state(guest_random_seed);
  447. sync_global_to_guest(vm, guest_rng);
  448. kvm_arch_vm_post_create(vm, nr_runnable_vcpus);
  449. return vm;
  450. }
  451. /*
  452. * VM Create with customized parameters
  453. *
  454. * Input Args:
  455. * mode - VM Mode (e.g. VM_MODE_P52V48_4K)
  456. * nr_vcpus - VCPU count
  457. * extra_mem_pages - Non-slot0 physical memory total size
  458. * guest_code - Guest entry point
  459. * vcpuids - VCPU IDs
  460. *
  461. * Output Args: None
  462. *
  463. * Return:
  464. * Pointer to opaque structure that describes the created VM.
  465. *
  466. * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
  467. * extra_mem_pages is only used to calculate the maximum page table size,
  468. * no real memory allocation for non-slot0 memory in this function.
  469. */
  470. struct kvm_vm *__vm_create_with_vcpus(struct vm_shape shape, uint32_t nr_vcpus,
  471. uint64_t extra_mem_pages,
  472. void *guest_code, struct kvm_vcpu *vcpus[])
  473. {
  474. struct kvm_vm *vm;
  475. int i;
  476. TEST_ASSERT(!nr_vcpus || vcpus, "Must provide vCPU array");
  477. vm = __vm_create(shape, nr_vcpus, extra_mem_pages);
  478. for (i = 0; i < nr_vcpus; ++i)
  479. vcpus[i] = vm_vcpu_add(vm, i, guest_code);
  480. kvm_arch_vm_finalize_vcpus(vm);
  481. return vm;
  482. }
  483. struct kvm_vm *__vm_create_shape_with_one_vcpu(struct vm_shape shape,
  484. struct kvm_vcpu **vcpu,
  485. uint64_t extra_mem_pages,
  486. void *guest_code)
  487. {
  488. struct kvm_vcpu *vcpus[1];
  489. struct kvm_vm *vm;
  490. vm = __vm_create_with_vcpus(shape, 1, extra_mem_pages, guest_code, vcpus);
  491. *vcpu = vcpus[0];
  492. return vm;
  493. }
  494. /*
  495. * VM Restart
  496. *
  497. * Input Args:
  498. * vm - VM that has been released before
  499. *
  500. * Output Args: None
  501. *
  502. * Reopens the file descriptors associated to the VM and reinstates the
  503. * global state, such as the irqchip and the memory regions that are mapped
  504. * into the guest.
  505. */
  506. void kvm_vm_restart(struct kvm_vm *vmp)
  507. {
  508. int ctr;
  509. struct userspace_mem_region *region;
  510. vm_open(vmp);
  511. if (vmp->has_irqchip)
  512. vm_create_irqchip(vmp);
  513. hash_for_each(vmp->regions.slot_hash, ctr, region, slot_node) {
  514. int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION2, &region->region);
  515. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n"
  516. " rc: %i errno: %i\n"
  517. " slot: %u flags: 0x%x\n"
  518. " guest_phys_addr: 0x%llx size: 0x%llx",
  519. ret, errno, region->region.slot,
  520. region->region.flags,
  521. region->region.guest_phys_addr,
  522. region->region.memory_size);
  523. }
  524. }
  525. __weak struct kvm_vcpu *vm_arch_vcpu_recreate(struct kvm_vm *vm,
  526. uint32_t vcpu_id)
  527. {
  528. return __vm_vcpu_add(vm, vcpu_id);
  529. }
  530. struct kvm_vcpu *vm_recreate_with_one_vcpu(struct kvm_vm *vm)
  531. {
  532. kvm_vm_restart(vm);
  533. return vm_vcpu_recreate(vm, 0);
  534. }
  535. int __pin_task_to_cpu(pthread_t task, int cpu)
  536. {
  537. cpu_set_t cpuset;
  538. CPU_ZERO(&cpuset);
  539. CPU_SET(cpu, &cpuset);
  540. return pthread_setaffinity_np(task, sizeof(cpuset), &cpuset);
  541. }
  542. static uint32_t parse_pcpu(const char *cpu_str, const cpu_set_t *allowed_mask)
  543. {
  544. uint32_t pcpu = atoi_non_negative("CPU number", cpu_str);
  545. TEST_ASSERT(CPU_ISSET(pcpu, allowed_mask),
  546. "Not allowed to run on pCPU '%d', check cgroups?", pcpu);
  547. return pcpu;
  548. }
  549. void kvm_print_vcpu_pinning_help(void)
  550. {
  551. const char *name = program_invocation_name;
  552. printf(" -c: Pin tasks to physical CPUs. Takes a list of comma separated\n"
  553. " values (target pCPU), one for each vCPU, plus an optional\n"
  554. " entry for the main application task (specified via entry\n"
  555. " <nr_vcpus + 1>). If used, entries must be provided for all\n"
  556. " vCPUs, i.e. pinning vCPUs is all or nothing.\n\n"
  557. " E.g. to create 3 vCPUs, pin vCPU0=>pCPU22, vCPU1=>pCPU23,\n"
  558. " vCPU2=>pCPU24, and pin the application task to pCPU50:\n\n"
  559. " %s -v 3 -c 22,23,24,50\n\n"
  560. " To leave the application task unpinned, drop the final entry:\n\n"
  561. " %s -v 3 -c 22,23,24\n\n"
  562. " (default: no pinning)\n", name, name);
  563. }
  564. void kvm_parse_vcpu_pinning(const char *pcpus_string, uint32_t vcpu_to_pcpu[],
  565. int nr_vcpus)
  566. {
  567. cpu_set_t allowed_mask;
  568. char *cpu, *cpu_list;
  569. char delim[2] = ",";
  570. int i, r;
  571. cpu_list = strdup(pcpus_string);
  572. TEST_ASSERT(cpu_list, "strdup() allocation failed.");
  573. r = sched_getaffinity(0, sizeof(allowed_mask), &allowed_mask);
  574. TEST_ASSERT(!r, "sched_getaffinity() failed");
  575. cpu = strtok(cpu_list, delim);
  576. /* 1. Get all pcpus for vcpus. */
  577. for (i = 0; i < nr_vcpus; i++) {
  578. TEST_ASSERT(cpu, "pCPU not provided for vCPU '%d'", i);
  579. vcpu_to_pcpu[i] = parse_pcpu(cpu, &allowed_mask);
  580. cpu = strtok(NULL, delim);
  581. }
  582. /* 2. Check if the main worker needs to be pinned. */
  583. if (cpu) {
  584. pin_self_to_cpu(parse_pcpu(cpu, &allowed_mask));
  585. cpu = strtok(NULL, delim);
  586. }
  587. TEST_ASSERT(!cpu, "pCPU list contains trailing garbage characters '%s'", cpu);
  588. free(cpu_list);
  589. }
  590. /*
  591. * Userspace Memory Region Find
  592. *
  593. * Input Args:
  594. * vm - Virtual Machine
  595. * start - Starting VM physical address
  596. * end - Ending VM physical address, inclusive.
  597. *
  598. * Output Args: None
  599. *
  600. * Return:
  601. * Pointer to overlapping region, NULL if no such region.
  602. *
  603. * Searches for a region with any physical memory that overlaps with
  604. * any portion of the guest physical addresses from start to end
  605. * inclusive. If multiple overlapping regions exist, a pointer to any
  606. * of the regions is returned. Null is returned only when no overlapping
  607. * region exists.
  608. */
  609. static struct userspace_mem_region *
  610. userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
  611. {
  612. struct rb_node *node;
  613. for (node = vm->regions.gpa_tree.rb_node; node; ) {
  614. struct userspace_mem_region *region =
  615. container_of(node, struct userspace_mem_region, gpa_node);
  616. uint64_t existing_start = region->region.guest_phys_addr;
  617. uint64_t existing_end = region->region.guest_phys_addr
  618. + region->region.memory_size - 1;
  619. if (start <= existing_end && end >= existing_start)
  620. return region;
  621. if (start < existing_start)
  622. node = node->rb_left;
  623. else
  624. node = node->rb_right;
  625. }
  626. return NULL;
  627. }
  628. static void kvm_stats_release(struct kvm_binary_stats *stats)
  629. {
  630. if (stats->fd < 0)
  631. return;
  632. if (stats->desc) {
  633. free(stats->desc);
  634. stats->desc = NULL;
  635. }
  636. kvm_close(stats->fd);
  637. stats->fd = -1;
  638. }
  639. __weak void vcpu_arch_free(struct kvm_vcpu *vcpu)
  640. {
  641. }
  642. /*
  643. * VM VCPU Remove
  644. *
  645. * Input Args:
  646. * vcpu - VCPU to remove
  647. *
  648. * Output Args: None
  649. *
  650. * Return: None, TEST_ASSERT failures for all error conditions
  651. *
  652. * Removes a vCPU from a VM and frees its resources.
  653. */
  654. static void vm_vcpu_rm(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
  655. {
  656. if (vcpu->dirty_gfns) {
  657. kvm_munmap(vcpu->dirty_gfns, vm->dirty_ring_size);
  658. vcpu->dirty_gfns = NULL;
  659. }
  660. kvm_munmap(vcpu->run, vcpu_mmap_sz());
  661. kvm_close(vcpu->fd);
  662. kvm_stats_release(&vcpu->stats);
  663. list_del(&vcpu->list);
  664. vcpu_arch_free(vcpu);
  665. free(vcpu);
  666. }
  667. void kvm_vm_release(struct kvm_vm *vmp)
  668. {
  669. struct kvm_vcpu *vcpu, *tmp;
  670. list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list)
  671. vm_vcpu_rm(vmp, vcpu);
  672. kvm_close(vmp->fd);
  673. kvm_close(vmp->kvm_fd);
  674. /* Free cached stats metadata and close FD */
  675. kvm_stats_release(&vmp->stats);
  676. kvm_arch_vm_release(vmp);
  677. }
  678. static void __vm_mem_region_delete(struct kvm_vm *vm,
  679. struct userspace_mem_region *region)
  680. {
  681. rb_erase(&region->gpa_node, &vm->regions.gpa_tree);
  682. rb_erase(&region->hva_node, &vm->regions.hva_tree);
  683. hash_del(&region->slot_node);
  684. sparsebit_free(&region->unused_phy_pages);
  685. sparsebit_free(&region->protected_phy_pages);
  686. kvm_munmap(region->mmap_start, region->mmap_size);
  687. if (region->fd >= 0) {
  688. /* There's an extra map when using shared memory. */
  689. kvm_munmap(region->mmap_alias, region->mmap_size);
  690. close(region->fd);
  691. }
  692. if (region->region.guest_memfd >= 0)
  693. close(region->region.guest_memfd);
  694. free(region);
  695. }
  696. /*
  697. * Destroys and frees the VM pointed to by vmp.
  698. */
  699. void kvm_vm_free(struct kvm_vm *vmp)
  700. {
  701. int ctr;
  702. struct hlist_node *node;
  703. struct userspace_mem_region *region;
  704. if (vmp == NULL)
  705. return;
  706. /* Free userspace_mem_regions. */
  707. hash_for_each_safe(vmp->regions.slot_hash, ctr, node, region, slot_node)
  708. __vm_mem_region_delete(vmp, region);
  709. /* Free sparsebit arrays. */
  710. sparsebit_free(&vmp->vpages_valid);
  711. sparsebit_free(&vmp->vpages_mapped);
  712. kvm_vm_release(vmp);
  713. /* Free the structure describing the VM. */
  714. free(vmp);
  715. }
  716. int kvm_memfd_alloc(size_t size, bool hugepages)
  717. {
  718. int memfd_flags = MFD_CLOEXEC;
  719. int fd;
  720. if (hugepages)
  721. memfd_flags |= MFD_HUGETLB;
  722. fd = memfd_create("kvm_selftest", memfd_flags);
  723. TEST_ASSERT(fd != -1, __KVM_SYSCALL_ERROR("memfd_create()", fd));
  724. kvm_ftruncate(fd, size);
  725. kvm_fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, size);
  726. return fd;
  727. }
  728. static void vm_userspace_mem_region_gpa_insert(struct rb_root *gpa_tree,
  729. struct userspace_mem_region *region)
  730. {
  731. struct rb_node **cur, *parent;
  732. for (cur = &gpa_tree->rb_node, parent = NULL; *cur; ) {
  733. struct userspace_mem_region *cregion;
  734. cregion = container_of(*cur, typeof(*cregion), gpa_node);
  735. parent = *cur;
  736. if (region->region.guest_phys_addr <
  737. cregion->region.guest_phys_addr)
  738. cur = &(*cur)->rb_left;
  739. else {
  740. TEST_ASSERT(region->region.guest_phys_addr !=
  741. cregion->region.guest_phys_addr,
  742. "Duplicate GPA in region tree");
  743. cur = &(*cur)->rb_right;
  744. }
  745. }
  746. rb_link_node(&region->gpa_node, parent, cur);
  747. rb_insert_color(&region->gpa_node, gpa_tree);
  748. }
  749. static void vm_userspace_mem_region_hva_insert(struct rb_root *hva_tree,
  750. struct userspace_mem_region *region)
  751. {
  752. struct rb_node **cur, *parent;
  753. for (cur = &hva_tree->rb_node, parent = NULL; *cur; ) {
  754. struct userspace_mem_region *cregion;
  755. cregion = container_of(*cur, typeof(*cregion), hva_node);
  756. parent = *cur;
  757. if (region->host_mem < cregion->host_mem)
  758. cur = &(*cur)->rb_left;
  759. else {
  760. TEST_ASSERT(region->host_mem !=
  761. cregion->host_mem,
  762. "Duplicate HVA in region tree");
  763. cur = &(*cur)->rb_right;
  764. }
  765. }
  766. rb_link_node(&region->hva_node, parent, cur);
  767. rb_insert_color(&region->hva_node, hva_tree);
  768. }
  769. int __vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
  770. uint64_t gpa, uint64_t size, void *hva)
  771. {
  772. struct kvm_userspace_memory_region region = {
  773. .slot = slot,
  774. .flags = flags,
  775. .guest_phys_addr = gpa,
  776. .memory_size = size,
  777. .userspace_addr = (uintptr_t)hva,
  778. };
  779. return ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region);
  780. }
  781. void vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
  782. uint64_t gpa, uint64_t size, void *hva)
  783. {
  784. int ret = __vm_set_user_memory_region(vm, slot, flags, gpa, size, hva);
  785. TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed, errno = %d (%s)",
  786. errno, strerror(errno));
  787. }
  788. #define TEST_REQUIRE_SET_USER_MEMORY_REGION2() \
  789. __TEST_REQUIRE(kvm_has_cap(KVM_CAP_USER_MEMORY2), \
  790. "KVM selftests now require KVM_SET_USER_MEMORY_REGION2 (introduced in v6.8)")
  791. int __vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
  792. uint64_t gpa, uint64_t size, void *hva,
  793. uint32_t guest_memfd, uint64_t guest_memfd_offset)
  794. {
  795. struct kvm_userspace_memory_region2 region = {
  796. .slot = slot,
  797. .flags = flags,
  798. .guest_phys_addr = gpa,
  799. .memory_size = size,
  800. .userspace_addr = (uintptr_t)hva,
  801. .guest_memfd = guest_memfd,
  802. .guest_memfd_offset = guest_memfd_offset,
  803. };
  804. TEST_REQUIRE_SET_USER_MEMORY_REGION2();
  805. return ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION2, &region);
  806. }
  807. void vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flags,
  808. uint64_t gpa, uint64_t size, void *hva,
  809. uint32_t guest_memfd, uint64_t guest_memfd_offset)
  810. {
  811. int ret = __vm_set_user_memory_region2(vm, slot, flags, gpa, size, hva,
  812. guest_memfd, guest_memfd_offset);
  813. TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION2 failed, errno = %d (%s)",
  814. errno, strerror(errno));
  815. }
  816. /* FIXME: This thing needs to be ripped apart and rewritten. */
  817. void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type,
  818. uint64_t gpa, uint32_t slot, uint64_t npages, uint32_t flags,
  819. int guest_memfd, uint64_t guest_memfd_offset)
  820. {
  821. int ret;
  822. struct userspace_mem_region *region;
  823. size_t backing_src_pagesz = get_backing_src_pagesz(src_type);
  824. size_t mem_size = npages * vm->page_size;
  825. size_t alignment;
  826. TEST_REQUIRE_SET_USER_MEMORY_REGION2();
  827. TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages,
  828. "Number of guest pages is not compatible with the host. "
  829. "Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages));
  830. TEST_ASSERT((gpa % vm->page_size) == 0, "Guest physical "
  831. "address not on a page boundary.\n"
  832. " gpa: 0x%lx vm->page_size: 0x%x",
  833. gpa, vm->page_size);
  834. TEST_ASSERT((((gpa >> vm->page_shift) + npages) - 1)
  835. <= vm->max_gfn, "Physical range beyond maximum "
  836. "supported physical address,\n"
  837. " gpa: 0x%lx npages: 0x%lx\n"
  838. " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
  839. gpa, npages, vm->max_gfn, vm->page_size);
  840. /*
  841. * Confirm a mem region with an overlapping address doesn't
  842. * already exist.
  843. */
  844. region = (struct userspace_mem_region *) userspace_mem_region_find(
  845. vm, gpa, (gpa + npages * vm->page_size) - 1);
  846. if (region != NULL)
  847. TEST_FAIL("overlapping userspace_mem_region already "
  848. "exists\n"
  849. " requested gpa: 0x%lx npages: 0x%lx page_size: 0x%x\n"
  850. " existing gpa: 0x%lx size: 0x%lx",
  851. gpa, npages, vm->page_size,
  852. (uint64_t) region->region.guest_phys_addr,
  853. (uint64_t) region->region.memory_size);
  854. /* Confirm no region with the requested slot already exists. */
  855. hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
  856. slot) {
  857. if (region->region.slot != slot)
  858. continue;
  859. TEST_FAIL("A mem region with the requested slot "
  860. "already exists.\n"
  861. " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
  862. " existing slot: %u paddr: 0x%lx size: 0x%lx",
  863. slot, gpa, npages, region->region.slot,
  864. (uint64_t) region->region.guest_phys_addr,
  865. (uint64_t) region->region.memory_size);
  866. }
  867. /* Allocate and initialize new mem region structure. */
  868. region = calloc(1, sizeof(*region));
  869. TEST_ASSERT(region != NULL, "Insufficient Memory");
  870. region->mmap_size = mem_size;
  871. #ifdef __s390x__
  872. /* On s390x, the host address must be aligned to 1M (due to PGSTEs) */
  873. alignment = 0x100000;
  874. #else
  875. alignment = 1;
  876. #endif
  877. /*
  878. * When using THP mmap is not guaranteed to returned a hugepage aligned
  879. * address so we have to pad the mmap. Padding is not needed for HugeTLB
  880. * because mmap will always return an address aligned to the HugeTLB
  881. * page size.
  882. */
  883. if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
  884. alignment = max(backing_src_pagesz, alignment);
  885. TEST_ASSERT_EQ(gpa, align_up(gpa, backing_src_pagesz));
  886. /* Add enough memory to align up if necessary */
  887. if (alignment > 1)
  888. region->mmap_size += alignment;
  889. region->fd = -1;
  890. if (backing_src_is_shared(src_type))
  891. region->fd = kvm_memfd_alloc(region->mmap_size,
  892. src_type == VM_MEM_SRC_SHARED_HUGETLB);
  893. region->mmap_start = kvm_mmap(region->mmap_size, PROT_READ | PROT_WRITE,
  894. vm_mem_backing_src_alias(src_type)->flag,
  895. region->fd);
  896. TEST_ASSERT(!is_backing_src_hugetlb(src_type) ||
  897. region->mmap_start == align_ptr_up(region->mmap_start, backing_src_pagesz),
  898. "mmap_start %p is not aligned to HugeTLB page size 0x%lx",
  899. region->mmap_start, backing_src_pagesz);
  900. /* Align host address */
  901. region->host_mem = align_ptr_up(region->mmap_start, alignment);
  902. /* As needed perform madvise */
  903. if ((src_type == VM_MEM_SRC_ANONYMOUS ||
  904. src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) {
  905. ret = madvise(region->host_mem, mem_size,
  906. src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
  907. TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s",
  908. region->host_mem, mem_size,
  909. vm_mem_backing_src_alias(src_type)->name);
  910. }
  911. region->backing_src_type = src_type;
  912. if (flags & KVM_MEM_GUEST_MEMFD) {
  913. if (guest_memfd < 0) {
  914. uint32_t guest_memfd_flags = 0;
  915. TEST_ASSERT(!guest_memfd_offset,
  916. "Offset must be zero when creating new guest_memfd");
  917. guest_memfd = vm_create_guest_memfd(vm, mem_size, guest_memfd_flags);
  918. } else {
  919. /*
  920. * Install a unique fd for each memslot so that the fd
  921. * can be closed when the region is deleted without
  922. * needing to track if the fd is owned by the framework
  923. * or by the caller.
  924. */
  925. guest_memfd = kvm_dup(guest_memfd);
  926. }
  927. region->region.guest_memfd = guest_memfd;
  928. region->region.guest_memfd_offset = guest_memfd_offset;
  929. } else {
  930. region->region.guest_memfd = -1;
  931. }
  932. region->unused_phy_pages = sparsebit_alloc();
  933. if (vm_arch_has_protected_memory(vm))
  934. region->protected_phy_pages = sparsebit_alloc();
  935. sparsebit_set_num(region->unused_phy_pages, gpa >> vm->page_shift, npages);
  936. region->region.slot = slot;
  937. region->region.flags = flags;
  938. region->region.guest_phys_addr = gpa;
  939. region->region.memory_size = npages * vm->page_size;
  940. region->region.userspace_addr = (uintptr_t) region->host_mem;
  941. ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &region->region);
  942. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n"
  943. " rc: %i errno: %i\n"
  944. " slot: %u flags: 0x%x\n"
  945. " guest_phys_addr: 0x%lx size: 0x%llx guest_memfd: %d",
  946. ret, errno, slot, flags, gpa, region->region.memory_size,
  947. region->region.guest_memfd);
  948. /* Add to quick lookup data structures */
  949. vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region);
  950. vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region);
  951. hash_add(vm->regions.slot_hash, &region->slot_node, slot);
  952. /* If shared memory, create an alias. */
  953. if (region->fd >= 0) {
  954. region->mmap_alias = kvm_mmap(region->mmap_size,
  955. PROT_READ | PROT_WRITE,
  956. vm_mem_backing_src_alias(src_type)->flag,
  957. region->fd);
  958. /* Align host alias address */
  959. region->host_alias = align_ptr_up(region->mmap_alias, alignment);
  960. }
  961. }
  962. void vm_userspace_mem_region_add(struct kvm_vm *vm,
  963. enum vm_mem_backing_src_type src_type,
  964. uint64_t gpa, uint32_t slot, uint64_t npages,
  965. uint32_t flags)
  966. {
  967. vm_mem_add(vm, src_type, gpa, slot, npages, flags, -1, 0);
  968. }
  969. /*
  970. * Memslot to region
  971. *
  972. * Input Args:
  973. * vm - Virtual Machine
  974. * memslot - KVM memory slot ID
  975. *
  976. * Output Args: None
  977. *
  978. * Return:
  979. * Pointer to memory region structure that describe memory region
  980. * using kvm memory slot ID given by memslot. TEST_ASSERT failure
  981. * on error (e.g. currently no memory region using memslot as a KVM
  982. * memory slot ID).
  983. */
  984. struct userspace_mem_region *
  985. memslot2region(struct kvm_vm *vm, uint32_t memslot)
  986. {
  987. struct userspace_mem_region *region;
  988. hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
  989. memslot)
  990. if (region->region.slot == memslot)
  991. return region;
  992. fprintf(stderr, "No mem region with the requested slot found,\n"
  993. " requested slot: %u\n", memslot);
  994. fputs("---- vm dump ----\n", stderr);
  995. vm_dump(stderr, vm, 2);
  996. TEST_FAIL("Mem region not found");
  997. return NULL;
  998. }
  999. /*
  1000. * VM Memory Region Flags Set
  1001. *
  1002. * Input Args:
  1003. * vm - Virtual Machine
  1004. * flags - Starting guest physical address
  1005. *
  1006. * Output Args: None
  1007. *
  1008. * Return: None
  1009. *
  1010. * Sets the flags of the memory region specified by the value of slot,
  1011. * to the values given by flags.
  1012. */
  1013. void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
  1014. {
  1015. int ret;
  1016. struct userspace_mem_region *region;
  1017. region = memslot2region(vm, slot);
  1018. region->region.flags = flags;
  1019. ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &region->region);
  1020. TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n"
  1021. " rc: %i errno: %i slot: %u flags: 0x%x",
  1022. ret, errno, slot, flags);
  1023. }
  1024. void vm_mem_region_reload(struct kvm_vm *vm, uint32_t slot)
  1025. {
  1026. struct userspace_mem_region *region = memslot2region(vm, slot);
  1027. struct kvm_userspace_memory_region2 tmp = region->region;
  1028. tmp.memory_size = 0;
  1029. vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &tmp);
  1030. vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &region->region);
  1031. }
  1032. /*
  1033. * VM Memory Region Move
  1034. *
  1035. * Input Args:
  1036. * vm - Virtual Machine
  1037. * slot - Slot of the memory region to move
  1038. * new_gpa - Starting guest physical address
  1039. *
  1040. * Output Args: None
  1041. *
  1042. * Return: None
  1043. *
  1044. * Change the gpa of a memory region.
  1045. */
  1046. void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
  1047. {
  1048. struct userspace_mem_region *region;
  1049. int ret;
  1050. region = memslot2region(vm, slot);
  1051. region->region.guest_phys_addr = new_gpa;
  1052. ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &region->region);
  1053. TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION2 failed\n"
  1054. "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
  1055. ret, errno, slot, new_gpa);
  1056. }
  1057. /*
  1058. * VM Memory Region Delete
  1059. *
  1060. * Input Args:
  1061. * vm - Virtual Machine
  1062. * slot - Slot of the memory region to delete
  1063. *
  1064. * Output Args: None
  1065. *
  1066. * Return: None
  1067. *
  1068. * Delete a memory region.
  1069. */
  1070. void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
  1071. {
  1072. struct userspace_mem_region *region = memslot2region(vm, slot);
  1073. region->region.memory_size = 0;
  1074. vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, &region->region);
  1075. __vm_mem_region_delete(vm, region);
  1076. }
  1077. void vm_guest_mem_fallocate(struct kvm_vm *vm, uint64_t base, uint64_t size,
  1078. bool punch_hole)
  1079. {
  1080. const int mode = FALLOC_FL_KEEP_SIZE | (punch_hole ? FALLOC_FL_PUNCH_HOLE : 0);
  1081. struct userspace_mem_region *region;
  1082. uint64_t end = base + size;
  1083. uint64_t gpa, len;
  1084. off_t fd_offset;
  1085. int ret;
  1086. for (gpa = base; gpa < end; gpa += len) {
  1087. uint64_t offset;
  1088. region = userspace_mem_region_find(vm, gpa, gpa);
  1089. TEST_ASSERT(region && region->region.flags & KVM_MEM_GUEST_MEMFD,
  1090. "Private memory region not found for GPA 0x%lx", gpa);
  1091. offset = gpa - region->region.guest_phys_addr;
  1092. fd_offset = region->region.guest_memfd_offset + offset;
  1093. len = min_t(uint64_t, end - gpa, region->region.memory_size - offset);
  1094. ret = fallocate(region->region.guest_memfd, mode, fd_offset, len);
  1095. TEST_ASSERT(!ret, "fallocate() failed to %s at %lx (len = %lu), fd = %d, mode = %x, offset = %lx",
  1096. punch_hole ? "punch hole" : "allocate", gpa, len,
  1097. region->region.guest_memfd, mode, fd_offset);
  1098. }
  1099. }
  1100. /* Returns the size of a vCPU's kvm_run structure. */
  1101. static size_t vcpu_mmap_sz(void)
  1102. {
  1103. int dev_fd, ret;
  1104. dev_fd = open_kvm_dev_path_or_exit();
  1105. ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
  1106. TEST_ASSERT(ret >= 0 && ret >= sizeof(struct kvm_run),
  1107. KVM_IOCTL_ERROR(KVM_GET_VCPU_MMAP_SIZE, ret));
  1108. close(dev_fd);
  1109. return ret;
  1110. }
  1111. static bool vcpu_exists(struct kvm_vm *vm, uint32_t vcpu_id)
  1112. {
  1113. struct kvm_vcpu *vcpu;
  1114. list_for_each_entry(vcpu, &vm->vcpus, list) {
  1115. if (vcpu->id == vcpu_id)
  1116. return true;
  1117. }
  1118. return false;
  1119. }
  1120. /*
  1121. * Adds a virtual CPU to the VM specified by vm with the ID given by vcpu_id.
  1122. * No additional vCPU setup is done. Returns the vCPU.
  1123. */
  1124. struct kvm_vcpu *__vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpu_id)
  1125. {
  1126. struct kvm_vcpu *vcpu;
  1127. /* Confirm a vcpu with the specified id doesn't already exist. */
  1128. TEST_ASSERT(!vcpu_exists(vm, vcpu_id), "vCPU%d already exists", vcpu_id);
  1129. /* Allocate and initialize new vcpu structure. */
  1130. vcpu = calloc(1, sizeof(*vcpu));
  1131. TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
  1132. vcpu->vm = vm;
  1133. vcpu->id = vcpu_id;
  1134. vcpu->fd = __vm_ioctl(vm, KVM_CREATE_VCPU, (void *)(unsigned long)vcpu_id);
  1135. TEST_ASSERT_VM_VCPU_IOCTL(vcpu->fd >= 0, KVM_CREATE_VCPU, vcpu->fd, vm);
  1136. TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->run), "vcpu mmap size "
  1137. "smaller than expected, vcpu_mmap_sz: %zi expected_min: %zi",
  1138. vcpu_mmap_sz(), sizeof(*vcpu->run));
  1139. vcpu->run = kvm_mmap(vcpu_mmap_sz(), PROT_READ | PROT_WRITE,
  1140. MAP_SHARED, vcpu->fd);
  1141. if (kvm_has_cap(KVM_CAP_BINARY_STATS_FD))
  1142. vcpu->stats.fd = vcpu_get_stats_fd(vcpu);
  1143. else
  1144. vcpu->stats.fd = -1;
  1145. /* Add to linked-list of VCPUs. */
  1146. list_add(&vcpu->list, &vm->vcpus);
  1147. return vcpu;
  1148. }
  1149. /*
  1150. * VM Virtual Address Unused Gap
  1151. *
  1152. * Input Args:
  1153. * vm - Virtual Machine
  1154. * sz - Size (bytes)
  1155. * vaddr_min - Minimum Virtual Address
  1156. *
  1157. * Output Args: None
  1158. *
  1159. * Return:
  1160. * Lowest virtual address at or above vaddr_min, with at least
  1161. * sz unused bytes. TEST_ASSERT failure if no area of at least
  1162. * size sz is available.
  1163. *
  1164. * Within the VM specified by vm, locates the lowest starting virtual
  1165. * address >= vaddr_min, that has at least sz unallocated bytes. A
  1166. * TEST_ASSERT failure occurs for invalid input or no area of at least
  1167. * sz unallocated bytes >= vaddr_min is available.
  1168. */
  1169. vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
  1170. vm_vaddr_t vaddr_min)
  1171. {
  1172. uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
  1173. /* Determine lowest permitted virtual page index. */
  1174. uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
  1175. if ((pgidx_start * vm->page_size) < vaddr_min)
  1176. goto no_va_found;
  1177. /* Loop over section with enough valid virtual page indexes. */
  1178. if (!sparsebit_is_set_num(vm->vpages_valid,
  1179. pgidx_start, pages))
  1180. pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
  1181. pgidx_start, pages);
  1182. do {
  1183. /*
  1184. * Are there enough unused virtual pages available at
  1185. * the currently proposed starting virtual page index.
  1186. * If not, adjust proposed starting index to next
  1187. * possible.
  1188. */
  1189. if (sparsebit_is_clear_num(vm->vpages_mapped,
  1190. pgidx_start, pages))
  1191. goto va_found;
  1192. pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
  1193. pgidx_start, pages);
  1194. if (pgidx_start == 0)
  1195. goto no_va_found;
  1196. /*
  1197. * If needed, adjust proposed starting virtual address,
  1198. * to next range of valid virtual addresses.
  1199. */
  1200. if (!sparsebit_is_set_num(vm->vpages_valid,
  1201. pgidx_start, pages)) {
  1202. pgidx_start = sparsebit_next_set_num(
  1203. vm->vpages_valid, pgidx_start, pages);
  1204. if (pgidx_start == 0)
  1205. goto no_va_found;
  1206. }
  1207. } while (pgidx_start != 0);
  1208. no_va_found:
  1209. TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
  1210. /* NOT REACHED */
  1211. return -1;
  1212. va_found:
  1213. TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
  1214. pgidx_start, pages),
  1215. "Unexpected, invalid virtual page index range,\n"
  1216. " pgidx_start: 0x%lx\n"
  1217. " pages: 0x%lx",
  1218. pgidx_start, pages);
  1219. TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
  1220. pgidx_start, pages),
  1221. "Unexpected, pages already mapped,\n"
  1222. " pgidx_start: 0x%lx\n"
  1223. " pages: 0x%lx",
  1224. pgidx_start, pages);
  1225. return pgidx_start * vm->page_size;
  1226. }
  1227. static vm_vaddr_t ____vm_vaddr_alloc(struct kvm_vm *vm, size_t sz,
  1228. vm_vaddr_t vaddr_min,
  1229. enum kvm_mem_region_type type,
  1230. bool protected)
  1231. {
  1232. uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
  1233. virt_pgd_alloc(vm);
  1234. vm_paddr_t paddr = __vm_phy_pages_alloc(vm, pages,
  1235. KVM_UTIL_MIN_PFN * vm->page_size,
  1236. vm->memslots[type], protected);
  1237. /*
  1238. * Find an unused range of virtual page addresses of at least
  1239. * pages in length.
  1240. */
  1241. vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
  1242. /* Map the virtual pages. */
  1243. for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
  1244. pages--, vaddr += vm->page_size, paddr += vm->page_size) {
  1245. virt_pg_map(vm, vaddr, paddr);
  1246. }
  1247. return vaddr_start;
  1248. }
  1249. vm_vaddr_t __vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
  1250. enum kvm_mem_region_type type)
  1251. {
  1252. return ____vm_vaddr_alloc(vm, sz, vaddr_min, type,
  1253. vm_arch_has_protected_memory(vm));
  1254. }
  1255. vm_vaddr_t vm_vaddr_alloc_shared(struct kvm_vm *vm, size_t sz,
  1256. vm_vaddr_t vaddr_min,
  1257. enum kvm_mem_region_type type)
  1258. {
  1259. return ____vm_vaddr_alloc(vm, sz, vaddr_min, type, false);
  1260. }
  1261. /*
  1262. * VM Virtual Address Allocate
  1263. *
  1264. * Input Args:
  1265. * vm - Virtual Machine
  1266. * sz - Size in bytes
  1267. * vaddr_min - Minimum starting virtual address
  1268. *
  1269. * Output Args: None
  1270. *
  1271. * Return:
  1272. * Starting guest virtual address
  1273. *
  1274. * Allocates at least sz bytes within the virtual address space of the vm
  1275. * given by vm. The allocated bytes are mapped to a virtual address >=
  1276. * the address given by vaddr_min. Note that each allocation uses a
  1277. * a unique set of pages, with the minimum real allocation being at least
  1278. * a page. The allocated physical space comes from the TEST_DATA memory region.
  1279. */
  1280. vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min)
  1281. {
  1282. return __vm_vaddr_alloc(vm, sz, vaddr_min, MEM_REGION_TEST_DATA);
  1283. }
  1284. /*
  1285. * VM Virtual Address Allocate Pages
  1286. *
  1287. * Input Args:
  1288. * vm - Virtual Machine
  1289. *
  1290. * Output Args: None
  1291. *
  1292. * Return:
  1293. * Starting guest virtual address
  1294. *
  1295. * Allocates at least N system pages worth of bytes within the virtual address
  1296. * space of the vm.
  1297. */
  1298. vm_vaddr_t vm_vaddr_alloc_pages(struct kvm_vm *vm, int nr_pages)
  1299. {
  1300. return vm_vaddr_alloc(vm, nr_pages * getpagesize(), KVM_UTIL_MIN_VADDR);
  1301. }
  1302. vm_vaddr_t __vm_vaddr_alloc_page(struct kvm_vm *vm, enum kvm_mem_region_type type)
  1303. {
  1304. return __vm_vaddr_alloc(vm, getpagesize(), KVM_UTIL_MIN_VADDR, type);
  1305. }
  1306. /*
  1307. * VM Virtual Address Allocate Page
  1308. *
  1309. * Input Args:
  1310. * vm - Virtual Machine
  1311. *
  1312. * Output Args: None
  1313. *
  1314. * Return:
  1315. * Starting guest virtual address
  1316. *
  1317. * Allocates at least one system page worth of bytes within the virtual address
  1318. * space of the vm.
  1319. */
  1320. vm_vaddr_t vm_vaddr_alloc_page(struct kvm_vm *vm)
  1321. {
  1322. return vm_vaddr_alloc_pages(vm, 1);
  1323. }
  1324. /*
  1325. * Map a range of VM virtual address to the VM's physical address
  1326. *
  1327. * Input Args:
  1328. * vm - Virtual Machine
  1329. * vaddr - Virtuall address to map
  1330. * paddr - VM Physical Address
  1331. * npages - The number of pages to map
  1332. *
  1333. * Output Args: None
  1334. *
  1335. * Return: None
  1336. *
  1337. * Within the VM given by @vm, creates a virtual translation for
  1338. * @npages starting at @vaddr to the page range starting at @paddr.
  1339. */
  1340. void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
  1341. unsigned int npages)
  1342. {
  1343. size_t page_size = vm->page_size;
  1344. size_t size = npages * page_size;
  1345. TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
  1346. TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
  1347. while (npages--) {
  1348. virt_pg_map(vm, vaddr, paddr);
  1349. vaddr += page_size;
  1350. paddr += page_size;
  1351. }
  1352. }
  1353. /*
  1354. * Address VM Physical to Host Virtual
  1355. *
  1356. * Input Args:
  1357. * vm - Virtual Machine
  1358. * gpa - VM physical address
  1359. *
  1360. * Output Args: None
  1361. *
  1362. * Return:
  1363. * Equivalent host virtual address
  1364. *
  1365. * Locates the memory region containing the VM physical address given
  1366. * by gpa, within the VM given by vm. When found, the host virtual
  1367. * address providing the memory to the vm physical address is returned.
  1368. * A TEST_ASSERT failure occurs if no region containing gpa exists.
  1369. */
  1370. void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
  1371. {
  1372. struct userspace_mem_region *region;
  1373. gpa = vm_untag_gpa(vm, gpa);
  1374. region = userspace_mem_region_find(vm, gpa, gpa);
  1375. if (!region) {
  1376. TEST_FAIL("No vm physical memory at 0x%lx", gpa);
  1377. return NULL;
  1378. }
  1379. return (void *)((uintptr_t)region->host_mem
  1380. + (gpa - region->region.guest_phys_addr));
  1381. }
  1382. /*
  1383. * Address Host Virtual to VM Physical
  1384. *
  1385. * Input Args:
  1386. * vm - Virtual Machine
  1387. * hva - Host virtual address
  1388. *
  1389. * Output Args: None
  1390. *
  1391. * Return:
  1392. * Equivalent VM physical address
  1393. *
  1394. * Locates the memory region containing the host virtual address given
  1395. * by hva, within the VM given by vm. When found, the equivalent
  1396. * VM physical address is returned. A TEST_ASSERT failure occurs if no
  1397. * region containing hva exists.
  1398. */
  1399. vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
  1400. {
  1401. struct rb_node *node;
  1402. for (node = vm->regions.hva_tree.rb_node; node; ) {
  1403. struct userspace_mem_region *region =
  1404. container_of(node, struct userspace_mem_region, hva_node);
  1405. if (hva >= region->host_mem) {
  1406. if (hva <= (region->host_mem
  1407. + region->region.memory_size - 1))
  1408. return (vm_paddr_t)((uintptr_t)
  1409. region->region.guest_phys_addr
  1410. + (hva - (uintptr_t)region->host_mem));
  1411. node = node->rb_right;
  1412. } else
  1413. node = node->rb_left;
  1414. }
  1415. TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
  1416. return -1;
  1417. }
  1418. /*
  1419. * Address VM physical to Host Virtual *alias*.
  1420. *
  1421. * Input Args:
  1422. * vm - Virtual Machine
  1423. * gpa - VM physical address
  1424. *
  1425. * Output Args: None
  1426. *
  1427. * Return:
  1428. * Equivalent address within the host virtual *alias* area, or NULL
  1429. * (without failing the test) if the guest memory is not shared (so
  1430. * no alias exists).
  1431. *
  1432. * Create a writable, shared virtual=>physical alias for the specific GPA.
  1433. * The primary use case is to allow the host selftest to manipulate guest
  1434. * memory without mapping said memory in the guest's address space. And, for
  1435. * userfaultfd-based demand paging, to do so without triggering userfaults.
  1436. */
  1437. void *addr_gpa2alias(struct kvm_vm *vm, vm_paddr_t gpa)
  1438. {
  1439. struct userspace_mem_region *region;
  1440. uintptr_t offset;
  1441. region = userspace_mem_region_find(vm, gpa, gpa);
  1442. if (!region)
  1443. return NULL;
  1444. if (!region->host_alias)
  1445. return NULL;
  1446. offset = gpa - region->region.guest_phys_addr;
  1447. return (void *) ((uintptr_t) region->host_alias + offset);
  1448. }
  1449. /* Create an interrupt controller chip for the specified VM. */
  1450. void vm_create_irqchip(struct kvm_vm *vm)
  1451. {
  1452. int r;
  1453. /*
  1454. * Allocate a fully in-kernel IRQ chip by default, but fall back to a
  1455. * split model (x86 only) if that fails (KVM x86 allows compiling out
  1456. * support for KVM_CREATE_IRQCHIP).
  1457. */
  1458. r = __vm_ioctl(vm, KVM_CREATE_IRQCHIP, NULL);
  1459. if (r && errno == ENOTTY && kvm_has_cap(KVM_CAP_SPLIT_IRQCHIP))
  1460. vm_enable_cap(vm, KVM_CAP_SPLIT_IRQCHIP, 24);
  1461. else
  1462. TEST_ASSERT_VM_VCPU_IOCTL(!r, KVM_CREATE_IRQCHIP, r, vm);
  1463. vm->has_irqchip = true;
  1464. }
  1465. int _vcpu_run(struct kvm_vcpu *vcpu)
  1466. {
  1467. int rc;
  1468. do {
  1469. rc = __vcpu_run(vcpu);
  1470. } while (rc == -1 && errno == EINTR);
  1471. if (!rc)
  1472. assert_on_unhandled_exception(vcpu);
  1473. return rc;
  1474. }
  1475. /*
  1476. * Invoke KVM_RUN on a vCPU until KVM returns something other than -EINTR.
  1477. * Assert if the KVM returns an error (other than -EINTR).
  1478. */
  1479. void vcpu_run(struct kvm_vcpu *vcpu)
  1480. {
  1481. int ret = _vcpu_run(vcpu);
  1482. TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_RUN, ret));
  1483. }
  1484. void vcpu_run_complete_io(struct kvm_vcpu *vcpu)
  1485. {
  1486. int ret;
  1487. vcpu->run->immediate_exit = 1;
  1488. ret = __vcpu_run(vcpu);
  1489. vcpu->run->immediate_exit = 0;
  1490. TEST_ASSERT(ret == -1 && errno == EINTR,
  1491. "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
  1492. ret, errno);
  1493. }
  1494. /*
  1495. * Get the list of guest registers which are supported for
  1496. * KVM_GET_ONE_REG/KVM_SET_ONE_REG ioctls. Returns a kvm_reg_list pointer,
  1497. * it is the caller's responsibility to free the list.
  1498. */
  1499. struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vcpu *vcpu)
  1500. {
  1501. struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list;
  1502. int ret;
  1503. ret = __vcpu_ioctl(vcpu, KVM_GET_REG_LIST, &reg_list_n);
  1504. TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0");
  1505. reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64));
  1506. reg_list->n = reg_list_n.n;
  1507. vcpu_ioctl(vcpu, KVM_GET_REG_LIST, reg_list);
  1508. return reg_list;
  1509. }
  1510. void *vcpu_map_dirty_ring(struct kvm_vcpu *vcpu)
  1511. {
  1512. uint32_t page_size = getpagesize();
  1513. uint32_t size = vcpu->vm->dirty_ring_size;
  1514. TEST_ASSERT(size > 0, "Should enable dirty ring first");
  1515. if (!vcpu->dirty_gfns) {
  1516. void *addr;
  1517. addr = mmap(NULL, size, PROT_READ, MAP_PRIVATE, vcpu->fd,
  1518. page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
  1519. TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private");
  1520. addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE, vcpu->fd,
  1521. page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
  1522. TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec");
  1523. addr = __kvm_mmap(size, PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd,
  1524. page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
  1525. vcpu->dirty_gfns = addr;
  1526. vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn);
  1527. }
  1528. return vcpu->dirty_gfns;
  1529. }
  1530. /*
  1531. * Device Ioctl
  1532. */
  1533. int __kvm_has_device_attr(int dev_fd, uint32_t group, uint64_t attr)
  1534. {
  1535. struct kvm_device_attr attribute = {
  1536. .group = group,
  1537. .attr = attr,
  1538. .flags = 0,
  1539. };
  1540. return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute);
  1541. }
  1542. int __kvm_test_create_device(struct kvm_vm *vm, uint64_t type)
  1543. {
  1544. struct kvm_create_device create_dev = {
  1545. .type = type,
  1546. .flags = KVM_CREATE_DEVICE_TEST,
  1547. };
  1548. return __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev);
  1549. }
  1550. int __kvm_create_device(struct kvm_vm *vm, uint64_t type)
  1551. {
  1552. struct kvm_create_device create_dev = {
  1553. .type = type,
  1554. .fd = -1,
  1555. .flags = 0,
  1556. };
  1557. int err;
  1558. err = __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev);
  1559. TEST_ASSERT(err <= 0, "KVM_CREATE_DEVICE shouldn't return a positive value");
  1560. return err ? : create_dev.fd;
  1561. }
  1562. int __kvm_device_attr_get(int dev_fd, uint32_t group, uint64_t attr, void *val)
  1563. {
  1564. struct kvm_device_attr kvmattr = {
  1565. .group = group,
  1566. .attr = attr,
  1567. .flags = 0,
  1568. .addr = (uintptr_t)val,
  1569. };
  1570. return __kvm_ioctl(dev_fd, KVM_GET_DEVICE_ATTR, &kvmattr);
  1571. }
  1572. int __kvm_device_attr_set(int dev_fd, uint32_t group, uint64_t attr, void *val)
  1573. {
  1574. struct kvm_device_attr kvmattr = {
  1575. .group = group,
  1576. .attr = attr,
  1577. .flags = 0,
  1578. .addr = (uintptr_t)val,
  1579. };
  1580. return __kvm_ioctl(dev_fd, KVM_SET_DEVICE_ATTR, &kvmattr);
  1581. }
  1582. /*
  1583. * IRQ related functions.
  1584. */
  1585. int _kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
  1586. {
  1587. struct kvm_irq_level irq_level = {
  1588. .irq = irq,
  1589. .level = level,
  1590. };
  1591. return __vm_ioctl(vm, KVM_IRQ_LINE, &irq_level);
  1592. }
  1593. void kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
  1594. {
  1595. int ret = _kvm_irq_line(vm, irq, level);
  1596. TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_IRQ_LINE, ret));
  1597. }
  1598. struct kvm_irq_routing *kvm_gsi_routing_create(void)
  1599. {
  1600. struct kvm_irq_routing *routing;
  1601. size_t size;
  1602. size = sizeof(struct kvm_irq_routing);
  1603. /* Allocate space for the max number of entries: this wastes 196 KBs. */
  1604. size += KVM_MAX_IRQ_ROUTES * sizeof(struct kvm_irq_routing_entry);
  1605. routing = calloc(1, size);
  1606. assert(routing);
  1607. return routing;
  1608. }
  1609. void kvm_gsi_routing_irqchip_add(struct kvm_irq_routing *routing,
  1610. uint32_t gsi, uint32_t pin)
  1611. {
  1612. int i;
  1613. assert(routing);
  1614. assert(routing->nr < KVM_MAX_IRQ_ROUTES);
  1615. i = routing->nr;
  1616. routing->entries[i].gsi = gsi;
  1617. routing->entries[i].type = KVM_IRQ_ROUTING_IRQCHIP;
  1618. routing->entries[i].flags = 0;
  1619. routing->entries[i].u.irqchip.irqchip = 0;
  1620. routing->entries[i].u.irqchip.pin = pin;
  1621. routing->nr++;
  1622. }
  1623. int _kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
  1624. {
  1625. int ret;
  1626. assert(routing);
  1627. ret = __vm_ioctl(vm, KVM_SET_GSI_ROUTING, routing);
  1628. free(routing);
  1629. return ret;
  1630. }
  1631. void kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
  1632. {
  1633. int ret;
  1634. ret = _kvm_gsi_routing_write(vm, routing);
  1635. TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_SET_GSI_ROUTING, ret));
  1636. }
  1637. /*
  1638. * VM Dump
  1639. *
  1640. * Input Args:
  1641. * vm - Virtual Machine
  1642. * indent - Left margin indent amount
  1643. *
  1644. * Output Args:
  1645. * stream - Output FILE stream
  1646. *
  1647. * Return: None
  1648. *
  1649. * Dumps the current state of the VM given by vm, to the FILE stream
  1650. * given by stream.
  1651. */
  1652. void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
  1653. {
  1654. int ctr;
  1655. struct userspace_mem_region *region;
  1656. struct kvm_vcpu *vcpu;
  1657. fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
  1658. fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
  1659. fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
  1660. fprintf(stream, "%*sMem Regions:\n", indent, "");
  1661. hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) {
  1662. fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
  1663. "host_virt: %p\n", indent + 2, "",
  1664. (uint64_t) region->region.guest_phys_addr,
  1665. (uint64_t) region->region.memory_size,
  1666. region->host_mem);
  1667. fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
  1668. sparsebit_dump(stream, region->unused_phy_pages, 0);
  1669. if (region->protected_phy_pages) {
  1670. fprintf(stream, "%*sprotected_phy_pages: ", indent + 2, "");
  1671. sparsebit_dump(stream, region->protected_phy_pages, 0);
  1672. }
  1673. }
  1674. fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
  1675. sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
  1676. fprintf(stream, "%*spgd_created: %u\n", indent, "",
  1677. vm->mmu.pgd_created);
  1678. if (vm->mmu.pgd_created) {
  1679. fprintf(stream, "%*sVirtual Translation Tables:\n",
  1680. indent + 2, "");
  1681. virt_dump(stream, vm, indent + 4);
  1682. }
  1683. fprintf(stream, "%*sVCPUs:\n", indent, "");
  1684. list_for_each_entry(vcpu, &vm->vcpus, list)
  1685. vcpu_dump(stream, vcpu, indent + 2);
  1686. }
  1687. #define KVM_EXIT_STRING(x) {KVM_EXIT_##x, #x}
  1688. /* Known KVM exit reasons */
  1689. static struct exit_reason {
  1690. unsigned int reason;
  1691. const char *name;
  1692. } exit_reasons_known[] = {
  1693. KVM_EXIT_STRING(UNKNOWN),
  1694. KVM_EXIT_STRING(EXCEPTION),
  1695. KVM_EXIT_STRING(IO),
  1696. KVM_EXIT_STRING(HYPERCALL),
  1697. KVM_EXIT_STRING(DEBUG),
  1698. KVM_EXIT_STRING(HLT),
  1699. KVM_EXIT_STRING(MMIO),
  1700. KVM_EXIT_STRING(IRQ_WINDOW_OPEN),
  1701. KVM_EXIT_STRING(SHUTDOWN),
  1702. KVM_EXIT_STRING(FAIL_ENTRY),
  1703. KVM_EXIT_STRING(INTR),
  1704. KVM_EXIT_STRING(SET_TPR),
  1705. KVM_EXIT_STRING(TPR_ACCESS),
  1706. KVM_EXIT_STRING(S390_SIEIC),
  1707. KVM_EXIT_STRING(S390_RESET),
  1708. KVM_EXIT_STRING(DCR),
  1709. KVM_EXIT_STRING(NMI),
  1710. KVM_EXIT_STRING(INTERNAL_ERROR),
  1711. KVM_EXIT_STRING(OSI),
  1712. KVM_EXIT_STRING(PAPR_HCALL),
  1713. KVM_EXIT_STRING(S390_UCONTROL),
  1714. KVM_EXIT_STRING(WATCHDOG),
  1715. KVM_EXIT_STRING(S390_TSCH),
  1716. KVM_EXIT_STRING(EPR),
  1717. KVM_EXIT_STRING(SYSTEM_EVENT),
  1718. KVM_EXIT_STRING(S390_STSI),
  1719. KVM_EXIT_STRING(IOAPIC_EOI),
  1720. KVM_EXIT_STRING(HYPERV),
  1721. KVM_EXIT_STRING(ARM_NISV),
  1722. KVM_EXIT_STRING(X86_RDMSR),
  1723. KVM_EXIT_STRING(X86_WRMSR),
  1724. KVM_EXIT_STRING(DIRTY_RING_FULL),
  1725. KVM_EXIT_STRING(AP_RESET_HOLD),
  1726. KVM_EXIT_STRING(X86_BUS_LOCK),
  1727. KVM_EXIT_STRING(XEN),
  1728. KVM_EXIT_STRING(RISCV_SBI),
  1729. KVM_EXIT_STRING(RISCV_CSR),
  1730. KVM_EXIT_STRING(NOTIFY),
  1731. KVM_EXIT_STRING(LOONGARCH_IOCSR),
  1732. KVM_EXIT_STRING(MEMORY_FAULT),
  1733. KVM_EXIT_STRING(ARM_SEA),
  1734. };
  1735. /*
  1736. * Exit Reason String
  1737. *
  1738. * Input Args:
  1739. * exit_reason - Exit reason
  1740. *
  1741. * Output Args: None
  1742. *
  1743. * Return:
  1744. * Constant string pointer describing the exit reason.
  1745. *
  1746. * Locates and returns a constant string that describes the KVM exit
  1747. * reason given by exit_reason. If no such string is found, a constant
  1748. * string of "Unknown" is returned.
  1749. */
  1750. const char *exit_reason_str(unsigned int exit_reason)
  1751. {
  1752. unsigned int n1;
  1753. for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
  1754. if (exit_reason == exit_reasons_known[n1].reason)
  1755. return exit_reasons_known[n1].name;
  1756. }
  1757. return "Unknown";
  1758. }
  1759. /*
  1760. * Physical Contiguous Page Allocator
  1761. *
  1762. * Input Args:
  1763. * vm - Virtual Machine
  1764. * num - number of pages
  1765. * paddr_min - Physical address minimum
  1766. * memslot - Memory region to allocate page from
  1767. * protected - True if the pages will be used as protected/private memory
  1768. *
  1769. * Output Args: None
  1770. *
  1771. * Return:
  1772. * Starting physical address
  1773. *
  1774. * Within the VM specified by vm, locates a range of available physical
  1775. * pages at or above paddr_min. If found, the pages are marked as in use
  1776. * and their base address is returned. A TEST_ASSERT failure occurs if
  1777. * not enough pages are available at or above paddr_min.
  1778. */
  1779. vm_paddr_t __vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
  1780. vm_paddr_t paddr_min, uint32_t memslot,
  1781. bool protected)
  1782. {
  1783. struct userspace_mem_region *region;
  1784. sparsebit_idx_t pg, base;
  1785. TEST_ASSERT(num > 0, "Must allocate at least one page");
  1786. TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
  1787. "not divisible by page size.\n"
  1788. " paddr_min: 0x%lx page_size: 0x%x",
  1789. paddr_min, vm->page_size);
  1790. region = memslot2region(vm, memslot);
  1791. TEST_ASSERT(!protected || region->protected_phy_pages,
  1792. "Region doesn't support protected memory");
  1793. base = pg = paddr_min >> vm->page_shift;
  1794. do {
  1795. for (; pg < base + num; ++pg) {
  1796. if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
  1797. base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
  1798. break;
  1799. }
  1800. }
  1801. } while (pg && pg != base + num);
  1802. if (pg == 0) {
  1803. fprintf(stderr, "No guest physical page available, "
  1804. "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
  1805. paddr_min, vm->page_size, memslot);
  1806. fputs("---- vm dump ----\n", stderr);
  1807. vm_dump(stderr, vm, 2);
  1808. abort();
  1809. }
  1810. for (pg = base; pg < base + num; ++pg) {
  1811. sparsebit_clear(region->unused_phy_pages, pg);
  1812. if (protected)
  1813. sparsebit_set(region->protected_phy_pages, pg);
  1814. }
  1815. return base * vm->page_size;
  1816. }
  1817. vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
  1818. uint32_t memslot)
  1819. {
  1820. return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
  1821. }
  1822. vm_paddr_t vm_alloc_page_table(struct kvm_vm *vm)
  1823. {
  1824. return vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR,
  1825. vm->memslots[MEM_REGION_PT]);
  1826. }
  1827. /*
  1828. * Address Guest Virtual to Host Virtual
  1829. *
  1830. * Input Args:
  1831. * vm - Virtual Machine
  1832. * gva - VM virtual address
  1833. *
  1834. * Output Args: None
  1835. *
  1836. * Return:
  1837. * Equivalent host virtual address
  1838. */
  1839. void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
  1840. {
  1841. return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
  1842. }
  1843. unsigned long __weak vm_compute_max_gfn(struct kvm_vm *vm)
  1844. {
  1845. return ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
  1846. }
  1847. static unsigned int vm_calc_num_pages(unsigned int num_pages,
  1848. unsigned int page_shift,
  1849. unsigned int new_page_shift,
  1850. bool ceil)
  1851. {
  1852. unsigned int n = 1 << (new_page_shift - page_shift);
  1853. if (page_shift >= new_page_shift)
  1854. return num_pages * (1 << (page_shift - new_page_shift));
  1855. return num_pages / n + !!(ceil && num_pages % n);
  1856. }
  1857. static inline int getpageshift(void)
  1858. {
  1859. return __builtin_ffs(getpagesize()) - 1;
  1860. }
  1861. unsigned int
  1862. vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
  1863. {
  1864. return vm_calc_num_pages(num_guest_pages,
  1865. vm_guest_mode_params[mode].page_shift,
  1866. getpageshift(), true);
  1867. }
  1868. unsigned int
  1869. vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
  1870. {
  1871. return vm_calc_num_pages(num_host_pages, getpageshift(),
  1872. vm_guest_mode_params[mode].page_shift, false);
  1873. }
  1874. unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
  1875. {
  1876. unsigned int n;
  1877. n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
  1878. return vm_adjust_num_guest_pages(mode, n);
  1879. }
  1880. /*
  1881. * Read binary stats descriptors
  1882. *
  1883. * Input Args:
  1884. * stats_fd - the file descriptor for the binary stats file from which to read
  1885. * header - the binary stats metadata header corresponding to the given FD
  1886. *
  1887. * Output Args: None
  1888. *
  1889. * Return:
  1890. * A pointer to a newly allocated series of stat descriptors.
  1891. * Caller is responsible for freeing the returned kvm_stats_desc.
  1892. *
  1893. * Read the stats descriptors from the binary stats interface.
  1894. */
  1895. struct kvm_stats_desc *read_stats_descriptors(int stats_fd,
  1896. struct kvm_stats_header *header)
  1897. {
  1898. struct kvm_stats_desc *stats_desc;
  1899. ssize_t desc_size, total_size, ret;
  1900. desc_size = get_stats_descriptor_size(header);
  1901. total_size = header->num_desc * desc_size;
  1902. stats_desc = calloc(header->num_desc, desc_size);
  1903. TEST_ASSERT(stats_desc, "Allocate memory for stats descriptors");
  1904. ret = pread(stats_fd, stats_desc, total_size, header->desc_offset);
  1905. TEST_ASSERT(ret == total_size, "Read KVM stats descriptors");
  1906. return stats_desc;
  1907. }
  1908. /*
  1909. * Read stat data for a particular stat
  1910. *
  1911. * Input Args:
  1912. * stats_fd - the file descriptor for the binary stats file from which to read
  1913. * header - the binary stats metadata header corresponding to the given FD
  1914. * desc - the binary stat metadata for the particular stat to be read
  1915. * max_elements - the maximum number of 8-byte values to read into data
  1916. *
  1917. * Output Args:
  1918. * data - the buffer into which stat data should be read
  1919. *
  1920. * Read the data values of a specified stat from the binary stats interface.
  1921. */
  1922. void read_stat_data(int stats_fd, struct kvm_stats_header *header,
  1923. struct kvm_stats_desc *desc, uint64_t *data,
  1924. size_t max_elements)
  1925. {
  1926. size_t nr_elements = min_t(ssize_t, desc->size, max_elements);
  1927. size_t size = nr_elements * sizeof(*data);
  1928. ssize_t ret;
  1929. TEST_ASSERT(desc->size, "No elements in stat '%s'", desc->name);
  1930. TEST_ASSERT(max_elements, "Zero elements requested for stat '%s'", desc->name);
  1931. ret = pread(stats_fd, data, size,
  1932. header->data_offset + desc->offset);
  1933. TEST_ASSERT(ret >= 0, "pread() failed on stat '%s', errno: %i (%s)",
  1934. desc->name, errno, strerror(errno));
  1935. TEST_ASSERT(ret == size,
  1936. "pread() on stat '%s' read %ld bytes, wanted %lu bytes",
  1937. desc->name, size, ret);
  1938. }
  1939. void kvm_get_stat(struct kvm_binary_stats *stats, const char *name,
  1940. uint64_t *data, size_t max_elements)
  1941. {
  1942. struct kvm_stats_desc *desc;
  1943. size_t size_desc;
  1944. int i;
  1945. if (!stats->desc) {
  1946. read_stats_header(stats->fd, &stats->header);
  1947. stats->desc = read_stats_descriptors(stats->fd, &stats->header);
  1948. }
  1949. size_desc = get_stats_descriptor_size(&stats->header);
  1950. for (i = 0; i < stats->header.num_desc; ++i) {
  1951. desc = (void *)stats->desc + (i * size_desc);
  1952. if (strcmp(desc->name, name))
  1953. continue;
  1954. read_stat_data(stats->fd, &stats->header, desc, data, max_elements);
  1955. return;
  1956. }
  1957. TEST_FAIL("Unable to find stat '%s'", name);
  1958. }
  1959. __weak void kvm_arch_vm_post_create(struct kvm_vm *vm, unsigned int nr_vcpus)
  1960. {
  1961. }
  1962. __weak void kvm_arch_vm_finalize_vcpus(struct kvm_vm *vm)
  1963. {
  1964. }
  1965. __weak void kvm_arch_vm_release(struct kvm_vm *vm)
  1966. {
  1967. }
  1968. __weak void kvm_selftest_arch_init(void)
  1969. {
  1970. }
  1971. static void report_unexpected_signal(int signum)
  1972. {
  1973. #define KVM_CASE_SIGNUM(sig) \
  1974. case sig: TEST_FAIL("Unexpected " #sig " (%d)\n", signum)
  1975. switch (signum) {
  1976. KVM_CASE_SIGNUM(SIGBUS);
  1977. KVM_CASE_SIGNUM(SIGSEGV);
  1978. KVM_CASE_SIGNUM(SIGILL);
  1979. KVM_CASE_SIGNUM(SIGFPE);
  1980. default:
  1981. TEST_FAIL("Unexpected signal %d\n", signum);
  1982. }
  1983. }
  1984. void __attribute((constructor)) kvm_selftest_init(void)
  1985. {
  1986. struct sigaction sig_sa = {
  1987. .sa_handler = report_unexpected_signal,
  1988. };
  1989. /* Tell stdout not to buffer its content. */
  1990. setbuf(stdout, NULL);
  1991. sigaction(SIGBUS, &sig_sa, NULL);
  1992. sigaction(SIGSEGV, &sig_sa, NULL);
  1993. sigaction(SIGILL, &sig_sa, NULL);
  1994. sigaction(SIGFPE, &sig_sa, NULL);
  1995. guest_random_seed = last_guest_seed = random();
  1996. pr_info("Random seed: 0x%x\n", guest_random_seed);
  1997. kvm_selftest_arch_init();
  1998. }
  1999. bool vm_is_gpa_protected(struct kvm_vm *vm, vm_paddr_t paddr)
  2000. {
  2001. sparsebit_idx_t pg = 0;
  2002. struct userspace_mem_region *region;
  2003. if (!vm_arch_has_protected_memory(vm))
  2004. return false;
  2005. region = userspace_mem_region_find(vm, paddr, paddr);
  2006. TEST_ASSERT(region, "No vm physical memory at 0x%lx", paddr);
  2007. pg = paddr >> vm->page_shift;
  2008. return sparsebit_is_set(region->protected_phy_pages, pg);
  2009. }
  2010. __weak bool kvm_arch_has_default_irqchip(void)
  2011. {
  2012. return false;
  2013. }