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