1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KVM dirty page logging test
4  *
5  * Copyright (C) 2018, Red Hat, Inc.
6  */
7 
8 #define _GNU_SOURCE /* for program_invocation_name */
9 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <time.h>
14 #include <pthread.h>
15 #include <linux/bitmap.h>
16 #include <linux/bitops.h>
17 
18 #include "test_util.h"
19 #include "kvm_util.h"
20 #include "processor.h"
21 
22 #define DEBUG printf
23 
24 #define VCPU_ID				1
25 
26 /* The memory slot index to track dirty pages */
27 #define TEST_MEM_SLOT_INDEX		1
28 
29 /* Default guest test virtual memory offset */
30 #define DEFAULT_GUEST_TEST_MEM		0xc0000000
31 
32 /* How many pages to dirty for each guest loop */
33 #define TEST_PAGES_PER_LOOP		1024
34 
35 /* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
36 #define TEST_HOST_LOOP_N		32UL
37 
38 /* Interval for each host loop (ms) */
39 #define TEST_HOST_LOOP_INTERVAL		10UL
40 
41 /* Dirty bitmaps are always little endian, so we need to swap on big endian */
42 #if defined(__s390x__)
43 # define BITOP_LE_SWIZZLE	((BITS_PER_LONG-1) & ~0x7)
44 # define test_bit_le(nr, addr) \
45 	test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
46 # define set_bit_le(nr, addr) \
47 	set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
48 # define clear_bit_le(nr, addr) \
49 	clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
50 # define test_and_set_bit_le(nr, addr) \
51 	test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
52 # define test_and_clear_bit_le(nr, addr) \
53 	test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
54 #else
55 # define test_bit_le		test_bit
56 # define set_bit_le		set_bit
57 # define clear_bit_le		clear_bit
58 # define test_and_set_bit_le	test_and_set_bit
59 # define test_and_clear_bit_le	test_and_clear_bit
60 #endif
61 
62 /*
63  * Guest/Host shared variables. Ensure addr_gva2hva() and/or
64  * sync_global_to/from_guest() are used when accessing from
65  * the host. READ/WRITE_ONCE() should also be used with anything
66  * that may change.
67  */
68 static uint64_t host_page_size;
69 static uint64_t guest_page_size;
70 static uint64_t guest_num_pages;
71 static uint64_t random_array[TEST_PAGES_PER_LOOP];
72 static uint64_t iteration;
73 
74 /*
75  * Guest physical memory offset of the testing memory slot.
76  * This will be set to the topmost valid physical address minus
77  * the test memory size.
78  */
79 static uint64_t guest_test_phys_mem;
80 
81 /*
82  * Guest virtual memory offset of the testing memory slot.
83  * Must not conflict with identity mapped test code.
84  */
85 static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
86 
87 /*
88  * Continuously write to the first 8 bytes of a random pages within
89  * the testing memory region.
90  */
91 static void guest_code(void)
92 {
93 	uint64_t addr;
94 	int i;
95 
96 	/*
97 	 * On s390x, all pages of a 1M segment are initially marked as dirty
98 	 * when a page of the segment is written to for the very first time.
99 	 * To compensate this specialty in this test, we need to touch all
100 	 * pages during the first iteration.
101 	 */
102 	for (i = 0; i < guest_num_pages; i++) {
103 		addr = guest_test_virt_mem + i * guest_page_size;
104 		*(uint64_t *)addr = READ_ONCE(iteration);
105 	}
106 
107 	while (true) {
108 		for (i = 0; i < TEST_PAGES_PER_LOOP; i++) {
109 			addr = guest_test_virt_mem;
110 			addr += (READ_ONCE(random_array[i]) % guest_num_pages)
111 				* guest_page_size;
112 			addr &= ~(host_page_size - 1);
113 			*(uint64_t *)addr = READ_ONCE(iteration);
114 		}
115 
116 		/* Tell the host that we need more random numbers */
117 		GUEST_SYNC(1);
118 	}
119 }
120 
121 /* Host variables */
122 static bool host_quit;
123 
124 /* Points to the test VM memory region on which we track dirty logs */
125 static void *host_test_mem;
126 static uint64_t host_num_pages;
127 
128 /* For statistics only */
129 static uint64_t host_dirty_count;
130 static uint64_t host_clear_count;
131 static uint64_t host_track_next_count;
132 
133 /*
134  * We use this bitmap to track some pages that should have its dirty
135  * bit set in the _next_ iteration.  For example, if we detected the
136  * page value changed to current iteration but at the same time the
137  * page bit is cleared in the latest bitmap, then the system must
138  * report that write in the next get dirty log call.
139  */
140 static unsigned long *host_bmap_track;
141 
142 static void generate_random_array(uint64_t *guest_array, uint64_t size)
143 {
144 	uint64_t i;
145 
146 	for (i = 0; i < size; i++)
147 		guest_array[i] = random();
148 }
149 
150 static void *vcpu_worker(void *data)
151 {
152 	int ret;
153 	struct kvm_vm *vm = data;
154 	uint64_t *guest_array;
155 	uint64_t pages_count = 0;
156 	struct kvm_run *run;
157 
158 	run = vcpu_state(vm, VCPU_ID);
159 
160 	guest_array = addr_gva2hva(vm, (vm_vaddr_t)random_array);
161 	generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
162 
163 	while (!READ_ONCE(host_quit)) {
164 		/* Let the guest dirty the random pages */
165 		ret = _vcpu_run(vm, VCPU_ID);
166 		TEST_ASSERT(ret == 0, "vcpu_run failed: %d\n", ret);
167 		if (get_ucall(vm, VCPU_ID, NULL) == UCALL_SYNC) {
168 			pages_count += TEST_PAGES_PER_LOOP;
169 			generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
170 		} else {
171 			TEST_ASSERT(false,
172 				    "Invalid guest sync status: "
173 				    "exit_reason=%s\n",
174 				    exit_reason_str(run->exit_reason));
175 		}
176 	}
177 
178 	DEBUG("Dirtied %"PRIu64" pages\n", pages_count);
179 
180 	return NULL;
181 }
182 
183 static void vm_dirty_log_verify(unsigned long *bmap)
184 {
185 	uint64_t page;
186 	uint64_t *value_ptr;
187 	uint64_t step = host_page_size >= guest_page_size ? 1 :
188 				guest_page_size / host_page_size;
189 
190 	for (page = 0; page < host_num_pages; page += step) {
191 		value_ptr = host_test_mem + page * host_page_size;
192 
193 		/* If this is a special page that we were tracking... */
194 		if (test_and_clear_bit_le(page, host_bmap_track)) {
195 			host_track_next_count++;
196 			TEST_ASSERT(test_bit_le(page, bmap),
197 				    "Page %"PRIu64" should have its dirty bit "
198 				    "set in this iteration but it is missing",
199 				    page);
200 		}
201 
202 		if (test_bit_le(page, bmap)) {
203 			host_dirty_count++;
204 			/*
205 			 * If the bit is set, the value written onto
206 			 * the corresponding page should be either the
207 			 * previous iteration number or the current one.
208 			 */
209 			TEST_ASSERT(*value_ptr == iteration ||
210 				    *value_ptr == iteration - 1,
211 				    "Set page %"PRIu64" value %"PRIu64
212 				    " incorrect (iteration=%"PRIu64")",
213 				    page, *value_ptr, iteration);
214 		} else {
215 			host_clear_count++;
216 			/*
217 			 * If cleared, the value written can be any
218 			 * value smaller or equals to the iteration
219 			 * number.  Note that the value can be exactly
220 			 * (iteration-1) if that write can happen
221 			 * like this:
222 			 *
223 			 * (1) increase loop count to "iteration-1"
224 			 * (2) write to page P happens (with value
225 			 *     "iteration-1")
226 			 * (3) get dirty log for "iteration-1"; we'll
227 			 *     see that page P bit is set (dirtied),
228 			 *     and not set the bit in host_bmap_track
229 			 * (4) increase loop count to "iteration"
230 			 *     (which is current iteration)
231 			 * (5) get dirty log for current iteration,
232 			 *     we'll see that page P is cleared, with
233 			 *     value "iteration-1".
234 			 */
235 			TEST_ASSERT(*value_ptr <= iteration,
236 				    "Clear page %"PRIu64" value %"PRIu64
237 				    " incorrect (iteration=%"PRIu64")",
238 				    page, *value_ptr, iteration);
239 			if (*value_ptr == iteration) {
240 				/*
241 				 * This page is _just_ modified; it
242 				 * should report its dirtyness in the
243 				 * next run
244 				 */
245 				set_bit_le(page, host_bmap_track);
246 			}
247 		}
248 	}
249 }
250 
251 static struct kvm_vm *create_vm(enum vm_guest_mode mode, uint32_t vcpuid,
252 				uint64_t extra_mem_pages, void *guest_code,
253 				unsigned long type)
254 {
255 	struct kvm_vm *vm;
256 	uint64_t extra_pg_pages = extra_mem_pages / 512 * 2;
257 
258 	vm = _vm_create(mode, DEFAULT_GUEST_PHY_PAGES + extra_pg_pages,
259 			O_RDWR, type);
260 	kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
261 #ifdef __x86_64__
262 	vm_create_irqchip(vm);
263 #endif
264 	vm_vcpu_add_default(vm, vcpuid, guest_code);
265 	return vm;
266 }
267 
268 static void run_test(enum vm_guest_mode mode, unsigned long iterations,
269 		     unsigned long interval, uint64_t phys_offset)
270 {
271 	unsigned int guest_pa_bits, guest_page_shift;
272 	pthread_t vcpu_thread;
273 	struct kvm_vm *vm;
274 	uint64_t max_gfn;
275 	unsigned long *bmap;
276 	unsigned long type = 0;
277 
278 	switch (mode) {
279 	case VM_MODE_P52V48_4K:
280 		guest_pa_bits = 52;
281 		guest_page_shift = 12;
282 		break;
283 	case VM_MODE_P52V48_64K:
284 		guest_pa_bits = 52;
285 		guest_page_shift = 16;
286 		break;
287 	case VM_MODE_P48V48_4K:
288 		guest_pa_bits = 48;
289 		guest_page_shift = 12;
290 		break;
291 	case VM_MODE_P48V48_64K:
292 		guest_pa_bits = 48;
293 		guest_page_shift = 16;
294 		break;
295 	case VM_MODE_P40V48_4K:
296 		guest_pa_bits = 40;
297 		guest_page_shift = 12;
298 		break;
299 	case VM_MODE_P40V48_64K:
300 		guest_pa_bits = 40;
301 		guest_page_shift = 16;
302 		break;
303 	default:
304 		TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
305 	}
306 
307 	DEBUG("Testing guest mode: %s\n", vm_guest_mode_string(mode));
308 
309 #ifdef __x86_64__
310 	/*
311 	 * FIXME
312 	 * The x86_64 kvm selftests framework currently only supports a
313 	 * single PML4 which restricts the number of physical address
314 	 * bits we can change to 39.
315 	 */
316 	guest_pa_bits = 39;
317 #endif
318 #ifdef __aarch64__
319 	if (guest_pa_bits != 40)
320 		type = KVM_VM_TYPE_ARM_IPA_SIZE(guest_pa_bits);
321 #endif
322 	max_gfn = (1ul << (guest_pa_bits - guest_page_shift)) - 1;
323 	guest_page_size = (1ul << guest_page_shift);
324 	/*
325 	 * A little more than 1G of guest page sized pages.  Cover the
326 	 * case where the size is not aligned to 64 pages.
327 	 */
328 	guest_num_pages = (1ul << (30 - guest_page_shift)) + 16;
329 #ifdef __s390x__
330 	/* Round up to multiple of 1M (segment size) */
331 	guest_num_pages = (guest_num_pages + 0xff) & ~0xffUL;
332 #endif
333 	host_page_size = getpagesize();
334 	host_num_pages = (guest_num_pages * guest_page_size) / host_page_size +
335 			 !!((guest_num_pages * guest_page_size) % host_page_size);
336 
337 	if (!phys_offset) {
338 		guest_test_phys_mem = (max_gfn - guest_num_pages) * guest_page_size;
339 		guest_test_phys_mem &= ~(host_page_size - 1);
340 	} else {
341 		guest_test_phys_mem = phys_offset;
342 	}
343 
344 #ifdef __s390x__
345 	/* Align to 1M (segment size) */
346 	guest_test_phys_mem &= ~((1 << 20) - 1);
347 #endif
348 
349 	DEBUG("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
350 
351 	bmap = bitmap_alloc(host_num_pages);
352 	host_bmap_track = bitmap_alloc(host_num_pages);
353 
354 	vm = create_vm(mode, VCPU_ID, guest_num_pages, guest_code, type);
355 
356 #ifdef USE_CLEAR_DIRTY_LOG
357 	struct kvm_enable_cap cap = {};
358 
359 	cap.cap = KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2;
360 	cap.args[0] = 1;
361 	vm_enable_cap(vm, &cap);
362 #endif
363 
364 	/* Add an extra memory slot for testing dirty logging */
365 	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
366 				    guest_test_phys_mem,
367 				    TEST_MEM_SLOT_INDEX,
368 				    guest_num_pages,
369 				    KVM_MEM_LOG_DIRTY_PAGES);
370 
371 	/* Do mapping for the dirty track memory slot */
372 	virt_map(vm, guest_test_virt_mem, guest_test_phys_mem,
373 		 guest_num_pages * guest_page_size, 0);
374 
375 	/* Cache the HVA pointer of the region */
376 	host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
377 
378 #ifdef __x86_64__
379 	vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
380 #endif
381 #ifdef __aarch64__
382 	ucall_init(vm, NULL);
383 #endif
384 
385 	/* Export the shared variables to the guest */
386 	sync_global_to_guest(vm, host_page_size);
387 	sync_global_to_guest(vm, guest_page_size);
388 	sync_global_to_guest(vm, guest_test_virt_mem);
389 	sync_global_to_guest(vm, guest_num_pages);
390 
391 	/* Start the iterations */
392 	iteration = 1;
393 	sync_global_to_guest(vm, iteration);
394 	host_quit = false;
395 	host_dirty_count = 0;
396 	host_clear_count = 0;
397 	host_track_next_count = 0;
398 
399 	pthread_create(&vcpu_thread, NULL, vcpu_worker, vm);
400 
401 	while (iteration < iterations) {
402 		/* Give the vcpu thread some time to dirty some pages */
403 		usleep(interval * 1000);
404 		kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap);
405 #ifdef USE_CLEAR_DIRTY_LOG
406 		kvm_vm_clear_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap, 0,
407 				       host_num_pages);
408 #endif
409 		vm_dirty_log_verify(bmap);
410 		iteration++;
411 		sync_global_to_guest(vm, iteration);
412 	}
413 
414 	/* Tell the vcpu thread to quit */
415 	host_quit = true;
416 	pthread_join(vcpu_thread, NULL);
417 
418 	DEBUG("Total bits checked: dirty (%"PRIu64"), clear (%"PRIu64"), "
419 	      "track_next (%"PRIu64")\n", host_dirty_count, host_clear_count,
420 	      host_track_next_count);
421 
422 	free(bmap);
423 	free(host_bmap_track);
424 	ucall_uninit(vm);
425 	kvm_vm_free(vm);
426 }
427 
428 struct vm_guest_mode_params {
429 	bool supported;
430 	bool enabled;
431 };
432 struct vm_guest_mode_params vm_guest_mode_params[NUM_VM_MODES];
433 
434 #define vm_guest_mode_params_init(mode, supported, enabled)					\
435 ({												\
436 	vm_guest_mode_params[mode] = (struct vm_guest_mode_params){ supported, enabled };	\
437 })
438 
439 static void help(char *name)
440 {
441 	int i;
442 
443 	puts("");
444 	printf("usage: %s [-h] [-i iterations] [-I interval] "
445 	       "[-p offset] [-m mode]\n", name);
446 	puts("");
447 	printf(" -i: specify iteration counts (default: %"PRIu64")\n",
448 	       TEST_HOST_LOOP_N);
449 	printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
450 	       TEST_HOST_LOOP_INTERVAL);
451 	printf(" -p: specify guest physical test memory offset\n"
452 	       "     Warning: a low offset can conflict with the loaded test code.\n");
453 	printf(" -m: specify the guest mode ID to test "
454 	       "(default: test all supported modes)\n"
455 	       "     This option may be used multiple times.\n"
456 	       "     Guest mode IDs:\n");
457 	for (i = 0; i < NUM_VM_MODES; ++i) {
458 		printf("         %d:    %s%s\n", i, vm_guest_mode_string(i),
459 		       vm_guest_mode_params[i].supported ? " (supported)" : "");
460 	}
461 	puts("");
462 	exit(0);
463 }
464 
465 int main(int argc, char *argv[])
466 {
467 	unsigned long iterations = TEST_HOST_LOOP_N;
468 	unsigned long interval = TEST_HOST_LOOP_INTERVAL;
469 	bool mode_selected = false;
470 	uint64_t phys_offset = 0;
471 	unsigned int mode;
472 	int opt, i;
473 #ifdef __aarch64__
474 	unsigned int host_ipa_limit;
475 #endif
476 
477 #ifdef USE_CLEAR_DIRTY_LOG
478 	if (!kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2)) {
479 		fprintf(stderr, "KVM_CLEAR_DIRTY_LOG not available, skipping tests\n");
480 		exit(KSFT_SKIP);
481 	}
482 #endif
483 
484 #ifdef __x86_64__
485 	vm_guest_mode_params_init(VM_MODE_P52V48_4K, true, true);
486 #endif
487 #ifdef __aarch64__
488 	vm_guest_mode_params_init(VM_MODE_P40V48_4K, true, true);
489 	vm_guest_mode_params_init(VM_MODE_P40V48_64K, true, true);
490 
491 	host_ipa_limit = kvm_check_cap(KVM_CAP_ARM_VM_IPA_SIZE);
492 	if (host_ipa_limit >= 52)
493 		vm_guest_mode_params_init(VM_MODE_P52V48_64K, true, true);
494 	if (host_ipa_limit >= 48) {
495 		vm_guest_mode_params_init(VM_MODE_P48V48_4K, true, true);
496 		vm_guest_mode_params_init(VM_MODE_P48V48_64K, true, true);
497 	}
498 #endif
499 #ifdef __s390x__
500 	vm_guest_mode_params_init(VM_MODE_P40V48_4K, true, true);
501 #endif
502 
503 	while ((opt = getopt(argc, argv, "hi:I:p:m:")) != -1) {
504 		switch (opt) {
505 		case 'i':
506 			iterations = strtol(optarg, NULL, 10);
507 			break;
508 		case 'I':
509 			interval = strtol(optarg, NULL, 10);
510 			break;
511 		case 'p':
512 			phys_offset = strtoull(optarg, NULL, 0);
513 			break;
514 		case 'm':
515 			if (!mode_selected) {
516 				for (i = 0; i < NUM_VM_MODES; ++i)
517 					vm_guest_mode_params[i].enabled = false;
518 				mode_selected = true;
519 			}
520 			mode = strtoul(optarg, NULL, 10);
521 			TEST_ASSERT(mode < NUM_VM_MODES,
522 				    "Guest mode ID %d too big", mode);
523 			vm_guest_mode_params[mode].enabled = true;
524 			break;
525 		case 'h':
526 		default:
527 			help(argv[0]);
528 			break;
529 		}
530 	}
531 
532 	TEST_ASSERT(iterations > 2, "Iterations must be greater than two");
533 	TEST_ASSERT(interval > 0, "Interval must be greater than zero");
534 
535 	DEBUG("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
536 	      iterations, interval);
537 
538 	srandom(time(0));
539 
540 	for (i = 0; i < NUM_VM_MODES; ++i) {
541 		if (!vm_guest_mode_params[i].enabled)
542 			continue;
543 		TEST_ASSERT(vm_guest_mode_params[i].supported,
544 			    "Guest mode ID %d (%s) not supported.",
545 			    i, vm_guest_mode_string(i));
546 		run_test(i, iterations, interval, phys_offset);
547 	}
548 
549 	return 0;
550 }
551