dirty_log_test.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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 pages to dirty for each guest loop */
  30. #define TEST_PAGES_PER_LOOP 1024
  31. /* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
  32. #define TEST_HOST_LOOP_N 32UL
  33. /* Interval for each host loop (ms) */
  34. #define TEST_HOST_LOOP_INTERVAL 10UL
  35. /* Dirty bitmaps are always little endian, so we need to swap on big endian */
  36. #if defined(__s390x__)
  37. # define BITOP_LE_SWIZZLE ((BITS_PER_LONG-1) & ~0x7)
  38. # define test_bit_le(nr, addr) \
  39. test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  40. # define __set_bit_le(nr, addr) \
  41. __set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  42. # define __clear_bit_le(nr, addr) \
  43. __clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  44. # define __test_and_set_bit_le(nr, addr) \
  45. __test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  46. # define __test_and_clear_bit_le(nr, addr) \
  47. __test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
  48. #else
  49. # define test_bit_le test_bit
  50. # define __set_bit_le __set_bit
  51. # define __clear_bit_le __clear_bit
  52. # define __test_and_set_bit_le __test_and_set_bit
  53. # define __test_and_clear_bit_le __test_and_clear_bit
  54. #endif
  55. #define TEST_DIRTY_RING_COUNT 65536
  56. #define SIG_IPI SIGUSR1
  57. /*
  58. * Guest/Host shared variables. Ensure addr_gva2hva() and/or
  59. * sync_global_to/from_guest() are used when accessing from
  60. * the host. READ/WRITE_ONCE() should also be used with anything
  61. * that may change.
  62. */
  63. static uint64_t host_page_size;
  64. static uint64_t guest_page_size;
  65. static uint64_t guest_num_pages;
  66. static uint64_t iteration;
  67. /*
  68. * Guest physical memory offset of the testing memory slot.
  69. * This will be set to the topmost valid physical address minus
  70. * the test memory size.
  71. */
  72. static uint64_t guest_test_phys_mem;
  73. /*
  74. * Guest virtual memory offset of the testing memory slot.
  75. * Must not conflict with identity mapped test code.
  76. */
  77. static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
  78. /*
  79. * Continuously write to the first 8 bytes of a random pages within
  80. * the testing memory region.
  81. */
  82. static void guest_code(void)
  83. {
  84. uint64_t addr;
  85. int i;
  86. /*
  87. * On s390x, all pages of a 1M segment are initially marked as dirty
  88. * when a page of the segment is written to for the very first time.
  89. * To compensate this specialty in this test, we need to touch all
  90. * pages during the first iteration.
  91. */
  92. for (i = 0; i < guest_num_pages; i++) {
  93. addr = guest_test_virt_mem + i * guest_page_size;
  94. vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));
  95. }
  96. while (true) {
  97. for (i = 0; i < TEST_PAGES_PER_LOOP; i++) {
  98. addr = guest_test_virt_mem;
  99. addr += (guest_random_u64(&guest_rng) % guest_num_pages)
  100. * guest_page_size;
  101. addr = align_down(addr, host_page_size);
  102. vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));
  103. }
  104. GUEST_SYNC(1);
  105. }
  106. }
  107. /* Host variables */
  108. static bool host_quit;
  109. /* Points to the test VM memory region on which we track dirty logs */
  110. static void *host_test_mem;
  111. static uint64_t host_num_pages;
  112. /* For statistics only */
  113. static uint64_t host_dirty_count;
  114. static uint64_t host_clear_count;
  115. static uint64_t host_track_next_count;
  116. /* Whether dirty ring reset is requested, or finished */
  117. static sem_t sem_vcpu_stop;
  118. static sem_t sem_vcpu_cont;
  119. /*
  120. * This is only set by main thread, and only cleared by vcpu thread. It is
  121. * used to request vcpu thread to stop at the next GUEST_SYNC, since GUEST_SYNC
  122. * is the only place that we'll guarantee both "dirty bit" and "dirty data"
  123. * will match. E.g., SIG_IPI won't guarantee that if the vcpu is interrupted
  124. * after setting dirty bit but before the data is written.
  125. */
  126. static atomic_t vcpu_sync_stop_requested;
  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;
  148. enum log_mode_t {
  149. /* Only use KVM_GET_DIRTY_LOG for logging */
  150. LOG_MODE_DIRTY_LOG = 0,
  151. /* Use both KVM_[GET|CLEAR]_DIRTY_LOG for logging */
  152. LOG_MODE_CLEAR_LOG = 1,
  153. /* Use dirty ring for logging */
  154. LOG_MODE_DIRTY_RING = 2,
  155. LOG_MODE_NUM,
  156. /* Run all supported modes */
  157. LOG_MODE_ALL = LOG_MODE_NUM,
  158. };
  159. /* Mode of logging to test. Default is to run all supported modes */
  160. static enum log_mode_t host_log_mode_option = LOG_MODE_ALL;
  161. /* Logging mode for current run */
  162. static enum log_mode_t host_log_mode;
  163. static pthread_t vcpu_thread;
  164. static uint32_t test_dirty_ring_count = TEST_DIRTY_RING_COUNT;
  165. static void vcpu_kick(void)
  166. {
  167. pthread_kill(vcpu_thread, SIG_IPI);
  168. }
  169. /*
  170. * In our test we do signal tricks, let's use a better version of
  171. * sem_wait to avoid signal interrupts
  172. */
  173. static void sem_wait_until(sem_t *sem)
  174. {
  175. int ret;
  176. do
  177. ret = sem_wait(sem);
  178. while (ret == -1 && errno == EINTR);
  179. }
  180. static bool clear_log_supported(void)
  181. {
  182. return kvm_has_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  183. }
  184. static void clear_log_create_vm_done(struct kvm_vm *vm)
  185. {
  186. u64 manual_caps;
  187. manual_caps = kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  188. TEST_ASSERT(manual_caps, "MANUAL_CAPS is zero!");
  189. manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
  190. KVM_DIRTY_LOG_INITIALLY_SET);
  191. vm_enable_cap(vm, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, manual_caps);
  192. }
  193. static void dirty_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  194. void *bitmap, uint32_t num_pages,
  195. uint32_t *unused)
  196. {
  197. kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);
  198. }
  199. static void clear_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  200. void *bitmap, uint32_t num_pages,
  201. uint32_t *unused)
  202. {
  203. kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);
  204. kvm_vm_clear_dirty_log(vcpu->vm, slot, bitmap, 0, num_pages);
  205. }
  206. /* Should only be called after a GUEST_SYNC */
  207. static void vcpu_handle_sync_stop(void)
  208. {
  209. if (atomic_read(&vcpu_sync_stop_requested)) {
  210. /* It means main thread is sleeping waiting */
  211. atomic_set(&vcpu_sync_stop_requested, false);
  212. sem_post(&sem_vcpu_stop);
  213. sem_wait_until(&sem_vcpu_cont);
  214. }
  215. }
  216. static void default_after_vcpu_run(struct kvm_vcpu *vcpu, int ret, int err)
  217. {
  218. struct kvm_run *run = vcpu->run;
  219. TEST_ASSERT(ret == 0 || (ret == -1 && err == EINTR),
  220. "vcpu run failed: errno=%d", err);
  221. TEST_ASSERT(get_ucall(vcpu, NULL) == UCALL_SYNC,
  222. "Invalid guest sync status: exit_reason=%s",
  223. exit_reason_str(run->exit_reason));
  224. vcpu_handle_sync_stop();
  225. }
  226. static bool dirty_ring_supported(void)
  227. {
  228. return (kvm_has_cap(KVM_CAP_DIRTY_LOG_RING) ||
  229. kvm_has_cap(KVM_CAP_DIRTY_LOG_RING_ACQ_REL));
  230. }
  231. static void dirty_ring_create_vm_done(struct kvm_vm *vm)
  232. {
  233. uint64_t pages;
  234. uint32_t limit;
  235. /*
  236. * We rely on vcpu exit due to full dirty ring state. Adjust
  237. * the ring buffer size to ensure we're able to reach the
  238. * full dirty ring state.
  239. */
  240. pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;
  241. pages = vm_adjust_num_guest_pages(vm->mode, pages);
  242. if (vm->page_size < getpagesize())
  243. pages = vm_num_host_pages(vm->mode, pages);
  244. limit = 1 << (31 - __builtin_clz(pages));
  245. test_dirty_ring_count = 1 << (31 - __builtin_clz(test_dirty_ring_count));
  246. test_dirty_ring_count = min(limit, test_dirty_ring_count);
  247. pr_info("dirty ring count: 0x%x\n", test_dirty_ring_count);
  248. /*
  249. * Switch to dirty ring mode after VM creation but before any
  250. * of the vcpu creation.
  251. */
  252. vm_enable_dirty_ring(vm, test_dirty_ring_count *
  253. sizeof(struct kvm_dirty_gfn));
  254. }
  255. static inline bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
  256. {
  257. return smp_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
  258. }
  259. static inline void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
  260. {
  261. smp_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
  262. }
  263. static uint32_t dirty_ring_collect_one(struct kvm_dirty_gfn *dirty_gfns,
  264. int slot, void *bitmap,
  265. uint32_t num_pages, uint32_t *fetch_index)
  266. {
  267. struct kvm_dirty_gfn *cur;
  268. uint32_t count = 0;
  269. while (true) {
  270. cur = &dirty_gfns[*fetch_index % test_dirty_ring_count];
  271. if (!dirty_gfn_is_dirtied(cur))
  272. break;
  273. TEST_ASSERT(cur->slot == slot, "Slot number didn't match: "
  274. "%u != %u", cur->slot, slot);
  275. TEST_ASSERT(cur->offset < num_pages, "Offset overflow: "
  276. "0x%llx >= 0x%x", cur->offset, num_pages);
  277. //pr_info("fetch 0x%x page %llu\n", *fetch_index, cur->offset);
  278. __set_bit_le(cur->offset, bitmap);
  279. dirty_ring_last_page = cur->offset;
  280. dirty_gfn_set_collected(cur);
  281. (*fetch_index)++;
  282. count++;
  283. }
  284. return count;
  285. }
  286. static void dirty_ring_wait_vcpu(void)
  287. {
  288. /* This makes sure that hardware PML cache flushed */
  289. vcpu_kick();
  290. sem_wait_until(&sem_vcpu_stop);
  291. }
  292. static void dirty_ring_continue_vcpu(void)
  293. {
  294. pr_info("Notifying vcpu to continue\n");
  295. sem_post(&sem_vcpu_cont);
  296. }
  297. static void dirty_ring_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  298. void *bitmap, uint32_t num_pages,
  299. uint32_t *ring_buf_idx)
  300. {
  301. uint32_t count = 0, cleared;
  302. bool continued_vcpu = false;
  303. dirty_ring_wait_vcpu();
  304. if (!dirty_ring_vcpu_ring_full) {
  305. /*
  306. * This is not a ring-full event, it's safe to allow
  307. * vcpu to continue
  308. */
  309. dirty_ring_continue_vcpu();
  310. continued_vcpu = true;
  311. }
  312. /* Only have one vcpu */
  313. count = dirty_ring_collect_one(vcpu_map_dirty_ring(vcpu),
  314. slot, bitmap, num_pages,
  315. ring_buf_idx);
  316. cleared = kvm_vm_reset_dirty_ring(vcpu->vm);
  317. /*
  318. * Cleared pages should be the same as collected, as KVM is supposed to
  319. * clear only the entries that have been harvested.
  320. */
  321. TEST_ASSERT(cleared == count, "Reset dirty pages (%u) mismatch "
  322. "with collected (%u)", cleared, count);
  323. if (!continued_vcpu) {
  324. TEST_ASSERT(dirty_ring_vcpu_ring_full,
  325. "Didn't continue vcpu even without ring full");
  326. dirty_ring_continue_vcpu();
  327. }
  328. pr_info("Iteration %ld collected %u pages\n", iteration, count);
  329. }
  330. static void dirty_ring_after_vcpu_run(struct kvm_vcpu *vcpu, int ret, int err)
  331. {
  332. struct kvm_run *run = vcpu->run;
  333. /* A ucall-sync or ring-full event is allowed */
  334. if (get_ucall(vcpu, NULL) == UCALL_SYNC) {
  335. /* We should allow this to continue */
  336. ;
  337. } else if (run->exit_reason == KVM_EXIT_DIRTY_RING_FULL ||
  338. (ret == -1 && err == EINTR)) {
  339. /* Update the flag first before pause */
  340. WRITE_ONCE(dirty_ring_vcpu_ring_full,
  341. run->exit_reason == KVM_EXIT_DIRTY_RING_FULL);
  342. sem_post(&sem_vcpu_stop);
  343. pr_info("vcpu stops because %s...\n",
  344. dirty_ring_vcpu_ring_full ?
  345. "dirty ring is full" : "vcpu is kicked out");
  346. sem_wait_until(&sem_vcpu_cont);
  347. pr_info("vcpu continues now.\n");
  348. } else {
  349. TEST_ASSERT(false, "Invalid guest sync status: "
  350. "exit_reason=%s",
  351. exit_reason_str(run->exit_reason));
  352. }
  353. }
  354. struct log_mode {
  355. const char *name;
  356. /* Return true if this mode is supported, otherwise false */
  357. bool (*supported)(void);
  358. /* Hook when the vm creation is done (before vcpu creation) */
  359. void (*create_vm_done)(struct kvm_vm *vm);
  360. /* Hook to collect the dirty pages into the bitmap provided */
  361. void (*collect_dirty_pages) (struct kvm_vcpu *vcpu, int slot,
  362. void *bitmap, uint32_t num_pages,
  363. uint32_t *ring_buf_idx);
  364. /* Hook to call when after each vcpu run */
  365. void (*after_vcpu_run)(struct kvm_vcpu *vcpu, int ret, int err);
  366. } log_modes[LOG_MODE_NUM] = {
  367. {
  368. .name = "dirty-log",
  369. .collect_dirty_pages = dirty_log_collect_dirty_pages,
  370. .after_vcpu_run = default_after_vcpu_run,
  371. },
  372. {
  373. .name = "clear-log",
  374. .supported = clear_log_supported,
  375. .create_vm_done = clear_log_create_vm_done,
  376. .collect_dirty_pages = clear_log_collect_dirty_pages,
  377. .after_vcpu_run = default_after_vcpu_run,
  378. },
  379. {
  380. .name = "dirty-ring",
  381. .supported = dirty_ring_supported,
  382. .create_vm_done = dirty_ring_create_vm_done,
  383. .collect_dirty_pages = dirty_ring_collect_dirty_pages,
  384. .after_vcpu_run = dirty_ring_after_vcpu_run,
  385. },
  386. };
  387. /*
  388. * We use this bitmap to track some pages that should have its dirty
  389. * bit set in the _next_ iteration. For example, if we detected the
  390. * page value changed to current iteration but at the same time the
  391. * page bit is cleared in the latest bitmap, then the system must
  392. * report that write in the next get dirty log call.
  393. */
  394. static unsigned long *host_bmap_track;
  395. static void log_modes_dump(void)
  396. {
  397. int i;
  398. printf("all");
  399. for (i = 0; i < LOG_MODE_NUM; i++)
  400. printf(", %s", log_modes[i].name);
  401. printf("\n");
  402. }
  403. static bool log_mode_supported(void)
  404. {
  405. struct log_mode *mode = &log_modes[host_log_mode];
  406. if (mode->supported)
  407. return mode->supported();
  408. return true;
  409. }
  410. static void log_mode_create_vm_done(struct kvm_vm *vm)
  411. {
  412. struct log_mode *mode = &log_modes[host_log_mode];
  413. if (mode->create_vm_done)
  414. mode->create_vm_done(vm);
  415. }
  416. static void log_mode_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,
  417. void *bitmap, uint32_t num_pages,
  418. uint32_t *ring_buf_idx)
  419. {
  420. struct log_mode *mode = &log_modes[host_log_mode];
  421. TEST_ASSERT(mode->collect_dirty_pages != NULL,
  422. "collect_dirty_pages() is required for any log mode!");
  423. mode->collect_dirty_pages(vcpu, slot, bitmap, num_pages, ring_buf_idx);
  424. }
  425. static void log_mode_after_vcpu_run(struct kvm_vcpu *vcpu, int ret, int err)
  426. {
  427. struct log_mode *mode = &log_modes[host_log_mode];
  428. if (mode->after_vcpu_run)
  429. mode->after_vcpu_run(vcpu, ret, err);
  430. }
  431. static void *vcpu_worker(void *data)
  432. {
  433. int ret;
  434. struct kvm_vcpu *vcpu = data;
  435. uint64_t pages_count = 0;
  436. struct kvm_signal_mask *sigmask = alloca(offsetof(struct kvm_signal_mask, sigset)
  437. + sizeof(sigset_t));
  438. sigset_t *sigset = (sigset_t *) &sigmask->sigset;
  439. /*
  440. * SIG_IPI is unblocked atomically while in KVM_RUN. It causes the
  441. * ioctl to return with -EINTR, but it is still pending and we need
  442. * to accept it with the sigwait.
  443. */
  444. sigmask->len = 8;
  445. pthread_sigmask(0, NULL, sigset);
  446. sigdelset(sigset, SIG_IPI);
  447. vcpu_ioctl(vcpu, KVM_SET_SIGNAL_MASK, sigmask);
  448. sigemptyset(sigset);
  449. sigaddset(sigset, SIG_IPI);
  450. while (!READ_ONCE(host_quit)) {
  451. /* Clear any existing kick signals */
  452. pages_count += TEST_PAGES_PER_LOOP;
  453. /* Let the guest dirty the random pages */
  454. ret = __vcpu_run(vcpu);
  455. if (ret == -1 && errno == EINTR) {
  456. int sig = -1;
  457. sigwait(sigset, &sig);
  458. assert(sig == SIG_IPI);
  459. }
  460. log_mode_after_vcpu_run(vcpu, ret, errno);
  461. }
  462. pr_info("Dirtied %"PRIu64" pages\n", pages_count);
  463. return NULL;
  464. }
  465. static void vm_dirty_log_verify(enum vm_guest_mode mode, unsigned long *bmap)
  466. {
  467. uint64_t step = vm_num_host_pages(mode, 1);
  468. uint64_t page;
  469. uint64_t *value_ptr;
  470. uint64_t min_iter = 0;
  471. for (page = 0; page < host_num_pages; page += step) {
  472. value_ptr = host_test_mem + page * host_page_size;
  473. /* If this is a special page that we were tracking... */
  474. if (__test_and_clear_bit_le(page, host_bmap_track)) {
  475. host_track_next_count++;
  476. TEST_ASSERT(test_bit_le(page, bmap),
  477. "Page %"PRIu64" should have its dirty bit "
  478. "set in this iteration but it is missing",
  479. page);
  480. }
  481. if (__test_and_clear_bit_le(page, bmap)) {
  482. bool matched;
  483. host_dirty_count++;
  484. /*
  485. * If the bit is set, the value written onto
  486. * the corresponding page should be either the
  487. * previous iteration number or the current one.
  488. */
  489. matched = (*value_ptr == iteration ||
  490. *value_ptr == iteration - 1);
  491. if (host_log_mode == LOG_MODE_DIRTY_RING && !matched) {
  492. if (*value_ptr == iteration - 2 && min_iter <= iteration - 2) {
  493. /*
  494. * Short answer: this case is special
  495. * only for dirty ring test where the
  496. * page is the last page before a kvm
  497. * dirty ring full in iteration N-2.
  498. *
  499. * Long answer: Assuming ring size R,
  500. * one possible condition is:
  501. *
  502. * main thr vcpu thr
  503. * -------- --------
  504. * iter=1
  505. * write 1 to page 0~(R-1)
  506. * full, vmexit
  507. * collect 0~(R-1)
  508. * kick vcpu
  509. * write 1 to (R-1)~(2R-2)
  510. * full, vmexit
  511. * iter=2
  512. * collect (R-1)~(2R-2)
  513. * kick vcpu
  514. * write 1 to (2R-2)
  515. * (NOTE!!! "1" cached in cpu reg)
  516. * write 2 to (2R-1)~(3R-3)
  517. * full, vmexit
  518. * iter=3
  519. * collect (2R-2)~(3R-3)
  520. * (here if we read value on page
  521. * "2R-2" is 1, while iter=3!!!)
  522. *
  523. * This however can only happen once per iteration.
  524. */
  525. min_iter = iteration - 1;
  526. continue;
  527. } else if (page == dirty_ring_last_page) {
  528. /*
  529. * Please refer to comments in
  530. * dirty_ring_last_page.
  531. */
  532. continue;
  533. }
  534. }
  535. TEST_ASSERT(matched,
  536. "Set page %"PRIu64" value %"PRIu64
  537. " incorrect (iteration=%"PRIu64")",
  538. page, *value_ptr, iteration);
  539. } else {
  540. host_clear_count++;
  541. /*
  542. * If cleared, the value written can be any
  543. * value smaller or equals to the iteration
  544. * number. Note that the value can be exactly
  545. * (iteration-1) if that write can happen
  546. * like this:
  547. *
  548. * (1) increase loop count to "iteration-1"
  549. * (2) write to page P happens (with value
  550. * "iteration-1")
  551. * (3) get dirty log for "iteration-1"; we'll
  552. * see that page P bit is set (dirtied),
  553. * and not set the bit in host_bmap_track
  554. * (4) increase loop count to "iteration"
  555. * (which is current iteration)
  556. * (5) get dirty log for current iteration,
  557. * we'll see that page P is cleared, with
  558. * value "iteration-1".
  559. */
  560. TEST_ASSERT(*value_ptr <= iteration,
  561. "Clear page %"PRIu64" value %"PRIu64
  562. " incorrect (iteration=%"PRIu64")",
  563. page, *value_ptr, iteration);
  564. if (*value_ptr == iteration) {
  565. /*
  566. * This page is _just_ modified; it
  567. * should report its dirtyness in the
  568. * next run
  569. */
  570. __set_bit_le(page, host_bmap_track);
  571. }
  572. }
  573. }
  574. }
  575. static struct kvm_vm *create_vm(enum vm_guest_mode mode, struct kvm_vcpu **vcpu,
  576. uint64_t extra_mem_pages, void *guest_code)
  577. {
  578. struct kvm_vm *vm;
  579. pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));
  580. vm = __vm_create(VM_SHAPE(mode), 1, extra_mem_pages);
  581. log_mode_create_vm_done(vm);
  582. *vcpu = vm_vcpu_add(vm, 0, guest_code);
  583. return vm;
  584. }
  585. struct test_params {
  586. unsigned long iterations;
  587. unsigned long interval;
  588. uint64_t phys_offset;
  589. };
  590. static void run_test(enum vm_guest_mode mode, void *arg)
  591. {
  592. struct test_params *p = arg;
  593. struct kvm_vcpu *vcpu;
  594. struct kvm_vm *vm;
  595. unsigned long *bmap;
  596. uint32_t ring_buf_idx = 0;
  597. int sem_val;
  598. if (!log_mode_supported()) {
  599. print_skip("Log mode '%s' not supported",
  600. log_modes[host_log_mode].name);
  601. return;
  602. }
  603. /*
  604. * We reserve page table for 2 times of extra dirty mem which
  605. * will definitely cover the original (1G+) test range. Here
  606. * we do the calculation with 4K page size which is the
  607. * smallest so the page number will be enough for all archs
  608. * (e.g., 64K page size guest will need even less memory for
  609. * page tables).
  610. */
  611. vm = create_vm(mode, &vcpu,
  612. 2ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K), guest_code);
  613. guest_page_size = vm->page_size;
  614. /*
  615. * A little more than 1G of guest page sized pages. Cover the
  616. * case where the size is not aligned to 64 pages.
  617. */
  618. guest_num_pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;
  619. guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
  620. host_page_size = getpagesize();
  621. host_num_pages = vm_num_host_pages(mode, guest_num_pages);
  622. if (!p->phys_offset) {
  623. guest_test_phys_mem = (vm->max_gfn - guest_num_pages) *
  624. guest_page_size;
  625. guest_test_phys_mem = align_down(guest_test_phys_mem, host_page_size);
  626. } else {
  627. guest_test_phys_mem = p->phys_offset;
  628. }
  629. #ifdef __s390x__
  630. /* Align to 1M (segment size) */
  631. guest_test_phys_mem = align_down(guest_test_phys_mem, 1 << 20);
  632. #endif
  633. pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
  634. bmap = bitmap_zalloc(host_num_pages);
  635. host_bmap_track = bitmap_zalloc(host_num_pages);
  636. /* Add an extra memory slot for testing dirty logging */
  637. vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
  638. guest_test_phys_mem,
  639. TEST_MEM_SLOT_INDEX,
  640. guest_num_pages,
  641. KVM_MEM_LOG_DIRTY_PAGES);
  642. /* Do mapping for the dirty track memory slot */
  643. virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages);
  644. /* Cache the HVA pointer of the region */
  645. host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
  646. /* Export the shared variables to the guest */
  647. sync_global_to_guest(vm, host_page_size);
  648. sync_global_to_guest(vm, guest_page_size);
  649. sync_global_to_guest(vm, guest_test_virt_mem);
  650. sync_global_to_guest(vm, guest_num_pages);
  651. /* Start the iterations */
  652. iteration = 1;
  653. sync_global_to_guest(vm, iteration);
  654. WRITE_ONCE(host_quit, false);
  655. host_dirty_count = 0;
  656. host_clear_count = 0;
  657. host_track_next_count = 0;
  658. WRITE_ONCE(dirty_ring_vcpu_ring_full, false);
  659. /*
  660. * Ensure the previous iteration didn't leave a dangling semaphore, i.e.
  661. * that the main task and vCPU worker were synchronized and completed
  662. * verification of all iterations.
  663. */
  664. sem_getvalue(&sem_vcpu_stop, &sem_val);
  665. TEST_ASSERT_EQ(sem_val, 0);
  666. sem_getvalue(&sem_vcpu_cont, &sem_val);
  667. TEST_ASSERT_EQ(sem_val, 0);
  668. pthread_create(&vcpu_thread, NULL, vcpu_worker, vcpu);
  669. while (iteration < p->iterations) {
  670. /* Give the vcpu thread some time to dirty some pages */
  671. usleep(p->interval * 1000);
  672. log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
  673. bmap, host_num_pages,
  674. &ring_buf_idx);
  675. /*
  676. * See vcpu_sync_stop_requested definition for details on why
  677. * we need to stop vcpu when verify data.
  678. */
  679. atomic_set(&vcpu_sync_stop_requested, true);
  680. sem_wait_until(&sem_vcpu_stop);
  681. /*
  682. * NOTE: for dirty ring, it's possible that we didn't stop at
  683. * GUEST_SYNC but instead we stopped because ring is full;
  684. * that's okay too because ring full means we're only missing
  685. * the flush of the last page, and since we handle the last
  686. * page specially verification will succeed anyway.
  687. */
  688. assert(host_log_mode == LOG_MODE_DIRTY_RING ||
  689. atomic_read(&vcpu_sync_stop_requested) == false);
  690. vm_dirty_log_verify(mode, bmap);
  691. /*
  692. * Set host_quit before sem_vcpu_cont in the final iteration to
  693. * ensure that the vCPU worker doesn't resume the guest. As
  694. * above, the dirty ring test may stop and wait even when not
  695. * explicitly request to do so, i.e. would hang waiting for a
  696. * "continue" if it's allowed to resume the guest.
  697. */
  698. if (++iteration == p->iterations)
  699. WRITE_ONCE(host_quit, true);
  700. sem_post(&sem_vcpu_cont);
  701. sync_global_to_guest(vm, iteration);
  702. }
  703. pthread_join(vcpu_thread, NULL);
  704. pr_info("Total bits checked: dirty (%"PRIu64"), clear (%"PRIu64"), "
  705. "track_next (%"PRIu64")\n", host_dirty_count, host_clear_count,
  706. host_track_next_count);
  707. free(bmap);
  708. free(host_bmap_track);
  709. kvm_vm_free(vm);
  710. }
  711. static void help(char *name)
  712. {
  713. puts("");
  714. printf("usage: %s [-h] [-i iterations] [-I interval] "
  715. "[-p offset] [-m mode]\n", name);
  716. puts("");
  717. printf(" -c: hint to dirty ring size, in number of entries\n");
  718. printf(" (only useful for dirty-ring test; default: %"PRIu32")\n",
  719. TEST_DIRTY_RING_COUNT);
  720. printf(" -i: specify iteration counts (default: %"PRIu64")\n",
  721. TEST_HOST_LOOP_N);
  722. printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
  723. TEST_HOST_LOOP_INTERVAL);
  724. printf(" -p: specify guest physical test memory offset\n"
  725. " Warning: a low offset can conflict with the loaded test code.\n");
  726. printf(" -M: specify the host logging mode "
  727. "(default: run all log modes). Supported modes: \n\t");
  728. log_modes_dump();
  729. guest_modes_help();
  730. puts("");
  731. exit(0);
  732. }
  733. int main(int argc, char *argv[])
  734. {
  735. struct test_params p = {
  736. .iterations = TEST_HOST_LOOP_N,
  737. .interval = TEST_HOST_LOOP_INTERVAL,
  738. };
  739. int opt, i;
  740. sigset_t sigset;
  741. sem_init(&sem_vcpu_stop, 0, 0);
  742. sem_init(&sem_vcpu_cont, 0, 0);
  743. guest_modes_append_default();
  744. while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {
  745. switch (opt) {
  746. case 'c':
  747. test_dirty_ring_count = strtol(optarg, NULL, 10);
  748. break;
  749. case 'i':
  750. p.iterations = strtol(optarg, NULL, 10);
  751. break;
  752. case 'I':
  753. p.interval = strtol(optarg, NULL, 10);
  754. break;
  755. case 'p':
  756. p.phys_offset = strtoull(optarg, NULL, 0);
  757. break;
  758. case 'm':
  759. guest_modes_cmdline(optarg);
  760. break;
  761. case 'M':
  762. if (!strcmp(optarg, "all")) {
  763. host_log_mode_option = LOG_MODE_ALL;
  764. break;
  765. }
  766. for (i = 0; i < LOG_MODE_NUM; i++) {
  767. if (!strcmp(optarg, log_modes[i].name)) {
  768. pr_info("Setting log mode to: '%s'\n",
  769. optarg);
  770. host_log_mode_option = i;
  771. break;
  772. }
  773. }
  774. if (i == LOG_MODE_NUM) {
  775. printf("Log mode '%s' invalid. Please choose "
  776. "from: ", optarg);
  777. log_modes_dump();
  778. exit(1);
  779. }
  780. break;
  781. case 'h':
  782. default:
  783. help(argv[0]);
  784. break;
  785. }
  786. }
  787. TEST_ASSERT(p.iterations > 2, "Iterations must be greater than two");
  788. TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");
  789. pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
  790. p.iterations, p.interval);
  791. srandom(time(0));
  792. /* Ensure that vCPU threads start with SIG_IPI blocked. */
  793. sigemptyset(&sigset);
  794. sigaddset(&sigset, SIG_IPI);
  795. pthread_sigmask(SIG_BLOCK, &sigset, NULL);
  796. if (host_log_mode_option == LOG_MODE_ALL) {
  797. /* Run each log mode */
  798. for (i = 0; i < LOG_MODE_NUM; i++) {
  799. pr_info("Testing Log Mode '%s'\n", log_modes[i].name);
  800. host_log_mode = i;
  801. for_each_guest_mode(run_test, &p);
  802. }
  803. } else {
  804. host_log_mode = host_log_mode_option;
  805. for_each_guest_mode(run_test, &p);
  806. }
  807. return 0;
  808. }