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