81edbd23d371c2ddadd1949d734c94dcb3890328
[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 <pthread.h>
13 #include <semaphore.h>
14 #include <sys/types.h>
15 #include <signal.h>
16 #include <errno.h>
17 #include <linux/bitmap.h>
18 #include <linux/bitops.h>
19 #include <asm/barrier.h>
20 #include <linux/atomic.h>
21
22 #include "kvm_util.h"
23 #include "test_util.h"
24 #include "guest_modes.h"
25 #include "processor.h"
26
27 #define VCPU_ID                         1
28
29 /* The memory slot index to track dirty pages */
30 #define TEST_MEM_SLOT_INDEX             1
31
32 /* Default guest test virtual memory offset */
33 #define DEFAULT_GUEST_TEST_MEM          0xc0000000
34
35 /* How many pages to dirty for each guest loop */
36 #define TEST_PAGES_PER_LOOP             1024
37
38 /* How many host loops to run (one KVM_GET_DIRTY_LOG for each loop) */
39 #define TEST_HOST_LOOP_N                32UL
40
41 /* Interval for each host loop (ms) */
42 #define TEST_HOST_LOOP_INTERVAL         10UL
43
44 /* Dirty bitmaps are always little endian, so we need to swap on big endian */
45 #if defined(__s390x__)
46 # define BITOP_LE_SWIZZLE       ((BITS_PER_LONG-1) & ~0x7)
47 # define test_bit_le(nr, addr) \
48         test_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
49 # define set_bit_le(nr, addr) \
50         set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
51 # define clear_bit_le(nr, addr) \
52         clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
53 # define test_and_set_bit_le(nr, addr) \
54         test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
55 # define test_and_clear_bit_le(nr, addr) \
56         test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, addr)
57 #else
58 # define test_bit_le            test_bit
59 # define set_bit_le             set_bit
60 # define clear_bit_le           clear_bit
61 # define test_and_set_bit_le    test_and_set_bit
62 # define test_and_clear_bit_le  test_and_clear_bit
63 #endif
64
65 #define TEST_DIRTY_RING_COUNT           65536
66
67 #define SIG_IPI SIGUSR1
68
69 /*
70  * Guest/Host shared variables. Ensure addr_gva2hva() and/or
71  * sync_global_to/from_guest() are used when accessing from
72  * the host. READ/WRITE_ONCE() should also be used with anything
73  * that may change.
74  */
75 static uint64_t host_page_size;
76 static uint64_t guest_page_size;
77 static uint64_t guest_num_pages;
78 static uint64_t random_array[TEST_PAGES_PER_LOOP];
79 static uint64_t iteration;
80
81 /*
82  * Guest physical memory offset of the testing memory slot.
83  * This will be set to the topmost valid physical address minus
84  * the test memory size.
85  */
86 static uint64_t guest_test_phys_mem;
87
88 /*
89  * Guest virtual memory offset of the testing memory slot.
90  * Must not conflict with identity mapped test code.
91  */
92 static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
93
94 /*
95  * Continuously write to the first 8 bytes of a random pages within
96  * the testing memory region.
97  */
98 static void guest_code(void)
99 {
100         uint64_t addr;
101         int i;
102
103         /*
104          * On s390x, all pages of a 1M segment are initially marked as dirty
105          * when a page of the segment is written to for the very first time.
106          * To compensate this specialty in this test, we need to touch all
107          * pages during the first iteration.
108          */
109         for (i = 0; i < guest_num_pages; i++) {
110                 addr = guest_test_virt_mem + i * guest_page_size;
111                 *(uint64_t *)addr = READ_ONCE(iteration);
112         }
113
114         while (true) {
115                 for (i = 0; i < TEST_PAGES_PER_LOOP; i++) {
116                         addr = guest_test_virt_mem;
117                         addr += (READ_ONCE(random_array[i]) % guest_num_pages)
118                                 * guest_page_size;
119                         addr &= ~(host_page_size - 1);
120                         *(uint64_t *)addr = READ_ONCE(iteration);
121                 }
122
123                 /* Tell the host that we need more random numbers */
124                 GUEST_SYNC(1);
125         }
126 }
127
128 /* Host variables */
129 static bool host_quit;
130
131 /* Points to the test VM memory region on which we track dirty logs */
132 static void *host_test_mem;
133 static uint64_t host_num_pages;
134
135 /* For statistics only */
136 static uint64_t host_dirty_count;
137 static uint64_t host_clear_count;
138 static uint64_t host_track_next_count;
139
140 /* Whether dirty ring reset is requested, or finished */
141 static sem_t sem_vcpu_stop;
142 static sem_t sem_vcpu_cont;
143 /*
144  * This is only set by main thread, and only cleared by vcpu thread.  It is
145  * used to request vcpu thread to stop at the next GUEST_SYNC, since GUEST_SYNC
146  * is the only place that we'll guarantee both "dirty bit" and "dirty data"
147  * will match.  E.g., SIG_IPI won't guarantee that if the vcpu is interrupted
148  * after setting dirty bit but before the data is written.
149  */
150 static atomic_t vcpu_sync_stop_requested;
151 /*
152  * This is updated by the vcpu thread to tell the host whether it's a
153  * ring-full event.  It should only be read until a sem_wait() of
154  * sem_vcpu_stop and before vcpu continues to run.
155  */
156 static bool dirty_ring_vcpu_ring_full;
157 /*
158  * This is only used for verifying the dirty pages.  Dirty ring has a very
159  * tricky case when the ring just got full, kvm will do userspace exit due to
160  * ring full.  When that happens, the very last PFN is set but actually the
161  * data is not changed (the guest WRITE is not really applied yet), because
162  * we found that the dirty ring is full, refused to continue the vcpu, and
163  * recorded the dirty gfn with the old contents.
164  *
165  * For this specific case, it's safe to skip checking this pfn for this
166  * bit, because it's a redundant bit, and when the write happens later the bit
167  * will be set again.  We use this variable to always keep track of the latest
168  * dirty gfn we've collected, so that if a mismatch of data found later in the
169  * verifying process, we let it pass.
170  */
171 static uint64_t dirty_ring_last_page;
172
173 enum log_mode_t {
174         /* Only use KVM_GET_DIRTY_LOG for logging */
175         LOG_MODE_DIRTY_LOG = 0,
176
177         /* Use both KVM_[GET|CLEAR]_DIRTY_LOG for logging */
178         LOG_MODE_CLEAR_LOG = 1,
179
180         /* Use dirty ring for logging */
181         LOG_MODE_DIRTY_RING = 2,
182
183         LOG_MODE_NUM,
184
185         /* Run all supported modes */
186         LOG_MODE_ALL = LOG_MODE_NUM,
187 };
188
189 /* Mode of logging to test.  Default is to run all supported modes */
190 static enum log_mode_t host_log_mode_option = LOG_MODE_ALL;
191 /* Logging mode for current run */
192 static enum log_mode_t host_log_mode;
193 static pthread_t vcpu_thread;
194 static uint32_t test_dirty_ring_count = TEST_DIRTY_RING_COUNT;
195
196 static void vcpu_kick(void)
197 {
198         pthread_kill(vcpu_thread, SIG_IPI);
199 }
200
201 /*
202  * In our test we do signal tricks, let's use a better version of
203  * sem_wait to avoid signal interrupts
204  */
205 static void sem_wait_until(sem_t *sem)
206 {
207         int ret;
208
209         do
210                 ret = sem_wait(sem);
211         while (ret == -1 && errno == EINTR);
212 }
213
214 static bool clear_log_supported(void)
215 {
216         return kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
217 }
218
219 static void clear_log_create_vm_done(struct kvm_vm *vm)
220 {
221         struct kvm_enable_cap cap = {};
222         u64 manual_caps;
223
224         manual_caps = kvm_check_cap(KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
225         TEST_ASSERT(manual_caps, "MANUAL_CAPS is zero!");
226         manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
227                         KVM_DIRTY_LOG_INITIALLY_SET);
228         cap.cap = KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2;
229         cap.args[0] = manual_caps;
230         vm_enable_cap(vm, &cap);
231 }
232
233 static void dirty_log_collect_dirty_pages(struct kvm_vm *vm, int slot,
234                                           void *bitmap, uint32_t num_pages)
235 {
236         kvm_vm_get_dirty_log(vm, slot, bitmap);
237 }
238
239 static void clear_log_collect_dirty_pages(struct kvm_vm *vm, int slot,
240                                           void *bitmap, uint32_t num_pages)
241 {
242         kvm_vm_get_dirty_log(vm, slot, bitmap);
243         kvm_vm_clear_dirty_log(vm, slot, bitmap, 0, num_pages);
244 }
245
246 /* Should only be called after a GUEST_SYNC */
247 static void vcpu_handle_sync_stop(void)
248 {
249         if (atomic_read(&vcpu_sync_stop_requested)) {
250                 /* It means main thread is sleeping waiting */
251                 atomic_set(&vcpu_sync_stop_requested, false);
252                 sem_post(&sem_vcpu_stop);
253                 sem_wait_until(&sem_vcpu_cont);
254         }
255 }
256
257 static void default_after_vcpu_run(struct kvm_vm *vm, int ret, int err)
258 {
259         struct kvm_run *run = vcpu_state(vm, VCPU_ID);
260
261         TEST_ASSERT(ret == 0 || (ret == -1 && err == EINTR),
262                     "vcpu run failed: errno=%d", err);
263
264         TEST_ASSERT(get_ucall(vm, VCPU_ID, NULL) == UCALL_SYNC,
265                     "Invalid guest sync status: exit_reason=%s\n",
266                     exit_reason_str(run->exit_reason));
267
268         vcpu_handle_sync_stop();
269 }
270
271 static bool dirty_ring_supported(void)
272 {
273         return kvm_check_cap(KVM_CAP_DIRTY_LOG_RING);
274 }
275
276 static void dirty_ring_create_vm_done(struct kvm_vm *vm)
277 {
278         /*
279          * Switch to dirty ring mode after VM creation but before any
280          * of the vcpu creation.
281          */
282         vm_enable_dirty_ring(vm, test_dirty_ring_count *
283                              sizeof(struct kvm_dirty_gfn));
284 }
285
286 static inline bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
287 {
288         return gfn->flags == KVM_DIRTY_GFN_F_DIRTY;
289 }
290
291 static inline void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
292 {
293         gfn->flags = KVM_DIRTY_GFN_F_RESET;
294 }
295
296 static uint32_t dirty_ring_collect_one(struct kvm_dirty_gfn *dirty_gfns,
297                                        int slot, void *bitmap,
298                                        uint32_t num_pages, uint32_t *fetch_index)
299 {
300         struct kvm_dirty_gfn *cur;
301         uint32_t count = 0;
302
303         while (true) {
304                 cur = &dirty_gfns[*fetch_index % test_dirty_ring_count];
305                 if (!dirty_gfn_is_dirtied(cur))
306                         break;
307                 TEST_ASSERT(cur->slot == slot, "Slot number didn't match: "
308                             "%u != %u", cur->slot, slot);
309                 TEST_ASSERT(cur->offset < num_pages, "Offset overflow: "
310                             "0x%llx >= 0x%x", cur->offset, num_pages);
311                 //pr_info("fetch 0x%x page %llu\n", *fetch_index, cur->offset);
312                 set_bit_le(cur->offset, bitmap);
313                 dirty_ring_last_page = cur->offset;
314                 dirty_gfn_set_collected(cur);
315                 (*fetch_index)++;
316                 count++;
317         }
318
319         return count;
320 }
321
322 static void dirty_ring_wait_vcpu(void)
323 {
324         /* This makes sure that hardware PML cache flushed */
325         vcpu_kick();
326         sem_wait_until(&sem_vcpu_stop);
327 }
328
329 static void dirty_ring_continue_vcpu(void)
330 {
331         pr_info("Notifying vcpu to continue\n");
332         sem_post(&sem_vcpu_cont);
333 }
334
335 static void dirty_ring_collect_dirty_pages(struct kvm_vm *vm, int slot,
336                                            void *bitmap, uint32_t num_pages)
337 {
338         /* We only have one vcpu */
339         static uint32_t fetch_index = 0;
340         uint32_t count = 0, cleared;
341         bool continued_vcpu = false;
342
343         dirty_ring_wait_vcpu();
344
345         if (!dirty_ring_vcpu_ring_full) {
346                 /*
347                  * This is not a ring-full event, it's safe to allow
348                  * vcpu to continue
349                  */
350                 dirty_ring_continue_vcpu();
351                 continued_vcpu = true;
352         }
353
354         /* Only have one vcpu */
355         count = dirty_ring_collect_one(vcpu_map_dirty_ring(vm, VCPU_ID),
356                                        slot, bitmap, num_pages, &fetch_index);
357
358         cleared = kvm_vm_reset_dirty_ring(vm);
359
360         /* Cleared pages should be the same as collected */
361         TEST_ASSERT(cleared == count, "Reset dirty pages (%u) mismatch "
362                     "with collected (%u)", cleared, count);
363
364         if (!continued_vcpu) {
365                 TEST_ASSERT(dirty_ring_vcpu_ring_full,
366                             "Didn't continue vcpu even without ring full");
367                 dirty_ring_continue_vcpu();
368         }
369
370         pr_info("Iteration %ld collected %u pages\n", iteration, count);
371 }
372
373 static void dirty_ring_after_vcpu_run(struct kvm_vm *vm, int ret, int err)
374 {
375         struct kvm_run *run = vcpu_state(vm, VCPU_ID);
376
377         /* A ucall-sync or ring-full event is allowed */
378         if (get_ucall(vm, VCPU_ID, NULL) == UCALL_SYNC) {
379                 /* We should allow this to continue */
380                 ;
381         } else if (run->exit_reason == KVM_EXIT_DIRTY_RING_FULL ||
382                    (ret == -1 && err == EINTR)) {
383                 /* Update the flag first before pause */
384                 WRITE_ONCE(dirty_ring_vcpu_ring_full,
385                            run->exit_reason == KVM_EXIT_DIRTY_RING_FULL);
386                 sem_post(&sem_vcpu_stop);
387                 pr_info("vcpu stops because %s...\n",
388                         dirty_ring_vcpu_ring_full ?
389                         "dirty ring is full" : "vcpu is kicked out");
390                 sem_wait_until(&sem_vcpu_cont);
391                 pr_info("vcpu continues now.\n");
392         } else {
393                 TEST_ASSERT(false, "Invalid guest sync status: "
394                             "exit_reason=%s\n",
395                             exit_reason_str(run->exit_reason));
396         }
397 }
398
399 static void dirty_ring_before_vcpu_join(void)
400 {
401         /* Kick another round of vcpu just to make sure it will quit */
402         sem_post(&sem_vcpu_cont);
403 }
404
405 struct log_mode {
406         const char *name;
407         /* Return true if this mode is supported, otherwise false */
408         bool (*supported)(void);
409         /* Hook when the vm creation is done (before vcpu creation) */
410         void (*create_vm_done)(struct kvm_vm *vm);
411         /* Hook to collect the dirty pages into the bitmap provided */
412         void (*collect_dirty_pages) (struct kvm_vm *vm, int slot,
413                                      void *bitmap, uint32_t num_pages);
414         /* Hook to call when after each vcpu run */
415         void (*after_vcpu_run)(struct kvm_vm *vm, int ret, int err);
416         void (*before_vcpu_join) (void);
417 } log_modes[LOG_MODE_NUM] = {
418         {
419                 .name = "dirty-log",
420                 .collect_dirty_pages = dirty_log_collect_dirty_pages,
421                 .after_vcpu_run = default_after_vcpu_run,
422         },
423         {
424                 .name = "clear-log",
425                 .supported = clear_log_supported,
426                 .create_vm_done = clear_log_create_vm_done,
427                 .collect_dirty_pages = clear_log_collect_dirty_pages,
428                 .after_vcpu_run = default_after_vcpu_run,
429         },
430         {
431                 .name = "dirty-ring",
432                 .supported = dirty_ring_supported,
433                 .create_vm_done = dirty_ring_create_vm_done,
434                 .collect_dirty_pages = dirty_ring_collect_dirty_pages,
435                 .before_vcpu_join = dirty_ring_before_vcpu_join,
436                 .after_vcpu_run = dirty_ring_after_vcpu_run,
437         },
438 };
439
440 /*
441  * We use this bitmap to track some pages that should have its dirty
442  * bit set in the _next_ iteration.  For example, if we detected the
443  * page value changed to current iteration but at the same time the
444  * page bit is cleared in the latest bitmap, then the system must
445  * report that write in the next get dirty log call.
446  */
447 static unsigned long *host_bmap_track;
448
449 static void log_modes_dump(void)
450 {
451         int i;
452
453         printf("all");
454         for (i = 0; i < LOG_MODE_NUM; i++)
455                 printf(", %s", log_modes[i].name);
456         printf("\n");
457 }
458
459 static bool log_mode_supported(void)
460 {
461         struct log_mode *mode = &log_modes[host_log_mode];
462
463         if (mode->supported)
464                 return mode->supported();
465
466         return true;
467 }
468
469 static void log_mode_create_vm_done(struct kvm_vm *vm)
470 {
471         struct log_mode *mode = &log_modes[host_log_mode];
472
473         if (mode->create_vm_done)
474                 mode->create_vm_done(vm);
475 }
476
477 static void log_mode_collect_dirty_pages(struct kvm_vm *vm, int slot,
478                                          void *bitmap, uint32_t num_pages)
479 {
480         struct log_mode *mode = &log_modes[host_log_mode];
481
482         TEST_ASSERT(mode->collect_dirty_pages != NULL,
483                     "collect_dirty_pages() is required for any log mode!");
484         mode->collect_dirty_pages(vm, slot, bitmap, num_pages);
485 }
486
487 static void log_mode_after_vcpu_run(struct kvm_vm *vm, int ret, int err)
488 {
489         struct log_mode *mode = &log_modes[host_log_mode];
490
491         if (mode->after_vcpu_run)
492                 mode->after_vcpu_run(vm, ret, err);
493 }
494
495 static void log_mode_before_vcpu_join(void)
496 {
497         struct log_mode *mode = &log_modes[host_log_mode];
498
499         if (mode->before_vcpu_join)
500                 mode->before_vcpu_join();
501 }
502
503 static void generate_random_array(uint64_t *guest_array, uint64_t size)
504 {
505         uint64_t i;
506
507         for (i = 0; i < size; i++)
508                 guest_array[i] = random();
509 }
510
511 static void *vcpu_worker(void *data)
512 {
513         int ret, vcpu_fd;
514         struct kvm_vm *vm = data;
515         uint64_t *guest_array;
516         uint64_t pages_count = 0;
517         struct kvm_signal_mask *sigmask = alloca(offsetof(struct kvm_signal_mask, sigset)
518                                                  + sizeof(sigset_t));
519         sigset_t *sigset = (sigset_t *) &sigmask->sigset;
520
521         vcpu_fd = vcpu_get_fd(vm, VCPU_ID);
522
523         /*
524          * SIG_IPI is unblocked atomically while in KVM_RUN.  It causes the
525          * ioctl to return with -EINTR, but it is still pending and we need
526          * to accept it with the sigwait.
527          */
528         sigmask->len = 8;
529         pthread_sigmask(0, NULL, sigset);
530         sigdelset(sigset, SIG_IPI);
531         vcpu_ioctl(vm, VCPU_ID, KVM_SET_SIGNAL_MASK, sigmask);
532
533         sigemptyset(sigset);
534         sigaddset(sigset, SIG_IPI);
535
536         guest_array = addr_gva2hva(vm, (vm_vaddr_t)random_array);
537
538         while (!READ_ONCE(host_quit)) {
539                 /* Clear any existing kick signals */
540                 generate_random_array(guest_array, TEST_PAGES_PER_LOOP);
541                 pages_count += TEST_PAGES_PER_LOOP;
542                 /* Let the guest dirty the random pages */
543                 ret = ioctl(vcpu_fd, KVM_RUN, NULL);
544                 if (ret == -1 && errno == EINTR) {
545                         int sig = -1;
546                         sigwait(sigset, &sig);
547                         assert(sig == SIG_IPI);
548                 }
549                 log_mode_after_vcpu_run(vm, ret, errno);
550         }
551
552         pr_info("Dirtied %"PRIu64" pages\n", pages_count);
553
554         return NULL;
555 }
556
557 static void vm_dirty_log_verify(enum vm_guest_mode mode, unsigned long *bmap)
558 {
559         uint64_t step = vm_num_host_pages(mode, 1);
560         uint64_t page;
561         uint64_t *value_ptr;
562         uint64_t min_iter = 0;
563
564         for (page = 0; page < host_num_pages; page += step) {
565                 value_ptr = host_test_mem + page * host_page_size;
566
567                 /* If this is a special page that we were tracking... */
568                 if (test_and_clear_bit_le(page, host_bmap_track)) {
569                         host_track_next_count++;
570                         TEST_ASSERT(test_bit_le(page, bmap),
571                                     "Page %"PRIu64" should have its dirty bit "
572                                     "set in this iteration but it is missing",
573                                     page);
574                 }
575
576                 if (test_and_clear_bit_le(page, bmap)) {
577                         bool matched;
578
579                         host_dirty_count++;
580
581                         /*
582                          * If the bit is set, the value written onto
583                          * the corresponding page should be either the
584                          * previous iteration number or the current one.
585                          */
586                         matched = (*value_ptr == iteration ||
587                                    *value_ptr == iteration - 1);
588
589                         if (host_log_mode == LOG_MODE_DIRTY_RING && !matched) {
590                                 if (*value_ptr == iteration - 2 && min_iter <= iteration - 2) {
591                                         /*
592                                          * Short answer: this case is special
593                                          * only for dirty ring test where the
594                                          * page is the last page before a kvm
595                                          * dirty ring full in iteration N-2.
596                                          *
597                                          * Long answer: Assuming ring size R,
598                                          * one possible condition is:
599                                          *
600                                          *      main thr       vcpu thr
601                                          *      --------       --------
602                                          *    iter=1
603                                          *                   write 1 to page 0~(R-1)
604                                          *                   full, vmexit
605                                          *    collect 0~(R-1)
606                                          *    kick vcpu
607                                          *                   write 1 to (R-1)~(2R-2)
608                                          *                   full, vmexit
609                                          *    iter=2
610                                          *    collect (R-1)~(2R-2)
611                                          *    kick vcpu
612                                          *                   write 1 to (2R-2)
613                                          *                   (NOTE!!! "1" cached in cpu reg)
614                                          *                   write 2 to (2R-1)~(3R-3)
615                                          *                   full, vmexit
616                                          *    iter=3
617                                          *    collect (2R-2)~(3R-3)
618                                          *    (here if we read value on page
619                                          *     "2R-2" is 1, while iter=3!!!)
620                                          *
621                                          * This however can only happen once per iteration.
622                                          */
623                                         min_iter = iteration - 1;
624                                         continue;
625                                 } else if (page == dirty_ring_last_page) {
626                                         /*
627                                          * Please refer to comments in
628                                          * dirty_ring_last_page.
629                                          */
630                                         continue;
631                                 }
632                         }
633
634                         TEST_ASSERT(matched,
635                                     "Set page %"PRIu64" value %"PRIu64
636                                     " incorrect (iteration=%"PRIu64")",
637                                     page, *value_ptr, iteration);
638                 } else {
639                         host_clear_count++;
640                         /*
641                          * If cleared, the value written can be any
642                          * value smaller or equals to the iteration
643                          * number.  Note that the value can be exactly
644                          * (iteration-1) if that write can happen
645                          * like this:
646                          *
647                          * (1) increase loop count to "iteration-1"
648                          * (2) write to page P happens (with value
649                          *     "iteration-1")
650                          * (3) get dirty log for "iteration-1"; we'll
651                          *     see that page P bit is set (dirtied),
652                          *     and not set the bit in host_bmap_track
653                          * (4) increase loop count to "iteration"
654                          *     (which is current iteration)
655                          * (5) get dirty log for current iteration,
656                          *     we'll see that page P is cleared, with
657                          *     value "iteration-1".
658                          */
659                         TEST_ASSERT(*value_ptr <= iteration,
660                                     "Clear page %"PRIu64" value %"PRIu64
661                                     " incorrect (iteration=%"PRIu64")",
662                                     page, *value_ptr, iteration);
663                         if (*value_ptr == iteration) {
664                                 /*
665                                  * This page is _just_ modified; it
666                                  * should report its dirtyness in the
667                                  * next run
668                                  */
669                                 set_bit_le(page, host_bmap_track);
670                         }
671                 }
672         }
673 }
674
675 static struct kvm_vm *create_vm(enum vm_guest_mode mode, uint32_t vcpuid,
676                                 uint64_t extra_mem_pages, void *guest_code)
677 {
678         struct kvm_vm *vm;
679         uint64_t extra_pg_pages = extra_mem_pages / 512 * 2;
680
681         pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));
682
683         vm = vm_create(mode, DEFAULT_GUEST_PHY_PAGES + extra_pg_pages, O_RDWR);
684         kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
685 #ifdef __x86_64__
686         vm_create_irqchip(vm);
687 #endif
688         log_mode_create_vm_done(vm);
689         vm_vcpu_add_default(vm, vcpuid, guest_code);
690         return vm;
691 }
692
693 #define DIRTY_MEM_BITS 30 /* 1G */
694 #define PAGE_SHIFT_4K  12
695
696 struct test_params {
697         unsigned long iterations;
698         unsigned long interval;
699         uint64_t phys_offset;
700 };
701
702 static void run_test(enum vm_guest_mode mode, void *arg)
703 {
704         struct test_params *p = arg;
705         struct kvm_vm *vm;
706         unsigned long *bmap;
707
708         if (!log_mode_supported()) {
709                 print_skip("Log mode '%s' not supported",
710                            log_modes[host_log_mode].name);
711                 return;
712         }
713
714         /*
715          * We reserve page table for 2 times of extra dirty mem which
716          * will definitely cover the original (1G+) test range.  Here
717          * we do the calculation with 4K page size which is the
718          * smallest so the page number will be enough for all archs
719          * (e.g., 64K page size guest will need even less memory for
720          * page tables).
721          */
722         vm = create_vm(mode, VCPU_ID,
723                        2ul << (DIRTY_MEM_BITS - PAGE_SHIFT_4K),
724                        guest_code);
725
726         guest_page_size = vm_get_page_size(vm);
727         /*
728          * A little more than 1G of guest page sized pages.  Cover the
729          * case where the size is not aligned to 64 pages.
730          */
731         guest_num_pages = (1ul << (DIRTY_MEM_BITS -
732                                    vm_get_page_shift(vm))) + 3;
733         guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
734
735         host_page_size = getpagesize();
736         host_num_pages = vm_num_host_pages(mode, guest_num_pages);
737
738         if (!p->phys_offset) {
739                 guest_test_phys_mem = (vm_get_max_gfn(vm) -
740                                        guest_num_pages) * guest_page_size;
741                 guest_test_phys_mem &= ~(host_page_size - 1);
742         } else {
743                 guest_test_phys_mem = p->phys_offset;
744         }
745
746 #ifdef __s390x__
747         /* Align to 1M (segment size) */
748         guest_test_phys_mem &= ~((1 << 20) - 1);
749 #endif
750
751         pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
752
753         bmap = bitmap_alloc(host_num_pages);
754         host_bmap_track = bitmap_alloc(host_num_pages);
755
756         /* Add an extra memory slot for testing dirty logging */
757         vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
758                                     guest_test_phys_mem,
759                                     TEST_MEM_SLOT_INDEX,
760                                     guest_num_pages,
761                                     KVM_MEM_LOG_DIRTY_PAGES);
762
763         /* Do mapping for the dirty track memory slot */
764         virt_map(vm, guest_test_virt_mem, guest_test_phys_mem, guest_num_pages, 0);
765
766         /* Cache the HVA pointer of the region */
767         host_test_mem = addr_gpa2hva(vm, (vm_paddr_t)guest_test_phys_mem);
768
769         ucall_init(vm, NULL);
770
771         /* Export the shared variables to the guest */
772         sync_global_to_guest(vm, host_page_size);
773         sync_global_to_guest(vm, guest_page_size);
774         sync_global_to_guest(vm, guest_test_virt_mem);
775         sync_global_to_guest(vm, guest_num_pages);
776
777         /* Start the iterations */
778         iteration = 1;
779         sync_global_to_guest(vm, iteration);
780         host_quit = false;
781         host_dirty_count = 0;
782         host_clear_count = 0;
783         host_track_next_count = 0;
784
785         pthread_create(&vcpu_thread, NULL, vcpu_worker, vm);
786
787         while (iteration < p->iterations) {
788                 /* Give the vcpu thread some time to dirty some pages */
789                 usleep(p->interval * 1000);
790                 log_mode_collect_dirty_pages(vm, TEST_MEM_SLOT_INDEX,
791                                              bmap, host_num_pages);
792
793                 /*
794                  * See vcpu_sync_stop_requested definition for details on why
795                  * we need to stop vcpu when verify data.
796                  */
797                 atomic_set(&vcpu_sync_stop_requested, true);
798                 sem_wait_until(&sem_vcpu_stop);
799                 /*
800                  * NOTE: for dirty ring, it's possible that we didn't stop at
801                  * GUEST_SYNC but instead we stopped because ring is full;
802                  * that's okay too because ring full means we're only missing
803                  * the flush of the last page, and since we handle the last
804                  * page specially verification will succeed anyway.
805                  */
806                 assert(host_log_mode == LOG_MODE_DIRTY_RING ||
807                        atomic_read(&vcpu_sync_stop_requested) == false);
808                 vm_dirty_log_verify(mode, bmap);
809                 sem_post(&sem_vcpu_cont);
810
811                 iteration++;
812                 sync_global_to_guest(vm, iteration);
813         }
814
815         /* Tell the vcpu thread to quit */
816         host_quit = true;
817         log_mode_before_vcpu_join();
818         pthread_join(vcpu_thread, NULL);
819
820         pr_info("Total bits checked: dirty (%"PRIu64"), clear (%"PRIu64"), "
821                 "track_next (%"PRIu64")\n", host_dirty_count, host_clear_count,
822                 host_track_next_count);
823
824         free(bmap);
825         free(host_bmap_track);
826         ucall_uninit(vm);
827         kvm_vm_free(vm);
828 }
829
830 static void help(char *name)
831 {
832         puts("");
833         printf("usage: %s [-h] [-i iterations] [-I interval] "
834                "[-p offset] [-m mode]\n", name);
835         puts("");
836         printf(" -c: specify dirty ring size, in number of entries\n");
837         printf("     (only useful for dirty-ring test; default: %"PRIu32")\n",
838                TEST_DIRTY_RING_COUNT);
839         printf(" -i: specify iteration counts (default: %"PRIu64")\n",
840                TEST_HOST_LOOP_N);
841         printf(" -I: specify interval in ms (default: %"PRIu64" ms)\n",
842                TEST_HOST_LOOP_INTERVAL);
843         printf(" -p: specify guest physical test memory offset\n"
844                "     Warning: a low offset can conflict with the loaded test code.\n");
845         printf(" -M: specify the host logging mode "
846                "(default: run all log modes).  Supported modes: \n\t");
847         log_modes_dump();
848         guest_modes_help();
849         puts("");
850         exit(0);
851 }
852
853 int main(int argc, char *argv[])
854 {
855         struct test_params p = {
856                 .iterations = TEST_HOST_LOOP_N,
857                 .interval = TEST_HOST_LOOP_INTERVAL,
858         };
859         int opt, i;
860         sigset_t sigset;
861
862         sem_init(&sem_vcpu_stop, 0, 0);
863         sem_init(&sem_vcpu_cont, 0, 0);
864
865         guest_modes_append_default();
866
867         while ((opt = getopt(argc, argv, "c:hi:I:p:m:M:")) != -1) {
868                 switch (opt) {
869                 case 'c':
870                         test_dirty_ring_count = strtol(optarg, NULL, 10);
871                         break;
872                 case 'i':
873                         p.iterations = strtol(optarg, NULL, 10);
874                         break;
875                 case 'I':
876                         p.interval = strtol(optarg, NULL, 10);
877                         break;
878                 case 'p':
879                         p.phys_offset = strtoull(optarg, NULL, 0);
880                         break;
881                 case 'm':
882                         guest_modes_cmdline(optarg);
883                         break;
884                 case 'M':
885                         if (!strcmp(optarg, "all")) {
886                                 host_log_mode_option = LOG_MODE_ALL;
887                                 break;
888                         }
889                         for (i = 0; i < LOG_MODE_NUM; i++) {
890                                 if (!strcmp(optarg, log_modes[i].name)) {
891                                         pr_info("Setting log mode to: '%s'\n",
892                                                 optarg);
893                                         host_log_mode_option = i;
894                                         break;
895                                 }
896                         }
897                         if (i == LOG_MODE_NUM) {
898                                 printf("Log mode '%s' invalid. Please choose "
899                                        "from: ", optarg);
900                                 log_modes_dump();
901                                 exit(1);
902                         }
903                         break;
904                 case 'h':
905                 default:
906                         help(argv[0]);
907                         break;
908                 }
909         }
910
911         TEST_ASSERT(p.iterations > 2, "Iterations must be greater than two");
912         TEST_ASSERT(p.interval > 0, "Interval must be greater than zero");
913
914         pr_info("Test iterations: %"PRIu64", interval: %"PRIu64" (ms)\n",
915                 p.iterations, p.interval);
916
917         srandom(time(0));
918
919         /* Ensure that vCPU threads start with SIG_IPI blocked.  */
920         sigemptyset(&sigset);
921         sigaddset(&sigset, SIG_IPI);
922         pthread_sigmask(SIG_BLOCK, &sigset, NULL);
923
924         if (host_log_mode_option == LOG_MODE_ALL) {
925                 /* Run each log mode */
926                 for (i = 0; i < LOG_MODE_NUM; i++) {
927                         pr_info("Testing Log Mode '%s'\n", log_modes[i].name);
928                         host_log_mode = i;
929                         for_each_guest_mode(run_test, &p);
930                 }
931         } else {
932                 host_log_mode = host_log_mode_option;
933                 for_each_guest_mode(run_test, &p);
934         }
935
936         return 0;
937 }