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  */
77 static uint64_t host_page_size;
78 static uint64_t guest_page_size;
79 static uint64_t guest_num_pages;
80 static uint64_t iteration;
81 static uint64_t nr_writes;
82 static 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  */
89 static 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  */
95 static 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  */
guest_code(void)101 static 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 */
137 static bool host_quit;
138 
139 /* Points to the test VM memory region on which we track dirty logs */
140 static void *host_test_mem;
141 static uint64_t host_num_pages;
142 
143 /* For statistics only */
144 static uint64_t host_dirty_count;
145 static uint64_t host_clear_count;
146 
147 /* Whether dirty ring reset is requested, or finished */
148 static sem_t sem_vcpu_stop;
149 static 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  */
156 static 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  */
172 static 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  */
216 static uint64_t dirty_ring_prev_iteration_last_page;
217 
218 enum 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 */
235 static enum log_mode_t host_log_mode_option = LOG_MODE_ALL;
236 /* Logging mode for current run */
237 static enum log_mode_t host_log_mode;
238 static pthread_t vcpu_thread;
239 static uint32_t test_dirty_ring_count = TEST_DIRTY_RING_COUNT;
240 
clear_log_supported(void)241 static bool clear_log_supported(void)
242 {
243 	return kvm_has_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
244 }
245 
clear_log_create_vm_done(struct kvm_vm * vm)246 static 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 
dirty_log_collect_dirty_pages(struct kvm_vcpu * vcpu,int slot,void * bitmap,uint32_t num_pages,uint32_t * unused)257 static 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 
clear_log_collect_dirty_pages(struct kvm_vcpu * vcpu,int slot,void * bitmap,uint32_t num_pages,uint32_t * unused)264 static 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 */
vcpu_handle_sync_stop(void)273 static 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 
default_after_vcpu_run(struct kvm_vcpu * vcpu)281 static 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 
dirty_ring_supported(void)292 static 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 
dirty_ring_create_vm_done(struct kvm_vm * vm)298 static 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 
dirty_gfn_is_dirtied(struct kvm_dirty_gfn * gfn)326 static 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 
dirty_gfn_set_collected(struct kvm_dirty_gfn * gfn)331 static 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 
dirty_ring_collect_one(struct kvm_dirty_gfn * dirty_gfns,int slot,void * bitmap,uint32_t num_pages,uint32_t * fetch_index)336 static 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 
dirty_ring_collect_dirty_pages(struct kvm_vcpu * vcpu,int slot,void * bitmap,uint32_t num_pages,uint32_t * ring_buf_idx)361 static 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 
dirty_ring_after_vcpu_run(struct kvm_vcpu * vcpu)382 static 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 
399 struct 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 
log_modes_dump(void)433 static 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 
log_mode_supported(void)443 static 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 
log_mode_create_vm_done(struct kvm_vm * vm)453 static 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 
log_mode_collect_dirty_pages(struct kvm_vcpu * vcpu,int slot,void * bitmap,uint32_t num_pages,uint32_t * ring_buf_idx)461 static 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 
log_mode_after_vcpu_run(struct kvm_vcpu * vcpu)472 static 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 
vcpu_worker(void * data)480 static 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 
vm_dirty_log_verify(enum vm_guest_mode mode,unsigned long ** bmap)495 static 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 
create_vm(enum vm_guest_mode mode,struct kvm_vcpu ** vcpu,uint64_t extra_mem_pages,void * guest_code)577 static 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 	return vm;
589 }
590 
591 struct test_params {
592 	unsigned long iterations;
593 	unsigned long interval;
594 	uint64_t phys_offset;
595 };
596 
run_test(enum vm_guest_mode mode,void * arg)597 static void run_test(enum vm_guest_mode mode, void *arg)
598 {
599 	struct test_params *p = arg;
600 	struct kvm_vcpu *vcpu;
601 	struct kvm_vm *vm;
602 	unsigned long *bmap[2];
603 	uint32_t ring_buf_idx = 0;
604 	int sem_val;
605 
606 	if (!log_mode_supported()) {
607 		print_skip("Log mode '%s' not supported",
608 			   log_modes[host_log_mode].name);
609 		return;
610 	}
611 
612 	/*
613 	 * We reserve page table for 2 times of extra dirty mem which
614 	 * will definitely cover the original (1G+) test range.  Here
615 	 * we do the calculation with 4K page size which is the
616 	 * smallest so the page number will be enough for all archs
617 	 * (e.g., 64K page size guest will need even less memory for
618 	 * page tables).
619 	 */
620 	vm = create_vm(mode, &vcpu,
621 		       2ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K), guest_code);
622 
623 	guest_page_size = vm->page_size;
624 	/*
625 	 * A little more than 1G of guest page sized pages.  Cover the
626 	 * case where the size is not aligned to 64 pages.
627 	 */
628 	guest_num_pages = (1ul << (DIRTY_MEM_BITS - vm->page_shift)) + 3;
629 	guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
630 
631 	host_page_size = getpagesize();
632 	host_num_pages = vm_num_host_pages(mode, guest_num_pages);
633 
634 	if (!p->phys_offset) {
635 		guest_test_phys_mem = (vm->max_gfn - guest_num_pages) *
636 				      guest_page_size;
637 		guest_test_phys_mem = align_down(guest_test_phys_mem, host_page_size);
638 	} else {
639 		guest_test_phys_mem = p->phys_offset;
640 	}
641 
642 #ifdef __s390x__
643 	/* Align to 1M (segment size) */
644 	guest_test_phys_mem = align_down(guest_test_phys_mem, 1 << 20);
645 
646 	/*
647 	 * The workaround in guest_code() to write all pages prior to the first
648 	 * iteration isn't compatible with the dirty ring, as the dirty ring
649 	 * support relies on the vCPU to actually stop when vcpu_stop is set so
650 	 * that the vCPU doesn't hang waiting for the dirty ring to be emptied.
651 	 */
652 	TEST_ASSERT(host_log_mode != LOG_MODE_DIRTY_RING,
653 		    "Test needs to be updated to support s390 dirty ring");
654 #endif
655 
656 	pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
657 
658 	bmap[0] = bitmap_zalloc(host_num_pages);
659 	bmap[1] = bitmap_zalloc(host_num_pages);
660 
661 	/* Add an extra memory slot for testing dirty logging */
662 	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
663 				    guest_test_phys_mem,
664 				    TEST_MEM_SLOT_INDEX,
665 				    guest_num_pages,
666 				    KVM_MEM_LOG_DIRTY_PAGES);
667 
668 	/* Do mapping for the dirty track memory slot */
669 	virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages);
670 
671 	/* Cache the HVA pointer of the region */
672 	host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
673 
674 	/* Export the shared variables to the guest */
675 	sync_global_to_guest(vm, host_page_size);
676 	sync_global_to_guest(vm, guest_page_size);
677 	sync_global_to_guest(vm, guest_test_virt_mem);
678 	sync_global_to_guest(vm, guest_num_pages);
679 
680 	host_dirty_count = 0;
681 	host_clear_count = 0;
682 	WRITE_ONCE(host_quit, false);
683 
684 	/*
685 	 * Ensure the previous iteration didn't leave a dangling semaphore, i.e.
686 	 * that the main task and vCPU worker were synchronized and completed
687 	 * verification of all iterations.
688 	 */
689 	sem_getvalue(&sem_vcpu_stop, &sem_val);
690 	TEST_ASSERT_EQ(sem_val, 0);
691 	sem_getvalue(&sem_vcpu_cont, &sem_val);
692 	TEST_ASSERT_EQ(sem_val, 0);
693 
694 	TEST_ASSERT_EQ(vcpu_stop, false);
695 
696 	pthread_create(&vcpu_thread, NULL, vcpu_worker, vcpu);
697 
698 	for (iteration = 1; iteration <= p->iterations; iteration++) {
699 		unsigned long i;
700 
701 		sync_global_to_guest(vm, iteration);
702 
703 		WRITE_ONCE(nr_writes, 0);
704 		sync_global_to_guest(vm, nr_writes);
705 
706 		dirty_ring_prev_iteration_last_page = dirty_ring_last_page;
707 		WRITE_ONCE(dirty_ring_vcpu_ring_full, false);
708 
709 		sem_post(&sem_vcpu_cont);
710 
711 		/*
712 		 * Let the vCPU run beyond the configured interval until it has
713 		 * performed the minimum number of writes.  This verifies the
714 		 * guest is making forward progress, e.g. isn't stuck because
715 		 * of a KVM bug, and puts a firm floor on test coverage.
716 		 */
717 		for (i = 0; i < p->interval || nr_writes < TEST_MIN_WRITES_PER_ITERATION; i++) {
718 			/*
719 			 * Sleep in 1ms chunks to keep the interval math simple
720 			 * and so that the test doesn't run too far beyond the
721 			 * specified interval.
722 			 */
723 			usleep(1000);
724 
725 			sync_global_from_guest(vm, nr_writes);
726 
727 			/*
728 			 * Reap dirty pages while the guest is running so that
729 			 * dirty ring full events are resolved, i.e. so that a
730 			 * larger interval doesn't always end up with a vCPU
731 			 * that's effectively blocked.  Collecting while the
732 			 * guest is running also verifies KVM doesn't lose any
733 			 * state.
734 			 *
735 			 * For bitmap modes, KVM overwrites the entire bitmap,
736 			 * i.e. collecting the bitmaps is destructive.  Collect
737 			 * the bitmap only on the first pass, otherwise this
738 			 * test would lose track of dirty pages.
739 			 */
740 			if (i && host_log_mode != LOG_MODE_DIRTY_RING)
741 				continue;
742 
743 			/*
744 			 * For the dirty ring, empty the ring on subsequent
745 			 * passes only if the ring was filled at least once,
746 			 * to verify KVM's handling of a full ring (emptying
747 			 * the ring on every pass would make it unlikely the
748 			 * vCPU would ever fill the fing).
749 			 */
750 			if (i && !READ_ONCE(dirty_ring_vcpu_ring_full))
751 				continue;
752 
753 			log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
754 						     bmap[0], host_num_pages,
755 						     &ring_buf_idx);
756 		}
757 
758 		/*
759 		 * Stop the vCPU prior to collecting and verifying the dirty
760 		 * log.  If the vCPU is allowed to run during collection, then
761 		 * pages that are written during this iteration may be missed,
762 		 * i.e. collected in the next iteration.  And if the vCPU is
763 		 * writing memory during verification, pages that this thread
764 		 * sees as clean may be written with this iteration's value.
765 		 */
766 		WRITE_ONCE(vcpu_stop, true);
767 		sync_global_to_guest(vm, vcpu_stop);
768 		sem_wait(&sem_vcpu_stop);
769 
770 		/*
771 		 * Clear vcpu_stop after the vCPU thread has acknowledge the
772 		 * stop request and is waiting, i.e. is definitely not running!
773 		 */
774 		WRITE_ONCE(vcpu_stop, false);
775 		sync_global_to_guest(vm, vcpu_stop);
776 
777 		/*
778 		 * Sync the number of writes performed before verification, the
779 		 * info will be printed along with the dirty/clean page counts.
780 		 */
781 		sync_global_from_guest(vm, nr_writes);
782 
783 		/*
784 		 * NOTE: for dirty ring, it's possible that we didn't stop at
785 		 * GUEST_SYNC but instead we stopped because ring is full;
786 		 * that's okay too because ring full means we're only missing
787 		 * the flush of the last page, and since we handle the last
788 		 * page specially verification will succeed anyway.
789 		 */
790 		log_mode_collect_dirty_pages(vcpu, TEST_MEM_SLOT_INDEX,
791 					     bmap[1], host_num_pages,
792 					     &ring_buf_idx);
793 		vm_dirty_log_verify(mode, bmap);
794 	}
795 
796 	WRITE_ONCE(host_quit, true);
797 	sem_post(&sem_vcpu_cont);
798 
799 	pthread_join(vcpu_thread, NULL);
800 
801 	pr_info("Total bits checked: dirty (%lu), clear (%lu)\n",
802 		host_dirty_count, host_clear_count);
803 
804 	free(bmap[0]);
805 	free(bmap[1]);
806 	kvm_vm_free(vm);
807 }
808 
help(char * name)809 static void help(char *name)
810 {
811 	puts("");
812 	printf("usage: %s [-h] [-i iterations] [-I interval] "
813 	       "[-p offset] [-m mode]\n", name);
814 	puts("");
815 	printf(" -c: hint to dirty ring size, in number of entries\n");
816 	printf("     (only useful for dirty-ring test; default: %"PRIu32")\n",
817 	       TEST_DIRTY_RING_COUNT);
818 	printf(" -i: specify iteration counts (default: %"PRIu64")\n",
819 	       TEST_HOST_LOOP_N);
820 	printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
821 	       TEST_HOST_LOOP_INTERVAL);
822 	printf(" -p: specify guest physical test memory offset\n"
823 	       "     Warning: a low offset can conflict with the loaded test code.\n");
824 	printf(" -M: specify the host logging mode "
825 	       "(default: run all log modes).  Supported modes: \n\t");
826 	log_modes_dump();
827 	guest_modes_help();
828 	puts("");
829 	exit(0);
830 }
831 
main(int argc,char * argv[])832 int main(int argc, char *argv[])
833 {
834 	struct test_params p = {
835 		.iterations = TEST_HOST_LOOP_N,
836 		.interval = TEST_HOST_LOOP_INTERVAL,
837 	};
838 	int opt, i;
839 
840 	sem_init(&sem_vcpu_stop, 0, 0);
841 	sem_init(&sem_vcpu_cont, 0, 0);
842 
843 	guest_modes_append_default();
844 
845 	while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {
846 		switch (opt) {
847 		case 'c':
848 			test_dirty_ring_count = strtol(optarg, NULL, 10);
849 			break;
850 		case 'i':
851 			p.iterations = strtol(optarg, NULL, 10);
852 			break;
853 		case 'I':
854 			p.interval = strtol(optarg, NULL, 10);
855 			break;
856 		case 'p':
857 			p.phys_offset = strtoull(optarg, NULL, 0);
858 			break;
859 		case 'm':
860 			guest_modes_cmdline(optarg);
861 			break;
862 		case 'M':
863 			if (!strcmp(optarg, "all")) {
864 				host_log_mode_option = LOG_MODE_ALL;
865 				break;
866 			}
867 			for (i = 0; i < LOG_MODE_NUM; i++) {
868 				if (!strcmp(optarg, log_modes[i].name)) {
869 					pr_info("Setting log mode to: '%s'\n",
870 						optarg);
871 					host_log_mode_option = i;
872 					break;
873 				}
874 			}
875 			if (i == LOG_MODE_NUM) {
876 				printf("Log mode '%s' invalid. Please choose "
877 				       "from: ", optarg);
878 				log_modes_dump();
879 				exit(1);
880 			}
881 			break;
882 		case 'h':
883 		default:
884 			help(argv[0]);
885 			break;
886 		}
887 	}
888 
889 	TEST_ASSERT(p.iterations > 0, "Iterations must be greater than zero");
890 	TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");
891 
892 	pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
893 		p.iterations, p.interval);
894 
895 	if (host_log_mode_option == LOG_MODE_ALL) {
896 		/* Run each log mode */
897 		for (i = 0; i < LOG_MODE_NUM; i++) {
898 			pr_info("Testing Log Mode '%s'\n", log_modes[i].name);
899 			host_log_mode = i;
900 			for_each_guest_mode(run_test, &p);
901 		}
902 	} else {
903 		host_log_mode = host_log_mode_option;
904 		for_each_guest_mode(run_test, &p);
905 	}
906 
907 	return 0;
908 }
909