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