xref: /openbmc/qemu/tests/qtest/migration-test.c (revision 9951ba94)
1 /*
2  * QTest testcase for migration
3  *
4  * Copyright (c) 2016-2018 Red Hat, Inc. and/or its affiliates
5  *   based on the vhost-user-test.c that is:
6  *      Copyright (c) 2014 Virtual Open Systems Sarl.
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  *
11  */
12 
13 #include "qemu/osdep.h"
14 
15 #include "libqos/libqtest.h"
16 #include "qapi/error.h"
17 #include "qapi/qmp/qdict.h"
18 #include "qemu/module.h"
19 #include "qemu/option.h"
20 #include "qemu/range.h"
21 #include "qemu/sockets.h"
22 #include "chardev/char.h"
23 #include "qapi/qapi-visit-sockets.h"
24 #include "qapi/qobject-input-visitor.h"
25 #include "qapi/qobject-output-visitor.h"
26 
27 #include "migration-helpers.h"
28 #include "tests/migration/migration-test.h"
29 
30 /* For dirty ring test; so far only x86_64 is supported */
31 #if defined(__linux__) && defined(HOST_X86_64)
32 #include "linux/kvm.h"
33 #endif
34 
35 /* TODO actually test the results and get rid of this */
36 #define qtest_qmp_discard_response(...) qobject_unref(qtest_qmp(__VA_ARGS__))
37 
38 unsigned start_address;
39 unsigned end_address;
40 static bool uffd_feature_thread_id;
41 
42 /* A downtime where the test really should converge */
43 #define CONVERGE_DOWNTIME 1000
44 
45 #if defined(__linux__)
46 #include <sys/syscall.h>
47 #include <sys/vfs.h>
48 #endif
49 
50 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
51 #include <sys/eventfd.h>
52 #include <sys/ioctl.h>
53 #include <linux/userfaultfd.h>
54 
55 static bool ufd_version_check(void)
56 {
57     struct uffdio_api api_struct;
58     uint64_t ioctl_mask;
59 
60     int ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
61 
62     if (ufd == -1) {
63         g_test_message("Skipping test: userfaultfd not available");
64         return false;
65     }
66 
67     api_struct.api = UFFD_API;
68     api_struct.features = 0;
69     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
70         g_test_message("Skipping test: UFFDIO_API failed");
71         return false;
72     }
73     uffd_feature_thread_id = api_struct.features & UFFD_FEATURE_THREAD_ID;
74 
75     ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
76                  (__u64)1 << _UFFDIO_UNREGISTER;
77     if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
78         g_test_message("Skipping test: Missing userfault feature");
79         return false;
80     }
81 
82     return true;
83 }
84 
85 #else
86 static bool ufd_version_check(void)
87 {
88     g_test_message("Skipping test: Userfault not available (builtdtime)");
89     return false;
90 }
91 
92 #endif
93 
94 static const char *tmpfs;
95 
96 /* The boot file modifies memory area in [start_address, end_address)
97  * repeatedly. It outputs a 'B' at a fixed rate while it's still running.
98  */
99 #include "tests/migration/i386/a-b-bootblock.h"
100 #include "tests/migration/aarch64/a-b-kernel.h"
101 #include "tests/migration/s390x/a-b-bios.h"
102 
103 static void init_bootfile(const char *bootpath, void *content, size_t len)
104 {
105     FILE *bootfile = fopen(bootpath, "wb");
106 
107     g_assert_cmpint(fwrite(content, len, 1, bootfile), ==, 1);
108     fclose(bootfile);
109 }
110 
111 /*
112  * Wait for some output in the serial output file,
113  * we get an 'A' followed by an endless string of 'B's
114  * but on the destination we won't have the A.
115  */
116 static void wait_for_serial(const char *side)
117 {
118     g_autofree char *serialpath = g_strdup_printf("%s/%s", tmpfs, side);
119     FILE *serialfile = fopen(serialpath, "r");
120     const char *arch = qtest_get_arch();
121     int started = (strcmp(side, "src_serial") == 0 &&
122                    strcmp(arch, "ppc64") == 0) ? 0 : 1;
123 
124     do {
125         int readvalue = fgetc(serialfile);
126 
127         if (!started) {
128             /* SLOF prints its banner before starting test,
129              * to ignore it, mark the start of the test with '_',
130              * ignore all characters until this marker
131              */
132             switch (readvalue) {
133             case '_':
134                 started = 1;
135                 break;
136             case EOF:
137                 fseek(serialfile, 0, SEEK_SET);
138                 usleep(1000);
139                 break;
140             }
141             continue;
142         }
143         switch (readvalue) {
144         case 'A':
145             /* Fine */
146             break;
147 
148         case 'B':
149             /* It's alive! */
150             fclose(serialfile);
151             return;
152 
153         case EOF:
154             started = (strcmp(side, "src_serial") == 0 &&
155                        strcmp(arch, "ppc64") == 0) ? 0 : 1;
156             fseek(serialfile, 0, SEEK_SET);
157             usleep(1000);
158             break;
159 
160         default:
161             fprintf(stderr, "Unexpected %d on %s serial\n", readvalue, side);
162             g_assert_not_reached();
163         }
164     } while (true);
165 }
166 
167 /*
168  * It's tricky to use qemu's migration event capability with qtest,
169  * events suddenly appearing confuse the qmp()/hmp() responses.
170  */
171 
172 static int64_t read_ram_property_int(QTestState *who, const char *property)
173 {
174     QDict *rsp_return, *rsp_ram;
175     int64_t result;
176 
177     rsp_return = migrate_query(who);
178     if (!qdict_haskey(rsp_return, "ram")) {
179         /* Still in setup */
180         result = 0;
181     } else {
182         rsp_ram = qdict_get_qdict(rsp_return, "ram");
183         result = qdict_get_try_int(rsp_ram, property, 0);
184     }
185     qobject_unref(rsp_return);
186     return result;
187 }
188 
189 static int64_t read_migrate_property_int(QTestState *who, const char *property)
190 {
191     QDict *rsp_return;
192     int64_t result;
193 
194     rsp_return = migrate_query(who);
195     result = qdict_get_try_int(rsp_return, property, 0);
196     qobject_unref(rsp_return);
197     return result;
198 }
199 
200 static uint64_t get_migration_pass(QTestState *who)
201 {
202     return read_ram_property_int(who, "dirty-sync-count");
203 }
204 
205 static void read_blocktime(QTestState *who)
206 {
207     QDict *rsp_return;
208 
209     rsp_return = migrate_query(who);
210     g_assert(qdict_haskey(rsp_return, "postcopy-blocktime"));
211     qobject_unref(rsp_return);
212 }
213 
214 static void wait_for_migration_pass(QTestState *who)
215 {
216     uint64_t initial_pass = get_migration_pass(who);
217     uint64_t pass;
218 
219     /* Wait for the 1st sync */
220     while (!got_stop && !initial_pass) {
221         usleep(1000);
222         initial_pass = get_migration_pass(who);
223     }
224 
225     do {
226         usleep(1000);
227         pass = get_migration_pass(who);
228     } while (pass == initial_pass && !got_stop);
229 }
230 
231 static void check_guests_ram(QTestState *who)
232 {
233     /* Our ASM test will have been incrementing one byte from each page from
234      * start_address to < end_address in order. This gives us a constraint
235      * that any page's byte should be equal or less than the previous pages
236      * byte (mod 256); and they should all be equal except for one transition
237      * at the point where we meet the incrementer. (We're running this with
238      * the guest stopped).
239      */
240     unsigned address;
241     uint8_t first_byte;
242     uint8_t last_byte;
243     bool hit_edge = false;
244     int bad = 0;
245 
246     qtest_memread(who, start_address, &first_byte, 1);
247     last_byte = first_byte;
248 
249     for (address = start_address + TEST_MEM_PAGE_SIZE; address < end_address;
250          address += TEST_MEM_PAGE_SIZE)
251     {
252         uint8_t b;
253         qtest_memread(who, address, &b, 1);
254         if (b != last_byte) {
255             if (((b + 1) % 256) == last_byte && !hit_edge) {
256                 /* This is OK, the guest stopped at the point of
257                  * incrementing the previous page but didn't get
258                  * to us yet.
259                  */
260                 hit_edge = true;
261                 last_byte = b;
262             } else {
263                 bad++;
264                 if (bad <= 10) {
265                     fprintf(stderr, "Memory content inconsistency at %x"
266                             " first_byte = %x last_byte = %x current = %x"
267                             " hit_edge = %x\n",
268                             address, first_byte, last_byte, b, hit_edge);
269                 }
270             }
271         }
272     }
273     if (bad >= 10) {
274         fprintf(stderr, "and in another %d pages", bad - 10);
275     }
276     g_assert(bad == 0);
277 }
278 
279 static void cleanup(const char *filename)
280 {
281     g_autofree char *path = g_strdup_printf("%s/%s", tmpfs, filename);
282 
283     unlink(path);
284 }
285 
286 static char *SocketAddress_to_str(SocketAddress *addr)
287 {
288     switch (addr->type) {
289     case SOCKET_ADDRESS_TYPE_INET:
290         return g_strdup_printf("tcp:%s:%s",
291                                addr->u.inet.host,
292                                addr->u.inet.port);
293     case SOCKET_ADDRESS_TYPE_UNIX:
294         return g_strdup_printf("unix:%s",
295                                addr->u.q_unix.path);
296     case SOCKET_ADDRESS_TYPE_FD:
297         return g_strdup_printf("fd:%s", addr->u.fd.str);
298     case SOCKET_ADDRESS_TYPE_VSOCK:
299         return g_strdup_printf("tcp:%s:%s",
300                                addr->u.vsock.cid,
301                                addr->u.vsock.port);
302     default:
303         return g_strdup("unknown address type");
304     }
305 }
306 
307 static char *migrate_get_socket_address(QTestState *who, const char *parameter)
308 {
309     QDict *rsp;
310     char *result;
311     SocketAddressList *addrs;
312     Visitor *iv = NULL;
313     QObject *object;
314 
315     rsp = migrate_query(who);
316     object = qdict_get(rsp, parameter);
317 
318     iv = qobject_input_visitor_new(object);
319     visit_type_SocketAddressList(iv, NULL, &addrs, &error_abort);
320     visit_free(iv);
321 
322     /* we are only using a single address */
323     result = SocketAddress_to_str(addrs->value);
324 
325     qapi_free_SocketAddressList(addrs);
326     qobject_unref(rsp);
327     return result;
328 }
329 
330 static long long migrate_get_parameter_int(QTestState *who,
331                                            const char *parameter)
332 {
333     QDict *rsp;
334     long long result;
335 
336     rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");
337     result = qdict_get_int(rsp, parameter);
338     qobject_unref(rsp);
339     return result;
340 }
341 
342 static void migrate_check_parameter_int(QTestState *who, const char *parameter,
343                                         long long value)
344 {
345     long long result;
346 
347     result = migrate_get_parameter_int(who, parameter);
348     g_assert_cmpint(result, ==, value);
349 }
350 
351 static void migrate_set_parameter_int(QTestState *who, const char *parameter,
352                                       long long value)
353 {
354     QDict *rsp;
355 
356     rsp = qtest_qmp(who,
357                     "{ 'execute': 'migrate-set-parameters',"
358                     "'arguments': { %s: %lld } }",
359                     parameter, value);
360     g_assert(qdict_haskey(rsp, "return"));
361     qobject_unref(rsp);
362     migrate_check_parameter_int(who, parameter, value);
363 }
364 
365 static char *migrate_get_parameter_str(QTestState *who,
366                                        const char *parameter)
367 {
368     QDict *rsp;
369     char *result;
370 
371     rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");
372     result = g_strdup(qdict_get_str(rsp, parameter));
373     qobject_unref(rsp);
374     return result;
375 }
376 
377 static void migrate_check_parameter_str(QTestState *who, const char *parameter,
378                                         const char *value)
379 {
380     g_autofree char *result = migrate_get_parameter_str(who, parameter);
381     g_assert_cmpstr(result, ==, value);
382 }
383 
384 static void migrate_set_parameter_str(QTestState *who, const char *parameter,
385                                       const char *value)
386 {
387     QDict *rsp;
388 
389     rsp = qtest_qmp(who,
390                     "{ 'execute': 'migrate-set-parameters',"
391                     "'arguments': { %s: %s } }",
392                     parameter, value);
393     g_assert(qdict_haskey(rsp, "return"));
394     qobject_unref(rsp);
395     migrate_check_parameter_str(who, parameter, value);
396 }
397 
398 static void migrate_pause(QTestState *who)
399 {
400     QDict *rsp;
401 
402     rsp = wait_command(who, "{ 'execute': 'migrate-pause' }");
403     qobject_unref(rsp);
404 }
405 
406 static void migrate_continue(QTestState *who, const char *state)
407 {
408     QDict *rsp;
409 
410     rsp = wait_command(who,
411                        "{ 'execute': 'migrate-continue',"
412                        "  'arguments': { 'state': %s } }",
413                        state);
414     qobject_unref(rsp);
415 }
416 
417 static void migrate_recover(QTestState *who, const char *uri)
418 {
419     QDict *rsp;
420 
421     rsp = wait_command(who,
422                        "{ 'execute': 'migrate-recover', "
423                        "  'id': 'recover-cmd', "
424                        "  'arguments': { 'uri': %s } }",
425                        uri);
426     qobject_unref(rsp);
427 }
428 
429 static void migrate_cancel(QTestState *who)
430 {
431     QDict *rsp;
432 
433     rsp = wait_command(who, "{ 'execute': 'migrate_cancel' }");
434     qobject_unref(rsp);
435 }
436 
437 static void migrate_set_capability(QTestState *who, const char *capability,
438                                    bool value)
439 {
440     QDict *rsp;
441 
442     rsp = qtest_qmp(who,
443                     "{ 'execute': 'migrate-set-capabilities',"
444                     "'arguments': { "
445                     "'capabilities': [ { "
446                     "'capability': %s, 'state': %i } ] } }",
447                     capability, value);
448     g_assert(qdict_haskey(rsp, "return"));
449     qobject_unref(rsp);
450 }
451 
452 static void migrate_postcopy_start(QTestState *from, QTestState *to)
453 {
454     QDict *rsp;
455 
456     rsp = wait_command(from, "{ 'execute': 'migrate-start-postcopy' }");
457     qobject_unref(rsp);
458 
459     if (!got_stop) {
460         qtest_qmp_eventwait(from, "STOP");
461     }
462 
463     qtest_qmp_eventwait(to, "RESUME");
464 }
465 
466 typedef struct {
467     /*
468      * QTEST_LOG=1 may override this.  When QTEST_LOG=1, we always dump errors
469      * unconditionally, because it means the user would like to be verbose.
470      */
471     bool hide_stderr;
472     bool use_shmem;
473     /* only launch the target process */
474     bool only_target;
475     /* Use dirty ring if true; dirty logging otherwise */
476     bool use_dirty_ring;
477     const char *opts_source;
478     const char *opts_target;
479 } MigrateStart;
480 
481 static int test_migrate_start(QTestState **from, QTestState **to,
482                               const char *uri, MigrateStart *args)
483 {
484     g_autofree gchar *arch_source = NULL;
485     g_autofree gchar *arch_target = NULL;
486     g_autofree gchar *cmd_source = NULL;
487     g_autofree gchar *cmd_target = NULL;
488     const gchar *ignore_stderr;
489     g_autofree char *bootpath = NULL;
490     g_autofree char *shmem_opts = NULL;
491     g_autofree char *shmem_path = NULL;
492     const char *arch = qtest_get_arch();
493     const char *machine_opts = NULL;
494     const char *memory_size;
495 
496     if (args->use_shmem) {
497         if (!g_file_test("/dev/shm", G_FILE_TEST_IS_DIR)) {
498             g_test_skip("/dev/shm is not supported");
499             return -1;
500         }
501     }
502 
503     got_stop = false;
504     bootpath = g_strdup_printf("%s/bootsect", tmpfs);
505     if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) {
506         /* the assembled x86 boot sector should be exactly one sector large */
507         assert(sizeof(x86_bootsect) == 512);
508         init_bootfile(bootpath, x86_bootsect, sizeof(x86_bootsect));
509         memory_size = "150M";
510         arch_source = g_strdup_printf("-drive file=%s,format=raw", bootpath);
511         arch_target = g_strdup(arch_source);
512         start_address = X86_TEST_MEM_START;
513         end_address = X86_TEST_MEM_END;
514     } else if (g_str_equal(arch, "s390x")) {
515         init_bootfile(bootpath, s390x_elf, sizeof(s390x_elf));
516         memory_size = "128M";
517         arch_source = g_strdup_printf("-bios %s", bootpath);
518         arch_target = g_strdup(arch_source);
519         start_address = S390_TEST_MEM_START;
520         end_address = S390_TEST_MEM_END;
521     } else if (strcmp(arch, "ppc64") == 0) {
522         machine_opts = "vsmt=8";
523         memory_size = "256M";
524         start_address = PPC_TEST_MEM_START;
525         end_address = PPC_TEST_MEM_END;
526         arch_source = g_strdup_printf("-nodefaults "
527                                       "-prom-env 'use-nvramrc?=true' -prom-env "
528                                       "'nvramrc=hex .\" _\" begin %x %x "
529                                       "do i c@ 1 + i c! 1000 +loop .\" B\" 0 "
530                                       "until'", end_address, start_address);
531         arch_target = g_strdup("");
532     } else if (strcmp(arch, "aarch64") == 0) {
533         init_bootfile(bootpath, aarch64_kernel, sizeof(aarch64_kernel));
534         machine_opts = "virt,gic-version=max";
535         memory_size = "150M";
536         arch_source = g_strdup_printf("-cpu max "
537                                       "-kernel %s",
538                                       bootpath);
539         arch_target = g_strdup(arch_source);
540         start_address = ARM_TEST_MEM_START;
541         end_address = ARM_TEST_MEM_END;
542 
543         g_assert(sizeof(aarch64_kernel) <= ARM_TEST_MAX_KERNEL_SIZE);
544     } else {
545         g_assert_not_reached();
546     }
547 
548     if (!getenv("QTEST_LOG") && args->hide_stderr) {
549         ignore_stderr = "2>/dev/null";
550     } else {
551         ignore_stderr = "";
552     }
553 
554     if (args->use_shmem) {
555         shmem_path = g_strdup_printf("/dev/shm/qemu-%d", getpid());
556         shmem_opts = g_strdup_printf(
557             "-object memory-backend-file,id=mem0,size=%s"
558             ",mem-path=%s,share=on -numa node,memdev=mem0",
559             memory_size, shmem_path);
560     } else {
561         shmem_path = NULL;
562         shmem_opts = g_strdup("");
563     }
564 
565     cmd_source = g_strdup_printf("-accel kvm%s -accel tcg%s%s "
566                                  "-name source,debug-threads=on "
567                                  "-m %s "
568                                  "-serial file:%s/src_serial "
569                                  "%s %s %s %s",
570                                  args->use_dirty_ring ?
571                                  ",dirty-ring-size=4096" : "",
572                                  machine_opts ? " -machine " : "",
573                                  machine_opts ? machine_opts : "",
574                                  memory_size, tmpfs,
575                                  arch_source, shmem_opts,
576                                  args->opts_source ? args->opts_source : "",
577                                  ignore_stderr);
578     if (!args->only_target) {
579         *from = qtest_init(cmd_source);
580     }
581 
582     cmd_target = g_strdup_printf("-accel kvm%s -accel tcg%s%s "
583                                  "-name target,debug-threads=on "
584                                  "-m %s "
585                                  "-serial file:%s/dest_serial "
586                                  "-incoming %s "
587                                  "%s %s %s %s",
588                                  args->use_dirty_ring ?
589                                  ",dirty-ring-size=4096" : "",
590                                  machine_opts ? " -machine " : "",
591                                  machine_opts ? machine_opts : "",
592                                  memory_size, tmpfs, uri,
593                                  arch_target, shmem_opts,
594                                  args->opts_target ? args->opts_target : "",
595                                  ignore_stderr);
596     *to = qtest_init(cmd_target);
597 
598     /*
599      * Remove shmem file immediately to avoid memory leak in test failed case.
600      * It's valid becase QEMU has already opened this file
601      */
602     if (args->use_shmem) {
603         unlink(shmem_path);
604     }
605 
606     return 0;
607 }
608 
609 static void test_migrate_end(QTestState *from, QTestState *to, bool test_dest)
610 {
611     unsigned char dest_byte_a, dest_byte_b, dest_byte_c, dest_byte_d;
612 
613     qtest_quit(from);
614 
615     if (test_dest) {
616         qtest_memread(to, start_address, &dest_byte_a, 1);
617 
618         /* Destination still running, wait for a byte to change */
619         do {
620             qtest_memread(to, start_address, &dest_byte_b, 1);
621             usleep(1000 * 10);
622         } while (dest_byte_a == dest_byte_b);
623 
624         qtest_qmp_discard_response(to, "{ 'execute' : 'stop'}");
625 
626         /* With it stopped, check nothing changes */
627         qtest_memread(to, start_address, &dest_byte_c, 1);
628         usleep(1000 * 200);
629         qtest_memread(to, start_address, &dest_byte_d, 1);
630         g_assert_cmpint(dest_byte_c, ==, dest_byte_d);
631 
632         check_guests_ram(to);
633     }
634 
635     qtest_quit(to);
636 
637     cleanup("bootsect");
638     cleanup("migsocket");
639     cleanup("src_serial");
640     cleanup("dest_serial");
641 }
642 
643 static int migrate_postcopy_prepare(QTestState **from_ptr,
644                                     QTestState **to_ptr,
645                                     MigrateStart *args)
646 {
647     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
648     QTestState *from, *to;
649 
650     if (test_migrate_start(&from, &to, uri, args)) {
651         return -1;
652     }
653 
654     migrate_set_capability(from, "postcopy-ram", true);
655     migrate_set_capability(to, "postcopy-ram", true);
656     migrate_set_capability(to, "postcopy-blocktime", true);
657 
658     /* We want to pick a speed slow enough that the test completes
659      * quickly, but that it doesn't complete precopy even on a slow
660      * machine, so also set the downtime.
661      */
662     migrate_set_parameter_int(from, "max-bandwidth", 30000000);
663     migrate_set_parameter_int(from, "downtime-limit", 1);
664 
665     /* Wait for the first serial output from the source */
666     wait_for_serial("src_serial");
667 
668     migrate_qmp(from, uri, "{}");
669 
670     wait_for_migration_pass(from);
671 
672     *from_ptr = from;
673     *to_ptr = to;
674 
675     return 0;
676 }
677 
678 static void migrate_postcopy_complete(QTestState *from, QTestState *to)
679 {
680     wait_for_migration_complete(from);
681 
682     /* Make sure we get at least one "B" on destination */
683     wait_for_serial("dest_serial");
684 
685     if (uffd_feature_thread_id) {
686         read_blocktime(to);
687     }
688 
689     test_migrate_end(from, to, true);
690 }
691 
692 static void test_postcopy(void)
693 {
694     MigrateStart args = {};
695     QTestState *from, *to;
696 
697     if (migrate_postcopy_prepare(&from, &to, &args)) {
698         return;
699     }
700     migrate_postcopy_start(from, to);
701     migrate_postcopy_complete(from, to);
702 }
703 
704 static void test_postcopy_recovery(void)
705 {
706     MigrateStart args = {
707         .hide_stderr = true,
708     };
709     QTestState *from, *to;
710     g_autofree char *uri = NULL;
711 
712     if (migrate_postcopy_prepare(&from, &to, &args)) {
713         return;
714     }
715 
716     /* Turn postcopy speed down, 4K/s is slow enough on any machines */
717     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 4096);
718 
719     /* Now we start the postcopy */
720     migrate_postcopy_start(from, to);
721 
722     /*
723      * Wait until postcopy is really started; we can only run the
724      * migrate-pause command during a postcopy
725      */
726     wait_for_migration_status(from, "postcopy-active", NULL);
727 
728     /*
729      * Manually stop the postcopy migration. This emulates a network
730      * failure with the migration socket
731      */
732     migrate_pause(from);
733 
734     /*
735      * Wait for destination side to reach postcopy-paused state.  The
736      * migrate-recover command can only succeed if destination machine
737      * is in the paused state
738      */
739     wait_for_migration_status(to, "postcopy-paused",
740                               (const char * []) { "failed", "active",
741                                                   "completed", NULL });
742 
743     /*
744      * Create a new socket to emulate a new channel that is different
745      * from the broken migration channel; tell the destination to
746      * listen to the new port
747      */
748     uri = g_strdup_printf("unix:%s/migsocket-recover", tmpfs);
749     migrate_recover(to, uri);
750 
751     /*
752      * Try to rebuild the migration channel using the resume flag and
753      * the newly created channel
754      */
755     wait_for_migration_status(from, "postcopy-paused",
756                               (const char * []) { "failed", "active",
757                                                   "completed", NULL });
758     migrate_qmp(from, uri, "{'resume': true}");
759 
760     /* Restore the postcopy bandwidth to unlimited */
761     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 0);
762 
763     migrate_postcopy_complete(from, to);
764 }
765 
766 static void test_baddest(void)
767 {
768     MigrateStart args = {
769         .hide_stderr = true
770     };
771     QTestState *from, *to;
772 
773     if (test_migrate_start(&from, &to, "tcp:127.0.0.1:0", &args)) {
774         return;
775     }
776     migrate_qmp(from, "tcp:127.0.0.1:0", "{}");
777     wait_for_migration_fail(from, false);
778     test_migrate_end(from, to, false);
779 }
780 
781 /*
782  * A hook that runs after the src and dst QEMUs have been
783  * created, but before the migration is started. This can
784  * be used to set migration parameters and capabilities.
785  *
786  * Returns: NULL, or a pointer to opaque state to be
787  *          later passed to the TestMigrateFinishHook
788  */
789 typedef void * (*TestMigrateStartHook)(QTestState *from,
790                                        QTestState *to);
791 
792 /*
793  * A hook that runs after the migration has finished,
794  * regardless of whether it succeeded or failed, but
795  * before QEMU has terminated (unless it self-terminated
796  * due to migration error)
797  *
798  * @opaque is a pointer to state previously returned
799  * by the TestMigrateStartHook if any, or NULL.
800  */
801 typedef void (*TestMigrateFinishHook)(QTestState *from,
802                                       QTestState *to,
803                                       void *opaque);
804 
805 typedef struct {
806     /* Optional: fine tune start parameters */
807     MigrateStart start;
808 
809     /* Required: the URI for the dst QEMU to listen on */
810     const char *listen_uri;
811 
812     /*
813      * Optional: the URI for the src QEMU to connect to
814      * If NULL, then it will query the dst QEMU for its actual
815      * listening address and use that as the connect address.
816      * This allows for dynamically picking a free TCP port.
817      */
818     const char *connect_uri;
819 
820     /* Optional: callback to run at start to set migration parameters */
821     TestMigrateStartHook start_hook;
822     /* Optional: callback to run at finish to cleanup */
823     TestMigrateFinishHook finish_hook;
824 
825     /*
826      * Optional: normally we expect the migration process to complete.
827      *
828      * There can be a variety of reasons and stages in which failure
829      * can happen during tests.
830      *
831      * If a failure is expected to happen at time of establishing
832      * the connection, then MIG_TEST_FAIL will indicate that the dst
833      * QEMU is expected to stay running and accept future migration
834      * connections.
835      *
836      * If a failure is expected to happen while processing the
837      * migration stream, then MIG_TEST_FAIL_DEST_QUIT_ERR will indicate
838      * that the dst QEMU is expected to quit with non-zero exit status
839      */
840     enum {
841         /* This test should succeed, the default */
842         MIG_TEST_SUCCEED = 0,
843         /* This test should fail, dest qemu should keep alive */
844         MIG_TEST_FAIL,
845         /* This test should fail, dest qemu should fail with abnormal status */
846         MIG_TEST_FAIL_DEST_QUIT_ERR,
847     } result;
848 } MigrateCommon;
849 
850 static void test_precopy_common(MigrateCommon *args)
851 {
852     QTestState *from, *to;
853     void *data_hook = NULL;
854 
855     if (test_migrate_start(&from, &to, args->listen_uri, &args->start)) {
856         return;
857     }
858 
859     /*
860      * We want to pick a speed slow enough that the test completes
861      * quickly, but that it doesn't complete precopy even on a slow
862      * machine, so also set the downtime.
863      */
864     /* 1 ms should make it not converge*/
865     migrate_set_parameter_int(from, "downtime-limit", 1);
866     /* 1GB/s */
867     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
868 
869     if (args->start_hook) {
870         data_hook = args->start_hook(from, to);
871     }
872 
873     /* Wait for the first serial output from the source */
874     wait_for_serial("src_serial");
875 
876     if (!args->connect_uri) {
877         g_autofree char *local_connect_uri =
878             migrate_get_socket_address(to, "socket-address");
879         migrate_qmp(from, local_connect_uri, "{}");
880     } else {
881         migrate_qmp(from, args->connect_uri, "{}");
882     }
883 
884 
885     if (args->result != MIG_TEST_SUCCEED) {
886         bool allow_active = args->result == MIG_TEST_FAIL;
887         wait_for_migration_fail(from, allow_active);
888 
889         if (args->result == MIG_TEST_FAIL_DEST_QUIT_ERR) {
890             qtest_set_expected_status(to, 1);
891         }
892     } else {
893         wait_for_migration_pass(from);
894 
895         migrate_set_parameter_int(from, "downtime-limit", CONVERGE_DOWNTIME);
896 
897         if (!got_stop) {
898             qtest_qmp_eventwait(from, "STOP");
899         }
900 
901         qtest_qmp_eventwait(to, "RESUME");
902 
903         wait_for_serial("dest_serial");
904         wait_for_migration_complete(from);
905     }
906 
907     if (args->finish_hook) {
908         args->finish_hook(from, to, data_hook);
909     }
910 
911     test_migrate_end(from, to, args->result == MIG_TEST_SUCCEED);
912 }
913 
914 static void test_precopy_unix(void)
915 {
916     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
917     MigrateCommon args = {
918         .listen_uri = uri,
919         .connect_uri = uri,
920     };
921 
922     test_precopy_common(&args);
923 }
924 
925 static void test_precopy_unix_dirty_ring(void)
926 {
927     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
928     MigrateCommon args = {
929         .start = {
930             .use_dirty_ring = true,
931         },
932         .listen_uri = uri,
933         .connect_uri = uri,
934     };
935 
936     test_precopy_common(&args);
937 }
938 
939 #if 0
940 /* Currently upset on aarch64 TCG */
941 static void test_ignore_shared(void)
942 {
943     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
944     QTestState *from, *to;
945 
946     if (test_migrate_start(&from, &to, uri, false, true, NULL, NULL)) {
947         return;
948     }
949 
950     migrate_set_capability(from, "x-ignore-shared", true);
951     migrate_set_capability(to, "x-ignore-shared", true);
952 
953     /* Wait for the first serial output from the source */
954     wait_for_serial("src_serial");
955 
956     migrate_qmp(from, uri, "{}");
957 
958     wait_for_migration_pass(from);
959 
960     if (!got_stop) {
961         qtest_qmp_eventwait(from, "STOP");
962     }
963 
964     qtest_qmp_eventwait(to, "RESUME");
965 
966     wait_for_serial("dest_serial");
967     wait_for_migration_complete(from);
968 
969     /* Check whether shared RAM has been really skipped */
970     g_assert_cmpint(read_ram_property_int(from, "transferred"), <, 1024 * 1024);
971 
972     test_migrate_end(from, to, true);
973 }
974 #endif
975 
976 static void test_xbzrle(const char *uri)
977 {
978     MigrateStart args = {};
979     QTestState *from, *to;
980 
981     if (test_migrate_start(&from, &to, uri, &args)) {
982         return;
983     }
984 
985     /*
986      * We want to pick a speed slow enough that the test completes
987      * quickly, but that it doesn't complete precopy even on a slow
988      * machine, so also set the downtime.
989      */
990     /* 1 ms should make it not converge*/
991     migrate_set_parameter_int(from, "downtime-limit", 1);
992     /* 1GB/s */
993     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
994 
995     migrate_set_parameter_int(from, "xbzrle-cache-size", 33554432);
996 
997     migrate_set_capability(from, "xbzrle", true);
998     migrate_set_capability(to, "xbzrle", true);
999     /* Wait for the first serial output from the source */
1000     wait_for_serial("src_serial");
1001 
1002     migrate_qmp(from, uri, "{}");
1003 
1004     wait_for_migration_pass(from);
1005     /* Make sure we have 2 passes, so the xbzrle cache gets a workout */
1006     wait_for_migration_pass(from);
1007 
1008     /* 1000ms should converge */
1009     migrate_set_parameter_int(from, "downtime-limit", 1000);
1010 
1011     if (!got_stop) {
1012         qtest_qmp_eventwait(from, "STOP");
1013     }
1014     qtest_qmp_eventwait(to, "RESUME");
1015 
1016     wait_for_serial("dest_serial");
1017     wait_for_migration_complete(from);
1018 
1019     test_migrate_end(from, to, true);
1020 }
1021 
1022 static void test_xbzrle_unix(void)
1023 {
1024     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1025 
1026     test_xbzrle(uri);
1027 }
1028 
1029 static void test_precopy_tcp(void)
1030 {
1031     MigrateCommon args = {
1032         .listen_uri = "tcp:127.0.0.1:0",
1033     };
1034 
1035     test_precopy_common(&args);
1036 }
1037 
1038 static void *test_migrate_fd_start_hook(QTestState *from,
1039                                         QTestState *to)
1040 {
1041     QDict *rsp;
1042     int ret;
1043     int pair[2];
1044 
1045     /* Create two connected sockets for migration */
1046     ret = socketpair(PF_LOCAL, SOCK_STREAM, 0, pair);
1047     g_assert_cmpint(ret, ==, 0);
1048 
1049     /* Send the 1st socket to the target */
1050     rsp = wait_command_fd(to, pair[0],
1051                           "{ 'execute': 'getfd',"
1052                           "  'arguments': { 'fdname': 'fd-mig' }}");
1053     qobject_unref(rsp);
1054     close(pair[0]);
1055 
1056     /* Start incoming migration from the 1st socket */
1057     rsp = wait_command(to, "{ 'execute': 'migrate-incoming',"
1058                            "  'arguments': { 'uri': 'fd:fd-mig' }}");
1059     qobject_unref(rsp);
1060 
1061     /* Send the 2nd socket to the target */
1062     rsp = wait_command_fd(from, pair[1],
1063                           "{ 'execute': 'getfd',"
1064                           "  'arguments': { 'fdname': 'fd-mig' }}");
1065     qobject_unref(rsp);
1066     close(pair[1]);
1067 
1068     return NULL;
1069 }
1070 
1071 static void test_migrate_fd_finish_hook(QTestState *from,
1072                                         QTestState *to,
1073                                         void *opaque)
1074 {
1075     QDict *rsp;
1076     const char *error_desc;
1077 
1078     /* Test closing fds */
1079     /* We assume, that QEMU removes named fd from its list,
1080      * so this should fail */
1081     rsp = qtest_qmp(from, "{ 'execute': 'closefd',"
1082                           "  'arguments': { 'fdname': 'fd-mig' }}");
1083     g_assert_true(qdict_haskey(rsp, "error"));
1084     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
1085     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
1086     qobject_unref(rsp);
1087 
1088     rsp = qtest_qmp(to, "{ 'execute': 'closefd',"
1089                         "  'arguments': { 'fdname': 'fd-mig' }}");
1090     g_assert_true(qdict_haskey(rsp, "error"));
1091     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
1092     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
1093     qobject_unref(rsp);
1094 }
1095 
1096 static void test_migrate_fd_proto(void)
1097 {
1098     MigrateCommon args = {
1099         .listen_uri = "defer",
1100         .connect_uri = "fd:fd-mig",
1101         .start_hook = test_migrate_fd_start_hook,
1102         .finish_hook = test_migrate_fd_finish_hook
1103     };
1104     test_precopy_common(&args);
1105 }
1106 
1107 static void do_test_validate_uuid(MigrateStart *args, bool should_fail)
1108 {
1109     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1110     QTestState *from, *to;
1111 
1112     if (test_migrate_start(&from, &to, uri, args)) {
1113         return;
1114     }
1115 
1116     /*
1117      * UUID validation is at the begin of migration. So, the main process of
1118      * migration is not interesting for us here. Thus, set huge downtime for
1119      * very fast migration.
1120      */
1121     migrate_set_parameter_int(from, "downtime-limit", 1000000);
1122     migrate_set_capability(from, "validate-uuid", true);
1123 
1124     /* Wait for the first serial output from the source */
1125     wait_for_serial("src_serial");
1126 
1127     migrate_qmp(from, uri, "{}");
1128 
1129     if (should_fail) {
1130         qtest_set_expected_status(to, 1);
1131         wait_for_migration_fail(from, true);
1132     } else {
1133         wait_for_migration_complete(from);
1134     }
1135 
1136     test_migrate_end(from, to, false);
1137 }
1138 
1139 static void test_validate_uuid(void)
1140 {
1141     MigrateStart args = {
1142         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
1143         .opts_target = "-uuid 11111111-1111-1111-1111-111111111111",
1144     };
1145 
1146     do_test_validate_uuid(&args, false);
1147 }
1148 
1149 static void test_validate_uuid_error(void)
1150 {
1151     MigrateStart args = {
1152         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
1153         .opts_target = "-uuid 22222222-2222-2222-2222-222222222222",
1154         .hide_stderr = true,
1155     };
1156 
1157     do_test_validate_uuid(&args, true);
1158 }
1159 
1160 static void test_validate_uuid_src_not_set(void)
1161 {
1162     MigrateStart args = {
1163         .opts_target = "-uuid 22222222-2222-2222-2222-222222222222",
1164         .hide_stderr = true,
1165     };
1166 
1167     do_test_validate_uuid(&args, false);
1168 }
1169 
1170 static void test_validate_uuid_dst_not_set(void)
1171 {
1172     MigrateStart args = {
1173         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
1174         .hide_stderr = true,
1175     };
1176 
1177     do_test_validate_uuid(&args, false);
1178 }
1179 
1180 static void test_migrate_auto_converge(void)
1181 {
1182     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1183     MigrateStart args = {};
1184     QTestState *from, *to;
1185     int64_t remaining, percentage;
1186 
1187     /*
1188      * We want the test to be stable and as fast as possible.
1189      * E.g., with 1Gb/s bandwith migration may pass without throttling,
1190      * so we need to decrease a bandwidth.
1191      */
1192     const int64_t init_pct = 5, inc_pct = 50, max_pct = 95;
1193     const int64_t max_bandwidth = 400000000; /* ~400Mb/s */
1194     const int64_t downtime_limit = 250; /* 250ms */
1195     /*
1196      * We migrate through unix-socket (> 500Mb/s).
1197      * Thus, expected migration speed ~= bandwidth limit (< 500Mb/s).
1198      * So, we can predict expected_threshold
1199      */
1200     const int64_t expected_threshold = max_bandwidth * downtime_limit / 1000;
1201 
1202     if (test_migrate_start(&from, &to, uri, &args)) {
1203         return;
1204     }
1205 
1206     migrate_set_capability(from, "auto-converge", true);
1207     migrate_set_parameter_int(from, "cpu-throttle-initial", init_pct);
1208     migrate_set_parameter_int(from, "cpu-throttle-increment", inc_pct);
1209     migrate_set_parameter_int(from, "max-cpu-throttle", max_pct);
1210 
1211     /*
1212      * Set the initial parameters so that the migration could not converge
1213      * without throttling.
1214      */
1215     migrate_set_parameter_int(from, "downtime-limit", 1);
1216     migrate_set_parameter_int(from, "max-bandwidth", 100000000); /* ~100Mb/s */
1217 
1218     /* To check remaining size after precopy */
1219     migrate_set_capability(from, "pause-before-switchover", true);
1220 
1221     /* Wait for the first serial output from the source */
1222     wait_for_serial("src_serial");
1223 
1224     migrate_qmp(from, uri, "{}");
1225 
1226     /* Wait for throttling begins */
1227     percentage = 0;
1228     while (percentage == 0) {
1229         percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
1230         usleep(100);
1231         g_assert_false(got_stop);
1232     }
1233     /* The first percentage of throttling should be equal to init_pct */
1234     g_assert_cmpint(percentage, ==, init_pct);
1235     /* Now, when we tested that throttling works, let it converge */
1236     migrate_set_parameter_int(from, "downtime-limit", downtime_limit);
1237     migrate_set_parameter_int(from, "max-bandwidth", max_bandwidth);
1238 
1239     /*
1240      * Wait for pre-switchover status to check last throttle percentage
1241      * and remaining. These values will be zeroed later
1242      */
1243     wait_for_migration_status(from, "pre-switchover", NULL);
1244 
1245     /* The final percentage of throttling shouldn't be greater than max_pct */
1246     percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
1247     g_assert_cmpint(percentage, <=, max_pct);
1248 
1249     remaining = read_ram_property_int(from, "remaining");
1250     g_assert_cmpint(remaining, <,
1251                     (expected_threshold + expected_threshold / 100));
1252 
1253     migrate_continue(from, "pre-switchover");
1254 
1255     qtest_qmp_eventwait(to, "RESUME");
1256 
1257     wait_for_serial("dest_serial");
1258     wait_for_migration_complete(from);
1259 
1260 
1261     test_migrate_end(from, to, true);
1262 }
1263 
1264 static void test_multifd_tcp(const char *method)
1265 {
1266     MigrateStart args = {};
1267     QTestState *from, *to;
1268     QDict *rsp;
1269     g_autofree char *uri = NULL;
1270 
1271     if (test_migrate_start(&from, &to, "defer", &args)) {
1272         return;
1273     }
1274 
1275     /*
1276      * We want to pick a speed slow enough that the test completes
1277      * quickly, but that it doesn't complete precopy even on a slow
1278      * machine, so also set the downtime.
1279      */
1280     /* 1 ms should make it not converge*/
1281     migrate_set_parameter_int(from, "downtime-limit", 1);
1282     /* 1GB/s */
1283     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
1284 
1285     migrate_set_parameter_int(from, "multifd-channels", 16);
1286     migrate_set_parameter_int(to, "multifd-channels", 16);
1287 
1288     migrate_set_parameter_str(from, "multifd-compression", method);
1289     migrate_set_parameter_str(to, "multifd-compression", method);
1290 
1291     migrate_set_capability(from, "multifd", true);
1292     migrate_set_capability(to, "multifd", true);
1293 
1294     /* Start incoming migration from the 1st socket */
1295     rsp = wait_command(to, "{ 'execute': 'migrate-incoming',"
1296                            "  'arguments': { 'uri': 'tcp:127.0.0.1:0' }}");
1297     qobject_unref(rsp);
1298 
1299     /* Wait for the first serial output from the source */
1300     wait_for_serial("src_serial");
1301 
1302     uri = migrate_get_socket_address(to, "socket-address");
1303 
1304     migrate_qmp(from, uri, "{}");
1305 
1306     wait_for_migration_pass(from);
1307 
1308     migrate_set_parameter_int(from, "downtime-limit", CONVERGE_DOWNTIME);
1309 
1310     if (!got_stop) {
1311         qtest_qmp_eventwait(from, "STOP");
1312     }
1313     qtest_qmp_eventwait(to, "RESUME");
1314 
1315     wait_for_serial("dest_serial");
1316     wait_for_migration_complete(from);
1317     test_migrate_end(from, to, true);
1318 }
1319 
1320 static void test_multifd_tcp_none(void)
1321 {
1322     test_multifd_tcp("none");
1323 }
1324 
1325 static void test_multifd_tcp_zlib(void)
1326 {
1327     test_multifd_tcp("zlib");
1328 }
1329 
1330 #ifdef CONFIG_ZSTD
1331 static void test_multifd_tcp_zstd(void)
1332 {
1333     test_multifd_tcp("zstd");
1334 }
1335 #endif
1336 
1337 /*
1338  * This test does:
1339  *  source               target
1340  *                       migrate_incoming
1341  *     migrate
1342  *     migrate_cancel
1343  *                       launch another target
1344  *     migrate
1345  *
1346  *  And see that it works
1347  */
1348 static void test_multifd_tcp_cancel(void)
1349 {
1350     MigrateStart args = {
1351         .hide_stderr = true,
1352     };
1353     QTestState *from, *to, *to2;
1354     QDict *rsp;
1355     g_autofree char *uri = NULL;
1356 
1357     if (test_migrate_start(&from, &to, "defer", &args)) {
1358         return;
1359     }
1360 
1361     /*
1362      * We want to pick a speed slow enough that the test completes
1363      * quickly, but that it doesn't complete precopy even on a slow
1364      * machine, so also set the downtime.
1365      */
1366     /* 1 ms should make it not converge*/
1367     migrate_set_parameter_int(from, "downtime-limit", 1);
1368     /* 300MB/s */
1369     migrate_set_parameter_int(from, "max-bandwidth", 30000000);
1370 
1371     migrate_set_parameter_int(from, "multifd-channels", 16);
1372     migrate_set_parameter_int(to, "multifd-channels", 16);
1373 
1374     migrate_set_capability(from, "multifd", true);
1375     migrate_set_capability(to, "multifd", true);
1376 
1377     /* Start incoming migration from the 1st socket */
1378     rsp = wait_command(to, "{ 'execute': 'migrate-incoming',"
1379                            "  'arguments': { 'uri': 'tcp:127.0.0.1:0' }}");
1380     qobject_unref(rsp);
1381 
1382     /* Wait for the first serial output from the source */
1383     wait_for_serial("src_serial");
1384 
1385     uri = migrate_get_socket_address(to, "socket-address");
1386 
1387     migrate_qmp(from, uri, "{}");
1388 
1389     wait_for_migration_pass(from);
1390 
1391     migrate_cancel(from);
1392 
1393     args = (MigrateStart){
1394         .only_target = true,
1395     };
1396 
1397     if (test_migrate_start(&from, &to2, "defer", &args)) {
1398         return;
1399     }
1400 
1401     migrate_set_parameter_int(to2, "multifd-channels", 16);
1402 
1403     migrate_set_capability(to2, "multifd", true);
1404 
1405     /* Start incoming migration from the 1st socket */
1406     rsp = wait_command(to2, "{ 'execute': 'migrate-incoming',"
1407                             "  'arguments': { 'uri': 'tcp:127.0.0.1:0' }}");
1408     qobject_unref(rsp);
1409 
1410     g_free(uri);
1411     uri = migrate_get_socket_address(to2, "socket-address");
1412 
1413     wait_for_migration_status(from, "cancelled", NULL);
1414 
1415     /* 300ms it should converge */
1416     migrate_set_parameter_int(from, "downtime-limit", 300);
1417     /* 1GB/s */
1418     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
1419 
1420     migrate_qmp(from, uri, "{}");
1421 
1422     wait_for_migration_pass(from);
1423 
1424     if (!got_stop) {
1425         qtest_qmp_eventwait(from, "STOP");
1426     }
1427     qtest_qmp_eventwait(to2, "RESUME");
1428 
1429     wait_for_serial("dest_serial");
1430     wait_for_migration_complete(from);
1431     test_migrate_end(from, to2, true);
1432 }
1433 
1434 static bool kvm_dirty_ring_supported(void)
1435 {
1436 #if defined(__linux__) && defined(HOST_X86_64)
1437     int ret, kvm_fd = open("/dev/kvm", O_RDONLY);
1438 
1439     if (kvm_fd < 0) {
1440         return false;
1441     }
1442 
1443     ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING);
1444     close(kvm_fd);
1445 
1446     /* We test with 4096 slots */
1447     if (ret < 4096) {
1448         return false;
1449     }
1450 
1451     return true;
1452 #else
1453     return false;
1454 #endif
1455 }
1456 
1457 int main(int argc, char **argv)
1458 {
1459     char template[] = "/tmp/migration-test-XXXXXX";
1460     const bool has_kvm = qtest_has_accel("kvm");
1461     int ret;
1462 
1463     g_test_init(&argc, &argv, NULL);
1464 
1465     if (!ufd_version_check()) {
1466         return g_test_run();
1467     }
1468 
1469     /*
1470      * On ppc64, the test only works with kvm-hv, but not with kvm-pr and TCG
1471      * is touchy due to race conditions on dirty bits (especially on PPC for
1472      * some reason)
1473      */
1474     if (g_str_equal(qtest_get_arch(), "ppc64") &&
1475         (!has_kvm || access("/sys/module/kvm_hv", F_OK))) {
1476         g_test_message("Skipping test: kvm_hv not available");
1477         return g_test_run();
1478     }
1479 
1480     /*
1481      * Similar to ppc64, s390x seems to be touchy with TCG, so disable it
1482      * there until the problems are resolved
1483      */
1484     if (g_str_equal(qtest_get_arch(), "s390x") && !has_kvm) {
1485         g_test_message("Skipping test: s390x host with KVM is required");
1486         return g_test_run();
1487     }
1488 
1489     tmpfs = mkdtemp(template);
1490     if (!tmpfs) {
1491         g_test_message("mkdtemp on path (%s): %s", template, strerror(errno));
1492     }
1493     g_assert(tmpfs);
1494 
1495     module_call_init(MODULE_INIT_QOM);
1496 
1497     qtest_add_func("/migration/postcopy/unix", test_postcopy);
1498     qtest_add_func("/migration/postcopy/recovery", test_postcopy_recovery);
1499     qtest_add_func("/migration/bad_dest", test_baddest);
1500     qtest_add_func("/migration/precopy/unix", test_precopy_unix);
1501     qtest_add_func("/migration/precopy/tcp", test_precopy_tcp);
1502     /* qtest_add_func("/migration/ignore_shared", test_ignore_shared); */
1503     qtest_add_func("/migration/xbzrle/unix", test_xbzrle_unix);
1504     qtest_add_func("/migration/fd_proto", test_migrate_fd_proto);
1505     qtest_add_func("/migration/validate_uuid", test_validate_uuid);
1506     qtest_add_func("/migration/validate_uuid_error", test_validate_uuid_error);
1507     qtest_add_func("/migration/validate_uuid_src_not_set",
1508                    test_validate_uuid_src_not_set);
1509     qtest_add_func("/migration/validate_uuid_dst_not_set",
1510                    test_validate_uuid_dst_not_set);
1511 
1512     qtest_add_func("/migration/auto_converge", test_migrate_auto_converge);
1513     qtest_add_func("/migration/multifd/tcp/none", test_multifd_tcp_none);
1514     qtest_add_func("/migration/multifd/tcp/cancel", test_multifd_tcp_cancel);
1515     qtest_add_func("/migration/multifd/tcp/zlib", test_multifd_tcp_zlib);
1516 #ifdef CONFIG_ZSTD
1517     qtest_add_func("/migration/multifd/tcp/zstd", test_multifd_tcp_zstd);
1518 #endif
1519 
1520     if (kvm_dirty_ring_supported()) {
1521         qtest_add_func("/migration/dirty_ring",
1522                        test_precopy_unix_dirty_ring);
1523     }
1524 
1525     ret = g_test_run();
1526 
1527     g_assert_cmpint(ret, ==, 0);
1528 
1529     ret = rmdir(tmpfs);
1530     if (ret != 0) {
1531         g_test_message("unable to rmdir: path (%s): %s",
1532                        tmpfs, strerror(errno));
1533     }
1534 
1535     return ret;
1536 }
1537