1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * access_tracking_perf_test
4 *
5 * Copyright (C) 2021, Google, Inc.
6 *
7 * This test measures the performance effects of KVM's access tracking.
8 * Access tracking is driven by the MMU notifiers test_young, clear_young, and
9 * clear_flush_young. These notifiers do not have a direct userspace API,
10 * however the clear_young notifier can be triggered either by
11 * 1. marking a pages as idle in /sys/kernel/mm/page_idle/bitmap OR
12 * 2. adding a new MGLRU generation using the lru_gen debugfs file.
13 * This test leverages page_idle to enable access tracking on guest memory
14 * unless MGLRU is enabled, in which case MGLRU is used.
15 *
16 * To measure performance this test runs a VM with a configurable number of
17 * vCPUs that each touch every page in disjoint regions of memory. Performance
18 * is measured in the time it takes all vCPUs to finish touching their
19 * predefined region.
20 *
21 * Note that a deterministic correctness test of access tracking is not possible
22 * by using page_idle or MGLRU aging as it exists today. This is for a few
23 * reasons:
24 *
25 * 1. page_idle and MGLRU only issue clear_young notifiers, which lack a TLB flush.
26 * This means subsequent guest accesses are not guaranteed to see page table
27 * updates made by KVM until some time in the future.
28 *
29 * 2. page_idle only operates on LRU pages. Newly allocated pages are not
30 * immediately allocated to LRU lists. Instead they are held in a "pagevec",
31 * which is drained to LRU lists some time in the future. There is no
32 * userspace API to force this drain to occur.
33 *
34 * These limitations are worked around in this test by using a large enough
35 * region of memory for each vCPU such that the number of translations cached in
36 * the TLB and the number of pages held in pagevecs are a small fraction of the
37 * overall workload. And if either of those conditions are not true (for example
38 * in nesting, where TLB size is unlimited) this test will print a warning
39 * rather than silently passing.
40 */
41 #include <inttypes.h>
42 #include <limits.h>
43 #include <pthread.h>
44 #include <sys/mman.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47
48 #include "kvm_util.h"
49 #include "test_util.h"
50 #include "memstress.h"
51 #include "guest_modes.h"
52 #include "processor.h"
53
54 #include "cgroup_util.h"
55 #include "lru_gen_util.h"
56
57 static const char *TEST_MEMCG_NAME = "access_tracking_perf_test";
58
59 /* Global variable used to synchronize all of the vCPU threads. */
60 static int iteration;
61
62 /* The cgroup memory controller root. Needed for lru_gen-based aging. */
63 char cgroup_root[PATH_MAX];
64
65 /* Defines what vCPU threads should do during a given iteration. */
66 static enum {
67 /* Run the vCPU to access all its memory. */
68 ITERATION_ACCESS_MEMORY,
69 /* Mark the vCPU's memory idle in page_idle. */
70 ITERATION_MARK_IDLE,
71 } iteration_work;
72
73 /* The iteration that was last completed by each vCPU. */
74 static int vcpu_last_completed_iteration[KVM_MAX_VCPUS];
75
76 /* Whether to overlap the regions of memory vCPUs access. */
77 static bool overlap_memory_access;
78
79 /*
80 * If the test should only warn if there are too many idle pages (i.e., it is
81 * expected).
82 * -1: Not yet set.
83 * 0: We do not expect too many idle pages, so FAIL if too many idle pages.
84 * 1: Having too many idle pages is expected, so merely print a warning if
85 * too many idle pages are found.
86 */
87 static int idle_pages_warn_only = -1;
88
89 /* Whether or not to use MGLRU instead of page_idle for access tracking */
90 static bool use_lru_gen;
91
92 /* Total number of pages to expect in the memcg after touching everything */
93 static long test_pages;
94
95 /* Last generation we found the pages in */
96 static int lru_gen_last_gen = -1;
97
98 struct test_params {
99 /* The backing source for the region of memory. */
100 enum vm_mem_backing_src_type backing_src;
101
102 /* The amount of memory to allocate for each vCPU. */
103 uint64_t vcpu_memory_bytes;
104
105 /* The number of vCPUs to create in the VM. */
106 int nr_vcpus;
107 };
108
pread_uint64(int fd,const char * filename,uint64_t index)109 static uint64_t pread_uint64(int fd, const char *filename, uint64_t index)
110 {
111 uint64_t value;
112 off_t offset = index * sizeof(value);
113
114 TEST_ASSERT(pread(fd, &value, sizeof(value), offset) == sizeof(value),
115 "pread from %s offset 0x%" PRIx64 " failed!",
116 filename, offset);
117
118 return value;
119
120 }
121
122 #define PAGEMAP_PRESENT (1ULL << 63)
123 #define PAGEMAP_PFN_MASK ((1ULL << 55) - 1)
124
lookup_pfn(int pagemap_fd,struct kvm_vm * vm,uint64_t gva)125 static uint64_t lookup_pfn(int pagemap_fd, struct kvm_vm *vm, uint64_t gva)
126 {
127 uint64_t hva = (uint64_t) addr_gva2hva(vm, gva);
128 uint64_t entry;
129 uint64_t pfn;
130
131 entry = pread_uint64(pagemap_fd, "pagemap", hva / getpagesize());
132 if (!(entry & PAGEMAP_PRESENT))
133 return 0;
134
135 pfn = entry & PAGEMAP_PFN_MASK;
136 __TEST_REQUIRE(pfn, "Looking up PFNs requires CAP_SYS_ADMIN");
137
138 return pfn;
139 }
140
is_page_idle(int page_idle_fd,uint64_t pfn)141 static bool is_page_idle(int page_idle_fd, uint64_t pfn)
142 {
143 uint64_t bits = pread_uint64(page_idle_fd, "page_idle", pfn / 64);
144
145 return !!((bits >> (pfn % 64)) & 1);
146 }
147
mark_page_idle(int page_idle_fd,uint64_t pfn)148 static void mark_page_idle(int page_idle_fd, uint64_t pfn)
149 {
150 uint64_t bits = 1ULL << (pfn % 64);
151
152 TEST_ASSERT(pwrite(page_idle_fd, &bits, 8, 8 * (pfn / 64)) == 8,
153 "Set page_idle bits for PFN 0x%" PRIx64, pfn);
154 }
155
too_many_idle_pages(long idle_pages,long total_pages,int vcpu_idx)156 static void too_many_idle_pages(long idle_pages, long total_pages, int vcpu_idx)
157 {
158 char prefix[18] = {};
159
160 if (vcpu_idx >= 0)
161 snprintf(prefix, 18, "vCPU%d: ", vcpu_idx);
162
163 TEST_ASSERT(idle_pages_warn_only,
164 "%sToo many pages still idle (%lu out of %lu)",
165 prefix, idle_pages, total_pages);
166
167 printf("WARNING: %sToo many pages still idle (%lu out of %lu), "
168 "this will affect performance results.\n",
169 prefix, idle_pages, total_pages);
170 }
171
pageidle_mark_vcpu_memory_idle(struct kvm_vm * vm,struct memstress_vcpu_args * vcpu_args)172 static void pageidle_mark_vcpu_memory_idle(struct kvm_vm *vm,
173 struct memstress_vcpu_args *vcpu_args)
174 {
175 int vcpu_idx = vcpu_args->vcpu_idx;
176 uint64_t base_gva = vcpu_args->gva;
177 uint64_t pages = vcpu_args->pages;
178 uint64_t page;
179 uint64_t still_idle = 0;
180 uint64_t no_pfn = 0;
181 int page_idle_fd;
182 int pagemap_fd;
183
184 /* If vCPUs are using an overlapping region, let vCPU 0 mark it idle. */
185 if (overlap_memory_access && vcpu_idx)
186 return;
187
188 page_idle_fd = open("/sys/kernel/mm/page_idle/bitmap", O_RDWR);
189 TEST_ASSERT(page_idle_fd > 0, "Failed to open page_idle.");
190
191 pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
192 TEST_ASSERT(pagemap_fd > 0, "Failed to open pagemap.");
193
194 for (page = 0; page < pages; page++) {
195 uint64_t gva = base_gva + page * memstress_args.guest_page_size;
196 uint64_t pfn = lookup_pfn(pagemap_fd, vm, gva);
197
198 if (!pfn) {
199 no_pfn++;
200 continue;
201 }
202
203 if (is_page_idle(page_idle_fd, pfn)) {
204 still_idle++;
205 continue;
206 }
207
208 mark_page_idle(page_idle_fd, pfn);
209 }
210
211 /*
212 * Assumption: Less than 1% of pages are going to be swapped out from
213 * under us during this test.
214 */
215 TEST_ASSERT(no_pfn < pages / 100,
216 "vCPU %d: No PFN for %" PRIu64 " out of %" PRIu64 " pages.",
217 vcpu_idx, no_pfn, pages);
218
219 /*
220 * Check that at least 90% of memory has been marked idle (the rest
221 * might not be marked idle because the pages have not yet made it to an
222 * LRU list or the translations are still cached in the TLB). 90% is
223 * arbitrary; high enough that we ensure most memory access went through
224 * access tracking but low enough as to not make the test too brittle
225 * over time and across architectures.
226 */
227 if (still_idle >= pages / 10)
228 too_many_idle_pages(still_idle, pages,
229 overlap_memory_access ? -1 : vcpu_idx);
230
231 close(page_idle_fd);
232 close(pagemap_fd);
233 }
234
find_generation(struct memcg_stats * stats,long total_pages)235 int find_generation(struct memcg_stats *stats, long total_pages)
236 {
237 /*
238 * For finding the generation that contains our pages, use the same
239 * 90% threshold that page_idle uses.
240 */
241 int gen = lru_gen_find_generation(stats, total_pages * 9 / 10);
242
243 if (gen >= 0)
244 return gen;
245
246 if (!idle_pages_warn_only) {
247 TEST_FAIL("Could not find a generation with 90%% of guest memory (%ld pages).",
248 total_pages * 9 / 10);
249 return gen;
250 }
251
252 /*
253 * We couldn't find a generation with 90% of guest memory, which can
254 * happen if access tracking is unreliable. Simply look for a majority
255 * of pages.
256 */
257 puts("WARNING: Couldn't find a generation with 90% of guest memory. "
258 "Performance results may not be accurate.");
259 gen = lru_gen_find_generation(stats, total_pages / 2);
260 TEST_ASSERT(gen >= 0,
261 "Could not find a generation with 50%% of guest memory (%ld pages).",
262 total_pages / 2);
263 return gen;
264 }
265
lru_gen_mark_memory_idle(struct kvm_vm * vm)266 static void lru_gen_mark_memory_idle(struct kvm_vm *vm)
267 {
268 struct timespec ts_start;
269 struct timespec ts_elapsed;
270 struct memcg_stats stats;
271 int new_gen;
272
273 /* Make a new generation */
274 clock_gettime(CLOCK_MONOTONIC, &ts_start);
275 lru_gen_do_aging(&stats, TEST_MEMCG_NAME);
276 ts_elapsed = timespec_elapsed(ts_start);
277
278 /* Check the generation again */
279 new_gen = find_generation(&stats, test_pages);
280
281 /*
282 * This function should only be invoked with newly-accessed pages,
283 * so pages should always move to a newer generation.
284 */
285 if (new_gen <= lru_gen_last_gen) {
286 /* We did not move to a newer generation. */
287 long idle_pages = lru_gen_sum_memcg_stats_for_gen(lru_gen_last_gen,
288 &stats);
289
290 too_many_idle_pages(min_t(long, idle_pages, test_pages),
291 test_pages, -1);
292 }
293 pr_info("%-30s: %ld.%09lds\n",
294 "Mark memory idle (lru_gen)", ts_elapsed.tv_sec,
295 ts_elapsed.tv_nsec);
296 lru_gen_last_gen = new_gen;
297 }
298
assert_ucall(struct kvm_vcpu * vcpu,uint64_t expected_ucall)299 static void assert_ucall(struct kvm_vcpu *vcpu, uint64_t expected_ucall)
300 {
301 struct ucall uc;
302 uint64_t actual_ucall = get_ucall(vcpu, &uc);
303
304 TEST_ASSERT(expected_ucall == actual_ucall,
305 "Guest exited unexpectedly (expected ucall %" PRIu64
306 ", got %" PRIu64 ")",
307 expected_ucall, actual_ucall);
308 }
309
spin_wait_for_next_iteration(int * current_iteration)310 static bool spin_wait_for_next_iteration(int *current_iteration)
311 {
312 int last_iteration = *current_iteration;
313
314 do {
315 if (READ_ONCE(memstress_args.stop_vcpus))
316 return false;
317
318 *current_iteration = READ_ONCE(iteration);
319 } while (last_iteration == *current_iteration);
320
321 return true;
322 }
323
vcpu_thread_main(struct memstress_vcpu_args * vcpu_args)324 static void vcpu_thread_main(struct memstress_vcpu_args *vcpu_args)
325 {
326 struct kvm_vcpu *vcpu = vcpu_args->vcpu;
327 struct kvm_vm *vm = memstress_args.vm;
328 int vcpu_idx = vcpu_args->vcpu_idx;
329 int current_iteration = 0;
330
331 while (spin_wait_for_next_iteration(¤t_iteration)) {
332 switch (READ_ONCE(iteration_work)) {
333 case ITERATION_ACCESS_MEMORY:
334 vcpu_run(vcpu);
335 assert_ucall(vcpu, UCALL_SYNC);
336 break;
337 case ITERATION_MARK_IDLE:
338 pageidle_mark_vcpu_memory_idle(vm, vcpu_args);
339 break;
340 }
341
342 vcpu_last_completed_iteration[vcpu_idx] = current_iteration;
343 }
344 }
345
spin_wait_for_vcpu(int vcpu_idx,int target_iteration)346 static void spin_wait_for_vcpu(int vcpu_idx, int target_iteration)
347 {
348 while (READ_ONCE(vcpu_last_completed_iteration[vcpu_idx]) !=
349 target_iteration) {
350 continue;
351 }
352 }
353
354 /* The type of memory accesses to perform in the VM. */
355 enum access_type {
356 ACCESS_READ,
357 ACCESS_WRITE,
358 };
359
run_iteration(struct kvm_vm * vm,int nr_vcpus,const char * description)360 static void run_iteration(struct kvm_vm *vm, int nr_vcpus, const char *description)
361 {
362 struct timespec ts_start;
363 struct timespec ts_elapsed;
364 int next_iteration, i;
365
366 /* Kick off the vCPUs by incrementing iteration. */
367 next_iteration = ++iteration;
368
369 clock_gettime(CLOCK_MONOTONIC, &ts_start);
370
371 /* Wait for all vCPUs to finish the iteration. */
372 for (i = 0; i < nr_vcpus; i++)
373 spin_wait_for_vcpu(i, next_iteration);
374
375 ts_elapsed = timespec_elapsed(ts_start);
376 pr_info("%-30s: %ld.%09lds\n",
377 description, ts_elapsed.tv_sec, ts_elapsed.tv_nsec);
378 }
379
access_memory(struct kvm_vm * vm,int nr_vcpus,enum access_type access,const char * description)380 static void access_memory(struct kvm_vm *vm, int nr_vcpus,
381 enum access_type access, const char *description)
382 {
383 memstress_set_write_percent(vm, (access == ACCESS_READ) ? 0 : 100);
384 iteration_work = ITERATION_ACCESS_MEMORY;
385 run_iteration(vm, nr_vcpus, description);
386 }
387
mark_memory_idle(struct kvm_vm * vm,int nr_vcpus)388 static void mark_memory_idle(struct kvm_vm *vm, int nr_vcpus)
389 {
390 if (use_lru_gen)
391 return lru_gen_mark_memory_idle(vm);
392
393 /*
394 * Even though this parallelizes the work across vCPUs, this is still a
395 * very slow operation because page_idle forces the test to mark one pfn
396 * at a time and the clear_young notifier may serialize on the KVM MMU
397 * lock.
398 */
399 pr_debug("Marking VM memory idle (slow)...\n");
400 iteration_work = ITERATION_MARK_IDLE;
401 run_iteration(vm, nr_vcpus, "Mark memory idle (page_idle)");
402 }
403
run_test(enum vm_guest_mode mode,void * arg)404 static void run_test(enum vm_guest_mode mode, void *arg)
405 {
406 struct test_params *params = arg;
407 struct kvm_vm *vm;
408 int nr_vcpus = params->nr_vcpus;
409
410 vm = memstress_create_vm(mode, nr_vcpus, params->vcpu_memory_bytes, 1,
411 params->backing_src, !overlap_memory_access);
412
413 /*
414 * If guest_page_size is larger than the host's page size, the
415 * guest (memstress) will only fault in a subset of the host's pages.
416 */
417 test_pages = params->nr_vcpus * params->vcpu_memory_bytes /
418 max(memstress_args.guest_page_size,
419 (uint64_t)getpagesize());
420
421 memstress_start_vcpu_threads(nr_vcpus, vcpu_thread_main);
422
423 pr_info("\n");
424 access_memory(vm, nr_vcpus, ACCESS_WRITE, "Populating memory");
425
426 if (use_lru_gen) {
427 struct memcg_stats stats;
428
429 /*
430 * Do a page table scan now. Following initial population, aging
431 * may not cause the pages to move to a newer generation. Do
432 * an aging pass now so that future aging passes always move
433 * pages to a newer generation.
434 */
435 printf("Initial aging pass (lru_gen)\n");
436 lru_gen_do_aging(&stats, TEST_MEMCG_NAME);
437 TEST_ASSERT(lru_gen_sum_memcg_stats(&stats) >= test_pages,
438 "Not all pages accounted for (looking for %ld). "
439 "Was the memcg set up correctly?", test_pages);
440 access_memory(vm, nr_vcpus, ACCESS_WRITE, "Re-populating memory");
441 lru_gen_read_memcg_stats(&stats, TEST_MEMCG_NAME);
442 lru_gen_last_gen = find_generation(&stats, test_pages);
443 }
444
445 /* As a control, read and write to the populated memory first. */
446 access_memory(vm, nr_vcpus, ACCESS_WRITE, "Writing to populated memory");
447 access_memory(vm, nr_vcpus, ACCESS_READ, "Reading from populated memory");
448
449 /* Repeat on memory that has been marked as idle. */
450 mark_memory_idle(vm, nr_vcpus);
451 access_memory(vm, nr_vcpus, ACCESS_WRITE, "Writing to idle memory");
452 mark_memory_idle(vm, nr_vcpus);
453 access_memory(vm, nr_vcpus, ACCESS_READ, "Reading from idle memory");
454
455 memstress_join_vcpu_threads(nr_vcpus);
456 memstress_destroy_vm(vm);
457 }
458
access_tracking_unreliable(void)459 static int access_tracking_unreliable(void)
460 {
461 #ifdef __x86_64__
462 /*
463 * When running nested, the TLB size may be effectively unlimited (for
464 * example, this is the case when running on KVM L0), and KVM doesn't
465 * explicitly flush the TLB when aging SPTEs. As a result, more pages
466 * are cached and the guest won't see the "idle" bit cleared.
467 */
468 if (this_cpu_has(X86_FEATURE_HYPERVISOR)) {
469 puts("Skipping idle page count sanity check, because the test is run nested");
470 return 1;
471 }
472 #endif
473 /*
474 * When NUMA balancing is enabled, guest memory will be unmapped to get
475 * NUMA faults, dropping the Accessed bits.
476 */
477 if (is_numa_balancing_enabled()) {
478 puts("Skipping idle page count sanity check, because NUMA balancing is enabled");
479 return 1;
480 }
481 return 0;
482 }
483
run_test_for_each_guest_mode(const char * cgroup,void * arg)484 static int run_test_for_each_guest_mode(const char *cgroup, void *arg)
485 {
486 for_each_guest_mode(run_test, arg);
487 return 0;
488 }
489
help(char * name)490 static void help(char *name)
491 {
492 puts("");
493 printf("usage: %s [-h] [-m mode] [-b vcpu_bytes] [-v vcpus] [-o] [-s mem_type]\n",
494 name);
495 puts("");
496 printf(" -h: Display this help message.");
497 guest_modes_help();
498 printf(" -b: specify the size of the memory region which should be\n"
499 " dirtied by each vCPU. e.g. 10M or 3G.\n"
500 " (default: 1G)\n");
501 printf(" -v: specify the number of vCPUs to run.\n");
502 printf(" -o: Overlap guest memory accesses instead of partitioning\n"
503 " them into a separate region of memory for each vCPU.\n");
504 printf(" -w: Control whether the test warns or fails if more than 10%%\n"
505 " of pages are still seen as idle/old after accessing guest\n"
506 " memory. >0 == warn only, 0 == fail, <0 == auto. For auto\n"
507 " mode, the test fails by default, but switches to warn only\n"
508 " if NUMA balancing is enabled or the test detects it's running\n"
509 " in a VM.\n");
510 backing_src_help("-s");
511 puts("");
512 exit(0);
513 }
514
destroy_cgroup(char * cg)515 void destroy_cgroup(char *cg)
516 {
517 printf("Destroying cgroup: %s\n", cg);
518 }
519
main(int argc,char * argv[])520 int main(int argc, char *argv[])
521 {
522 struct test_params params = {
523 .backing_src = DEFAULT_VM_MEM_SRC,
524 .vcpu_memory_bytes = DEFAULT_PER_VCPU_MEM_SIZE,
525 .nr_vcpus = 1,
526 };
527 char *new_cg = NULL;
528 int page_idle_fd;
529 int opt;
530
531 guest_modes_append_default();
532
533 while ((opt = getopt(argc, argv, "hm:b:v:os:w:")) != -1) {
534 switch (opt) {
535 case 'm':
536 guest_modes_cmdline(optarg);
537 break;
538 case 'b':
539 params.vcpu_memory_bytes = parse_size(optarg);
540 break;
541 case 'v':
542 params.nr_vcpus = atoi_positive("Number of vCPUs", optarg);
543 break;
544 case 'o':
545 overlap_memory_access = true;
546 break;
547 case 's':
548 params.backing_src = parse_backing_src_type(optarg);
549 break;
550 case 'w':
551 idle_pages_warn_only =
552 atoi_non_negative("Idle pages warning",
553 optarg);
554 break;
555 case 'h':
556 default:
557 help(argv[0]);
558 break;
559 }
560 }
561
562 if (idle_pages_warn_only == -1)
563 idle_pages_warn_only = access_tracking_unreliable();
564
565 if (lru_gen_usable()) {
566 bool cg_created = true;
567 int ret;
568
569 puts("Using lru_gen for aging");
570 use_lru_gen = true;
571
572 if (cg_find_controller_root(cgroup_root, sizeof(cgroup_root), "memory"))
573 ksft_exit_skip("Cannot find memory cgroup controller\n");
574
575 new_cg = cg_name(cgroup_root, TEST_MEMCG_NAME);
576 printf("Creating cgroup: %s\n", new_cg);
577 if (cg_create(new_cg)) {
578 if (errno == EEXIST) {
579 printf("Found existing cgroup");
580 cg_created = false;
581 } else {
582 ksft_exit_skip("could not create new cgroup: %s\n", new_cg);
583 }
584 }
585
586 /*
587 * This will fork off a new process to run the test within
588 * a new memcg, so we need to properly propagate the return
589 * value up.
590 */
591 ret = cg_run(new_cg, &run_test_for_each_guest_mode, ¶ms);
592 if (cg_created)
593 cg_destroy(new_cg);
594 if (ret < 0)
595 TEST_FAIL("child did not spawn or was abnormally killed");
596 if (ret)
597 return ret;
598 } else {
599 page_idle_fd = __open_path_or_exit("/sys/kernel/mm/page_idle/bitmap", O_RDWR,
600 "Is CONFIG_IDLE_PAGE_TRACKING enabled?");
601 close(page_idle_fd);
602
603 puts("Using page_idle for aging");
604 run_test_for_each_guest_mode(NULL, ¶ms);
605 }
606
607 return 0;
608 }
609