File Index
Files and directories
Sign in
FILE

dirty_log_test.c

File preview with syntax highlighting.

linux-6.19.14/tools/testing/selftests/kvm/dirty_log_test.c C
  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 uint64_t host_page_size;
 78static uint64_t guest_page_size;
 79static uint64_t guest_num_pages;
 80static uint64_t iteration;
 81static uint64_t 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 uint64_t 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 uint64_t 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	uint64_t addr;
104
105#ifdef __s390x__
106	uint64_t 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(*(uint64_t *)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(*(uint64_t *)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 uint64_t host_num_pages;
142
143/* For statistics only */
144static uint64_t host_dirty_count;
145static uint64_t 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 uint64_t 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 uint64_t 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 uint32_t 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, uint32_t num_pages,
259					  uint32_t *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, uint32_t num_pages,
266					  uint32_t *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	uint64_t pages;
301	uint32_t 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 uint32_t dirty_ring_collect_one(struct kvm_dirty_gfn *dirty_gfns,
337				       int slot, void *bitmap,
338				       uint32_t num_pages, uint32_t *fetch_index)
339{
340	struct kvm_dirty_gfn *cur;
341	uint32_t 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, uint32_t num_pages,
363					   uint32_t *ring_buf_idx)
364{
365	uint32_t 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, uint32_t num_pages,
408				     uint32_t *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, uint32_t num_pages,
463					 uint32_t *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	uint64_t page, nr_dirty_pages = 0, nr_clean_pages = 0;
498	uint64_t step = vm_num_host_pages(mode, 1);
499
500	for (page = 0; page < host_num_pages; page += step) {
501		uint64_t val = *(uint64_t *)(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				uint64_t 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	uint64_t 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	uint32_t 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	/* Align to 1M (segment size) */
645	guest_test_phys_mem = align_down(guest_test_phys_mem, 1 << 20);
646
647	/*
648	 * The workaround in guest_code() to write all pages prior to the first
649	 * iteration isn't compatible with the dirty ring, as the dirty ring
650	 * support relies on the vCPU to actually stop when vcpu_stop is set so
651	 * that the vCPU doesn't hang waiting for the dirty ring to be emptied.
652	 */
653	TEST_ASSERT(host_log_mode != LOG_MODE_DIRTY_RING,
654		    "Test needs to be updated to support s390 dirty ring");
655#endif
656
657	pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
658
659	bmap[0] = bitmap_zalloc(host_num_pages);
660	bmap[1] = bitmap_zalloc(host_num_pages);
661
662	/* Add an extra memory slot for testing dirty logging */
663	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
664				    guest_test_phys_mem,
665				    TEST_MEM_SLOT_INDEX,
666				    guest_num_pages,
667				    KVM_MEM_LOG_DIRTY_PAGES);
668
669	/* Do mapping for the dirty track memory slot */
670	virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages);
671
672	/* Cache the HVA pointer of the region */
673	host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
674
675	/* Export the shared variables to the guest */
676	sync_global_to_guest(vm, host_page_size);
677	sync_global_to_guest(vm, guest_page_size);
678	sync_global_to_guest(vm, guest_test_virt_mem);
679	sync_global_to_guest(vm, guest_num_pages);
680
681	host_dirty_count = 0;
682	host_clear_count = 0;
683	WRITE_ONCE(host_quit, false);
684
685	/*
686	 * Ensure the previous iteration didn't leave a dangling semaphore, i.e.
687	 * that the main task and vCPU worker were synchronized and completed
688	 * verification of all iterations.
689	 */
690	sem_getvalue(&sem_vcpu_stop, &sem_val);
691	TEST_ASSERT_EQ(sem_val, 0);
692	sem_getvalue(&sem_vcpu_cont, &sem_val);
693	TEST_ASSERT_EQ(sem_val, 0);
694
695	TEST_ASSERT_EQ(vcpu_stop, false);
696
697	pthread_create(&vcpu_thread, NULL, vcpu_worker, vcpu);
698
699	for (iteration = 1; iteration <= p->iterations; iteration++) {
700		unsigned long i;
701
702		sync_global_to_guest(vm, iteration);
703
704		WRITE_ONCE(nr_writes, 0);
705		sync_global_to_guest(vm, nr_writes);
706
707		dirty_ring_prev_iteration_last_page = dirty_ring_last_page;
708		WRITE_ONCE(dirty_ring_vcpu_ring_full, false);
709
710		sem_post(&sem_vcpu_cont);
711
712		/*
713		 * Let the vCPU run beyond the configured interval until it has
714		 * performed the minimum number of writes.  This verifies the
715		 * guest is making forward progress, e.g. isn't stuck because
716		 * of a KVM bug, and puts a firm floor on test coverage.
717		 */
718		for (i = 0; i < p->interval || nr_writes < TEST_MIN_WRITES_PER_ITERATION; i++) {
719			/*
720			 * Sleep in 1ms chunks to keep the interval math simple
721			 * and so that the test doesn't run too far beyond the
722			 * specified interval.
723			 */
724			usleep(1000);
725
726			sync_global_from_guest(vm, nr_writes);
727
728			/*
729			 * Reap dirty pages while the guest is running so that
730			 * dirty ring full events are resolved, i.e. so that a
731			 * larger interval doesn't always end up with a vCPU
732			 * that's effectively blocked.  Collecting while the
733			 * guest is running also verifies KVM doesn't lose any
734			 * state.
735			 *
736			 * For bitmap modes, KVM overwrites the entire bitmap,
737			 * i.e. collecting the bitmaps is destructive.  Collect
738			 * the bitmap only on the first pass, otherwise this
739			 * test would lose track of dirty pages.
740			 */
741			if (i && host_log_mode != LOG_MODE_DIRTY_RING)
742				continue;
743
744			/*
745			 * For the dirty ring, empty the ring on subsequent
746			 * passes only if the ring was filled at least once,
747			 * to verify KVM's handling of a full ring (emptying
748			 * the ring on every pass would make it unlikely the
749			 * vCPU would ever fill the fing).
750			 */
751			if (i && !READ_ONCE(dirty_ring_vcpu_ring_full))
752				continue;
753
754			log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
755						     bmap[0], host_num_pages,
756						     &ring_buf_idx);
757		}
758
759		/*
760		 * Stop the vCPU prior to collecting and verifying the dirty
761		 * log.  If the vCPU is allowed to run during collection, then
762		 * pages that are written during this iteration may be missed,
763		 * i.e. collected in the next iteration.  And if the vCPU is
764		 * writing memory during verification, pages that this thread
765		 * sees as clean may be written with this iteration's value.
766		 */
767		WRITE_ONCE(vcpu_stop, true);
768		sync_global_to_guest(vm, vcpu_stop);
769		sem_wait(&sem_vcpu_stop);
770
771		/*
772		 * Clear vcpu_stop after the vCPU thread has acknowledge the
773		 * stop request and is waiting, i.e. is definitely not running!
774		 */
775		WRITE_ONCE(vcpu_stop, false);
776		sync_global_to_guest(vm, vcpu_stop);
777
778		/*
779		 * Sync the number of writes performed before verification, the
780		 * info will be printed along with the dirty/clean page counts.
781		 */
782		sync_global_from_guest(vm, nr_writes);
783
784		/*
785		 * NOTE: for dirty ring, it's possible that we didn't stop at
786		 * GUEST_SYNC but instead we stopped because ring is full;
787		 * that's okay too because ring full means we're only missing
788		 * the flush of the last page, and since we handle the last
789		 * page specially verification will succeed anyway.
790		 */
791		log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
792					     bmap[1], host_num_pages,
793					     &ring_buf_idx);
794		vm_dirty_log_verify(mode, bmap);
795	}
796
797	WRITE_ONCE(host_quit, true);
798	sem_post(&sem_vcpu_cont);
799
800	pthread_join(vcpu_thread, NULL);
801
802	pr_info("Total bits checked: dirty (%lu), clear (%lu)\n",
803		host_dirty_count, host_clear_count);
804
805	free(bmap[0]);
806	free(bmap[1]);
807	kvm_vm_free(vm);
808}
809
810static void help(char *name)
811{
812	puts("");
813	printf("usage: %s [-h] [-i iterations] [-I interval] "
814	       "[-p offset] [-m mode]\n", name);
815	puts("");
816	printf(" -c: hint to dirty ring size, in number of entries\n");
817	printf("     (only useful for dirty-ring test; default: %"PRIu32")\n",
818	       TEST_DIRTY_RING_COUNT);
819	printf(" -i: specify iteration counts (default: %"PRIu64")\n",
820	       TEST_HOST_LOOP_N);
821	printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
822	       TEST_HOST_LOOP_INTERVAL);
823	printf(" -p: specify guest physical test memory offset\n"
824	       "     Warning: a low offset can conflict with the loaded test code.\n");
825	printf(" -M: specify the host logging mode "
826	       "(default: run all log modes).  Supported modes: \n\t");
827	log_modes_dump();
828	guest_modes_help();
829	puts("");
830	exit(0);
831}
832
833int main(int argc, char *argv[])
834{
835	struct test_params p = {
836		.iterations = TEST_HOST_LOOP_N,
837		.interval = TEST_HOST_LOOP_INTERVAL,
838	};
839	int opt, i;
840
841	sem_init(&sem_vcpu_stop, 0, 0);
842	sem_init(&sem_vcpu_cont, 0, 0);
843
844	guest_modes_append_default();
845
846	while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {
847		switch (opt) {
848		case 'c':
849			test_dirty_ring_count = strtol(optarg, NULL, 10);
850			break;
851		case 'i':
852			p.iterations = strtol(optarg, NULL, 10);
853			break;
854		case 'I':
855			p.interval = strtol(optarg, NULL, 10);
856			break;
857		case 'p':
858			p.phys_offset = strtoull(optarg, NULL, 0);
859			break;
860		case 'm':
861			guest_modes_cmdline(optarg);
862			break;
863		case 'M':
864			if (!strcmp(optarg, "all")) {
865				host_log_mode_option = LOG_MODE_ALL;
866				break;
867			}
868			for (i = 0; i < LOG_MODE_NUM; i++) {
869				if (!strcmp(optarg, log_modes[i].name)) {
870					pr_info("Setting log mode to: '%s'\n",
871						optarg);
872					host_log_mode_option = i;
873					break;
874				}
875			}
876			if (i == LOG_MODE_NUM) {
877				printf("Log mode '%s' invalid. Please choose "
878				       "from: ", optarg);
879				log_modes_dump();
880				exit(1);
881			}
882			break;
883		case 'h':
884		default:
885			help(argv[0]);
886			break;
887		}
888	}
889
890	TEST_ASSERT(p.iterations > 0, "Iterations must be greater than zero");
891	TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");
892
893	pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
894		p.iterations, p.interval);
895
896	if (host_log_mode_option == LOG_MODE_ALL) {
897		/* Run each log mode */
898		for (i = 0; i < LOG_MODE_NUM; i++) {
899			pr_info("Testing Log Mode '%s'\n", log_modes[i].name);
900			host_log_mode = i;
901			for_each_guest_mode(run_test, &p);
902		}
903	} else {
904		host_log_mode = host_log_mode_option;
905		for_each_guest_mode(run_test, &p);
906	}
907
908	return 0;
909}
~/ Read-only file preview.