KVM: selftests: Use consistent message for test skipping
[linux-2.6-microblaze.git] / tools / testing / selftests / kvm / dirty_log_test.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KVM dirty page logging test
4  *
5  * Copyright (C) 2018, Red Hat, Inc.
6  */
7
8 #define _GNU_SOURCE /* for program_invocation_name */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <time.h>
14 #include <pthread.h>
15 #include <linux/bitmap.h>
16 #include <linux/bitops.h>
17
18 #include "test_util.h"
19 #include "kvm_util.h"
20 #include "processor.h"
21
22 #define VCPU_ID                         1
23
24 /* The memory slot index to track dirty pages */
25 #define TEST_MEM_SLOT_INDEX             1
26
27 /* Default guest test virtual memory offset */
28 #define DEFAULT_GUEST_TEST_MEM          0xc0000000
29
30 /* How many pages to dirty for each guest loop */
31 #define TEST_PAGES_PER_LOOP             1024
32
33 /* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
34 #define TEST_HOST_LOOP_N                32UL
35
36 /* Interval for each host loop (ms) */
37 #define TEST_HOST_LOOP_INTERVAL         10UL
38
39 /* Dirty bitmaps are always little endian, so we need to swap on big endian */
40 #if defined(__s390x__)
41 # define BITOP_LE_SWIZZLE       ((BITS_PER_LONG-1) & ~0x7)
42 # define test_bit_le(nr, addr) \
43         test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
44 # define set_bit_le(nr, addr) \
45         set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
46 # define clear_bit_le(nr, addr) \
47         clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
48 # define test_and_set_bit_le(nr, addr) \
49         test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
50 # define test_and_clear_bit_le(nr, addr) \
51         test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
52 #else
53 # define test_bit_le            test_bit
54 # define set_bit_le             set_bit
55 # define clear_bit_le           clear_bit
56 # define test_and_set_bit_le    test_and_set_bit
57 # define test_and_clear_bit_le  test_and_clear_bit
58 #endif
59
60 /*
61  * Guest/Host shared variables. Ensure addr_gva2hva() and/or
62  * sync_global_to/from_guest() are used when accessing from
63  * the host. READ/WRITE_ONCE() should also be used with anything
64  * that may change.
65  */
66 static uint64_t host_page_size;
67 static uint64_t guest_page_size;
68 static uint64_t guest_num_pages;
69 static uint64_t random_array[TEST_PAGES_PER_LOOP];
70 static uint64_t iteration;
71
72 /*
73  * Guest physical memory offset of the testing memory slot.
74  * This will be set to the topmost valid physical address minus
75  * the test memory size.
76  */
77 static uint64_t guest_test_phys_mem;
78
79 /*
80  * Guest virtual memory offset of the testing memory slot.
81  * Must not conflict with identity mapped test code.
82  */
83 static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
84
85 /*
86  * Continuously write to the first 8 bytes of a random pages within
87  * the testing memory region.
88  */
89 static void guest_code(void)
90 {
91         uint64_t addr;
92         int i;
93
94         /*
95          * On s390x, all pages of a 1M segment are initially marked as dirty
96          * when a page of the segment is written to for the very first time.
97          * To compensate this specialty in this test, we need to touch all
98          * pages during the first iteration.
99          */
100         for (i = 0; i < guest_num_pages; i++) {
101                 addr = guest_test_virt_mem + i * guest_page_size;
102                 *(uint64_t *)addr = READ_ONCE(iteration);
103         }
104
105         while (true) {
106                 for (i = 0; i < TEST_PAGES_PER_LOOP; i++) {
107                         addr = guest_test_virt_mem;
108                         addr += (READ_ONCE(random_array[i]) % guest_num_pages)
109                                 * guest_page_size;
110                         addr &= ~(host_page_size - 1);
111                         *(uint64_t *)addr = READ_ONCE(iteration);
112                 }
113
114                 /* Tell the host that we need more random numbers */
115                 GUEST_SYNC(1);
116         }
117 }
118
119 /* Host variables */
120 static bool host_quit;
121
122 /* Points to the test VM memory region on which we track dirty logs */
123 static void *host_test_mem;
124 static uint64_t host_num_pages;
125
126 /* For statistics only */
127 static uint64_t host_dirty_count;
128 static uint64_t host_clear_count;
129 static uint64_t host_track_next_count;
130
131 /*
132  * We use this bitmap to track some pages that should have its dirty
133  * bit set in the _next_ iteration.  For example, if we detected the
134  * page value changed to current iteration but at the same time the
135  * page bit is cleared in the latest bitmap, then the system must
136  * report that write in the next get dirty log call.
137  */
138 static unsigned long *host_bmap_track;
139
140 static void generate_random_array(uint64_t *guest_array, uint64_t size)
141 {
142         uint64_t i;
143
144         for (i = 0; i < size; i++)
145                 guest_array[i] = random();
146 }
147
148 static void *vcpu_worker(void *data)
149 {
150         int ret;
151         struct kvm_vm *vm = data;
152         uint64_t *guest_array;
153         uint64_t pages_count = 0;
154         struct kvm_run *run;
155
156         run = vcpu_state(vm, VCPU_ID);
157
158         guest_array = addr_gva2hva(vm, (vm_vaddr_t)random_array);
159         generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
160
161         while (!READ_ONCE(host_quit)) {
162                 /* Let the guest dirty the random pages */
163                 ret = _vcpu_run(vm, VCPU_ID);
164                 TEST_ASSERT(ret == 0, "vcpu_run failed: %d\n", ret);
165                 if (get_ucall(vm, VCPU_ID, NULL) == UCALL_SYNC) {
166                         pages_count += TEST_PAGES_PER_LOOP;
167                         generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
168                 } else {
169                         TEST_ASSERT(false,
170                                     "Invalid guest sync status: "
171                                     "exit_reason=%s\n",
172                                     exit_reason_str(run->exit_reason));
173                 }
174         }
175
176         pr_info("Dirtied %"PRIu64" pages\n", pages_count);
177
178         return NULL;
179 }
180
181 static void vm_dirty_log_verify(enum vm_guest_mode mode, unsigned long *bmap)
182 {
183         uint64_t step = vm_num_host_pages(mode, 1);
184         uint64_t page;
185         uint64_t *value_ptr;
186
187         for (page = 0; page < host_num_pages; page += step) {
188                 value_ptr = host_test_mem + page * host_page_size;
189
190                 /* If this is a special page that we were tracking... */
191                 if (test_and_clear_bit_le(page, host_bmap_track)) {
192                         host_track_next_count++;
193                         TEST_ASSERT(test_bit_le(page, bmap),
194                                     "Page %"PRIu64" should have its dirty bit "
195                                     "set in this iteration but it is missing",
196                                     page);
197                 }
198
199                 if (test_bit_le(page, bmap)) {
200                         host_dirty_count++;
201                         /*
202                          * If the bit is set, the value written onto
203                          * the corresponding page should be either the
204                          * previous iteration number or the current one.
205                          */
206                         TEST_ASSERT(*value_ptr == iteration ||
207                                     *value_ptr == iteration - 1,
208                                     "Set page %"PRIu64" value %"PRIu64
209                                     " incorrect (iteration=%"PRIu64")",
210                                     page, *value_ptr, iteration);
211                 } else {
212                         host_clear_count++;
213                         /*
214                          * If cleared, the value written can be any
215                          * value smaller or equals to the iteration
216                          * number.  Note that the value can be exactly
217                          * (iteration-1) if that write can happen
218                          * like this:
219                          *
220                          * (1) increase loop count to "iteration-1"
221                          * (2) write to page P happens (with value
222                          *     "iteration-1")
223                          * (3) get dirty log for "iteration-1"; we'll
224                          *     see that page P bit is set (dirtied),
225                          *     and not set the bit in host_bmap_track
226                          * (4) increase loop count to "iteration"
227                          *     (which is current iteration)
228                          * (5) get dirty log for current iteration,
229                          *     we'll see that page P is cleared, with
230                          *     value "iteration-1".
231                          */
232                         TEST_ASSERT(*value_ptr <= iteration,
233                                     "Clear page %"PRIu64" value %"PRIu64
234                                     " incorrect (iteration=%"PRIu64")",
235                                     page, *value_ptr, iteration);
236                         if (*value_ptr == iteration) {
237                                 /*
238                                  * This page is _just_ modified; it
239                                  * should report its dirtyness in the
240                                  * next run
241                                  */
242                                 set_bit_le(page, host_bmap_track);
243                         }
244                 }
245         }
246 }
247
248 static struct kvm_vm *create_vm(enum vm_guest_mode mode, uint32_t vcpuid,
249                                 uint64_t extra_mem_pages, void *guest_code)
250 {
251         struct kvm_vm *vm;
252         uint64_t extra_pg_pages = extra_mem_pages / 512 * 2;
253
254         pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));
255
256         vm = _vm_create(mode, DEFAULT_GUEST_PHY_PAGES + extra_pg_pages, O_RDWR);
257         kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
258 #ifdef __x86_64__
259         vm_create_irqchip(vm);
260 #endif
261         vm_vcpu_add_default(vm, vcpuid, guest_code);
262         return vm;
263 }
264
265 #define DIRTY_MEM_BITS 30 /* 1G */
266 #define PAGE_SHIFT_4K  12
267
268 #ifdef USE_CLEAR_DIRTY_LOG
269 static u64 dirty_log_manual_caps;
270 #endif
271
272 static void run_test(enum vm_guest_mode mode, unsigned long iterations,
273                      unsigned long interval, uint64_t phys_offset)
274 {
275         pthread_t vcpu_thread;
276         struct kvm_vm *vm;
277         unsigned long *bmap;
278
279         /*
280          * We reserve page table for 2 times of extra dirty mem which
281          * will definitely cover the original (1G+) test range.  Here
282          * we do the calculation with 4K page size which is the
283          * smallest so the page number will be enough for all archs
284          * (e.g., 64K page size guest will need even less memory for
285          * page tables).
286          */
287         vm = create_vm(mode, VCPU_ID,
288                        2ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K),
289                        guest_code);
290
291         guest_page_size = vm_get_page_size(vm);
292         /*
293          * A little more than 1G of guest page sized pages.  Cover the
294          * case where the size is not aligned to 64 pages.
295          */
296         guest_num_pages = (1ul << (DIRTY_MEM_BITS -
297                                    vm_get_page_shift(vm))) + 3;
298         guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
299
300         host_page_size = getpagesize();
301         host_num_pages = vm_num_host_pages(mode, guest_num_pages);
302
303         if (!phys_offset) {
304                 guest_test_phys_mem = (vm_get_max_gfn(vm) -
305                                        guest_num_pages) * guest_page_size;
306                 guest_test_phys_mem &= ~(host_page_size - 1);
307         } else {
308                 guest_test_phys_mem = phys_offset;
309         }
310
311 #ifdef __s390x__
312         /* Align to 1M (segment size) */
313         guest_test_phys_mem &= ~((1 << 20) - 1);
314 #endif
315
316         pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
317
318         bmap = bitmap_alloc(host_num_pages);
319         host_bmap_track = bitmap_alloc(host_num_pages);
320
321 #ifdef USE_CLEAR_DIRTY_LOG
322         struct kvm_enable_cap cap = {};
323
324         cap.cap = KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2;
325         cap.args[0] = dirty_log_manual_caps;
326         vm_enable_cap(vm, &cap);
327 #endif
328
329         /* Add an extra memory slot for testing dirty logging */
330         vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
331                                     guest_test_phys_mem,
332                                     TEST_MEM_SLOT_INDEX,
333                                     guest_num_pages,
334                                     KVM_MEM_LOG_DIRTY_PAGES);
335
336         /* Do mapping for the dirty track memory slot */
337         virt_map(vm, guest_test_virt_mem, guest_test_phys_mem,
338                  guest_num_pages * guest_page_size, 0);
339
340         /* Cache the HVA pointer of the region */
341         host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
342
343 #ifdef __x86_64__
344         vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
345 #endif
346         ucall_init(vm, NULL);
347
348         /* Export the shared variables to the guest */
349         sync_global_to_guest(vm, host_page_size);
350         sync_global_to_guest(vm, guest_page_size);
351         sync_global_to_guest(vm, guest_test_virt_mem);
352         sync_global_to_guest(vm, guest_num_pages);
353
354         /* Start the iterations */
355         iteration = 1;
356         sync_global_to_guest(vm, iteration);
357         host_quit = false;
358         host_dirty_count = 0;
359         host_clear_count = 0;
360         host_track_next_count = 0;
361
362         pthread_create(&vcpu_thread, NULL, vcpu_worker, vm);
363
364         while (iteration < iterations) {
365                 /* Give the vcpu thread some time to dirty some pages */
366                 usleep(interval * 1000);
367                 kvm_vm_get_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap);
368 #ifdef USE_CLEAR_DIRTY_LOG
369                 kvm_vm_clear_dirty_log(vm, TEST_MEM_SLOT_INDEX, bmap, 0,
370                                        host_num_pages);
371 #endif
372                 vm_dirty_log_verify(mode, bmap);
373                 iteration++;
374                 sync_global_to_guest(vm, iteration);
375         }
376
377         /* Tell the vcpu thread to quit */
378         host_quit = true;
379         pthread_join(vcpu_thread, NULL);
380
381         pr_info("Total bits checked: dirty (%"PRIu64"), clear (%"PRIu64"), "
382                 "track_next (%"PRIu64")\n", host_dirty_count, host_clear_count,
383                 host_track_next_count);
384
385         free(bmap);
386         free(host_bmap_track);
387         ucall_uninit(vm);
388         kvm_vm_free(vm);
389 }
390
391 struct guest_mode {
392         bool supported;
393         bool enabled;
394 };
395 static struct guest_mode guest_modes[NUM_VM_MODES];
396
397 #define guest_mode_init(mode, supported, enabled) ({ \
398         guest_modes[mode] = (struct guest_mode){ supported, enabled }; \
399 })
400
401 static void help(char *name)
402 {
403         int i;
404
405         puts("");
406         printf("usage: %s [-h] [-i iterations] [-I interval] "
407                "[-p offset] [-m mode]\n", name);
408         puts("");
409         printf(" -i: specify iteration counts (default: %"PRIu64")\n",
410                TEST_HOST_LOOP_N);
411         printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
412                TEST_HOST_LOOP_INTERVAL);
413         printf(" -p: specify guest physical test memory offset\n"
414                "     Warning: a low offset can conflict with the loaded test code.\n");
415         printf(" -m: specify the guest mode ID to test "
416                "(default: test all supported modes)\n"
417                "     This option may be used multiple times.\n"
418                "     Guest mode IDs:\n");
419         for (i = 0; i < NUM_VM_MODES; ++i) {
420                 printf("         %d:    %s%s\n", i, vm_guest_mode_string(i),
421                        guest_modes[i].supported ? " (supported)" : "");
422         }
423         puts("");
424         exit(0);
425 }
426
427 int main(int argc, char *argv[])
428 {
429         unsigned long iterations = TEST_HOST_LOOP_N;
430         unsigned long interval = TEST_HOST_LOOP_INTERVAL;
431         bool mode_selected = false;
432         uint64_t phys_offset = 0;
433         unsigned int mode;
434         int opt, i;
435
436 #ifdef USE_CLEAR_DIRTY_LOG
437         dirty_log_manual_caps =
438                 kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
439         if (!dirty_log_manual_caps) {
440                 print_skip("KVM_CLEAR_DIRTY_LOG not available");
441                 exit(KSFT_SKIP);
442         }
443         dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
444                                   KVM_DIRTY_LOG_INITIALLY_SET);
445 #endif
446
447 #ifdef __x86_64__
448         guest_mode_init(VM_MODE_PXXV48_4K, true, true);
449 #endif
450 #ifdef __aarch64__
451         guest_mode_init(VM_MODE_P40V48_4K, true, true);
452         guest_mode_init(VM_MODE_P40V48_64K, true, true);
453
454         {
455                 unsigned int limit = kvm_check_cap(KVM_CAP_ARM_VM_IPA_SIZE);
456
457                 if (limit >= 52)
458                         guest_mode_init(VM_MODE_P52V48_64K, true, true);
459                 if (limit >= 48) {
460                         guest_mode_init(VM_MODE_P48V48_4K, true, true);
461                         guest_mode_init(VM_MODE_P48V48_64K, true, true);
462                 }
463         }
464 #endif
465 #ifdef __s390x__
466         guest_mode_init(VM_MODE_P40V48_4K, true, true);
467 #endif
468
469         while ((opt = getopt(argc, argv, "hi:I:p:m:")) != -1) {
470                 switch (opt) {
471                 case 'i':
472                         iterations = strtol(optarg, NULL, 10);
473                         break;
474                 case 'I':
475                         interval = strtol(optarg, NULL, 10);
476                         break;
477                 case 'p':
478                         phys_offset = strtoull(optarg, NULL, 0);
479                         break;
480                 case 'm':
481                         if (!mode_selected) {
482                                 for (i = 0; i < NUM_VM_MODES; ++i)
483                                         guest_modes[i].enabled = false;
484                                 mode_selected = true;
485                         }
486                         mode = strtoul(optarg, NULL, 10);
487                         TEST_ASSERT(mode < NUM_VM_MODES,
488                                     "Guest mode ID %d too big", mode);
489                         guest_modes[mode].enabled = true;
490                         break;
491                 case 'h':
492                 default:
493                         help(argv[0]);
494                         break;
495                 }
496         }
497
498         TEST_ASSERT(iterations > 2, "Iterations must be greater than two");
499         TEST_ASSERT(interval > 0, "Interval must be greater than zero");
500
501         pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
502                 iterations, interval);
503
504         srandom(time(0));
505
506         for (i = 0; i < NUM_VM_MODES; ++i) {
507                 if (!guest_modes[i].enabled)
508                         continue;
509                 TEST_ASSERT(guest_modes[i].supported,
510                             "Guest mode ID %d (%s) not supported.",
511                             i, vm_guest_mode_string(i));
512                 run_test(i, iterations, interval, phys_offset);
513         }
514
515         return 0;
516 }