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