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