Path: blob/master/tools/testing/selftests/kvm/dirty_log_test.c
38189 views
// SPDX-License-Identifier: GPL-2.01/*2* KVM dirty page logging test3*4* Copyright (C) 2018, Red Hat, Inc.5*/6#include <stdio.h>7#include <stdlib.h>8#include <pthread.h>9#include <semaphore.h>10#include <sys/types.h>11#include <signal.h>12#include <errno.h>13#include <linux/bitmap.h>14#include <linux/bitops.h>15#include <linux/atomic.h>16#include <asm/barrier.h>1718#include "kvm_util.h"19#include "test_util.h"20#include "guest_modes.h"21#include "processor.h"22#include "ucall_common.h"2324#define DIRTY_MEM_BITS 30 /* 1G */25#define PAGE_SHIFT_4K 122627/* The memory slot index to track dirty pages */28#define TEST_MEM_SLOT_INDEX 12930/* Default guest test virtual memory offset */31#define DEFAULT_GUEST_TEST_MEM 0xc00000003233/* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */34#define TEST_HOST_LOOP_N 32UL3536/* Interval for each host loop (ms) */37#define TEST_HOST_LOOP_INTERVAL 10UL3839/*40* Ensure the vCPU is able to perform a reasonable number of writes in each41* iteration to provide a lower bound on coverage.42*/43#define TEST_MIN_WRITES_PER_ITERATION 0x1004445/* Dirty bitmaps are always little endian, so we need to swap on big endian */46#if defined(__s390x__)47# define BITOP_LE_SWIZZLE ((BITS_PER_LONG-1) & ~0x7)48# define test_bit_le(nr, addr) \49test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)50# define __set_bit_le(nr, addr) \51__set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)52# define __clear_bit_le(nr, addr) \53__clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)54# define __test_and_set_bit_le(nr, addr) \55__test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)56# define __test_and_clear_bit_le(nr, addr) \57__test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)58#else59# define test_bit_le test_bit60# define __set_bit_le __set_bit61# define __clear_bit_le __clear_bit62# define __test_and_set_bit_le __test_and_set_bit63# define __test_and_clear_bit_le __test_and_clear_bit64#endif6566#define TEST_DIRTY_RING_COUNT 655366768#define SIG_IPI SIGUSR16970/*71* Guest/Host shared variables. Ensure addr_gva2hva() and/or72* sync_global_to/from_guest() are used when accessing from73* the host. READ/WRITE_ONCE() should also be used with anything74* that may change.75*/76static uint64_t host_page_size;77static uint64_t guest_page_size;78static uint64_t guest_num_pages;79static uint64_t iteration;80static uint64_t nr_writes;81static bool vcpu_stop;8283/*84* Guest physical memory offset of the testing memory slot.85* This will be set to the topmost valid physical address minus86* the test memory size.87*/88static uint64_t guest_test_phys_mem;8990/*91* Guest virtual memory offset of the testing memory slot.92* Must not conflict with identity mapped test code.93*/94static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;9596/*97* Continuously write to the first 8 bytes of a random pages within98* the testing memory region.99*/100static void guest_code(void)101{102uint64_t addr;103104#ifdef __s390x__105uint64_t i;106107/*108* On s390x, all pages of a 1M segment are initially marked as dirty109* when a page of the segment is written to for the very first time.110* To compensate this specialty in this test, we need to touch all111* pages during the first iteration.112*/113for (i = 0; i < guest_num_pages; i++) {114addr = guest_test_virt_mem + i * guest_page_size;115vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));116nr_writes++;117}118#endif119120while (true) {121while (!READ_ONCE(vcpu_stop)) {122addr = guest_test_virt_mem;123addr += (guest_random_u64(&guest_rng) % guest_num_pages)124* guest_page_size;125addr = align_down(addr, host_page_size);126127vcpu_arch_put_guest(*(uint64_t *)addr, READ_ONCE(iteration));128nr_writes++;129}130131GUEST_SYNC(1);132}133}134135/* Host variables */136static bool host_quit;137138/* Points to the test VM memory region on which we track dirty logs */139static void *host_test_mem;140static uint64_t host_num_pages;141142/* For statistics only */143static uint64_t host_dirty_count;144static uint64_t host_clear_count;145146/* Whether dirty ring reset is requested, or finished */147static sem_t sem_vcpu_stop;148static sem_t sem_vcpu_cont;149150/*151* This is updated by the vcpu thread to tell the host whether it's a152* ring-full event. It should only be read until a sem_wait() of153* sem_vcpu_stop and before vcpu continues to run.154*/155static bool dirty_ring_vcpu_ring_full;156157/*158* This is only used for verifying the dirty pages. Dirty ring has a very159* tricky case when the ring just got full, kvm will do userspace exit due to160* ring full. When that happens, the very last PFN is set but actually the161* data is not changed (the guest WRITE is not really applied yet), because162* we found that the dirty ring is full, refused to continue the vcpu, and163* recorded the dirty gfn with the old contents.164*165* For this specific case, it's safe to skip checking this pfn for this166* bit, because it's a redundant bit, and when the write happens later the bit167* will be set again. We use this variable to always keep track of the latest168* dirty gfn we've collected, so that if a mismatch of data found later in the169* verifying process, we let it pass.170*/171static uint64_t dirty_ring_last_page = -1ULL;172173/*174* In addition to the above, it is possible (especially if this175* test is run nested) for the above scenario to repeat multiple times:176*177* The following can happen:178*179* - L1 vCPU: Memory write is logged to PML but not committed.180*181* - L1 test thread: Ignores the write because its last dirty ring entry182* Resets the dirty ring which:183* - Resets the A/D bits in EPT184* - Issues tlb flush (invept), which is intercepted by L0185*186* - L0: frees the whole nested ept mmu root as the response to invept,187* and thus ensures that when memory write is retried, it will fault again188*189* - L1 vCPU: Same memory write is logged to the PML but not committed again.190*191* - L1 test thread: Ignores the write because its last dirty ring entry (again)192* Resets the dirty ring which:193* - Resets the A/D bits in EPT (again)194* - Issues tlb flush (again) which is intercepted by L0195*196* ...197*198* N times199*200* - L1 vCPU: Memory write is logged in the PML and then committed.201* Lots of other memory writes are logged and committed.202* ...203*204* - L1 test thread: Sees the memory write along with other memory writes205* in the dirty ring, and since the write is usually not206* the last entry in the dirty-ring and has a very outdated207* iteration, the test fails.208*209*210* Note that this is only possible when the write was the last log entry211* write during iteration N-1, thus remember last iteration last log entry212* and also don't fail when it is reported in the next iteration, together with213* an outdated iteration count.214*/215static uint64_t dirty_ring_prev_iteration_last_page;216217enum log_mode_t {218/* Only use KVM_GET_DIRTY_LOG for logging */219LOG_MODE_DIRTY_LOG = 0,220221/* Use both KVM_[GET|CLEAR]_DIRTY_LOG for logging */222LOG_MODE_CLEAR_LOG = 1,223224/* Use dirty ring for logging */225LOG_MODE_DIRTY_RING = 2,226227LOG_MODE_NUM,228229/* Run all supported modes */230LOG_MODE_ALL = LOG_MODE_NUM,231};232233/* Mode of logging to test. Default is to run all supported modes */234static enum log_mode_t host_log_mode_option = LOG_MODE_ALL;235/* Logging mode for current run */236static enum log_mode_t host_log_mode;237static pthread_t vcpu_thread;238static uint32_t test_dirty_ring_count = TEST_DIRTY_RING_COUNT;239240static bool clear_log_supported(void)241{242return kvm_has_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);243}244245static void clear_log_create_vm_done(struct kvm_vm *vm)246{247u64 manual_caps;248249manual_caps = kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);250TEST_ASSERT(manual_caps, "MANUAL_CAPS is zero!");251manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |252KVM_DIRTY_LOG_INITIALLY_SET);253vm_enable_cap(vm, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, manual_caps);254}255256static void dirty_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,257void *bitmap, uint32_t num_pages,258uint32_t *unused)259{260kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);261}262263static void clear_log_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,264void *bitmap, uint32_t num_pages,265uint32_t *unused)266{267kvm_vm_get_dirty_log(vcpu->vm, slot, bitmap);268kvm_vm_clear_dirty_log(vcpu->vm, slot, bitmap, 0, num_pages);269}270271/* Should only be called after a GUEST_SYNC */272static void vcpu_handle_sync_stop(void)273{274if (READ_ONCE(vcpu_stop)) {275sem_post(&sem_vcpu_stop);276sem_wait(&sem_vcpu_cont);277}278}279280static void default_after_vcpu_run(struct kvm_vcpu *vcpu)281{282struct kvm_run *run = vcpu->run;283284TEST_ASSERT(get_ucall(vcpu, NULL) == UCALL_SYNC,285"Invalid guest sync status: exit_reason=%s",286exit_reason_str(run->exit_reason));287288vcpu_handle_sync_stop();289}290291static bool dirty_ring_supported(void)292{293return (kvm_has_cap(KVM_CAP_DIRTY_LOG_RING) ||294kvm_has_cap(KVM_CAP_DIRTY_LOG_RING_ACQ_REL));295}296297static void dirty_ring_create_vm_done(struct kvm_vm *vm)298{299uint64_t pages;300uint32_t limit;301302/*303* We rely on vcpu exit due to full dirty ring state. Adjust304* the ring buffer size to ensure we're able to reach the305* full dirty ring state.306*/307pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;308pages = vm_adjust_num_guest_pages(vm->mode, pages);309if (vm->page_size < getpagesize())310pages = vm_num_host_pages(vm->mode, pages);311312limit = 1 << (31 - __builtin_clz(pages));313test_dirty_ring_count = 1 << (31 - __builtin_clz(test_dirty_ring_count));314test_dirty_ring_count = min(limit, test_dirty_ring_count);315pr_info("dirty ring count: 0x%x\n", test_dirty_ring_count);316317/*318* Switch to dirty ring mode after VM creation but before any319* of the vcpu creation.320*/321vm_enable_dirty_ring(vm, test_dirty_ring_count *322sizeof(struct kvm_dirty_gfn));323}324325static inline bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)326{327return smp_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;328}329330static inline void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)331{332smp_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);333}334335static uint32_t dirty_ring_collect_one(struct kvm_dirty_gfn *dirty_gfns,336int slot, void *bitmap,337uint32_t num_pages, uint32_t *fetch_index)338{339struct kvm_dirty_gfn *cur;340uint32_t count = 0;341342while (true) {343cur = &dirty_gfns[*fetch_index % test_dirty_ring_count];344if (!dirty_gfn_is_dirtied(cur))345break;346TEST_ASSERT(cur->slot == slot, "Slot number didn't match: "347"%u != %u", cur->slot, slot);348TEST_ASSERT(cur->offset < num_pages, "Offset overflow: "349"0x%llx >= 0x%x", cur->offset, num_pages);350__set_bit_le(cur->offset, bitmap);351dirty_ring_last_page = cur->offset;352dirty_gfn_set_collected(cur);353(*fetch_index)++;354count++;355}356357return count;358}359360static void dirty_ring_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,361void *bitmap, uint32_t num_pages,362uint32_t *ring_buf_idx)363{364uint32_t count, cleared;365366/* Only have one vcpu */367count = dirty_ring_collect_one(vcpu_map_dirty_ring(vcpu),368slot, bitmap, num_pages,369ring_buf_idx);370371cleared = kvm_vm_reset_dirty_ring(vcpu->vm);372373/*374* Cleared pages should be the same as collected, as KVM is supposed to375* clear only the entries that have been harvested.376*/377TEST_ASSERT(cleared == count, "Reset dirty pages (%u) mismatch "378"with collected (%u)", cleared, count);379}380381static void dirty_ring_after_vcpu_run(struct kvm_vcpu *vcpu)382{383struct kvm_run *run = vcpu->run;384385/* A ucall-sync or ring-full event is allowed */386if (get_ucall(vcpu, NULL) == UCALL_SYNC) {387vcpu_handle_sync_stop();388} else if (run->exit_reason == KVM_EXIT_DIRTY_RING_FULL) {389WRITE_ONCE(dirty_ring_vcpu_ring_full, true);390vcpu_handle_sync_stop();391} else {392TEST_ASSERT(false, "Invalid guest sync status: "393"exit_reason=%s",394exit_reason_str(run->exit_reason));395}396}397398struct log_mode {399const char *name;400/* Return true if this mode is supported, otherwise false */401bool (*supported)(void);402/* Hook when the vm creation is done (before vcpu creation) */403void (*create_vm_done)(struct kvm_vm *vm);404/* Hook to collect the dirty pages into the bitmap provided */405void (*collect_dirty_pages) (struct kvm_vcpu *vcpu, int slot,406void *bitmap, uint32_t num_pages,407uint32_t *ring_buf_idx);408/* Hook to call when after each vcpu run */409void (*after_vcpu_run)(struct kvm_vcpu *vcpu);410} log_modes[LOG_MODE_NUM] = {411{412.name = "dirty-log",413.collect_dirty_pages = dirty_log_collect_dirty_pages,414.after_vcpu_run = default_after_vcpu_run,415},416{417.name = "clear-log",418.supported = clear_log_supported,419.create_vm_done = clear_log_create_vm_done,420.collect_dirty_pages = clear_log_collect_dirty_pages,421.after_vcpu_run = default_after_vcpu_run,422},423{424.name = "dirty-ring",425.supported = dirty_ring_supported,426.create_vm_done = dirty_ring_create_vm_done,427.collect_dirty_pages = dirty_ring_collect_dirty_pages,428.after_vcpu_run = dirty_ring_after_vcpu_run,429},430};431432static void log_modes_dump(void)433{434int i;435436printf("all");437for (i = 0; i < LOG_MODE_NUM; i++)438printf(", %s", log_modes[i].name);439printf("\n");440}441442static bool log_mode_supported(void)443{444struct log_mode *mode = &log_modes[host_log_mode];445446if (mode->supported)447return mode->supported();448449return true;450}451452static void log_mode_create_vm_done(struct kvm_vm *vm)453{454struct log_mode *mode = &log_modes[host_log_mode];455456if (mode->create_vm_done)457mode->create_vm_done(vm);458}459460static void log_mode_collect_dirty_pages(struct kvm_vcpu *vcpu, int slot,461void *bitmap, uint32_t num_pages,462uint32_t *ring_buf_idx)463{464struct log_mode *mode = &log_modes[host_log_mode];465466TEST_ASSERT(mode->collect_dirty_pages != NULL,467"collect_dirty_pages() is required for any log mode!");468mode->collect_dirty_pages(vcpu, slot, bitmap, num_pages, ring_buf_idx);469}470471static void log_mode_after_vcpu_run(struct kvm_vcpu *vcpu)472{473struct log_mode *mode = &log_modes[host_log_mode];474475if (mode->after_vcpu_run)476mode->after_vcpu_run(vcpu);477}478479static void *vcpu_worker(void *data)480{481struct kvm_vcpu *vcpu = data;482483sem_wait(&sem_vcpu_cont);484485while (!READ_ONCE(host_quit)) {486/* Let the guest dirty the random pages */487vcpu_run(vcpu);488log_mode_after_vcpu_run(vcpu);489}490491return NULL;492}493494static void vm_dirty_log_verify(enum vm_guest_mode mode, unsigned long **bmap)495{496uint64_t page, nr_dirty_pages = 0, nr_clean_pages = 0;497uint64_t step = vm_num_host_pages(mode, 1);498499for (page = 0; page < host_num_pages; page += step) {500uint64_t val = *(uint64_t *)(host_test_mem + page * host_page_size);501bool bmap0_dirty = __test_and_clear_bit_le(page, bmap[0]);502503/*504* Ensure both bitmaps are cleared, as a page can be written505* multiple times per iteration, i.e. can show up in both506* bitmaps, and the dirty ring is additive, i.e. doesn't purge507* bitmap entries from previous collections.508*/509if (__test_and_clear_bit_le(page, bmap[1]) || bmap0_dirty) {510nr_dirty_pages++;511512/*513* If the page is dirty, the value written to memory514* should be the current iteration number.515*/516if (val == iteration)517continue;518519if (host_log_mode == LOG_MODE_DIRTY_RING) {520/*521* The last page in the ring from previous522* iteration can be written with the value523* from the previous iteration, as the value to524* be written may be cached in a CPU register.525*/526if (page == dirty_ring_prev_iteration_last_page &&527val == iteration - 1)528continue;529530/*531* Any value from a previous iteration is legal532* for the last entry, as the write may not yet533* have retired, i.e. the page may hold whatever534* it had before this iteration started.535*/536if (page == dirty_ring_last_page &&537val < iteration)538continue;539} else if (!val && iteration == 1 && bmap0_dirty) {540/*541* When testing get+clear, the dirty bitmap542* starts with all bits set, and so the first543* iteration can observe a "dirty" page that544* was never written, but only in the first545* bitmap (collecting the bitmap also clears546* all dirty pages).547*/548continue;549}550551TEST_FAIL("Dirty page %lu value (%lu) != iteration (%lu) "552"(last = %lu, prev_last = %lu)",553page, val, iteration, dirty_ring_last_page,554dirty_ring_prev_iteration_last_page);555} else {556nr_clean_pages++;557/*558* If cleared, the value written can be any559* value smaller than the iteration number.560*/561TEST_ASSERT(val < iteration,562"Clear page %lu value (%lu) >= iteration (%lu) "563"(last = %lu, prev_last = %lu)",564page, val, iteration, dirty_ring_last_page,565dirty_ring_prev_iteration_last_page);566}567}568569pr_info("Iteration %2ld: dirty: %-6lu clean: %-6lu writes: %-6lu\n",570iteration, nr_dirty_pages, nr_clean_pages, nr_writes);571572host_dirty_count += nr_dirty_pages;573host_clear_count += nr_clean_pages;574}575576static struct kvm_vm *create_vm(enum vm_guest_mode mode, struct kvm_vcpu **vcpu,577uint64_t extra_mem_pages, void *guest_code)578{579struct kvm_vm *vm;580581pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));582583vm = __vm_create(VM_SHAPE(mode), 1, extra_mem_pages);584585log_mode_create_vm_done(vm);586*vcpu = vm_vcpu_add(vm, 0, guest_code);587kvm_arch_vm_finalize_vcpus(vm);588return vm;589}590591struct test_params {592unsigned long iterations;593unsigned long interval;594uint64_t phys_offset;595};596597static void run_test(enum vm_guest_mode mode, void *arg)598{599struct test_params *p = arg;600struct kvm_vcpu *vcpu;601struct kvm_vm *vm;602unsigned long *bmap[2];603uint32_t ring_buf_idx = 0;604int sem_val;605606if (!log_mode_supported()) {607print_skip("Log mode '%s' not supported",608log_modes[host_log_mode].name);609return;610}611612/*613* We reserve page table for 2 times of extra dirty mem which614* will definitely cover the original (1G+) test range. Here615* we do the calculation with 4K page size which is the616* smallest so the page number will be enough for all archs617* (e.g., 64K page size guest will need even less memory for618* page tables).619*/620vm = create_vm(mode, &vcpu,6212ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K), guest_code);622623guest_page_size = vm->page_size;624/*625* A little more than 1G of guest page sized pages. Cover the626* case where the size is not aligned to 64 pages.627*/628guest_num_pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;629guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);630631host_page_size = getpagesize();632host_num_pages = vm_num_host_pages(mode, guest_num_pages);633634if (!p->phys_offset) {635guest_test_phys_mem = (vm->max_gfn - guest_num_pages) *636guest_page_size;637guest_test_phys_mem = align_down(guest_test_phys_mem, host_page_size);638} else {639guest_test_phys_mem = p->phys_offset;640}641642#ifdef __s390x__643/* Align to 1M (segment size) */644guest_test_phys_mem = align_down(guest_test_phys_mem, 1 << 20);645646/*647* The workaround in guest_code() to write all pages prior to the first648* iteration isn't compatible with the dirty ring, as the dirty ring649* support relies on the vCPU to actually stop when vcpu_stop is set so650* that the vCPU doesn't hang waiting for the dirty ring to be emptied.651*/652TEST_ASSERT(host_log_mode != LOG_MODE_DIRTY_RING,653"Test needs to be updated to support s390 dirty ring");654#endif655656pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);657658bmap[0] = bitmap_zalloc(host_num_pages);659bmap[1] = bitmap_zalloc(host_num_pages);660661/* Add an extra memory slot for testing dirty logging */662vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,663guest_test_phys_mem,664TEST_MEM_SLOT_INDEX,665guest_num_pages,666KVM_MEM_LOG_DIRTY_PAGES);667668/* Do mapping for the dirty track memory slot */669virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages);670671/* Cache the HVA pointer of the region */672host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);673674/* Export the shared variables to the guest */675sync_global_to_guest(vm, host_page_size);676sync_global_to_guest(vm, guest_page_size);677sync_global_to_guest(vm, guest_test_virt_mem);678sync_global_to_guest(vm, guest_num_pages);679680host_dirty_count = 0;681host_clear_count = 0;682WRITE_ONCE(host_quit, false);683684/*685* Ensure the previous iteration didn't leave a dangling semaphore, i.e.686* that the main task and vCPU worker were synchronized and completed687* verification of all iterations.688*/689sem_getvalue(&sem_vcpu_stop, &sem_val);690TEST_ASSERT_EQ(sem_val, 0);691sem_getvalue(&sem_vcpu_cont, &sem_val);692TEST_ASSERT_EQ(sem_val, 0);693694TEST_ASSERT_EQ(vcpu_stop, false);695696pthread_create(&vcpu_thread, NULL, vcpu_worker, vcpu);697698for (iteration = 1; iteration <= p->iterations; iteration++) {699unsigned long i;700701sync_global_to_guest(vm, iteration);702703WRITE_ONCE(nr_writes, 0);704sync_global_to_guest(vm, nr_writes);705706dirty_ring_prev_iteration_last_page = dirty_ring_last_page;707WRITE_ONCE(dirty_ring_vcpu_ring_full, false);708709sem_post(&sem_vcpu_cont);710711/*712* Let the vCPU run beyond the configured interval until it has713* performed the minimum number of writes. This verifies the714* guest is making forward progress, e.g. isn't stuck because715* of a KVM bug, and puts a firm floor on test coverage.716*/717for (i = 0; i < p->interval || nr_writes < TEST_MIN_WRITES_PER_ITERATION; i++) {718/*719* Sleep in 1ms chunks to keep the interval math simple720* and so that the test doesn't run too far beyond the721* specified interval.722*/723usleep(1000);724725sync_global_from_guest(vm, nr_writes);726727/*728* Reap dirty pages while the guest is running so that729* dirty ring full events are resolved, i.e. so that a730* larger interval doesn't always end up with a vCPU731* that's effectively blocked. Collecting while the732* guest is running also verifies KVM doesn't lose any733* state.734*735* For bitmap modes, KVM overwrites the entire bitmap,736* i.e. collecting the bitmaps is destructive. Collect737* the bitmap only on the first pass, otherwise this738* test would lose track of dirty pages.739*/740if (i && host_log_mode != LOG_MODE_DIRTY_RING)741continue;742743/*744* For the dirty ring, empty the ring on subsequent745* passes only if the ring was filled at least once,746* to verify KVM's handling of a full ring (emptying747* the ring on every pass would make it unlikely the748* vCPU would ever fill the fing).749*/750if (i && !READ_ONCE(dirty_ring_vcpu_ring_full))751continue;752753log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,754bmap[0], host_num_pages,755&ring_buf_idx);756}757758/*759* Stop the vCPU prior to collecting and verifying the dirty760* log. If the vCPU is allowed to run during collection, then761* pages that are written during this iteration may be missed,762* i.e. collected in the next iteration. And if the vCPU is763* writing memory during verification, pages that this thread764* sees as clean may be written with this iteration's value.765*/766WRITE_ONCE(vcpu_stop, true);767sync_global_to_guest(vm, vcpu_stop);768sem_wait(&sem_vcpu_stop);769770/*771* Clear vcpu_stop after the vCPU thread has acknowledge the772* stop request and is waiting, i.e. is definitely not running!773*/774WRITE_ONCE(vcpu_stop, false);775sync_global_to_guest(vm, vcpu_stop);776777/*778* Sync the number of writes performed before verification, the779* info will be printed along with the dirty/clean page counts.780*/781sync_global_from_guest(vm, nr_writes);782783/*784* NOTE: for dirty ring, it's possible that we didn't stop at785* GUEST_SYNC but instead we stopped because ring is full;786* that's okay too because ring full means we're only missing787* the flush of the last page, and since we handle the last788* page specially verification will succeed anyway.789*/790log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,791bmap[1], host_num_pages,792&ring_buf_idx);793vm_dirty_log_verify(mode, bmap);794}795796WRITE_ONCE(host_quit, true);797sem_post(&sem_vcpu_cont);798799pthread_join(vcpu_thread, NULL);800801pr_info("Total bits checked: dirty (%lu), clear (%lu)\n",802host_dirty_count, host_clear_count);803804free(bmap[0]);805free(bmap[1]);806kvm_vm_free(vm);807}808809static void help(char *name)810{811puts("");812printf("usage: %s [-h] [-i iterations] [-I interval] "813"[-p offset] [-m mode]\n", name);814puts("");815printf(" -c: hint to dirty ring size, in number of entries\n");816printf(" (only useful for dirty-ring test; default: %"PRIu32")\n",817TEST_DIRTY_RING_COUNT);818printf(" -i: specify iteration counts (default: %"PRIu64")\n",819TEST_HOST_LOOP_N);820printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",821TEST_HOST_LOOP_INTERVAL);822printf(" -p: specify guest physical test memory offset\n"823" Warning: a low offset can conflict with the loaded test code.\n");824printf(" -M: specify the host logging mode "825"(default: run all log modes). Supported modes: \n\t");826log_modes_dump();827guest_modes_help();828puts("");829exit(0);830}831832int main(int argc, char *argv[])833{834struct test_params p = {835.iterations = TEST_HOST_LOOP_N,836.interval = TEST_HOST_LOOP_INTERVAL,837};838int opt, i;839840sem_init(&sem_vcpu_stop, 0, 0);841sem_init(&sem_vcpu_cont, 0, 0);842843guest_modes_append_default();844845while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {846switch (opt) {847case 'c':848test_dirty_ring_count = strtol(optarg, NULL, 10);849break;850case 'i':851p.iterations = strtol(optarg, NULL, 10);852break;853case 'I':854p.interval = strtol(optarg, NULL, 10);855break;856case 'p':857p.phys_offset = strtoull(optarg, NULL, 0);858break;859case 'm':860guest_modes_cmdline(optarg);861break;862case 'M':863if (!strcmp(optarg, "all")) {864host_log_mode_option = LOG_MODE_ALL;865break;866}867for (i = 0; i < LOG_MODE_NUM; i++) {868if (!strcmp(optarg, log_modes[i].name)) {869pr_info("Setting log mode to: '%s'\n",870optarg);871host_log_mode_option = i;872break;873}874}875if (i == LOG_MODE_NUM) {876printf("Log mode '%s' invalid. Please choose "877"from: ", optarg);878log_modes_dump();879exit(1);880}881break;882case 'h':883default:884help(argv[0]);885break;886}887}888889TEST_ASSERT(p.iterations > 0, "Iterations must be greater than zero");890TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");891892pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",893p.iterations, p.interval);894895if (host_log_mode_option == LOG_MODE_ALL) {896/* Run each log mode */897for (i = 0; i < LOG_MODE_NUM; i++) {898pr_info("Testing Log Mode '%s'\n", log_modes[i].name);899host_log_mode = i;900for_each_guest_mode(run_test, &p);901}902} else {903host_log_mode = host_log_mode_option;904for_each_guest_mode(run_test, &p);905}906907return 0;908}909910911