1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KVM dirty page logging performance test
4  *
5  * Based on dirty_log_test.c
6  *
7  * Copyright (C) 2018, Red Hat, Inc.
8  * Copyright (C) 2020, Google, Inc.
9  */
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <time.h>
14 #include <pthread.h>
15 #include <linux/bitmap.h>
16 
17 #include "kvm_util.h"
18 #include "test_util.h"
19 #include "perf_test_util.h"
20 #include "guest_modes.h"
21 
22 /* How many host loops to run by default (one KVM_GET_DIRTY_LOG for each loop)*/
23 #define TEST_HOST_LOOP_N		2UL
24 
25 static int nr_vcpus = 1;
26 static uint64_t guest_percpu_mem_size = DEFAULT_PER_VCPU_MEM_SIZE;
27 
28 /* Host variables */
29 static u64 dirty_log_manual_caps;
30 static bool host_quit;
31 static int iteration;
32 static int vcpu_last_completed_iteration[KVM_MAX_VCPUS];
33 
34 static void *vcpu_worker(void *data)
35 {
36 	int ret;
37 	struct kvm_vm *vm = perf_test_args.vm;
38 	uint64_t pages_count = 0;
39 	struct kvm_run *run;
40 	struct timespec start;
41 	struct timespec ts_diff;
42 	struct timespec total = (struct timespec){0};
43 	struct timespec avg;
44 	struct perf_test_vcpu_args *vcpu_args = (struct perf_test_vcpu_args *)data;
45 	int vcpu_id = vcpu_args->vcpu_id;
46 
47 	run = vcpu_state(vm, vcpu_id);
48 
49 	while (!READ_ONCE(host_quit)) {
50 		int current_iteration = READ_ONCE(iteration);
51 
52 		clock_gettime(CLOCK_MONOTONIC, &start);
53 		ret = _vcpu_run(vm, vcpu_id);
54 		ts_diff = timespec_elapsed(start);
55 
56 		TEST_ASSERT(ret == 0, "vcpu_run failed: %d\n", ret);
57 		TEST_ASSERT(get_ucall(vm, vcpu_id, NULL) == UCALL_SYNC,
58 			    "Invalid guest sync status: exit_reason=%s\n",
59 			    exit_reason_str(run->exit_reason));
60 
61 		pr_debug("Got sync event from vCPU %d\n", vcpu_id);
62 		vcpu_last_completed_iteration[vcpu_id] = current_iteration;
63 		pr_debug("vCPU %d updated last completed iteration to %d\n",
64 			 vcpu_id, vcpu_last_completed_iteration[vcpu_id]);
65 
66 		if (current_iteration) {
67 			pages_count += vcpu_args->pages;
68 			total = timespec_add(total, ts_diff);
69 			pr_debug("vCPU %d iteration %d dirty memory time: %ld.%.9lds\n",
70 				vcpu_id, current_iteration, ts_diff.tv_sec,
71 				ts_diff.tv_nsec);
72 		} else {
73 			pr_debug("vCPU %d iteration %d populate memory time: %ld.%.9lds\n",
74 				vcpu_id, current_iteration, ts_diff.tv_sec,
75 				ts_diff.tv_nsec);
76 		}
77 
78 		while (current_iteration == READ_ONCE(iteration) &&
79 		       !READ_ONCE(host_quit)) {}
80 	}
81 
82 	avg = timespec_div(total, vcpu_last_completed_iteration[vcpu_id]);
83 	pr_debug("\nvCPU %d dirtied 0x%lx pages over %d iterations in %ld.%.9lds. (Avg %ld.%.9lds/iteration)\n",
84 		vcpu_id, pages_count, vcpu_last_completed_iteration[vcpu_id],
85 		total.tv_sec, total.tv_nsec, avg.tv_sec, avg.tv_nsec);
86 
87 	return NULL;
88 }
89 
90 struct test_params {
91 	unsigned long iterations;
92 	uint64_t phys_offset;
93 	int wr_fract;
94 	bool partition_vcpu_memory_access;
95 	enum vm_mem_backing_src_type backing_src;
96 	int slots;
97 };
98 
99 static void toggle_dirty_logging(struct kvm_vm *vm, int slots, bool enable)
100 {
101 	int i;
102 
103 	for (i = 0; i < slots; i++) {
104 		int slot = PERF_TEST_MEM_SLOT_INDEX + i;
105 		int flags = enable ? KVM_MEM_LOG_DIRTY_PAGES : 0;
106 
107 		vm_mem_region_set_flags(vm, slot, flags);
108 	}
109 }
110 
111 static inline void enable_dirty_logging(struct kvm_vm *vm, int slots)
112 {
113 	toggle_dirty_logging(vm, slots, true);
114 }
115 
116 static inline void disable_dirty_logging(struct kvm_vm *vm, int slots)
117 {
118 	toggle_dirty_logging(vm, slots, false);
119 }
120 
121 static void get_dirty_log(struct kvm_vm *vm, unsigned long *bitmaps[], int slots)
122 {
123 	int i;
124 
125 	for (i = 0; i < slots; i++) {
126 		int slot = PERF_TEST_MEM_SLOT_INDEX + i;
127 
128 		kvm_vm_get_dirty_log(vm, slot, bitmaps[i]);
129 	}
130 }
131 
132 static void clear_dirty_log(struct kvm_vm *vm, unsigned long *bitmaps[],
133 			    int slots, uint64_t pages_per_slot)
134 {
135 	int i;
136 
137 	for (i = 0; i < slots; i++) {
138 		int slot = PERF_TEST_MEM_SLOT_INDEX + i;
139 
140 		kvm_vm_clear_dirty_log(vm, slot, bitmaps[i], 0, pages_per_slot);
141 	}
142 }
143 
144 static unsigned long **alloc_bitmaps(int slots, uint64_t pages_per_slot)
145 {
146 	unsigned long **bitmaps;
147 	int i;
148 
149 	bitmaps = malloc(slots * sizeof(bitmaps[0]));
150 	TEST_ASSERT(bitmaps, "Failed to allocate bitmaps array.");
151 
152 	for (i = 0; i < slots; i++) {
153 		bitmaps[i] = bitmap_zalloc(pages_per_slot);
154 		TEST_ASSERT(bitmaps[i], "Failed to allocate slot bitmap.");
155 	}
156 
157 	return bitmaps;
158 }
159 
160 static void free_bitmaps(unsigned long *bitmaps[], int slots)
161 {
162 	int i;
163 
164 	for (i = 0; i < slots; i++)
165 		free(bitmaps[i]);
166 
167 	free(bitmaps);
168 }
169 
170 static void run_test(enum vm_guest_mode mode, void *arg)
171 {
172 	struct test_params *p = arg;
173 	pthread_t *vcpu_threads;
174 	struct kvm_vm *vm;
175 	unsigned long **bitmaps;
176 	uint64_t guest_num_pages;
177 	uint64_t host_num_pages;
178 	uint64_t pages_per_slot;
179 	int vcpu_id;
180 	struct timespec start;
181 	struct timespec ts_diff;
182 	struct timespec get_dirty_log_total = (struct timespec){0};
183 	struct timespec vcpu_dirty_total = (struct timespec){0};
184 	struct timespec avg;
185 	struct kvm_enable_cap cap = {};
186 	struct timespec clear_dirty_log_total = (struct timespec){0};
187 
188 	vm = perf_test_create_vm(mode, nr_vcpus, guest_percpu_mem_size,
189 				 p->slots, p->backing_src);
190 
191 	perf_test_args.wr_fract = p->wr_fract;
192 
193 	guest_num_pages = (nr_vcpus * guest_percpu_mem_size) >> vm_get_page_shift(vm);
194 	guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
195 	host_num_pages = vm_num_host_pages(mode, guest_num_pages);
196 	pages_per_slot = host_num_pages / p->slots;
197 
198 	bitmaps = alloc_bitmaps(p->slots, pages_per_slot);
199 
200 	if (dirty_log_manual_caps) {
201 		cap.cap = KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2;
202 		cap.args[0] = dirty_log_manual_caps;
203 		vm_enable_cap(vm, &cap);
204 	}
205 
206 	vcpu_threads = malloc(nr_vcpus * sizeof(*vcpu_threads));
207 	TEST_ASSERT(vcpu_threads, "Memory allocation failed");
208 
209 	perf_test_setup_vcpus(vm, nr_vcpus, guest_percpu_mem_size,
210 			      p->partition_vcpu_memory_access);
211 
212 	sync_global_to_guest(vm, perf_test_args);
213 
214 	/* Start the iterations */
215 	iteration = 0;
216 	host_quit = false;
217 
218 	clock_gettime(CLOCK_MONOTONIC, &start);
219 	for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
220 		vcpu_last_completed_iteration[vcpu_id] = -1;
221 
222 		pthread_create(&vcpu_threads[vcpu_id], NULL, vcpu_worker,
223 			       &perf_test_args.vcpu_args[vcpu_id]);
224 	}
225 
226 	/* Allow the vCPUs to populate memory */
227 	pr_debug("Starting iteration %d - Populating\n", iteration);
228 	for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
229 		while (READ_ONCE(vcpu_last_completed_iteration[vcpu_id]) !=
230 		       iteration)
231 			;
232 	}
233 
234 	ts_diff = timespec_elapsed(start);
235 	pr_info("Populate memory time: %ld.%.9lds\n",
236 		ts_diff.tv_sec, ts_diff.tv_nsec);
237 
238 	/* Enable dirty logging */
239 	clock_gettime(CLOCK_MONOTONIC, &start);
240 	enable_dirty_logging(vm, p->slots);
241 	ts_diff = timespec_elapsed(start);
242 	pr_info("Enabling dirty logging time: %ld.%.9lds\n\n",
243 		ts_diff.tv_sec, ts_diff.tv_nsec);
244 
245 	while (iteration < p->iterations) {
246 		/*
247 		 * Incrementing the iteration number will start the vCPUs
248 		 * dirtying memory again.
249 		 */
250 		clock_gettime(CLOCK_MONOTONIC, &start);
251 		iteration++;
252 
253 		pr_debug("Starting iteration %d\n", iteration);
254 		for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
255 			while (READ_ONCE(vcpu_last_completed_iteration[vcpu_id])
256 			       != iteration)
257 				;
258 		}
259 
260 		ts_diff = timespec_elapsed(start);
261 		vcpu_dirty_total = timespec_add(vcpu_dirty_total, ts_diff);
262 		pr_info("Iteration %d dirty memory time: %ld.%.9lds\n",
263 			iteration, ts_diff.tv_sec, ts_diff.tv_nsec);
264 
265 		clock_gettime(CLOCK_MONOTONIC, &start);
266 		get_dirty_log(vm, bitmaps, p->slots);
267 		ts_diff = timespec_elapsed(start);
268 		get_dirty_log_total = timespec_add(get_dirty_log_total,
269 						   ts_diff);
270 		pr_info("Iteration %d get dirty log time: %ld.%.9lds\n",
271 			iteration, ts_diff.tv_sec, ts_diff.tv_nsec);
272 
273 		if (dirty_log_manual_caps) {
274 			clock_gettime(CLOCK_MONOTONIC, &start);
275 			clear_dirty_log(vm, bitmaps, p->slots, pages_per_slot);
276 			ts_diff = timespec_elapsed(start);
277 			clear_dirty_log_total = timespec_add(clear_dirty_log_total,
278 							     ts_diff);
279 			pr_info("Iteration %d clear dirty log time: %ld.%.9lds\n",
280 				iteration, ts_diff.tv_sec, ts_diff.tv_nsec);
281 		}
282 	}
283 
284 	/* Disable dirty logging */
285 	clock_gettime(CLOCK_MONOTONIC, &start);
286 	disable_dirty_logging(vm, p->slots);
287 	ts_diff = timespec_elapsed(start);
288 	pr_info("Disabling dirty logging time: %ld.%.9lds\n",
289 		ts_diff.tv_sec, ts_diff.tv_nsec);
290 
291 	/* Tell the vcpu thread to quit */
292 	host_quit = true;
293 	for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++)
294 		pthread_join(vcpu_threads[vcpu_id], NULL);
295 
296 	avg = timespec_div(get_dirty_log_total, p->iterations);
297 	pr_info("Get dirty log over %lu iterations took %ld.%.9lds. (Avg %ld.%.9lds/iteration)\n",
298 		p->iterations, get_dirty_log_total.tv_sec,
299 		get_dirty_log_total.tv_nsec, avg.tv_sec, avg.tv_nsec);
300 
301 	if (dirty_log_manual_caps) {
302 		avg = timespec_div(clear_dirty_log_total, p->iterations);
303 		pr_info("Clear dirty log over %lu iterations took %ld.%.9lds. (Avg %ld.%.9lds/iteration)\n",
304 			p->iterations, clear_dirty_log_total.tv_sec,
305 			clear_dirty_log_total.tv_nsec, avg.tv_sec, avg.tv_nsec);
306 	}
307 
308 	free_bitmaps(bitmaps, p->slots);
309 	free(vcpu_threads);
310 	perf_test_destroy_vm(vm);
311 }
312 
313 static void help(char *name)
314 {
315 	puts("");
316 	printf("usage: %s [-h] [-i iterations] [-p offset] "
317 	       "[-m mode] [-b vcpu bytes] [-v vcpus] [-o] [-s mem type]"
318 	       "[-x memslots]\n", name);
319 	puts("");
320 	printf(" -i: specify iteration counts (default: %"PRIu64")\n",
321 	       TEST_HOST_LOOP_N);
322 	printf(" -p: specify guest physical test memory offset\n"
323 	       "     Warning: a low offset can conflict with the loaded test code.\n");
324 	guest_modes_help();
325 	printf(" -b: specify the size of the memory region which should be\n"
326 	       "     dirtied by each vCPU. e.g. 10M or 3G.\n"
327 	       "     (default: 1G)\n");
328 	printf(" -f: specify the fraction of pages which should be written to\n"
329 	       "     as opposed to simply read, in the form\n"
330 	       "     1/<fraction of pages to write>.\n"
331 	       "     (default: 1 i.e. all pages are written to.)\n");
332 	printf(" -v: specify the number of vCPUs to run.\n");
333 	printf(" -o: Overlap guest memory accesses instead of partitioning\n"
334 	       "     them into a separate region of memory for each vCPU.\n");
335 	backing_src_help("-s");
336 	printf(" -x: Split the memory region into this number of memslots.\n"
337 	       "     (default: 1)\n");
338 	puts("");
339 	exit(0);
340 }
341 
342 int main(int argc, char *argv[])
343 {
344 	int max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
345 	struct test_params p = {
346 		.iterations = TEST_HOST_LOOP_N,
347 		.wr_fract = 1,
348 		.partition_vcpu_memory_access = true,
349 		.backing_src = DEFAULT_VM_MEM_SRC,
350 		.slots = 1,
351 	};
352 	int opt;
353 
354 	dirty_log_manual_caps =
355 		kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
356 	dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
357 				  KVM_DIRTY_LOG_INITIALLY_SET);
358 
359 	guest_modes_append_default();
360 
361 	while ((opt = getopt(argc, argv, "hi:p:m:b:f:v:os:x:")) != -1) {
362 		switch (opt) {
363 		case 'i':
364 			p.iterations = atoi(optarg);
365 			break;
366 		case 'p':
367 			p.phys_offset = strtoull(optarg, NULL, 0);
368 			break;
369 		case 'm':
370 			guest_modes_cmdline(optarg);
371 			break;
372 		case 'b':
373 			guest_percpu_mem_size = parse_size(optarg);
374 			break;
375 		case 'f':
376 			p.wr_fract = atoi(optarg);
377 			TEST_ASSERT(p.wr_fract >= 1,
378 				    "Write fraction cannot be less than one");
379 			break;
380 		case 'v':
381 			nr_vcpus = atoi(optarg);
382 			TEST_ASSERT(nr_vcpus > 0 && nr_vcpus <= max_vcpus,
383 				    "Invalid number of vcpus, must be between 1 and %d", max_vcpus);
384 			break;
385 		case 'o':
386 			p.partition_vcpu_memory_access = false;
387 			break;
388 		case 's':
389 			p.backing_src = parse_backing_src_type(optarg);
390 			break;
391 		case 'x':
392 			p.slots = atoi(optarg);
393 			break;
394 		case 'h':
395 		default:
396 			help(argv[0]);
397 			break;
398 		}
399 	}
400 
401 	TEST_ASSERT(p.iterations >= 2, "The test should have at least two iterations");
402 
403 	pr_info("Test iterations: %"PRIu64"\n",	p.iterations);
404 
405 	for_each_guest_mode(run_test, &p);
406 
407 	return 0;
408 }
409