dirty_log_test.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * KVM dirty page logging test
  4. *
  5. * Copyright (C) 2018, Red Hat, Inc.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <pthread.h>
  10. #include <semaphore.h>
  11. #include <sys/types.h>
  12. #include <signal.h>
  13. #include <errno.h>
  14. #include <linux/bitmap.h>
  15. #include <linux/bitops.h>
  16. #include <linux/atomic.h>
  17. #include <asm/barrier.h>
  18. #include "kvm_util.h"
  19. #include "test_util.h"
  20. #include "guest_modes.h"
  21. #include "processor.h"
  22. #include "ucall_common.h"
  23. #define DIRTY_MEM_BITS 30 /* 1G */
  24. #define PAGE_SHIFT_4K 12
  25. /* The memory slot index to track dirty pages */
  26. #define TEST_MEM_SLOT_INDEX 1
  27. /* Default guest test virtual memory offset */
  28. #define DEFAULT_GUEST_TEST_MEM 0xc0000000
  29. /* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
  30. #define TEST_HOST_LOOP_N 32UL
  31. /* Interval for each host loop (ms) */
  32. #define TEST_HOST_LOOP_INTERVAL 10UL
  33. /*
  34. * Ensure the vCPU is able to perform a reasonable number of writes in each
  35. * iteration to provide a lower bound on coverage.
  36. */
  37. #define TEST_MIN_WRITES_PER_ITERATION 0x100
  38. /* Dirty bitmaps are always little endian, so we need to swap on big endian */
  39. #if defined(__s390x__)
  40. # define BITOP_LE_SWIZZLE ((BITS_PER_LONG-1) & ~0x7)
  41. # define test_bit_le(nr, addr) \
  42. test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  43. # define __set_bit_le(nr, addr) \
  44. __set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  45. # define __clear_bit_le(nr, addr) \
  46. __clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  47. # define __test_and_set_bit_le(nr, addr) \
  48. __test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  49. # define __test_and_clear_bit_le(nr, addr) \
  50. __test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  51. #else
  52. # define test_bit_le test_bit
  53. # define __set_bit_le __set_bit
  54. # define __clear_bit_le __clear_bit
  55. # define __test_and_set_bit_le __test_and_set_bit
  56. # define __test_and_clear_bit_le __test_and_clear_bit
  57. #endif
  58. #define TEST_DIRTY_RING_COUNT 65536
  59. #define SIG_IPI SIGUSR1
  60. /*
  61. * Guest/Host shared variables. Ensure addr_gva2hva() and/or
  62. * sync_global_to/from_guest() are used when accessing from
  63. * the host. READ/WRITE_ONCE() should also be used with anything
  64. * that may change.
  65. */
  66. static uint64_t host_page_size;
  67. static uint64_t guest_page_size;
  68. static uint64_t guest_num_pages;
  69. static uint64_t iteration;
  70. static uint64_t nr_writes;
  71. static bool vcpu_stop;
  72. /*
  73. * Guest physical memory offset of the testing memory slot.
  74. * This will be set to the topmost valid physical address minus
  75. * the test memory size.
  76. */
  77. static uint64_t guest_test_phys_mem;
  78. /*
  79. * Guest virtual memory offset of the testing memory slot.
  80. * Must not conflict with identity mapped test code.
  81. */
  82. static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
  83. /*
  84. * Continuously write to the first 8 bytes of a random pages within
  85. * the testing memory region.
  86. */
  87. static void guest_code(void)
  88. {
  89. uint64_t addr;
  90. #ifdef __s390x__
  91. uint64_t i;
  92. /*
  93. * On s390x, all pages of a 1M segment are initially marked as dirty
  94. * when a page of the segment is written to for the very first time.
  95. * To compensate this specialty in this test, we need to touch all
  96. * pages during the first iteration.
  97. */
  98. for (i = 0; i < guest_num_pages; i++) {
  99. addr = guest_test_virt_mem + i * guest_page_size;
  100. vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));
  101. nr_writes++;
  102. }
  103. #endif
  104. while (true) {
  105. while (!READ_ONCE(vcpu_stop)) {
  106. addr = guest_test_virt_mem;
  107. addr += (guest_random_u64(&guest_rng) % guest_num_pages)
  108. * guest_page_size;
  109. addr = align_down(addr, host_page_size);
  110. vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));
  111. nr_writes++;
  112. }
  113. GUEST_SYNC(1);
  114. }
  115. }
  116. /* Host variables */
  117. static bool host_quit;
  118. /* Points to the test VM memory region on which we track dirty logs */
  119. static void *host_test_mem;
  120. static uint64_t host_num_pages;
  121. /* For statistics only */
  122. static uint64_t host_dirty_count;
  123. static uint64_t host_clear_count;
  124. /* Whether dirty ring reset is requested, or finished */
  125. static sem_t sem_vcpu_stop;
  126. static sem_t sem_vcpu_cont;
  127. /*
  128. * This is updated by the vcpu thread to tell the host whether it's a
  129. * ring-full event. It should only be read until a sem_wait() of
  130. * sem_vcpu_stop and before vcpu continues to run.
  131. */
  132. static bool dirty_ring_vcpu_ring_full;
  133. /*
  134. * This is only used for verifying the dirty pages. Dirty ring has a very
  135. * tricky case when the ring just got full, kvm will do userspace exit due to
  136. * ring full. When that happens, the very last PFN is set but actually the
  137. * data is not changed (the guest WRITE is not really applied yet), because
  138. * we found that the dirty ring is full, refused to continue the vcpu, and
  139. * recorded the dirty gfn with the old contents.
  140. *
  141. * For this specific case, it's safe to skip checking this pfn for this
  142. * bit, because it's a redundant bit, and when the write happens later the bit
  143. * will be set again. We use this variable to always keep track of the latest
  144. * dirty gfn we've collected, so that if a mismatch of data found later in the
  145. * verifying process, we let it pass.
  146. */
  147. static uint64_t dirty_ring_last_page = -1ULL;
  148. /*
  149. * In addition to the above, it is possible (especially if this
  150. * test is run nested) for the above scenario to repeat multiple times:
  151. *
  152. * The following can happen:
  153. *
  154. * - L1 vCPU: Memory write is logged to PML but not committed.
  155. *
  156. * - L1 test thread: Ignores the write because its last dirty ring entry
  157. * Resets the dirty ring which:
  158. * - Resets the A/D bits in EPT
  159. * - Issues tlb flush (invept), which is intercepted by L0
  160. *
  161. * - L0: frees the whole nested ept mmu root as the response to invept,
  162. * and thus ensures that when memory write is retried, it will fault again
  163. *
  164. * - L1 vCPU: Same memory write is logged to the PML but not committed again.
  165. *
  166. * - L1 test thread: Ignores the write because its last dirty ring entry (again)
  167. * Resets the dirty ring which:
  168. * - Resets the A/D bits in EPT (again)
  169. * - Issues tlb flush (again) which is intercepted by L0
  170. *
  171. * ...
  172. *
  173. * N times
  174. *
  175. * - L1 vCPU: Memory write is logged in the PML and then committed.
  176. * Lots of other memory writes are logged and committed.
  177. * ...
  178. *
  179. * - L1 test thread: Sees the memory write along with other memory writes
  180. * in the dirty ring, and since the write is usually not
  181. * the last entry in the dirty-ring and has a very outdated
  182. * iteration, the test fails.
  183. *
  184. *
  185. * Note that this is only possible when the write was the last log entry
  186. * write during iteration N-1, thus remember last iteration last log entry
  187. * and also don't fail when it is reported in the next iteration, together with
  188. * an outdated iteration count.
  189. */
  190. static uint64_t dirty_ring_prev_iteration_last_page;
  191. enum log_mode_t {
  192. /* Only use KVM_GET_DIRTY_LOG for logging */
  193. LOG_MODE_DIRTY_LOG = 0,
  194. /* Use both KVM_[GET|CLEAR]_DIRTY_LOG for logging */
  195. LOG_MODE_CLEAR_LOG = 1,
  196. /* Use dirty ring for logging */
  197. LOG_MODE_DIRTY_RING = 2,
  198. LOG_MODE_NUM,
  199. /* Run all supported modes */
  200. LOG_MODE_ALL = LOG_MODE_NUM,
  201. };
  202. /* Mode of logging to test. Default is to run all supported modes */
  203. static enum log_mode_t host_log_mode_option = LOG_MODE_ALL;
  204. /* Logging mode for current run */
  205. static enum log_mode_t host_log_mode;
  206. static pthread_t vcpu_thread;
  207. static uint32_t test_dirty_ring_count = TEST_DIRTY_RING_COUNT;
  208. static bool clear_log_supported(void)
  209. {
  210. return kvm_has_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  211. }
  212. static void clear_log_create_vm_done(struct kvm_vm *vm)
  213. {
  214. u64 manual_caps;
  215. manual_caps = kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  216. TEST_ASSERT(manual_caps, "MANUAL_CAPS is zero!");
  217. manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
  218. KVM_DIRTY_LOG_INITIALLY_SET);
  219. vm_enable_cap(vm, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, manual_caps);
  220. }
  221. static void dirty_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  222. void *bitmap, uint32_t num_pages,
  223. uint32_t *unused)
  224. {
  225. kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);
  226. }
  227. static void clear_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  228. void *bitmap, uint32_t num_pages,
  229. uint32_t *unused)
  230. {
  231. kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);
  232. kvm_vm_clear_dirty_log(vcpu->vm, slot, bitmap, 0, num_pages);
  233. }
  234. /* Should only be called after a GUEST_SYNC */
  235. static void vcpu_handle_sync_stop(void)
  236. {
  237. if (READ_ONCE(vcpu_stop)) {
  238. sem_post(&sem_vcpu_stop);
  239. sem_wait(&sem_vcpu_cont);
  240. }
  241. }
  242. static void default_after_vcpu_run(struct kvm_vcpu *vcpu)
  243. {
  244. struct kvm_run *run = vcpu->run;
  245. TEST_ASSERT(get_ucall(vcpu, NULL) == UCALL_SYNC,
  246. "Invalid guest sync status: exit_reason=%s",
  247. exit_reason_str(run->exit_reason));
  248. vcpu_handle_sync_stop();
  249. }
  250. static bool dirty_ring_supported(void)
  251. {
  252. return (kvm_has_cap(KVM_CAP_DIRTY_LOG_RING) ||
  253. kvm_has_cap(KVM_CAP_DIRTY_LOG_RING_ACQ_REL));
  254. }
  255. static void dirty_ring_create_vm_done(struct kvm_vm *vm)
  256. {
  257. uint64_t pages;
  258. uint32_t limit;
  259. /*
  260. * We rely on vcpu exit due to full dirty ring state. Adjust
  261. * the ring buffer size to ensure we're able to reach the
  262. * full dirty ring state.
  263. */
  264. pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;
  265. pages = vm_adjust_num_guest_pages(vm->mode, pages);
  266. if (vm->page_size < getpagesize())
  267. pages = vm_num_host_pages(vm->mode, pages);
  268. limit = 1 << (31 - __builtin_clz(pages));
  269. test_dirty_ring_count = 1 << (31 - __builtin_clz(test_dirty_ring_count));
  270. test_dirty_ring_count = min(limit, test_dirty_ring_count);
  271. pr_info("dirty ring count: 0x%x\n", test_dirty_ring_count);
  272. /*
  273. * Switch to dirty ring mode after VM creation but before any
  274. * of the vcpu creation.
  275. */
  276. vm_enable_dirty_ring(vm, test_dirty_ring_count *
  277. sizeof(struct kvm_dirty_gfn));
  278. }
  279. static inline bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
  280. {
  281. return smp_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
  282. }
  283. static inline void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
  284. {
  285. smp_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
  286. }
  287. static uint32_t dirty_ring_collect_one(struct kvm_dirty_gfn *dirty_gfns,
  288. int slot, void *bitmap,
  289. uint32_t num_pages, uint32_t *fetch_index)
  290. {
  291. struct kvm_dirty_gfn *cur;
  292. uint32_t count = 0;
  293. while (true) {
  294. cur = &dirty_gfns[*fetch_index % test_dirty_ring_count];
  295. if (!dirty_gfn_is_dirtied(cur))
  296. break;
  297. TEST_ASSERT(cur->slot == slot, "Slot number didn't match: "
  298. "%u != %u", cur->slot, slot);
  299. TEST_ASSERT(cur->offset < num_pages, "Offset overflow: "
  300. "0x%llx >= 0x%x", cur->offset, num_pages);
  301. __set_bit_le(cur->offset, bitmap);
  302. dirty_ring_last_page = cur->offset;
  303. dirty_gfn_set_collected(cur);
  304. (*fetch_index)++;
  305. count++;
  306. }
  307. return count;
  308. }
  309. static void dirty_ring_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  310. void *bitmap, uint32_t num_pages,
  311. uint32_t *ring_buf_idx)
  312. {
  313. uint32_t count, cleared;
  314. /* Only have one vcpu */
  315. count = dirty_ring_collect_one(vcpu_map_dirty_ring(vcpu),
  316. slot, bitmap, num_pages,
  317. ring_buf_idx);
  318. cleared = kvm_vm_reset_dirty_ring(vcpu->vm);
  319. /*
  320. * Cleared pages should be the same as collected, as KVM is supposed to
  321. * clear only the entries that have been harvested.
  322. */
  323. TEST_ASSERT(cleared == count, "Reset dirty pages (%u) mismatch "
  324. "with collected (%u)", cleared, count);
  325. }
  326. static void dirty_ring_after_vcpu_run(struct kvm_vcpu *vcpu)
  327. {
  328. struct kvm_run *run = vcpu->run;
  329. /* A ucall-sync or ring-full event is allowed */
  330. if (get_ucall(vcpu, NULL) == UCALL_SYNC) {
  331. vcpu_handle_sync_stop();
  332. } else if (run->exit_reason == KVM_EXIT_DIRTY_RING_FULL) {
  333. WRITE_ONCE(dirty_ring_vcpu_ring_full, true);
  334. vcpu_handle_sync_stop();
  335. } else {
  336. TEST_ASSERT(false, "Invalid guest sync status: "
  337. "exit_reason=%s",
  338. exit_reason_str(run->exit_reason));
  339. }
  340. }
  341. struct log_mode {
  342. const char *name;
  343. /* Return true if this mode is supported, otherwise false */
  344. bool (*supported)(void);
  345. /* Hook when the vm creation is done (before vcpu creation) */
  346. void (*create_vm_done)(struct kvm_vm *vm);
  347. /* Hook to collect the dirty pages into the bitmap provided */
  348. void (*collect_dirty_pages) (struct kvm_vcpu *vcpu, int slot,
  349. void *bitmap, uint32_t num_pages,
  350. uint32_t *ring_buf_idx);
  351. /* Hook to call when after each vcpu run */
  352. void (*after_vcpu_run)(struct kvm_vcpu *vcpu);
  353. } log_modes[LOG_MODE_NUM] = {
  354. {
  355. .name = "dirty-log",
  356. .collect_dirty_pages = dirty_log_collect_dirty_pages,
  357. .after_vcpu_run = default_after_vcpu_run,
  358. },
  359. {
  360. .name = "clear-log",
  361. .supported = clear_log_supported,
  362. .create_vm_done = clear_log_create_vm_done,
  363. .collect_dirty_pages = clear_log_collect_dirty_pages,
  364. .after_vcpu_run = default_after_vcpu_run,
  365. },
  366. {
  367. .name = "dirty-ring",
  368. .supported = dirty_ring_supported,
  369. .create_vm_done = dirty_ring_create_vm_done,
  370. .collect_dirty_pages = dirty_ring_collect_dirty_pages,
  371. .after_vcpu_run = dirty_ring_after_vcpu_run,
  372. },
  373. };
  374. static void log_modes_dump(void)
  375. {
  376. int i;
  377. printf("all");
  378. for (i = 0; i < LOG_MODE_NUM; i++)
  379. printf(", %s", log_modes[i].name);
  380. printf("\n");
  381. }
  382. static bool log_mode_supported(void)
  383. {
  384. struct log_mode *mode = &log_modes[host_log_mode];
  385. if (mode->supported)
  386. return mode->supported();
  387. return true;
  388. }
  389. static void log_mode_create_vm_done(struct kvm_vm *vm)
  390. {
  391. struct log_mode *mode = &log_modes[host_log_mode];
  392. if (mode->create_vm_done)
  393. mode->create_vm_done(vm);
  394. }
  395. static void log_mode_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  396. void *bitmap, uint32_t num_pages,
  397. uint32_t *ring_buf_idx)
  398. {
  399. struct log_mode *mode = &log_modes[host_log_mode];
  400. TEST_ASSERT(mode->collect_dirty_pages != NULL,
  401. "collect_dirty_pages() is required for any log mode!");
  402. mode->collect_dirty_pages(vcpu, slot, bitmap, num_pages, ring_buf_idx);
  403. }
  404. static void log_mode_after_vcpu_run(struct kvm_vcpu *vcpu)
  405. {
  406. struct log_mode *mode = &log_modes[host_log_mode];
  407. if (mode->after_vcpu_run)
  408. mode->after_vcpu_run(vcpu);
  409. }
  410. static void *vcpu_worker(void *data)
  411. {
  412. struct kvm_vcpu *vcpu = data;
  413. sem_wait(&sem_vcpu_cont);
  414. while (!READ_ONCE(host_quit)) {
  415. /* Let the guest dirty the random pages */
  416. vcpu_run(vcpu);
  417. log_mode_after_vcpu_run(vcpu);
  418. }
  419. return NULL;
  420. }
  421. static void vm_dirty_log_verify(enum vm_guest_mode mode, unsigned long **bmap)
  422. {
  423. uint64_t page, nr_dirty_pages = 0, nr_clean_pages = 0;
  424. uint64_t step = vm_num_host_pages(mode, 1);
  425. for (page = 0; page < host_num_pages; page += step) {
  426. uint64_t val = *(uint64_t *)(host_test_mem + page * host_page_size);
  427. bool bmap0_dirty = __test_and_clear_bit_le(page, bmap[0]);
  428. /*
  429. * Ensure both bitmaps are cleared, as a page can be written
  430. * multiple times per iteration, i.e. can show up in both
  431. * bitmaps, and the dirty ring is additive, i.e. doesn't purge
  432. * bitmap entries from previous collections.
  433. */
  434. if (__test_and_clear_bit_le(page, bmap[1]) || bmap0_dirty) {
  435. nr_dirty_pages++;
  436. /*
  437. * If the page is dirty, the value written to memory
  438. * should be the current iteration number.
  439. */
  440. if (val == iteration)
  441. continue;
  442. if (host_log_mode == LOG_MODE_DIRTY_RING) {
  443. /*
  444. * The last page in the ring from previous
  445. * iteration can be written with the value
  446. * from the previous iteration, as the value to
  447. * be written may be cached in a CPU register.
  448. */
  449. if (page == dirty_ring_prev_iteration_last_page &&
  450. val == iteration - 1)
  451. continue;
  452. /*
  453. * Any value from a previous iteration is legal
  454. * for the last entry, as the write may not yet
  455. * have retired, i.e. the page may hold whatever
  456. * it had before this iteration started.
  457. */
  458. if (page == dirty_ring_last_page &&
  459. val < iteration)
  460. continue;
  461. } else if (!val && iteration == 1 && bmap0_dirty) {
  462. /*
  463. * When testing get+clear, the dirty bitmap
  464. * starts with all bits set, and so the first
  465. * iteration can observe a "dirty" page that
  466. * was never written, but only in the first
  467. * bitmap (collecting the bitmap also clears
  468. * all dirty pages).
  469. */
  470. continue;
  471. }
  472. TEST_FAIL("Dirty page %lu value (%lu) != iteration (%lu) "
  473. "(last = %lu, prev_last = %lu)",
  474. page, val, iteration, dirty_ring_last_page,
  475. dirty_ring_prev_iteration_last_page);
  476. } else {
  477. nr_clean_pages++;
  478. /*
  479. * If cleared, the value written can be any
  480. * value smaller than the iteration number.
  481. */
  482. TEST_ASSERT(val < iteration,
  483. "Clear page %lu value (%lu) >= iteration (%lu) "
  484. "(last = %lu, prev_last = %lu)",
  485. page, val, iteration, dirty_ring_last_page,
  486. dirty_ring_prev_iteration_last_page);
  487. }
  488. }
  489. pr_info("Iteration %2ld: dirty: %-6lu clean: %-6lu writes: %-6lu\n",
  490. iteration, nr_dirty_pages, nr_clean_pages, nr_writes);
  491. host_dirty_count += nr_dirty_pages;
  492. host_clear_count += nr_clean_pages;
  493. }
  494. static struct kvm_vm *create_vm(enum vm_guest_mode mode, struct kvm_vcpu **vcpu,
  495. uint64_t extra_mem_pages, void *guest_code)
  496. {
  497. struct kvm_vm *vm;
  498. pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));
  499. vm = __vm_create(VM_SHAPE(mode), 1, extra_mem_pages);
  500. log_mode_create_vm_done(vm);
  501. *vcpu = vm_vcpu_add(vm, 0, guest_code);
  502. kvm_arch_vm_finalize_vcpus(vm);
  503. return vm;
  504. }
  505. struct test_params {
  506. unsigned long iterations;
  507. unsigned long interval;
  508. uint64_t phys_offset;
  509. };
  510. static void run_test(enum vm_guest_mode mode, void *arg)
  511. {
  512. struct test_params *p = arg;
  513. struct kvm_vcpu *vcpu;
  514. struct kvm_vm *vm;
  515. unsigned long *bmap[2];
  516. uint32_t ring_buf_idx = 0;
  517. int sem_val;
  518. if (!log_mode_supported()) {
  519. print_skip("Log mode '%s' not supported",
  520. log_modes[host_log_mode].name);
  521. return;
  522. }
  523. /*
  524. * We reserve page table for 2 times of extra dirty mem which
  525. * will definitely cover the original (1G+) test range. Here
  526. * we do the calculation with 4K page size which is the
  527. * smallest so the page number will be enough for all archs
  528. * (e.g., 64K page size guest will need even less memory for
  529. * page tables).
  530. */
  531. vm = create_vm(mode, &vcpu,
  532. 2ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K), guest_code);
  533. guest_page_size = vm->page_size;
  534. /*
  535. * A little more than 1G of guest page sized pages. Cover the
  536. * case where the size is not aligned to 64 pages.
  537. */
  538. guest_num_pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;
  539. guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
  540. host_page_size = getpagesize();
  541. host_num_pages = vm_num_host_pages(mode, guest_num_pages);
  542. if (!p->phys_offset) {
  543. guest_test_phys_mem = (vm->max_gfn - guest_num_pages) *
  544. guest_page_size;
  545. guest_test_phys_mem = align_down(guest_test_phys_mem, host_page_size);
  546. } else {
  547. guest_test_phys_mem = p->phys_offset;
  548. }
  549. #ifdef __s390x__
  550. /* Align to 1M (segment size) */
  551. guest_test_phys_mem = align_down(guest_test_phys_mem, 1 << 20);
  552. /*
  553. * The workaround in guest_code() to write all pages prior to the first
  554. * iteration isn't compatible with the dirty ring, as the dirty ring
  555. * support relies on the vCPU to actually stop when vcpu_stop is set so
  556. * that the vCPU doesn't hang waiting for the dirty ring to be emptied.
  557. */
  558. TEST_ASSERT(host_log_mode != LOG_MODE_DIRTY_RING,
  559. "Test needs to be updated to support s390 dirty ring");
  560. #endif
  561. pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
  562. bmap[0] = bitmap_zalloc(host_num_pages);
  563. bmap[1] = bitmap_zalloc(host_num_pages);
  564. /* Add an extra memory slot for testing dirty logging */
  565. vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
  566. guest_test_phys_mem,
  567. TEST_MEM_SLOT_INDEX,
  568. guest_num_pages,
  569. KVM_MEM_LOG_DIRTY_PAGES);
  570. /* Do mapping for the dirty track memory slot */
  571. virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages);
  572. /* Cache the HVA pointer of the region */
  573. host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
  574. /* Export the shared variables to the guest */
  575. sync_global_to_guest(vm, host_page_size);
  576. sync_global_to_guest(vm, guest_page_size);
  577. sync_global_to_guest(vm, guest_test_virt_mem);
  578. sync_global_to_guest(vm, guest_num_pages);
  579. host_dirty_count = 0;
  580. host_clear_count = 0;
  581. WRITE_ONCE(host_quit, false);
  582. /*
  583. * Ensure the previous iteration didn't leave a dangling semaphore, i.e.
  584. * that the main task and vCPU worker were synchronized and completed
  585. * verification of all iterations.
  586. */
  587. sem_getvalue(&sem_vcpu_stop, &sem_val);
  588. TEST_ASSERT_EQ(sem_val, 0);
  589. sem_getvalue(&sem_vcpu_cont, &sem_val);
  590. TEST_ASSERT_EQ(sem_val, 0);
  591. TEST_ASSERT_EQ(vcpu_stop, false);
  592. pthread_create(&vcpu_thread, NULL, vcpu_worker, vcpu);
  593. for (iteration = 1; iteration <= p->iterations; iteration++) {
  594. unsigned long i;
  595. sync_global_to_guest(vm, iteration);
  596. WRITE_ONCE(nr_writes, 0);
  597. sync_global_to_guest(vm, nr_writes);
  598. dirty_ring_prev_iteration_last_page = dirty_ring_last_page;
  599. WRITE_ONCE(dirty_ring_vcpu_ring_full, false);
  600. sem_post(&sem_vcpu_cont);
  601. /*
  602. * Let the vCPU run beyond the configured interval until it has
  603. * performed the minimum number of writes. This verifies the
  604. * guest is making forward progress, e.g. isn't stuck because
  605. * of a KVM bug, and puts a firm floor on test coverage.
  606. */
  607. for (i = 0; i < p->interval || nr_writes < TEST_MIN_WRITES_PER_ITERATION; i++) {
  608. /*
  609. * Sleep in 1ms chunks to keep the interval math simple
  610. * and so that the test doesn't run too far beyond the
  611. * specified interval.
  612. */
  613. usleep(1000);
  614. sync_global_from_guest(vm, nr_writes);
  615. /*
  616. * Reap dirty pages while the guest is running so that
  617. * dirty ring full events are resolved, i.e. so that a
  618. * larger interval doesn't always end up with a vCPU
  619. * that's effectively blocked. Collecting while the
  620. * guest is running also verifies KVM doesn't lose any
  621. * state.
  622. *
  623. * For bitmap modes, KVM overwrites the entire bitmap,
  624. * i.e. collecting the bitmaps is destructive. Collect
  625. * the bitmap only on the first pass, otherwise this
  626. * test would lose track of dirty pages.
  627. */
  628. if (i && host_log_mode != LOG_MODE_DIRTY_RING)
  629. continue;
  630. /*
  631. * For the dirty ring, empty the ring on subsequent
  632. * passes only if the ring was filled at least once,
  633. * to verify KVM's handling of a full ring (emptying
  634. * the ring on every pass would make it unlikely the
  635. * vCPU would ever fill the fing).
  636. */
  637. if (i && !READ_ONCE(dirty_ring_vcpu_ring_full))
  638. continue;
  639. log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
  640. bmap[0], host_num_pages,
  641. &ring_buf_idx);
  642. }
  643. /*
  644. * Stop the vCPU prior to collecting and verifying the dirty
  645. * log. If the vCPU is allowed to run during collection, then
  646. * pages that are written during this iteration may be missed,
  647. * i.e. collected in the next iteration. And if the vCPU is
  648. * writing memory during verification, pages that this thread
  649. * sees as clean may be written with this iteration's value.
  650. */
  651. WRITE_ONCE(vcpu_stop, true);
  652. sync_global_to_guest(vm, vcpu_stop);
  653. sem_wait(&sem_vcpu_stop);
  654. /*
  655. * Clear vcpu_stop after the vCPU thread has acknowledge the
  656. * stop request and is waiting, i.e. is definitely not running!
  657. */
  658. WRITE_ONCE(vcpu_stop, false);
  659. sync_global_to_guest(vm, vcpu_stop);
  660. /*
  661. * Sync the number of writes performed before verification, the
  662. * info will be printed along with the dirty/clean page counts.
  663. */
  664. sync_global_from_guest(vm, nr_writes);
  665. /*
  666. * NOTE: for dirty ring, it's possible that we didn't stop at
  667. * GUEST_SYNC but instead we stopped because ring is full;
  668. * that's okay too because ring full means we're only missing
  669. * the flush of the last page, and since we handle the last
  670. * page specially verification will succeed anyway.
  671. */
  672. log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
  673. bmap[1], host_num_pages,
  674. &ring_buf_idx);
  675. vm_dirty_log_verify(mode, bmap);
  676. }
  677. WRITE_ONCE(host_quit, true);
  678. sem_post(&sem_vcpu_cont);
  679. pthread_join(vcpu_thread, NULL);
  680. pr_info("Total bits checked: dirty (%lu), clear (%lu)\n",
  681. host_dirty_count, host_clear_count);
  682. free(bmap[0]);
  683. free(bmap[1]);
  684. kvm_vm_free(vm);
  685. }
  686. static void help(char *name)
  687. {
  688. puts("");
  689. printf("usage: %s [-h] [-i iterations] [-I interval] "
  690. "[-p offset] [-m mode]\n", name);
  691. puts("");
  692. printf(" -c: hint to dirty ring size, in number of entries\n");
  693. printf(" (only useful for dirty-ring test; default: %"PRIu32")\n",
  694. TEST_DIRTY_RING_COUNT);
  695. printf(" -i: specify iteration counts (default: %"PRIu64")\n",
  696. TEST_HOST_LOOP_N);
  697. printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
  698. TEST_HOST_LOOP_INTERVAL);
  699. printf(" -p: specify guest physical test memory offset\n"
  700. " Warning: a low offset can conflict with the loaded test code.\n");
  701. printf(" -M: specify the host logging mode "
  702. "(default: run all log modes). Supported modes: \n\t");
  703. log_modes_dump();
  704. guest_modes_help();
  705. puts("");
  706. exit(0);
  707. }
  708. int main(int argc, char *argv[])
  709. {
  710. struct test_params p = {
  711. .iterations = TEST_HOST_LOOP_N,
  712. .interval = TEST_HOST_LOOP_INTERVAL,
  713. };
  714. int opt, i;
  715. sem_init(&sem_vcpu_stop, 0, 0);
  716. sem_init(&sem_vcpu_cont, 0, 0);
  717. guest_modes_append_default();
  718. while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {
  719. switch (opt) {
  720. case 'c':
  721. test_dirty_ring_count = strtol(optarg, NULL, 10);
  722. break;
  723. case 'i':
  724. p.iterations = strtol(optarg, NULL, 10);
  725. break;
  726. case 'I':
  727. p.interval = strtol(optarg, NULL, 10);
  728. break;
  729. case 'p':
  730. p.phys_offset = strtoull(optarg, NULL, 0);
  731. break;
  732. case 'm':
  733. guest_modes_cmdline(optarg);
  734. break;
  735. case 'M':
  736. if (!strcmp(optarg, "all")) {
  737. host_log_mode_option = LOG_MODE_ALL;
  738. break;
  739. }
  740. for (i = 0; i < LOG_MODE_NUM; i++) {
  741. if (!strcmp(optarg, log_modes[i].name)) {
  742. pr_info("Setting log mode to: '%s'\n",
  743. optarg);
  744. host_log_mode_option = i;
  745. break;
  746. }
  747. }
  748. if (i == LOG_MODE_NUM) {
  749. printf("Log mode '%s' invalid. Please choose "
  750. "from: ", optarg);
  751. log_modes_dump();
  752. exit(1);
  753. }
  754. break;
  755. case 'h':
  756. default:
  757. help(argv[0]);
  758. break;
  759. }
  760. }
  761. TEST_ASSERT(p.iterations > 0, "Iterations must be greater than zero");
  762. TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");
  763. pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
  764. p.iterations, p.interval);
  765. if (host_log_mode_option == LOG_MODE_ALL) {
  766. /* Run each log mode */
  767. for (i = 0; i < LOG_MODE_NUM; i++) {
  768. pr_info("Testing Log Mode '%s'\n", log_modes[i].name);
  769. host_log_mode = i;
  770. for_each_guest_mode(run_test, &p);
  771. }
  772. } else {
  773. host_log_mode = host_log_mode_option;
  774. for_each_guest_mode(run_test, &p);
  775. }
  776. return 0;
  777. }