xref: /linux/tools/testing/selftests/kvm/memslot_perf_test.c (revision dc88244bf5488b04fb7bbe47d8d9c38ff8f7dbb4)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * A memslot-related performance benchmark.
4  *
5  * Copyright (C) 2021 Oracle and/or its affiliates.
6  *
7  * Basic guest setup / host vCPU thread code lifted from set_memory_region_test.
8  */
9 #include <pthread.h>
10 #include <sched.h>
11 #include <semaphore.h>
12 #include <stdatomic.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/mman.h>
19 #include <time.h>
20 #include <unistd.h>
21 
22 #include <linux/compiler.h>
23 
24 #include <test_util.h>
25 #include <kvm_util.h>
26 #include <processor.h>
27 
28 #define MEM_SIZE		((512U << 20) + 4096)
29 #define MEM_SIZE_PAGES		(MEM_SIZE / 4096)
30 #define MEM_GPA		0x10000000UL
31 #define MEM_AUX_GPA		MEM_GPA
32 #define MEM_SYNC_GPA		MEM_AUX_GPA
33 #define MEM_TEST_GPA		(MEM_AUX_GPA + 4096)
34 #define MEM_TEST_SIZE		(MEM_SIZE - 4096)
35 static_assert(MEM_SIZE % 4096 == 0, "invalid mem size");
36 static_assert(MEM_TEST_SIZE % 4096 == 0, "invalid mem test size");
37 
38 /*
39  * 32 MiB is max size that gets well over 100 iterations on 509 slots.
40  * Considering that each slot needs to have at least one page up to
41  * 8194 slots in use can then be tested (although with slightly
42  * limited resolution).
43  */
44 #define MEM_SIZE_MAP		((32U << 20) + 4096)
45 #define MEM_SIZE_MAP_PAGES	(MEM_SIZE_MAP / 4096)
46 #define MEM_TEST_MAP_SIZE	(MEM_SIZE_MAP - 4096)
47 #define MEM_TEST_MAP_SIZE_PAGES (MEM_TEST_MAP_SIZE / 4096)
48 static_assert(MEM_SIZE_MAP % 4096 == 0, "invalid map test region size");
49 static_assert(MEM_TEST_MAP_SIZE % 4096 == 0, "invalid map test region size");
50 static_assert(MEM_TEST_MAP_SIZE_PAGES % 2 == 0, "invalid map test region size");
51 static_assert(MEM_TEST_MAP_SIZE_PAGES > 2, "invalid map test region size");
52 
53 /*
54  * 128 MiB is min size that fills 32k slots with at least one page in each
55  * while at the same time gets 100+ iterations in such test
56  */
57 #define MEM_TEST_UNMAP_SIZE		(128U << 20)
58 #define MEM_TEST_UNMAP_SIZE_PAGES	(MEM_TEST_UNMAP_SIZE / 4096)
59 /* 2 MiB chunk size like a typical huge page */
60 #define MEM_TEST_UNMAP_CHUNK_PAGES	(2U << (20 - 12))
61 static_assert(MEM_TEST_UNMAP_SIZE <= MEM_TEST_SIZE,
62 	      "invalid unmap test region size");
63 static_assert(MEM_TEST_UNMAP_SIZE % 4096 == 0,
64 	      "invalid unmap test region size");
65 static_assert(MEM_TEST_UNMAP_SIZE_PAGES %
66 	      (2 * MEM_TEST_UNMAP_CHUNK_PAGES) == 0,
67 	      "invalid unmap test region size");
68 
69 /*
70  * For the move active test the middle of the test area is placed on
71  * a memslot boundary: half lies in the memslot being moved, half in
72  * other memslot(s).
73  *
74  * When running this test with 32k memslots (32764, really) each memslot
75  * contains 4 pages.
76  * The last one additionally contains the remaining 21 pages of memory,
77  * for the total size of 25 pages.
78  * Hence, the maximum size here is 50 pages.
79  */
80 #define MEM_TEST_MOVE_SIZE_PAGES	(50)
81 #define MEM_TEST_MOVE_SIZE		(MEM_TEST_MOVE_SIZE_PAGES * 4096)
82 #define MEM_TEST_MOVE_GPA_DEST		(MEM_GPA + MEM_SIZE)
83 static_assert(MEM_TEST_MOVE_SIZE <= MEM_TEST_SIZE,
84 	      "invalid move test region size");
85 
86 #define MEM_TEST_VAL_1 0x1122334455667788
87 #define MEM_TEST_VAL_2 0x99AABBCCDDEEFF00
88 
89 struct vm_data {
90 	struct kvm_vm *vm;
91 	struct kvm_vcpu *vcpu;
92 	pthread_t vcpu_thread;
93 	uint32_t nslots;
94 	uint64_t npages;
95 	uint64_t pages_per_slot;
96 	void **hva_slots;
97 	bool mmio_ok;
98 	uint64_t mmio_gpa_min;
99 	uint64_t mmio_gpa_max;
100 };
101 
102 struct sync_area {
103 	atomic_bool start_flag;
104 	atomic_bool exit_flag;
105 	atomic_bool sync_flag;
106 	void *move_area_ptr;
107 };
108 
109 /*
110  * Technically, we need also for the atomic bool to be address-free, which
111  * is recommended, but not strictly required, by C11 for lockless
112  * implementations.
113  * However, in practice both GCC and Clang fulfill this requirement on
114  * all KVM-supported platforms.
115  */
116 static_assert(ATOMIC_BOOL_LOCK_FREE == 2, "atomic bool is not lockless");
117 
118 static sem_t vcpu_ready;
119 
120 static bool map_unmap_verify;
121 
122 static bool verbose;
123 #define pr_info_v(...)				\
124 	do {					\
125 		if (verbose)			\
126 			pr_info(__VA_ARGS__);	\
127 	} while (0)
128 
129 static void check_mmio_access(struct vm_data *data, struct kvm_run *run)
130 {
131 	TEST_ASSERT(data->mmio_ok, "Unexpected mmio exit");
132 	TEST_ASSERT(run->mmio.is_write, "Unexpected mmio read");
133 	TEST_ASSERT(run->mmio.len == 8,
134 		    "Unexpected exit mmio size = %u", run->mmio.len);
135 	TEST_ASSERT(run->mmio.phys_addr >= data->mmio_gpa_min &&
136 		    run->mmio.phys_addr <= data->mmio_gpa_max,
137 		    "Unexpected exit mmio address = 0x%llx",
138 		    run->mmio.phys_addr);
139 }
140 
141 static void *vcpu_worker(void *__data)
142 {
143 	struct vm_data *data = __data;
144 	struct kvm_vcpu *vcpu = data->vcpu;
145 	struct kvm_run *run = vcpu->run;
146 	struct ucall uc;
147 
148 	while (1) {
149 		vcpu_run(vcpu);
150 
151 		switch (get_ucall(vcpu, &uc)) {
152 		case UCALL_SYNC:
153 			TEST_ASSERT(uc.args[1] == 0,
154 				"Unexpected sync ucall, got %lx",
155 				(ulong)uc.args[1]);
156 			sem_post(&vcpu_ready);
157 			continue;
158 		case UCALL_NONE:
159 			if (run->exit_reason == KVM_EXIT_MMIO)
160 				check_mmio_access(data, run);
161 			else
162 				goto done;
163 			break;
164 		case UCALL_ABORT:
165 			REPORT_GUEST_ASSERT_1(uc, "val = %lu");
166 			break;
167 		case UCALL_DONE:
168 			goto done;
169 		default:
170 			TEST_FAIL("Unknown ucall %lu", uc.cmd);
171 		}
172 	}
173 
174 done:
175 	return NULL;
176 }
177 
178 static void wait_for_vcpu(void)
179 {
180 	struct timespec ts;
181 
182 	TEST_ASSERT(!clock_gettime(CLOCK_REALTIME, &ts),
183 		    "clock_gettime() failed: %d\n", errno);
184 
185 	ts.tv_sec += 2;
186 	TEST_ASSERT(!sem_timedwait(&vcpu_ready, &ts),
187 		    "sem_timedwait() failed: %d\n", errno);
188 }
189 
190 static void *vm_gpa2hva(struct vm_data *data, uint64_t gpa, uint64_t *rempages)
191 {
192 	uint64_t gpage, pgoffs;
193 	uint32_t slot, slotoffs;
194 	void *base;
195 
196 	TEST_ASSERT(gpa >= MEM_GPA, "Too low gpa to translate");
197 	TEST_ASSERT(gpa < MEM_GPA + data->npages * 4096,
198 		    "Too high gpa to translate");
199 	gpa -= MEM_GPA;
200 
201 	gpage = gpa / 4096;
202 	pgoffs = gpa % 4096;
203 	slot = min(gpage / data->pages_per_slot, (uint64_t)data->nslots - 1);
204 	slotoffs = gpage - (slot * data->pages_per_slot);
205 
206 	if (rempages) {
207 		uint64_t slotpages;
208 
209 		if (slot == data->nslots - 1)
210 			slotpages = data->npages - slot * data->pages_per_slot;
211 		else
212 			slotpages = data->pages_per_slot;
213 
214 		TEST_ASSERT(!pgoffs,
215 			    "Asking for remaining pages in slot but gpa not page aligned");
216 		*rempages = slotpages - slotoffs;
217 	}
218 
219 	base = data->hva_slots[slot];
220 	return (uint8_t *)base + slotoffs * 4096 + pgoffs;
221 }
222 
223 static uint64_t vm_slot2gpa(struct vm_data *data, uint32_t slot)
224 {
225 	TEST_ASSERT(slot < data->nslots, "Too high slot number");
226 
227 	return MEM_GPA + slot * data->pages_per_slot * 4096;
228 }
229 
230 static struct vm_data *alloc_vm(void)
231 {
232 	struct vm_data *data;
233 
234 	data = malloc(sizeof(*data));
235 	TEST_ASSERT(data, "malloc(vmdata) failed");
236 
237 	data->vm = NULL;
238 	data->vcpu = NULL;
239 	data->hva_slots = NULL;
240 
241 	return data;
242 }
243 
244 static bool prepare_vm(struct vm_data *data, int nslots, uint64_t *maxslots,
245 		       void *guest_code, uint64_t mempages,
246 		       struct timespec *slot_runtime)
247 {
248 	uint32_t max_mem_slots;
249 	uint64_t rempages;
250 	uint64_t guest_addr;
251 	uint32_t slot;
252 	struct timespec tstart;
253 	struct sync_area *sync;
254 
255 	max_mem_slots = kvm_check_cap(KVM_CAP_NR_MEMSLOTS);
256 	TEST_ASSERT(max_mem_slots > 1,
257 		    "KVM_CAP_NR_MEMSLOTS should be greater than 1");
258 	TEST_ASSERT(nslots > 1 || nslots == -1,
259 		    "Slot count cap should be greater than 1");
260 	if (nslots != -1)
261 		max_mem_slots = min(max_mem_slots, (uint32_t)nslots);
262 	pr_info_v("Allowed number of memory slots: %"PRIu32"\n", max_mem_slots);
263 
264 	TEST_ASSERT(mempages > 1,
265 		    "Can't test without any memory");
266 
267 	data->npages = mempages;
268 	data->nslots = max_mem_slots - 1;
269 	data->pages_per_slot = mempages / data->nslots;
270 	if (!data->pages_per_slot) {
271 		*maxslots = mempages + 1;
272 		return false;
273 	}
274 
275 	rempages = mempages % data->nslots;
276 	data->hva_slots = malloc(sizeof(*data->hva_slots) * data->nslots);
277 	TEST_ASSERT(data->hva_slots, "malloc() fail");
278 
279 	data->vm = __vm_create_with_one_vcpu(&data->vcpu, mempages, guest_code);
280 
281 	pr_info_v("Adding slots 1..%i, each slot with %"PRIu64" pages + %"PRIu64" extra pages last\n",
282 		max_mem_slots - 1, data->pages_per_slot, rempages);
283 
284 	clock_gettime(CLOCK_MONOTONIC, &tstart);
285 	for (slot = 1, guest_addr = MEM_GPA; slot < max_mem_slots; slot++) {
286 		uint64_t npages;
287 
288 		npages = data->pages_per_slot;
289 		if (slot == max_mem_slots - 1)
290 			npages += rempages;
291 
292 		vm_userspace_mem_region_add(data->vm, VM_MEM_SRC_ANONYMOUS,
293 					    guest_addr, slot, npages,
294 					    0);
295 		guest_addr += npages * 4096;
296 	}
297 	*slot_runtime = timespec_elapsed(tstart);
298 
299 	for (slot = 0, guest_addr = MEM_GPA; slot < max_mem_slots - 1; slot++) {
300 		uint64_t npages;
301 		uint64_t gpa;
302 
303 		npages = data->pages_per_slot;
304 		if (slot == max_mem_slots - 2)
305 			npages += rempages;
306 
307 		gpa = vm_phy_pages_alloc(data->vm, npages, guest_addr,
308 					 slot + 1);
309 		TEST_ASSERT(gpa == guest_addr,
310 			    "vm_phy_pages_alloc() failed\n");
311 
312 		data->hva_slots[slot] = addr_gpa2hva(data->vm, guest_addr);
313 		memset(data->hva_slots[slot], 0, npages * 4096);
314 
315 		guest_addr += npages * 4096;
316 	}
317 
318 	virt_map(data->vm, MEM_GPA, MEM_GPA, mempages);
319 
320 	sync = (typeof(sync))vm_gpa2hva(data, MEM_SYNC_GPA, NULL);
321 	atomic_init(&sync->start_flag, false);
322 	atomic_init(&sync->exit_flag, false);
323 	atomic_init(&sync->sync_flag, false);
324 
325 	data->mmio_ok = false;
326 
327 	return true;
328 }
329 
330 static void launch_vm(struct vm_data *data)
331 {
332 	pr_info_v("Launching the test VM\n");
333 
334 	pthread_create(&data->vcpu_thread, NULL, vcpu_worker, data);
335 
336 	/* Ensure the guest thread is spun up. */
337 	wait_for_vcpu();
338 }
339 
340 static void free_vm(struct vm_data *data)
341 {
342 	kvm_vm_free(data->vm);
343 	free(data->hva_slots);
344 	free(data);
345 }
346 
347 static void wait_guest_exit(struct vm_data *data)
348 {
349 	pthread_join(data->vcpu_thread, NULL);
350 }
351 
352 static void let_guest_run(struct sync_area *sync)
353 {
354 	atomic_store_explicit(&sync->start_flag, true, memory_order_release);
355 }
356 
357 static void guest_spin_until_start(void)
358 {
359 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
360 
361 	while (!atomic_load_explicit(&sync->start_flag, memory_order_acquire))
362 		;
363 }
364 
365 static void make_guest_exit(struct sync_area *sync)
366 {
367 	atomic_store_explicit(&sync->exit_flag, true, memory_order_release);
368 }
369 
370 static bool _guest_should_exit(void)
371 {
372 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
373 
374 	return atomic_load_explicit(&sync->exit_flag, memory_order_acquire);
375 }
376 
377 #define guest_should_exit() unlikely(_guest_should_exit())
378 
379 /*
380  * noinline so we can easily see how much time the host spends waiting
381  * for the guest.
382  * For the same reason use alarm() instead of polling clock_gettime()
383  * to implement a wait timeout.
384  */
385 static noinline void host_perform_sync(struct sync_area *sync)
386 {
387 	alarm(2);
388 
389 	atomic_store_explicit(&sync->sync_flag, true, memory_order_release);
390 	while (atomic_load_explicit(&sync->sync_flag, memory_order_acquire))
391 		;
392 
393 	alarm(0);
394 }
395 
396 static bool guest_perform_sync(void)
397 {
398 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
399 	bool expected;
400 
401 	do {
402 		if (guest_should_exit())
403 			return false;
404 
405 		expected = true;
406 	} while (!atomic_compare_exchange_weak_explicit(&sync->sync_flag,
407 							&expected, false,
408 							memory_order_acq_rel,
409 							memory_order_relaxed));
410 
411 	return true;
412 }
413 
414 static void guest_code_test_memslot_move(void)
415 {
416 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
417 	uintptr_t base = (typeof(base))READ_ONCE(sync->move_area_ptr);
418 
419 	GUEST_SYNC(0);
420 
421 	guest_spin_until_start();
422 
423 	while (!guest_should_exit()) {
424 		uintptr_t ptr;
425 
426 		for (ptr = base; ptr < base + MEM_TEST_MOVE_SIZE;
427 		     ptr += 4096)
428 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
429 
430 		/*
431 		 * No host sync here since the MMIO exits are so expensive
432 		 * that the host would spend most of its time waiting for
433 		 * the guest and so instead of measuring memslot move
434 		 * performance we would measure the performance and
435 		 * likelihood of MMIO exits
436 		 */
437 	}
438 
439 	GUEST_DONE();
440 }
441 
442 static void guest_code_test_memslot_map(void)
443 {
444 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
445 
446 	GUEST_SYNC(0);
447 
448 	guest_spin_until_start();
449 
450 	while (1) {
451 		uintptr_t ptr;
452 
453 		for (ptr = MEM_TEST_GPA;
454 		     ptr < MEM_TEST_GPA + MEM_TEST_MAP_SIZE / 2; ptr += 4096)
455 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
456 
457 		if (!guest_perform_sync())
458 			break;
459 
460 		for (ptr = MEM_TEST_GPA + MEM_TEST_MAP_SIZE / 2;
461 		     ptr < MEM_TEST_GPA + MEM_TEST_MAP_SIZE; ptr += 4096)
462 			*(uint64_t *)ptr = MEM_TEST_VAL_2;
463 
464 		if (!guest_perform_sync())
465 			break;
466 	}
467 
468 	GUEST_DONE();
469 }
470 
471 static void guest_code_test_memslot_unmap(void)
472 {
473 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
474 
475 	GUEST_SYNC(0);
476 
477 	guest_spin_until_start();
478 
479 	while (1) {
480 		uintptr_t ptr = MEM_TEST_GPA;
481 
482 		/*
483 		 * We can afford to access (map) just a small number of pages
484 		 * per host sync as otherwise the host will spend
485 		 * a significant amount of its time waiting for the guest
486 		 * (instead of doing unmap operations), so this will
487 		 * effectively turn this test into a map performance test.
488 		 *
489 		 * Just access a single page to be on the safe side.
490 		 */
491 		*(uint64_t *)ptr = MEM_TEST_VAL_1;
492 
493 		if (!guest_perform_sync())
494 			break;
495 
496 		ptr += MEM_TEST_UNMAP_SIZE / 2;
497 		*(uint64_t *)ptr = MEM_TEST_VAL_2;
498 
499 		if (!guest_perform_sync())
500 			break;
501 	}
502 
503 	GUEST_DONE();
504 }
505 
506 static void guest_code_test_memslot_rw(void)
507 {
508 	GUEST_SYNC(0);
509 
510 	guest_spin_until_start();
511 
512 	while (1) {
513 		uintptr_t ptr;
514 
515 		for (ptr = MEM_TEST_GPA;
516 		     ptr < MEM_TEST_GPA + MEM_TEST_SIZE; ptr += 4096)
517 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
518 
519 		if (!guest_perform_sync())
520 			break;
521 
522 		for (ptr = MEM_TEST_GPA + 4096 / 2;
523 		     ptr < MEM_TEST_GPA + MEM_TEST_SIZE; ptr += 4096) {
524 			uint64_t val = *(uint64_t *)ptr;
525 
526 			GUEST_ASSERT_1(val == MEM_TEST_VAL_2, val);
527 			*(uint64_t *)ptr = 0;
528 		}
529 
530 		if (!guest_perform_sync())
531 			break;
532 	}
533 
534 	GUEST_DONE();
535 }
536 
537 static bool test_memslot_move_prepare(struct vm_data *data,
538 				      struct sync_area *sync,
539 				      uint64_t *maxslots, bool isactive)
540 {
541 	uint64_t movesrcgpa, movetestgpa;
542 
543 	movesrcgpa = vm_slot2gpa(data, data->nslots - 1);
544 
545 	if (isactive) {
546 		uint64_t lastpages;
547 
548 		vm_gpa2hva(data, movesrcgpa, &lastpages);
549 		if (lastpages < MEM_TEST_MOVE_SIZE_PAGES / 2) {
550 			*maxslots = 0;
551 			return false;
552 		}
553 	}
554 
555 	movetestgpa = movesrcgpa - (MEM_TEST_MOVE_SIZE / (isactive ? 2 : 1));
556 	sync->move_area_ptr = (void *)movetestgpa;
557 
558 	if (isactive) {
559 		data->mmio_ok = true;
560 		data->mmio_gpa_min = movesrcgpa;
561 		data->mmio_gpa_max = movesrcgpa + MEM_TEST_MOVE_SIZE / 2 - 1;
562 	}
563 
564 	return true;
565 }
566 
567 static bool test_memslot_move_prepare_active(struct vm_data *data,
568 					     struct sync_area *sync,
569 					     uint64_t *maxslots)
570 {
571 	return test_memslot_move_prepare(data, sync, maxslots, true);
572 }
573 
574 static bool test_memslot_move_prepare_inactive(struct vm_data *data,
575 					       struct sync_area *sync,
576 					       uint64_t *maxslots)
577 {
578 	return test_memslot_move_prepare(data, sync, maxslots, false);
579 }
580 
581 static void test_memslot_move_loop(struct vm_data *data, struct sync_area *sync)
582 {
583 	uint64_t movesrcgpa;
584 
585 	movesrcgpa = vm_slot2gpa(data, data->nslots - 1);
586 	vm_mem_region_move(data->vm, data->nslots - 1 + 1,
587 			   MEM_TEST_MOVE_GPA_DEST);
588 	vm_mem_region_move(data->vm, data->nslots - 1 + 1, movesrcgpa);
589 }
590 
591 static void test_memslot_do_unmap(struct vm_data *data,
592 				  uint64_t offsp, uint64_t count)
593 {
594 	uint64_t gpa, ctr;
595 
596 	for (gpa = MEM_TEST_GPA + offsp * 4096, ctr = 0; ctr < count; ) {
597 		uint64_t npages;
598 		void *hva;
599 		int ret;
600 
601 		hva = vm_gpa2hva(data, gpa, &npages);
602 		TEST_ASSERT(npages, "Empty memory slot at gptr 0x%"PRIx64, gpa);
603 		npages = min(npages, count - ctr);
604 		ret = madvise(hva, npages * 4096, MADV_DONTNEED);
605 		TEST_ASSERT(!ret,
606 			    "madvise(%p, MADV_DONTNEED) on VM memory should not fail for gptr 0x%"PRIx64,
607 			    hva, gpa);
608 		ctr += npages;
609 		gpa += npages * 4096;
610 	}
611 	TEST_ASSERT(ctr == count,
612 		    "madvise(MADV_DONTNEED) should exactly cover all of the requested area");
613 }
614 
615 static void test_memslot_map_unmap_check(struct vm_data *data,
616 					 uint64_t offsp, uint64_t valexp)
617 {
618 	uint64_t gpa;
619 	uint64_t *val;
620 
621 	if (!map_unmap_verify)
622 		return;
623 
624 	gpa = MEM_TEST_GPA + offsp * 4096;
625 	val = (typeof(val))vm_gpa2hva(data, gpa, NULL);
626 	TEST_ASSERT(*val == valexp,
627 		    "Guest written values should read back correctly before unmap (%"PRIu64" vs %"PRIu64" @ %"PRIx64")",
628 		    *val, valexp, gpa);
629 	*val = 0;
630 }
631 
632 static void test_memslot_map_loop(struct vm_data *data, struct sync_area *sync)
633 {
634 	/*
635 	 * Unmap the second half of the test area while guest writes to (maps)
636 	 * the first half.
637 	 */
638 	test_memslot_do_unmap(data, MEM_TEST_MAP_SIZE_PAGES / 2,
639 			      MEM_TEST_MAP_SIZE_PAGES / 2);
640 
641 	/*
642 	 * Wait for the guest to finish writing the first half of the test
643 	 * area, verify the written value on the first and the last page of
644 	 * this area and then unmap it.
645 	 * Meanwhile, the guest is writing to (mapping) the second half of
646 	 * the test area.
647 	 */
648 	host_perform_sync(sync);
649 	test_memslot_map_unmap_check(data, 0, MEM_TEST_VAL_1);
650 	test_memslot_map_unmap_check(data,
651 				     MEM_TEST_MAP_SIZE_PAGES / 2 - 1,
652 				     MEM_TEST_VAL_1);
653 	test_memslot_do_unmap(data, 0, MEM_TEST_MAP_SIZE_PAGES / 2);
654 
655 
656 	/*
657 	 * Wait for the guest to finish writing the second half of the test
658 	 * area and verify the written value on the first and the last page
659 	 * of this area.
660 	 * The area will be unmapped at the beginning of the next loop
661 	 * iteration.
662 	 * Meanwhile, the guest is writing to (mapping) the first half of
663 	 * the test area.
664 	 */
665 	host_perform_sync(sync);
666 	test_memslot_map_unmap_check(data, MEM_TEST_MAP_SIZE_PAGES / 2,
667 				     MEM_TEST_VAL_2);
668 	test_memslot_map_unmap_check(data, MEM_TEST_MAP_SIZE_PAGES - 1,
669 				     MEM_TEST_VAL_2);
670 }
671 
672 static void test_memslot_unmap_loop_common(struct vm_data *data,
673 					   struct sync_area *sync,
674 					   uint64_t chunk)
675 {
676 	uint64_t ctr;
677 
678 	/*
679 	 * Wait for the guest to finish mapping page(s) in the first half
680 	 * of the test area, verify the written value and then perform unmap
681 	 * of this area.
682 	 * Meanwhile, the guest is writing to (mapping) page(s) in the second
683 	 * half of the test area.
684 	 */
685 	host_perform_sync(sync);
686 	test_memslot_map_unmap_check(data, 0, MEM_TEST_VAL_1);
687 	for (ctr = 0; ctr < MEM_TEST_UNMAP_SIZE_PAGES / 2; ctr += chunk)
688 		test_memslot_do_unmap(data, ctr, chunk);
689 
690 	/* Likewise, but for the opposite host / guest areas */
691 	host_perform_sync(sync);
692 	test_memslot_map_unmap_check(data, MEM_TEST_UNMAP_SIZE_PAGES / 2,
693 				     MEM_TEST_VAL_2);
694 	for (ctr = MEM_TEST_UNMAP_SIZE_PAGES / 2;
695 	     ctr < MEM_TEST_UNMAP_SIZE_PAGES; ctr += chunk)
696 		test_memslot_do_unmap(data, ctr, chunk);
697 }
698 
699 static void test_memslot_unmap_loop(struct vm_data *data,
700 				    struct sync_area *sync)
701 {
702 	test_memslot_unmap_loop_common(data, sync, 1);
703 }
704 
705 static void test_memslot_unmap_loop_chunked(struct vm_data *data,
706 					    struct sync_area *sync)
707 {
708 	test_memslot_unmap_loop_common(data, sync, MEM_TEST_UNMAP_CHUNK_PAGES);
709 }
710 
711 static void test_memslot_rw_loop(struct vm_data *data, struct sync_area *sync)
712 {
713 	uint64_t gptr;
714 
715 	for (gptr = MEM_TEST_GPA + 4096 / 2;
716 	     gptr < MEM_TEST_GPA + MEM_TEST_SIZE; gptr += 4096)
717 		*(uint64_t *)vm_gpa2hva(data, gptr, NULL) = MEM_TEST_VAL_2;
718 
719 	host_perform_sync(sync);
720 
721 	for (gptr = MEM_TEST_GPA;
722 	     gptr < MEM_TEST_GPA + MEM_TEST_SIZE; gptr += 4096) {
723 		uint64_t *vptr = (typeof(vptr))vm_gpa2hva(data, gptr, NULL);
724 		uint64_t val = *vptr;
725 
726 		TEST_ASSERT(val == MEM_TEST_VAL_1,
727 			    "Guest written values should read back correctly (is %"PRIu64" @ %"PRIx64")",
728 			    val, gptr);
729 		*vptr = 0;
730 	}
731 
732 	host_perform_sync(sync);
733 }
734 
735 struct test_data {
736 	const char *name;
737 	uint64_t mem_size;
738 	void (*guest_code)(void);
739 	bool (*prepare)(struct vm_data *data, struct sync_area *sync,
740 			uint64_t *maxslots);
741 	void (*loop)(struct vm_data *data, struct sync_area *sync);
742 };
743 
744 static bool test_execute(int nslots, uint64_t *maxslots,
745 			 unsigned int maxtime,
746 			 const struct test_data *tdata,
747 			 uint64_t *nloops,
748 			 struct timespec *slot_runtime,
749 			 struct timespec *guest_runtime)
750 {
751 	uint64_t mem_size = tdata->mem_size ? : MEM_SIZE_PAGES;
752 	struct vm_data *data;
753 	struct sync_area *sync;
754 	struct timespec tstart;
755 	bool ret = true;
756 
757 	data = alloc_vm();
758 	if (!prepare_vm(data, nslots, maxslots, tdata->guest_code,
759 			mem_size, slot_runtime)) {
760 		ret = false;
761 		goto exit_free;
762 	}
763 
764 	sync = (typeof(sync))vm_gpa2hva(data, MEM_SYNC_GPA, NULL);
765 
766 	if (tdata->prepare &&
767 	    !tdata->prepare(data, sync, maxslots)) {
768 		ret = false;
769 		goto exit_free;
770 	}
771 
772 	launch_vm(data);
773 
774 	clock_gettime(CLOCK_MONOTONIC, &tstart);
775 	let_guest_run(sync);
776 
777 	while (1) {
778 		*guest_runtime = timespec_elapsed(tstart);
779 		if (guest_runtime->tv_sec >= maxtime)
780 			break;
781 
782 		tdata->loop(data, sync);
783 
784 		(*nloops)++;
785 	}
786 
787 	make_guest_exit(sync);
788 	wait_guest_exit(data);
789 
790 exit_free:
791 	free_vm(data);
792 
793 	return ret;
794 }
795 
796 static const struct test_data tests[] = {
797 	{
798 		.name = "map",
799 		.mem_size = MEM_SIZE_MAP_PAGES,
800 		.guest_code = guest_code_test_memslot_map,
801 		.loop = test_memslot_map_loop,
802 	},
803 	{
804 		.name = "unmap",
805 		.mem_size = MEM_TEST_UNMAP_SIZE_PAGES + 1,
806 		.guest_code = guest_code_test_memslot_unmap,
807 		.loop = test_memslot_unmap_loop,
808 	},
809 	{
810 		.name = "unmap chunked",
811 		.mem_size = MEM_TEST_UNMAP_SIZE_PAGES + 1,
812 		.guest_code = guest_code_test_memslot_unmap,
813 		.loop = test_memslot_unmap_loop_chunked,
814 	},
815 	{
816 		.name = "move active area",
817 		.guest_code = guest_code_test_memslot_move,
818 		.prepare = test_memslot_move_prepare_active,
819 		.loop = test_memslot_move_loop,
820 	},
821 	{
822 		.name = "move inactive area",
823 		.guest_code = guest_code_test_memslot_move,
824 		.prepare = test_memslot_move_prepare_inactive,
825 		.loop = test_memslot_move_loop,
826 	},
827 	{
828 		.name = "RW",
829 		.guest_code = guest_code_test_memslot_rw,
830 		.loop = test_memslot_rw_loop
831 	},
832 };
833 
834 #define NTESTS ARRAY_SIZE(tests)
835 
836 struct test_args {
837 	int tfirst;
838 	int tlast;
839 	int nslots;
840 	int seconds;
841 	int runs;
842 };
843 
844 static void help(char *name, struct test_args *targs)
845 {
846 	int ctr;
847 
848 	pr_info("usage: %s [-h] [-v] [-d] [-s slots] [-f first_test] [-e last_test] [-l test_length] [-r run_count]\n",
849 		name);
850 	pr_info(" -h: print this help screen.\n");
851 	pr_info(" -v: enable verbose mode (not for benchmarking).\n");
852 	pr_info(" -d: enable extra debug checks.\n");
853 	pr_info(" -s: specify memslot count cap (-1 means no cap; currently: %i)\n",
854 		targs->nslots);
855 	pr_info(" -f: specify the first test to run (currently: %i; max %zu)\n",
856 		targs->tfirst, NTESTS - 1);
857 	pr_info(" -e: specify the last test to run (currently: %i; max %zu)\n",
858 		targs->tlast, NTESTS - 1);
859 	pr_info(" -l: specify the test length in seconds (currently: %i)\n",
860 		targs->seconds);
861 	pr_info(" -r: specify the number of runs per test (currently: %i)\n",
862 		targs->runs);
863 
864 	pr_info("\nAvailable tests:\n");
865 	for (ctr = 0; ctr < NTESTS; ctr++)
866 		pr_info("%d: %s\n", ctr, tests[ctr].name);
867 }
868 
869 static bool parse_args(int argc, char *argv[],
870 		       struct test_args *targs)
871 {
872 	int opt;
873 
874 	while ((opt = getopt(argc, argv, "hvds:f:e:l:r:")) != -1) {
875 		switch (opt) {
876 		case 'h':
877 		default:
878 			help(argv[0], targs);
879 			return false;
880 		case 'v':
881 			verbose = true;
882 			break;
883 		case 'd':
884 			map_unmap_verify = true;
885 			break;
886 		case 's':
887 			targs->nslots = atoi_paranoid(optarg);
888 			if (targs->nslots <= 0 && targs->nslots != -1) {
889 				pr_info("Slot count cap has to be positive or -1 for no cap\n");
890 				return false;
891 			}
892 			break;
893 		case 'f':
894 			targs->tfirst = atoi_non_negative("First test", optarg);
895 			break;
896 		case 'e':
897 			targs->tlast = atoi_non_negative("Last test", optarg);
898 			if (targs->tlast >= NTESTS) {
899 				pr_info("Last test to run has to be non-negative and less than %zu\n",
900 					NTESTS);
901 				return false;
902 			}
903 			break;
904 		case 'l':
905 			targs->seconds = atoi_non_negative("Test length", optarg);
906 			break;
907 		case 'r':
908 			targs->runs = atoi_positive("Runs per test", optarg);
909 			break;
910 		}
911 	}
912 
913 	if (optind < argc) {
914 		help(argv[0], targs);
915 		return false;
916 	}
917 
918 	if (targs->tfirst > targs->tlast) {
919 		pr_info("First test to run cannot be greater than the last test to run\n");
920 		return false;
921 	}
922 
923 	return true;
924 }
925 
926 struct test_result {
927 	struct timespec slot_runtime, guest_runtime, iter_runtime;
928 	int64_t slottimens, runtimens;
929 	uint64_t nloops;
930 };
931 
932 static bool test_loop(const struct test_data *data,
933 		      const struct test_args *targs,
934 		      struct test_result *rbestslottime,
935 		      struct test_result *rbestruntime)
936 {
937 	uint64_t maxslots;
938 	struct test_result result;
939 
940 	result.nloops = 0;
941 	if (!test_execute(targs->nslots, &maxslots, targs->seconds, data,
942 			  &result.nloops,
943 			  &result.slot_runtime, &result.guest_runtime)) {
944 		if (maxslots)
945 			pr_info("Memslot count too high for this test, decrease the cap (max is %"PRIu64")\n",
946 				maxslots);
947 		else
948 			pr_info("Memslot count may be too high for this test, try adjusting the cap\n");
949 
950 		return false;
951 	}
952 
953 	pr_info("Test took %ld.%.9lds for slot setup + %ld.%.9lds all iterations\n",
954 		result.slot_runtime.tv_sec, result.slot_runtime.tv_nsec,
955 		result.guest_runtime.tv_sec, result.guest_runtime.tv_nsec);
956 	if (!result.nloops) {
957 		pr_info("No full loops done - too short test time or system too loaded?\n");
958 		return true;
959 	}
960 
961 	result.iter_runtime = timespec_div(result.guest_runtime,
962 					   result.nloops);
963 	pr_info("Done %"PRIu64" iterations, avg %ld.%.9lds each\n",
964 		result.nloops,
965 		result.iter_runtime.tv_sec,
966 		result.iter_runtime.tv_nsec);
967 	result.slottimens = timespec_to_ns(result.slot_runtime);
968 	result.runtimens = timespec_to_ns(result.iter_runtime);
969 
970 	/*
971 	 * Only rank the slot setup time for tests using the whole test memory
972 	 * area so they are comparable
973 	 */
974 	if (!data->mem_size &&
975 	    (!rbestslottime->slottimens ||
976 	     result.slottimens < rbestslottime->slottimens))
977 		*rbestslottime = result;
978 	if (!rbestruntime->runtimens ||
979 	    result.runtimens < rbestruntime->runtimens)
980 		*rbestruntime = result;
981 
982 	return true;
983 }
984 
985 int main(int argc, char *argv[])
986 {
987 	struct test_args targs = {
988 		.tfirst = 0,
989 		.tlast = NTESTS - 1,
990 		.nslots = -1,
991 		.seconds = 5,
992 		.runs = 1,
993 	};
994 	struct test_result rbestslottime;
995 	int tctr;
996 
997 	/* Tell stdout not to buffer its content */
998 	setbuf(stdout, NULL);
999 
1000 	if (!parse_args(argc, argv, &targs))
1001 		return -1;
1002 
1003 	rbestslottime.slottimens = 0;
1004 	for (tctr = targs.tfirst; tctr <= targs.tlast; tctr++) {
1005 		const struct test_data *data = &tests[tctr];
1006 		unsigned int runctr;
1007 		struct test_result rbestruntime;
1008 
1009 		if (tctr > targs.tfirst)
1010 			pr_info("\n");
1011 
1012 		pr_info("Testing %s performance with %i runs, %d seconds each\n",
1013 			data->name, targs.runs, targs.seconds);
1014 
1015 		rbestruntime.runtimens = 0;
1016 		for (runctr = 0; runctr < targs.runs; runctr++)
1017 			if (!test_loop(data, &targs,
1018 				       &rbestslottime, &rbestruntime))
1019 				break;
1020 
1021 		if (rbestruntime.runtimens)
1022 			pr_info("Best runtime result was %ld.%.9lds per iteration (with %"PRIu64" iterations)\n",
1023 				rbestruntime.iter_runtime.tv_sec,
1024 				rbestruntime.iter_runtime.tv_nsec,
1025 				rbestruntime.nloops);
1026 	}
1027 
1028 	if (rbestslottime.slottimens)
1029 		pr_info("Best slot setup time for the whole test area was %ld.%.9lds\n",
1030 			rbestslottime.slot_runtime.tv_sec,
1031 			rbestslottime.slot_runtime.tv_nsec);
1032 
1033 	return 0;
1034 }
1035