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