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 	ucall_init(data->vm, NULL);
281 
282 	pr_info_v("Adding slots 1..%i, each slot with %"PRIu64" pages + %"PRIu64" extra pages last\n",
283 		max_mem_slots - 1, data->pages_per_slot, rempages);
284 
285 	clock_gettime(CLOCK_MONOTONIC, &tstart);
286 	for (slot = 1, guest_addr = MEM_GPA; slot < max_mem_slots; slot++) {
287 		uint64_t npages;
288 
289 		npages = data->pages_per_slot;
290 		if (slot == max_mem_slots - 1)
291 			npages += rempages;
292 
293 		vm_userspace_mem_region_add(data->vm, VM_MEM_SRC_ANONYMOUS,
294 					    guest_addr, slot, npages,
295 					    0);
296 		guest_addr += npages * 4096;
297 	}
298 	*slot_runtime = timespec_elapsed(tstart);
299 
300 	for (slot = 0, guest_addr = MEM_GPA; slot < max_mem_slots - 1; slot++) {
301 		uint64_t npages;
302 		uint64_t gpa;
303 
304 		npages = data->pages_per_slot;
305 		if (slot == max_mem_slots - 2)
306 			npages += rempages;
307 
308 		gpa = vm_phy_pages_alloc(data->vm, npages, guest_addr,
309 					 slot + 1);
310 		TEST_ASSERT(gpa == guest_addr,
311 			    "vm_phy_pages_alloc() failed\n");
312 
313 		data->hva_slots[slot] = addr_gpa2hva(data->vm, guest_addr);
314 		memset(data->hva_slots[slot], 0, npages * 4096);
315 
316 		guest_addr += npages * 4096;
317 	}
318 
319 	virt_map(data->vm, MEM_GPA, MEM_GPA, mempages);
320 
321 	sync = (typeof(sync))vm_gpa2hva(data, MEM_SYNC_GPA, NULL);
322 	atomic_init(&sync->start_flag, false);
323 	atomic_init(&sync->exit_flag, false);
324 	atomic_init(&sync->sync_flag, false);
325 
326 	data->mmio_ok = false;
327 
328 	return true;
329 }
330 
331 static void launch_vm(struct vm_data *data)
332 {
333 	pr_info_v("Launching the test VM\n");
334 
335 	pthread_create(&data->vcpu_thread, NULL, vcpu_worker, data);
336 
337 	/* Ensure the guest thread is spun up. */
338 	wait_for_vcpu();
339 }
340 
341 static void free_vm(struct vm_data *data)
342 {
343 	kvm_vm_free(data->vm);
344 	free(data->hva_slots);
345 	free(data);
346 }
347 
348 static void wait_guest_exit(struct vm_data *data)
349 {
350 	pthread_join(data->vcpu_thread, NULL);
351 }
352 
353 static void let_guest_run(struct sync_area *sync)
354 {
355 	atomic_store_explicit(&sync->start_flag, true, memory_order_release);
356 }
357 
358 static void guest_spin_until_start(void)
359 {
360 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
361 
362 	while (!atomic_load_explicit(&sync->start_flag, memory_order_acquire))
363 		;
364 }
365 
366 static void make_guest_exit(struct sync_area *sync)
367 {
368 	atomic_store_explicit(&sync->exit_flag, true, memory_order_release);
369 }
370 
371 static bool _guest_should_exit(void)
372 {
373 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
374 
375 	return atomic_load_explicit(&sync->exit_flag, memory_order_acquire);
376 }
377 
378 #define guest_should_exit() unlikely(_guest_should_exit())
379 
380 /*
381  * noinline so we can easily see how much time the host spends waiting
382  * for the guest.
383  * For the same reason use alarm() instead of polling clock_gettime()
384  * to implement a wait timeout.
385  */
386 static noinline void host_perform_sync(struct sync_area *sync)
387 {
388 	alarm(2);
389 
390 	atomic_store_explicit(&sync->sync_flag, true, memory_order_release);
391 	while (atomic_load_explicit(&sync->sync_flag, memory_order_acquire))
392 		;
393 
394 	alarm(0);
395 }
396 
397 static bool guest_perform_sync(void)
398 {
399 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
400 	bool expected;
401 
402 	do {
403 		if (guest_should_exit())
404 			return false;
405 
406 		expected = true;
407 	} while (!atomic_compare_exchange_weak_explicit(&sync->sync_flag,
408 							&expected, false,
409 							memory_order_acq_rel,
410 							memory_order_relaxed));
411 
412 	return true;
413 }
414 
415 static void guest_code_test_memslot_move(void)
416 {
417 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
418 	uintptr_t base = (typeof(base))READ_ONCE(sync->move_area_ptr);
419 
420 	GUEST_SYNC(0);
421 
422 	guest_spin_until_start();
423 
424 	while (!guest_should_exit()) {
425 		uintptr_t ptr;
426 
427 		for (ptr = base; ptr < base + MEM_TEST_MOVE_SIZE;
428 		     ptr += 4096)
429 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
430 
431 		/*
432 		 * No host sync here since the MMIO exits are so expensive
433 		 * that the host would spend most of its time waiting for
434 		 * the guest and so instead of measuring memslot move
435 		 * performance we would measure the performance and
436 		 * likelihood of MMIO exits
437 		 */
438 	}
439 
440 	GUEST_DONE();
441 }
442 
443 static void guest_code_test_memslot_map(void)
444 {
445 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
446 
447 	GUEST_SYNC(0);
448 
449 	guest_spin_until_start();
450 
451 	while (1) {
452 		uintptr_t ptr;
453 
454 		for (ptr = MEM_TEST_GPA;
455 		     ptr < MEM_TEST_GPA + MEM_TEST_MAP_SIZE / 2; ptr += 4096)
456 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
457 
458 		if (!guest_perform_sync())
459 			break;
460 
461 		for (ptr = MEM_TEST_GPA + MEM_TEST_MAP_SIZE / 2;
462 		     ptr < MEM_TEST_GPA + MEM_TEST_MAP_SIZE; ptr += 4096)
463 			*(uint64_t *)ptr = MEM_TEST_VAL_2;
464 
465 		if (!guest_perform_sync())
466 			break;
467 	}
468 
469 	GUEST_DONE();
470 }
471 
472 static void guest_code_test_memslot_unmap(void)
473 {
474 	struct sync_area *sync = (typeof(sync))MEM_SYNC_GPA;
475 
476 	GUEST_SYNC(0);
477 
478 	guest_spin_until_start();
479 
480 	while (1) {
481 		uintptr_t ptr = MEM_TEST_GPA;
482 
483 		/*
484 		 * We can afford to access (map) just a small number of pages
485 		 * per host sync as otherwise the host will spend
486 		 * a significant amount of its time waiting for the guest
487 		 * (instead of doing unmap operations), so this will
488 		 * effectively turn this test into a map performance test.
489 		 *
490 		 * Just access a single page to be on the safe side.
491 		 */
492 		*(uint64_t *)ptr = MEM_TEST_VAL_1;
493 
494 		if (!guest_perform_sync())
495 			break;
496 
497 		ptr += MEM_TEST_UNMAP_SIZE / 2;
498 		*(uint64_t *)ptr = MEM_TEST_VAL_2;
499 
500 		if (!guest_perform_sync())
501 			break;
502 	}
503 
504 	GUEST_DONE();
505 }
506 
507 static void guest_code_test_memslot_rw(void)
508 {
509 	GUEST_SYNC(0);
510 
511 	guest_spin_until_start();
512 
513 	while (1) {
514 		uintptr_t ptr;
515 
516 		for (ptr = MEM_TEST_GPA;
517 		     ptr < MEM_TEST_GPA + MEM_TEST_SIZE; ptr += 4096)
518 			*(uint64_t *)ptr = MEM_TEST_VAL_1;
519 
520 		if (!guest_perform_sync())
521 			break;
522 
523 		for (ptr = MEM_TEST_GPA + 4096 / 2;
524 		     ptr < MEM_TEST_GPA + MEM_TEST_SIZE; ptr += 4096) {
525 			uint64_t val = *(uint64_t *)ptr;
526 
527 			GUEST_ASSERT_1(val == MEM_TEST_VAL_2, val);
528 			*(uint64_t *)ptr = 0;
529 		}
530 
531 		if (!guest_perform_sync())
532 			break;
533 	}
534 
535 	GUEST_DONE();
536 }
537 
538 static bool test_memslot_move_prepare(struct vm_data *data,
539 				      struct sync_area *sync,
540 				      uint64_t *maxslots, bool isactive)
541 {
542 	uint64_t movesrcgpa, movetestgpa;
543 
544 	movesrcgpa = vm_slot2gpa(data, data->nslots - 1);
545 
546 	if (isactive) {
547 		uint64_t lastpages;
548 
549 		vm_gpa2hva(data, movesrcgpa, &lastpages);
550 		if (lastpages < MEM_TEST_MOVE_SIZE_PAGES / 2) {
551 			*maxslots = 0;
552 			return false;
553 		}
554 	}
555 
556 	movetestgpa = movesrcgpa - (MEM_TEST_MOVE_SIZE / (isactive ? 2 : 1));
557 	sync->move_area_ptr = (void *)movetestgpa;
558 
559 	if (isactive) {
560 		data->mmio_ok = true;
561 		data->mmio_gpa_min = movesrcgpa;
562 		data->mmio_gpa_max = movesrcgpa + MEM_TEST_MOVE_SIZE / 2 - 1;
563 	}
564 
565 	return true;
566 }
567 
568 static bool test_memslot_move_prepare_active(struct vm_data *data,
569 					     struct sync_area *sync,
570 					     uint64_t *maxslots)
571 {
572 	return test_memslot_move_prepare(data, sync, maxslots, true);
573 }
574 
575 static bool test_memslot_move_prepare_inactive(struct vm_data *data,
576 					       struct sync_area *sync,
577 					       uint64_t *maxslots)
578 {
579 	return test_memslot_move_prepare(data, sync, maxslots, false);
580 }
581 
582 static void test_memslot_move_loop(struct vm_data *data, struct sync_area *sync)
583 {
584 	uint64_t movesrcgpa;
585 
586 	movesrcgpa = vm_slot2gpa(data, data->nslots - 1);
587 	vm_mem_region_move(data->vm, data->nslots - 1 + 1,
588 			   MEM_TEST_MOVE_GPA_DEST);
589 	vm_mem_region_move(data->vm, data->nslots - 1 + 1, movesrcgpa);
590 }
591 
592 static void test_memslot_do_unmap(struct vm_data *data,
593 				  uint64_t offsp, uint64_t count)
594 {
595 	uint64_t gpa, ctr;
596 
597 	for (gpa = MEM_TEST_GPA + offsp * 4096, ctr = 0; ctr < count; ) {
598 		uint64_t npages;
599 		void *hva;
600 		int ret;
601 
602 		hva = vm_gpa2hva(data, gpa, &npages);
603 		TEST_ASSERT(npages, "Empty memory slot at gptr 0x%"PRIx64, gpa);
604 		npages = min(npages, count - ctr);
605 		ret = madvise(hva, npages * 4096, MADV_DONTNEED);
606 		TEST_ASSERT(!ret,
607 			    "madvise(%p, MADV_DONTNEED) on VM memory should not fail for gptr 0x%"PRIx64,
608 			    hva, gpa);
609 		ctr += npages;
610 		gpa += npages * 4096;
611 	}
612 	TEST_ASSERT(ctr == count,
613 		    "madvise(MADV_DONTNEED) should exactly cover all of the requested area");
614 }
615 
616 static void test_memslot_map_unmap_check(struct vm_data *data,
617 					 uint64_t offsp, uint64_t valexp)
618 {
619 	uint64_t gpa;
620 	uint64_t *val;
621 
622 	if (!map_unmap_verify)
623 		return;
624 
625 	gpa = MEM_TEST_GPA + offsp * 4096;
626 	val = (typeof(val))vm_gpa2hva(data, gpa, NULL);
627 	TEST_ASSERT(*val == valexp,
628 		    "Guest written values should read back correctly before unmap (%"PRIu64" vs %"PRIu64" @ %"PRIx64")",
629 		    *val, valexp, gpa);
630 	*val = 0;
631 }
632 
633 static void test_memslot_map_loop(struct vm_data *data, struct sync_area *sync)
634 {
635 	/*
636 	 * Unmap the second half of the test area while guest writes to (maps)
637 	 * the first half.
638 	 */
639 	test_memslot_do_unmap(data, MEM_TEST_MAP_SIZE_PAGES / 2,
640 			      MEM_TEST_MAP_SIZE_PAGES / 2);
641 
642 	/*
643 	 * Wait for the guest to finish writing the first half of the test
644 	 * area, verify the written value on the first and the last page of
645 	 * this area and then unmap it.
646 	 * Meanwhile, the guest is writing to (mapping) the second half of
647 	 * the test area.
648 	 */
649 	host_perform_sync(sync);
650 	test_memslot_map_unmap_check(data, 0, MEM_TEST_VAL_1);
651 	test_memslot_map_unmap_check(data,
652 				     MEM_TEST_MAP_SIZE_PAGES / 2 - 1,
653 				     MEM_TEST_VAL_1);
654 	test_memslot_do_unmap(data, 0, MEM_TEST_MAP_SIZE_PAGES / 2);
655 
656 
657 	/*
658 	 * Wait for the guest to finish writing the second half of the test
659 	 * area and verify the written value on the first and the last page
660 	 * of this area.
661 	 * The area will be unmapped at the beginning of the next loop
662 	 * iteration.
663 	 * Meanwhile, the guest is writing to (mapping) the first half of
664 	 * the test area.
665 	 */
666 	host_perform_sync(sync);
667 	test_memslot_map_unmap_check(data, MEM_TEST_MAP_SIZE_PAGES / 2,
668 				     MEM_TEST_VAL_2);
669 	test_memslot_map_unmap_check(data, MEM_TEST_MAP_SIZE_PAGES - 1,
670 				     MEM_TEST_VAL_2);
671 }
672 
673 static void test_memslot_unmap_loop_common(struct vm_data *data,
674 					   struct sync_area *sync,
675 					   uint64_t chunk)
676 {
677 	uint64_t ctr;
678 
679 	/*
680 	 * Wait for the guest to finish mapping page(s) in the first half
681 	 * of the test area, verify the written value and then perform unmap
682 	 * of this area.
683 	 * Meanwhile, the guest is writing to (mapping) page(s) in the second
684 	 * half of the test area.
685 	 */
686 	host_perform_sync(sync);
687 	test_memslot_map_unmap_check(data, 0, MEM_TEST_VAL_1);
688 	for (ctr = 0; ctr < MEM_TEST_UNMAP_SIZE_PAGES / 2; ctr += chunk)
689 		test_memslot_do_unmap(data, ctr, chunk);
690 
691 	/* Likewise, but for the opposite host / guest areas */
692 	host_perform_sync(sync);
693 	test_memslot_map_unmap_check(data, MEM_TEST_UNMAP_SIZE_PAGES / 2,
694 				     MEM_TEST_VAL_2);
695 	for (ctr = MEM_TEST_UNMAP_SIZE_PAGES / 2;
696 	     ctr < MEM_TEST_UNMAP_SIZE_PAGES; ctr += chunk)
697 		test_memslot_do_unmap(data, ctr, chunk);
698 }
699 
700 static void test_memslot_unmap_loop(struct vm_data *data,
701 				    struct sync_area *sync)
702 {
703 	test_memslot_unmap_loop_common(data, sync, 1);
704 }
705 
706 static void test_memslot_unmap_loop_chunked(struct vm_data *data,
707 					    struct sync_area *sync)
708 {
709 	test_memslot_unmap_loop_common(data, sync, MEM_TEST_UNMAP_CHUNK_PAGES);
710 }
711 
712 static void test_memslot_rw_loop(struct vm_data *data, struct sync_area *sync)
713 {
714 	uint64_t gptr;
715 
716 	for (gptr = MEM_TEST_GPA + 4096 / 2;
717 	     gptr < MEM_TEST_GPA + MEM_TEST_SIZE; gptr += 4096)
718 		*(uint64_t *)vm_gpa2hva(data, gptr, NULL) = MEM_TEST_VAL_2;
719 
720 	host_perform_sync(sync);
721 
722 	for (gptr = MEM_TEST_GPA;
723 	     gptr < MEM_TEST_GPA + MEM_TEST_SIZE; gptr += 4096) {
724 		uint64_t *vptr = (typeof(vptr))vm_gpa2hva(data, gptr, NULL);
725 		uint64_t val = *vptr;
726 
727 		TEST_ASSERT(val == MEM_TEST_VAL_1,
728 			    "Guest written values should read back correctly (is %"PRIu64" @ %"PRIx64")",
729 			    val, gptr);
730 		*vptr = 0;
731 	}
732 
733 	host_perform_sync(sync);
734 }
735 
736 struct test_data {
737 	const char *name;
738 	uint64_t mem_size;
739 	void (*guest_code)(void);
740 	bool (*prepare)(struct vm_data *data, struct sync_area *sync,
741 			uint64_t *maxslots);
742 	void (*loop)(struct vm_data *data, struct sync_area *sync);
743 };
744 
745 static bool test_execute(int nslots, uint64_t *maxslots,
746 			 unsigned int maxtime,
747 			 const struct test_data *tdata,
748 			 uint64_t *nloops,
749 			 struct timespec *slot_runtime,
750 			 struct timespec *guest_runtime)
751 {
752 	uint64_t mem_size = tdata->mem_size ? : MEM_SIZE_PAGES;
753 	struct vm_data *data;
754 	struct sync_area *sync;
755 	struct timespec tstart;
756 	bool ret = true;
757 
758 	data = alloc_vm();
759 	if (!prepare_vm(data, nslots, maxslots, tdata->guest_code,
760 			mem_size, slot_runtime)) {
761 		ret = false;
762 		goto exit_free;
763 	}
764 
765 	sync = (typeof(sync))vm_gpa2hva(data, MEM_SYNC_GPA, NULL);
766 
767 	if (tdata->prepare &&
768 	    !tdata->prepare(data, sync, maxslots)) {
769 		ret = false;
770 		goto exit_free;
771 	}
772 
773 	launch_vm(data);
774 
775 	clock_gettime(CLOCK_MONOTONIC, &tstart);
776 	let_guest_run(sync);
777 
778 	while (1) {
779 		*guest_runtime = timespec_elapsed(tstart);
780 		if (guest_runtime->tv_sec >= maxtime)
781 			break;
782 
783 		tdata->loop(data, sync);
784 
785 		(*nloops)++;
786 	}
787 
788 	make_guest_exit(sync);
789 	wait_guest_exit(data);
790 
791 exit_free:
792 	free_vm(data);
793 
794 	return ret;
795 }
796 
797 static const struct test_data tests[] = {
798 	{
799 		.name = "map",
800 		.mem_size = MEM_SIZE_MAP_PAGES,
801 		.guest_code = guest_code_test_memslot_map,
802 		.loop = test_memslot_map_loop,
803 	},
804 	{
805 		.name = "unmap",
806 		.mem_size = MEM_TEST_UNMAP_SIZE_PAGES + 1,
807 		.guest_code = guest_code_test_memslot_unmap,
808 		.loop = test_memslot_unmap_loop,
809 	},
810 	{
811 		.name = "unmap chunked",
812 		.mem_size = MEM_TEST_UNMAP_SIZE_PAGES + 1,
813 		.guest_code = guest_code_test_memslot_unmap,
814 		.loop = test_memslot_unmap_loop_chunked,
815 	},
816 	{
817 		.name = "move active area",
818 		.guest_code = guest_code_test_memslot_move,
819 		.prepare = test_memslot_move_prepare_active,
820 		.loop = test_memslot_move_loop,
821 	},
822 	{
823 		.name = "move inactive area",
824 		.guest_code = guest_code_test_memslot_move,
825 		.prepare = test_memslot_move_prepare_inactive,
826 		.loop = test_memslot_move_loop,
827 	},
828 	{
829 		.name = "RW",
830 		.guest_code = guest_code_test_memslot_rw,
831 		.loop = test_memslot_rw_loop
832 	},
833 };
834 
835 #define NTESTS ARRAY_SIZE(tests)
836 
837 struct test_args {
838 	int tfirst;
839 	int tlast;
840 	int nslots;
841 	int seconds;
842 	int runs;
843 };
844 
845 static void help(char *name, struct test_args *targs)
846 {
847 	int ctr;
848 
849 	pr_info("usage: %s [-h] [-v] [-d] [-s slots] [-f first_test] [-e last_test] [-l test_length] [-r run_count]\n",
850 		name);
851 	pr_info(" -h: print this help screen.\n");
852 	pr_info(" -v: enable verbose mode (not for benchmarking).\n");
853 	pr_info(" -d: enable extra debug checks.\n");
854 	pr_info(" -s: specify memslot count cap (-1 means no cap; currently: %i)\n",
855 		targs->nslots);
856 	pr_info(" -f: specify the first test to run (currently: %i; max %zu)\n",
857 		targs->tfirst, NTESTS - 1);
858 	pr_info(" -e: specify the last test to run (currently: %i; max %zu)\n",
859 		targs->tlast, NTESTS - 1);
860 	pr_info(" -l: specify the test length in seconds (currently: %i)\n",
861 		targs->seconds);
862 	pr_info(" -r: specify the number of runs per test (currently: %i)\n",
863 		targs->runs);
864 
865 	pr_info("\nAvailable tests:\n");
866 	for (ctr = 0; ctr < NTESTS; ctr++)
867 		pr_info("%d: %s\n", ctr, tests[ctr].name);
868 }
869 
870 static bool parse_args(int argc, char *argv[],
871 		       struct test_args *targs)
872 {
873 	int opt;
874 
875 	while ((opt = getopt(argc, argv, "hvds:f:e:l:r:")) != -1) {
876 		switch (opt) {
877 		case 'h':
878 		default:
879 			help(argv[0], targs);
880 			return false;
881 		case 'v':
882 			verbose = true;
883 			break;
884 		case 'd':
885 			map_unmap_verify = true;
886 			break;
887 		case 's':
888 			targs->nslots = atoi(optarg);
889 			if (targs->nslots <= 0 && targs->nslots != -1) {
890 				pr_info("Slot count cap has to be positive or -1 for no cap\n");
891 				return false;
892 			}
893 			break;
894 		case 'f':
895 			targs->tfirst = atoi(optarg);
896 			if (targs->tfirst < 0) {
897 				pr_info("First test to run has to be non-negative\n");
898 				return false;
899 			}
900 			break;
901 		case 'e':
902 			targs->tlast = atoi(optarg);
903 			if (targs->tlast < 0 || targs->tlast >= NTESTS) {
904 				pr_info("Last test to run has to be non-negative and less than %zu\n",
905 					NTESTS);
906 				return false;
907 			}
908 			break;
909 		case 'l':
910 			targs->seconds = atoi(optarg);
911 			if (targs->seconds < 0) {
912 				pr_info("Test length in seconds has to be non-negative\n");
913 				return false;
914 			}
915 			break;
916 		case 'r':
917 			targs->runs = atoi(optarg);
918 			if (targs->runs <= 0) {
919 				pr_info("Runs per test has to be positive\n");
920 				return false;
921 			}
922 			break;
923 		}
924 	}
925 
926 	if (optind < argc) {
927 		help(argv[0], targs);
928 		return false;
929 	}
930 
931 	if (targs->tfirst > targs->tlast) {
932 		pr_info("First test to run cannot be greater than the last test to run\n");
933 		return false;
934 	}
935 
936 	return true;
937 }
938 
939 struct test_result {
940 	struct timespec slot_runtime, guest_runtime, iter_runtime;
941 	int64_t slottimens, runtimens;
942 	uint64_t nloops;
943 };
944 
945 static bool test_loop(const struct test_data *data,
946 		      const struct test_args *targs,
947 		      struct test_result *rbestslottime,
948 		      struct test_result *rbestruntime)
949 {
950 	uint64_t maxslots;
951 	struct test_result result;
952 
953 	result.nloops = 0;
954 	if (!test_execute(targs->nslots, &maxslots, targs->seconds, data,
955 			  &result.nloops,
956 			  &result.slot_runtime, &result.guest_runtime)) {
957 		if (maxslots)
958 			pr_info("Memslot count too high for this test, decrease the cap (max is %"PRIu64")\n",
959 				maxslots);
960 		else
961 			pr_info("Memslot count may be too high for this test, try adjusting the cap\n");
962 
963 		return false;
964 	}
965 
966 	pr_info("Test took %ld.%.9lds for slot setup + %ld.%.9lds all iterations\n",
967 		result.slot_runtime.tv_sec, result.slot_runtime.tv_nsec,
968 		result.guest_runtime.tv_sec, result.guest_runtime.tv_nsec);
969 	if (!result.nloops) {
970 		pr_info("No full loops done - too short test time or system too loaded?\n");
971 		return true;
972 	}
973 
974 	result.iter_runtime = timespec_div(result.guest_runtime,
975 					   result.nloops);
976 	pr_info("Done %"PRIu64" iterations, avg %ld.%.9lds each\n",
977 		result.nloops,
978 		result.iter_runtime.tv_sec,
979 		result.iter_runtime.tv_nsec);
980 	result.slottimens = timespec_to_ns(result.slot_runtime);
981 	result.runtimens = timespec_to_ns(result.iter_runtime);
982 
983 	/*
984 	 * Only rank the slot setup time for tests using the whole test memory
985 	 * area so they are comparable
986 	 */
987 	if (!data->mem_size &&
988 	    (!rbestslottime->slottimens ||
989 	     result.slottimens < rbestslottime->slottimens))
990 		*rbestslottime = result;
991 	if (!rbestruntime->runtimens ||
992 	    result.runtimens < rbestruntime->runtimens)
993 		*rbestruntime = result;
994 
995 	return true;
996 }
997 
998 int main(int argc, char *argv[])
999 {
1000 	struct test_args targs = {
1001 		.tfirst = 0,
1002 		.tlast = NTESTS - 1,
1003 		.nslots = -1,
1004 		.seconds = 5,
1005 		.runs = 1,
1006 	};
1007 	struct test_result rbestslottime;
1008 	int tctr;
1009 
1010 	/* Tell stdout not to buffer its content */
1011 	setbuf(stdout, NULL);
1012 
1013 	if (!parse_args(argc, argv, &targs))
1014 		return -1;
1015 
1016 	rbestslottime.slottimens = 0;
1017 	for (tctr = targs.tfirst; tctr <= targs.tlast; tctr++) {
1018 		const struct test_data *data = &tests[tctr];
1019 		unsigned int runctr;
1020 		struct test_result rbestruntime;
1021 
1022 		if (tctr > targs.tfirst)
1023 			pr_info("\n");
1024 
1025 		pr_info("Testing %s performance with %i runs, %d seconds each\n",
1026 			data->name, targs.runs, targs.seconds);
1027 
1028 		rbestruntime.runtimens = 0;
1029 		for (runctr = 0; runctr < targs.runs; runctr++)
1030 			if (!test_loop(data, &targs,
1031 				       &rbestslottime, &rbestruntime))
1032 				break;
1033 
1034 		if (rbestruntime.runtimens)
1035 			pr_info("Best runtime result was %ld.%.9lds per iteration (with %"PRIu64" iterations)\n",
1036 				rbestruntime.iter_runtime.tv_sec,
1037 				rbestruntime.iter_runtime.tv_nsec,
1038 				rbestruntime.nloops);
1039 	}
1040 
1041 	if (rbestslottime.slottimens)
1042 		pr_info("Best slot setup time for the whole test area was %ld.%.9lds\n",
1043 			rbestslottime.slot_runtime.tv_sec,
1044 			rbestslottime.slot_runtime.tv_nsec);
1045 
1046 	return 0;
1047 }
1048