xref: /qemu/tests/qtest/migration-test.c (revision f0649758)
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 "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 #include "crypto/tlscredspsk.h"
27 #include "qapi/qmp/qlist.h"
28 
29 #include "migration-helpers.h"
30 #include "tests/migration/migration-test.h"
31 #ifdef CONFIG_GNUTLS
32 # include "tests/unit/crypto-tls-psk-helpers.h"
33 # ifdef CONFIG_TASN1
34 #  include "tests/unit/crypto-tls-x509-helpers.h"
35 # endif /* CONFIG_TASN1 */
36 #endif /* CONFIG_GNUTLS */
37 
38 /* For dirty ring test; so far only x86_64 is supported */
39 #if defined(__linux__) && defined(HOST_X86_64)
40 #include "linux/kvm.h"
41 #endif
42 
43 unsigned start_address;
44 unsigned end_address;
45 static bool uffd_feature_thread_id;
46 static QTestMigrationState src_state;
47 static QTestMigrationState dst_state;
48 
49 /*
50  * An initial 3 MB offset is used as that corresponds
51  * to ~1 sec of data transfer with our bandwidth setting.
52  */
53 #define MAGIC_OFFSET_BASE (3 * 1024 * 1024)
54 /*
55  * A further 1k is added to ensure we're not a multiple
56  * of TEST_MEM_PAGE_SIZE, thus avoid clash with writes
57  * from the migration guest workload.
58  */
59 #define MAGIC_OFFSET_SHUFFLE 1024
60 #define MAGIC_OFFSET (MAGIC_OFFSET_BASE + MAGIC_OFFSET_SHUFFLE)
61 #define MAGIC_MARKER 0xFEED12345678CAFEULL
62 
63 /*
64  * Dirtylimit stop working if dirty page rate error
65  * value less than DIRTYLIMIT_TOLERANCE_RANGE
66  */
67 #define DIRTYLIMIT_TOLERANCE_RANGE  25  /* MB/s */
68 
69 #define ANALYZE_SCRIPT "scripts/analyze-migration.py"
70 
71 #define QEMU_VM_FILE_MAGIC 0x5145564d
72 #define FILE_TEST_FILENAME "migfile"
73 #define FILE_TEST_OFFSET 0x1000
74 #define QEMU_ENV_SRC "QTEST_QEMU_BINARY_SRC"
75 #define QEMU_ENV_DST "QTEST_QEMU_BINARY_DST"
76 
77 #if defined(__linux__)
78 #include <sys/syscall.h>
79 #include <sys/vfs.h>
80 #endif
81 
82 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
83 #include <sys/eventfd.h>
84 #include <sys/ioctl.h>
85 #include "qemu/userfaultfd.h"
86 
87 static bool ufd_version_check(void)
88 {
89     struct uffdio_api api_struct;
90     uint64_t ioctl_mask;
91 
92     int ufd = uffd_open(O_CLOEXEC);
93 
94     if (ufd == -1) {
95         g_test_message("Skipping test: userfaultfd not available");
96         return false;
97     }
98 
99     api_struct.api = UFFD_API;
100     api_struct.features = 0;
101     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
102         g_test_message("Skipping test: UFFDIO_API failed");
103         return false;
104     }
105     uffd_feature_thread_id = api_struct.features & UFFD_FEATURE_THREAD_ID;
106 
107     ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
108                  (__u64)1 << _UFFDIO_UNREGISTER;
109     if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
110         g_test_message("Skipping test: Missing userfault feature");
111         return false;
112     }
113 
114     return true;
115 }
116 
117 #else
118 static bool ufd_version_check(void)
119 {
120     g_test_message("Skipping test: Userfault not available (builtdtime)");
121     return false;
122 }
123 
124 #endif
125 
126 static char *tmpfs;
127 static char *bootpath;
128 
129 /* The boot file modifies memory area in [start_address, end_address)
130  * repeatedly. It outputs a 'B' at a fixed rate while it's still running.
131  */
132 #include "tests/migration/i386/a-b-bootblock.h"
133 #include "tests/migration/aarch64/a-b-kernel.h"
134 #include "tests/migration/s390x/a-b-bios.h"
135 
136 static void bootfile_create(char *dir)
137 {
138     const char *arch = qtest_get_arch();
139     unsigned char *content;
140     size_t len;
141 
142     bootpath = g_strdup_printf("%s/bootsect", dir);
143     if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) {
144         /* the assembled x86 boot sector should be exactly one sector large */
145         g_assert(sizeof(x86_bootsect) == 512);
146         content = x86_bootsect;
147         len = sizeof(x86_bootsect);
148     } else if (g_str_equal(arch, "s390x")) {
149         content = s390x_elf;
150         len = sizeof(s390x_elf);
151     } else if (strcmp(arch, "ppc64") == 0) {
152         /*
153          * sane architectures can be programmed at the boot prompt
154          */
155         return;
156     } else if (strcmp(arch, "aarch64") == 0) {
157         content = aarch64_kernel;
158         len = sizeof(aarch64_kernel);
159         g_assert(sizeof(aarch64_kernel) <= ARM_TEST_MAX_KERNEL_SIZE);
160     } else {
161         g_assert_not_reached();
162     }
163 
164     FILE *bootfile = fopen(bootpath, "wb");
165 
166     g_assert_cmpint(fwrite(content, len, 1, bootfile), ==, 1);
167     fclose(bootfile);
168 }
169 
170 static void bootfile_delete(void)
171 {
172     unlink(bootpath);
173     g_free(bootpath);
174     bootpath = NULL;
175 }
176 
177 /*
178  * Wait for some output in the serial output file,
179  * we get an 'A' followed by an endless string of 'B's
180  * but on the destination we won't have the A.
181  */
182 static void wait_for_serial(const char *side)
183 {
184     g_autofree char *serialpath = g_strdup_printf("%s/%s", tmpfs, side);
185     FILE *serialfile = fopen(serialpath, "r");
186     const char *arch = qtest_get_arch();
187     int started = (strcmp(side, "src_serial") == 0 &&
188                    strcmp(arch, "ppc64") == 0) ? 0 : 1;
189 
190     do {
191         int readvalue = fgetc(serialfile);
192 
193         if (!started) {
194             /* SLOF prints its banner before starting test,
195              * to ignore it, mark the start of the test with '_',
196              * ignore all characters until this marker
197              */
198             switch (readvalue) {
199             case '_':
200                 started = 1;
201                 break;
202             case EOF:
203                 fseek(serialfile, 0, SEEK_SET);
204                 usleep(1000);
205                 break;
206             }
207             continue;
208         }
209         switch (readvalue) {
210         case 'A':
211             /* Fine */
212             break;
213 
214         case 'B':
215             /* It's alive! */
216             fclose(serialfile);
217             return;
218 
219         case EOF:
220             started = (strcmp(side, "src_serial") == 0 &&
221                        strcmp(arch, "ppc64") == 0) ? 0 : 1;
222             fseek(serialfile, 0, SEEK_SET);
223             usleep(1000);
224             break;
225 
226         default:
227             fprintf(stderr, "Unexpected %d on %s serial\n", readvalue, side);
228             g_assert_not_reached();
229         }
230     } while (true);
231 }
232 
233 static void wait_for_stop(QTestState *who, QTestMigrationState *state)
234 {
235     if (!state->stop_seen) {
236         qtest_qmp_eventwait(who, "STOP");
237     }
238 }
239 
240 static void wait_for_resume(QTestState *who, QTestMigrationState *state)
241 {
242     if (!state->resume_seen) {
243         qtest_qmp_eventwait(who, "RESUME");
244     }
245 }
246 
247 /*
248  * It's tricky to use qemu's migration event capability with qtest,
249  * events suddenly appearing confuse the qmp()/hmp() responses.
250  */
251 
252 static int64_t read_ram_property_int(QTestState *who, const char *property)
253 {
254     QDict *rsp_return, *rsp_ram;
255     int64_t result;
256 
257     rsp_return = migrate_query_not_failed(who);
258     if (!qdict_haskey(rsp_return, "ram")) {
259         /* Still in setup */
260         result = 0;
261     } else {
262         rsp_ram = qdict_get_qdict(rsp_return, "ram");
263         result = qdict_get_try_int(rsp_ram, property, 0);
264     }
265     qobject_unref(rsp_return);
266     return result;
267 }
268 
269 static int64_t read_migrate_property_int(QTestState *who, const char *property)
270 {
271     QDict *rsp_return;
272     int64_t result;
273 
274     rsp_return = migrate_query_not_failed(who);
275     result = qdict_get_try_int(rsp_return, property, 0);
276     qobject_unref(rsp_return);
277     return result;
278 }
279 
280 static uint64_t get_migration_pass(QTestState *who)
281 {
282     return read_ram_property_int(who, "dirty-sync-count");
283 }
284 
285 static void read_blocktime(QTestState *who)
286 {
287     QDict *rsp_return;
288 
289     rsp_return = migrate_query_not_failed(who);
290     g_assert(qdict_haskey(rsp_return, "postcopy-blocktime"));
291     qobject_unref(rsp_return);
292 }
293 
294 /*
295  * Wait for two changes in the migration pass count, but bail if we stop.
296  */
297 static void wait_for_migration_pass(QTestState *who)
298 {
299     uint64_t pass, prev_pass = 0, changes = 0;
300 
301     while (changes < 2 && !src_state.stop_seen) {
302         usleep(1000);
303         pass = get_migration_pass(who);
304         changes += (pass != prev_pass);
305         prev_pass = pass;
306     }
307 }
308 
309 static void check_guests_ram(QTestState *who)
310 {
311     /* Our ASM test will have been incrementing one byte from each page from
312      * start_address to < end_address in order. This gives us a constraint
313      * that any page's byte should be equal or less than the previous pages
314      * byte (mod 256); and they should all be equal except for one transition
315      * at the point where we meet the incrementer. (We're running this with
316      * the guest stopped).
317      */
318     unsigned address;
319     uint8_t first_byte;
320     uint8_t last_byte;
321     bool hit_edge = false;
322     int bad = 0;
323 
324     qtest_memread(who, start_address, &first_byte, 1);
325     last_byte = first_byte;
326 
327     for (address = start_address + TEST_MEM_PAGE_SIZE; address < end_address;
328          address += TEST_MEM_PAGE_SIZE)
329     {
330         uint8_t b;
331         qtest_memread(who, address, &b, 1);
332         if (b != last_byte) {
333             if (((b + 1) % 256) == last_byte && !hit_edge) {
334                 /* This is OK, the guest stopped at the point of
335                  * incrementing the previous page but didn't get
336                  * to us yet.
337                  */
338                 hit_edge = true;
339                 last_byte = b;
340             } else {
341                 bad++;
342                 if (bad <= 10) {
343                     fprintf(stderr, "Memory content inconsistency at %x"
344                             " first_byte = %x last_byte = %x current = %x"
345                             " hit_edge = %x\n",
346                             address, first_byte, last_byte, b, hit_edge);
347                 }
348             }
349         }
350     }
351     if (bad >= 10) {
352         fprintf(stderr, "and in another %d pages", bad - 10);
353     }
354     g_assert(bad == 0);
355 }
356 
357 static void cleanup(const char *filename)
358 {
359     g_autofree char *path = g_strdup_printf("%s/%s", tmpfs, filename);
360 
361     unlink(path);
362 }
363 
364 static char *SocketAddress_to_str(SocketAddress *addr)
365 {
366     switch (addr->type) {
367     case SOCKET_ADDRESS_TYPE_INET:
368         return g_strdup_printf("tcp:%s:%s",
369                                addr->u.inet.host,
370                                addr->u.inet.port);
371     case SOCKET_ADDRESS_TYPE_UNIX:
372         return g_strdup_printf("unix:%s",
373                                addr->u.q_unix.path);
374     case SOCKET_ADDRESS_TYPE_FD:
375         return g_strdup_printf("fd:%s", addr->u.fd.str);
376     case SOCKET_ADDRESS_TYPE_VSOCK:
377         return g_strdup_printf("tcp:%s:%s",
378                                addr->u.vsock.cid,
379                                addr->u.vsock.port);
380     default:
381         return g_strdup("unknown address type");
382     }
383 }
384 
385 static char *migrate_get_socket_address(QTestState *who, const char *parameter)
386 {
387     QDict *rsp;
388     char *result;
389     SocketAddressList *addrs;
390     Visitor *iv = NULL;
391     QObject *object;
392 
393     rsp = migrate_query(who);
394     object = qdict_get(rsp, parameter);
395 
396     iv = qobject_input_visitor_new(object);
397     visit_type_SocketAddressList(iv, NULL, &addrs, &error_abort);
398     visit_free(iv);
399 
400     /* we are only using a single address */
401     result = SocketAddress_to_str(addrs->value);
402 
403     qapi_free_SocketAddressList(addrs);
404     qobject_unref(rsp);
405     return result;
406 }
407 
408 static long long migrate_get_parameter_int(QTestState *who,
409                                            const char *parameter)
410 {
411     QDict *rsp;
412     long long result;
413 
414     rsp = qtest_qmp_assert_success_ref(
415         who, "{ 'execute': 'query-migrate-parameters' }");
416     result = qdict_get_int(rsp, parameter);
417     qobject_unref(rsp);
418     return result;
419 }
420 
421 static void migrate_check_parameter_int(QTestState *who, const char *parameter,
422                                         long long value)
423 {
424     long long result;
425 
426     result = migrate_get_parameter_int(who, parameter);
427     g_assert_cmpint(result, ==, value);
428 }
429 
430 static void migrate_set_parameter_int(QTestState *who, const char *parameter,
431                                       long long value)
432 {
433     qtest_qmp_assert_success(who,
434                              "{ 'execute': 'migrate-set-parameters',"
435                              "'arguments': { %s: %lld } }",
436                              parameter, value);
437     migrate_check_parameter_int(who, parameter, value);
438 }
439 
440 static char *migrate_get_parameter_str(QTestState *who,
441                                        const char *parameter)
442 {
443     QDict *rsp;
444     char *result;
445 
446     rsp = qtest_qmp_assert_success_ref(
447         who, "{ 'execute': 'query-migrate-parameters' }");
448     result = g_strdup(qdict_get_str(rsp, parameter));
449     qobject_unref(rsp);
450     return result;
451 }
452 
453 static void migrate_check_parameter_str(QTestState *who, const char *parameter,
454                                         const char *value)
455 {
456     g_autofree char *result = migrate_get_parameter_str(who, parameter);
457     g_assert_cmpstr(result, ==, value);
458 }
459 
460 static void migrate_set_parameter_str(QTestState *who, const char *parameter,
461                                       const char *value)
462 {
463     qtest_qmp_assert_success(who,
464                              "{ 'execute': 'migrate-set-parameters',"
465                              "'arguments': { %s: %s } }",
466                              parameter, value);
467     migrate_check_parameter_str(who, parameter, value);
468 }
469 
470 static long long migrate_get_parameter_bool(QTestState *who,
471                                            const char *parameter)
472 {
473     QDict *rsp;
474     int result;
475 
476     rsp = qtest_qmp_assert_success_ref(
477         who, "{ 'execute': 'query-migrate-parameters' }");
478     result = qdict_get_bool(rsp, parameter);
479     qobject_unref(rsp);
480     return !!result;
481 }
482 
483 static void migrate_check_parameter_bool(QTestState *who, const char *parameter,
484                                         int value)
485 {
486     int result;
487 
488     result = migrate_get_parameter_bool(who, parameter);
489     g_assert_cmpint(result, ==, value);
490 }
491 
492 static void migrate_set_parameter_bool(QTestState *who, const char *parameter,
493                                       int value)
494 {
495     qtest_qmp_assert_success(who,
496                              "{ 'execute': 'migrate-set-parameters',"
497                              "'arguments': { %s: %i } }",
498                              parameter, value);
499     migrate_check_parameter_bool(who, parameter, value);
500 }
501 
502 static void migrate_ensure_non_converge(QTestState *who)
503 {
504     /* Can't converge with 1ms downtime + 3 mbs bandwidth limit */
505     migrate_set_parameter_int(who, "max-bandwidth", 3 * 1000 * 1000);
506     migrate_set_parameter_int(who, "downtime-limit", 1);
507 }
508 
509 static void migrate_ensure_converge(QTestState *who)
510 {
511     /* Should converge with 30s downtime + 1 gbs bandwidth limit */
512     migrate_set_parameter_int(who, "max-bandwidth", 1 * 1000 * 1000 * 1000);
513     migrate_set_parameter_int(who, "downtime-limit", 30 * 1000);
514 }
515 
516 /*
517  * Our goal is to ensure that we run a single full migration
518  * iteration, and also dirty memory, ensuring that at least
519  * one further iteration is required.
520  *
521  * We can't directly synchronize with the start of a migration
522  * so we have to apply some tricks monitoring memory that is
523  * transferred.
524  *
525  * Initially we set the migration bandwidth to an insanely
526  * low value, with tiny max downtime too. This basically
527  * guarantees migration will never complete.
528  *
529  * This will result in a test that is unacceptably slow though,
530  * so we can't let the entire migration pass run at this speed.
531  * Our intent is to let it run just long enough that we can
532  * prove data prior to the marker has been transferred *AND*
533  * also prove this transferred data is dirty again.
534  *
535  * Before migration starts, we write a 64-bit magic marker
536  * into a fixed location in the src VM RAM.
537  *
538  * Then watch dst memory until the marker appears. This is
539  * proof that start_address -> MAGIC_OFFSET_BASE has been
540  * transferred.
541  *
542  * Finally we go back to the source and read a byte just
543  * before the marker until we see it flip in value. This
544  * is proof that start_address -> MAGIC_OFFSET_BASE
545  * is now dirty again.
546  *
547  * IOW, we're guaranteed at least a 2nd migration pass
548  * at this point.
549  *
550  * We can now let migration run at full speed to finish
551  * the test
552  */
553 static void migrate_prepare_for_dirty_mem(QTestState *from)
554 {
555     /*
556      * The guest workflow iterates from start_address to
557      * end_address, writing 1 byte every TEST_MEM_PAGE_SIZE
558      * bytes.
559      *
560      * IOW, if we write to mem at a point which is NOT
561      * a multiple of TEST_MEM_PAGE_SIZE, our write won't
562      * conflict with the migration workflow.
563      *
564      * We put in a marker here, that we'll use to determine
565      * when the data has been transferred to the dst.
566      */
567     qtest_writeq(from, start_address + MAGIC_OFFSET, MAGIC_MARKER);
568 }
569 
570 static void migrate_wait_for_dirty_mem(QTestState *from,
571                                        QTestState *to)
572 {
573     uint64_t watch_address = start_address + MAGIC_OFFSET_BASE;
574     uint64_t marker_address = start_address + MAGIC_OFFSET;
575     uint8_t watch_byte;
576 
577     /*
578      * Wait for the MAGIC_MARKER to get transferred, as an
579      * indicator that a migration pass has made some known
580      * amount of progress.
581      */
582     do {
583         usleep(1000 * 10);
584     } while (qtest_readq(to, marker_address) != MAGIC_MARKER);
585 
586     /*
587      * Now ensure that already transferred bytes are
588      * dirty again from the guest workload. Note the
589      * guest byte value will wrap around and by chance
590      * match the original watch_byte. This is harmless
591      * as we'll eventually see a different value if we
592      * keep watching
593      */
594     watch_byte = qtest_readb(from, watch_address);
595     do {
596         usleep(1000 * 10);
597     } while (qtest_readb(from, watch_address) == watch_byte);
598 }
599 
600 
601 static void migrate_pause(QTestState *who)
602 {
603     qtest_qmp_assert_success(who, "{ 'execute': 'migrate-pause' }");
604 }
605 
606 static void migrate_continue(QTestState *who, const char *state)
607 {
608     qtest_qmp_assert_success(who,
609                              "{ 'execute': 'migrate-continue',"
610                              "  'arguments': { 'state': %s } }",
611                              state);
612 }
613 
614 static void migrate_recover(QTestState *who, const char *uri)
615 {
616     qtest_qmp_assert_success(who,
617                              "{ 'execute': 'migrate-recover', "
618                              "  'id': 'recover-cmd', "
619                              "  'arguments': { 'uri': %s } }",
620                              uri);
621 }
622 
623 static void migrate_cancel(QTestState *who)
624 {
625     qtest_qmp_assert_success(who, "{ 'execute': 'migrate_cancel' }");
626 }
627 
628 static void migrate_postcopy_start(QTestState *from, QTestState *to)
629 {
630     qtest_qmp_assert_success(from, "{ 'execute': 'migrate-start-postcopy' }");
631 
632     wait_for_stop(from, &src_state);
633     qtest_qmp_eventwait(to, "RESUME");
634 }
635 
636 typedef struct {
637     /*
638      * QTEST_LOG=1 may override this.  When QTEST_LOG=1, we always dump errors
639      * unconditionally, because it means the user would like to be verbose.
640      */
641     bool hide_stderr;
642     bool use_shmem;
643     /* only launch the target process */
644     bool only_target;
645     /* Use dirty ring if true; dirty logging otherwise */
646     bool use_dirty_ring;
647     const char *opts_source;
648     const char *opts_target;
649 } MigrateStart;
650 
651 /*
652  * A hook that runs after the src and dst QEMUs have been
653  * created, but before the migration is started. This can
654  * be used to set migration parameters and capabilities.
655  *
656  * Returns: NULL, or a pointer to opaque state to be
657  *          later passed to the TestMigrateFinishHook
658  */
659 typedef void * (*TestMigrateStartHook)(QTestState *from,
660                                        QTestState *to);
661 
662 /*
663  * A hook that runs after the migration has finished,
664  * regardless of whether it succeeded or failed, but
665  * before QEMU has terminated (unless it self-terminated
666  * due to migration error)
667  *
668  * @opaque is a pointer to state previously returned
669  * by the TestMigrateStartHook if any, or NULL.
670  */
671 typedef void (*TestMigrateFinishHook)(QTestState *from,
672                                       QTestState *to,
673                                       void *opaque);
674 
675 typedef struct {
676     /* Optional: fine tune start parameters */
677     MigrateStart start;
678 
679     /* Required: the URI for the dst QEMU to listen on */
680     const char *listen_uri;
681 
682     /*
683      * Optional: the URI for the src QEMU to connect to
684      * If NULL, then it will query the dst QEMU for its actual
685      * listening address and use that as the connect address.
686      * This allows for dynamically picking a free TCP port.
687      */
688     const char *connect_uri;
689 
690     /* Optional: callback to run at start to set migration parameters */
691     TestMigrateStartHook start_hook;
692     /* Optional: callback to run at finish to cleanup */
693     TestMigrateFinishHook finish_hook;
694 
695     /*
696      * Optional: normally we expect the migration process to complete.
697      *
698      * There can be a variety of reasons and stages in which failure
699      * can happen during tests.
700      *
701      * If a failure is expected to happen at time of establishing
702      * the connection, then MIG_TEST_FAIL will indicate that the dst
703      * QEMU is expected to stay running and accept future migration
704      * connections.
705      *
706      * If a failure is expected to happen while processing the
707      * migration stream, then MIG_TEST_FAIL_DEST_QUIT_ERR will indicate
708      * that the dst QEMU is expected to quit with non-zero exit status
709      */
710     enum {
711         /* This test should succeed, the default */
712         MIG_TEST_SUCCEED = 0,
713         /* This test should fail, dest qemu should keep alive */
714         MIG_TEST_FAIL,
715         /* This test should fail, dest qemu should fail with abnormal status */
716         MIG_TEST_FAIL_DEST_QUIT_ERR,
717         /* The QMP command for this migration should fail with an error */
718         MIG_TEST_QMP_ERROR,
719     } result;
720 
721     /*
722      * Optional: set number of migration passes to wait for, if live==true.
723      * If zero, then merely wait for a few MB of dirty data
724      */
725     unsigned int iterations;
726 
727     /*
728      * Optional: whether the guest CPUs should be running during a precopy
729      * migration test.  We used to always run with live but it took much
730      * longer so we reduced live tests to only the ones that have solid
731      * reason to be tested live-only.  For each of the new test cases for
732      * precopy please provide justifications to use live explicitly (please
733      * refer to existing ones with live=true), or use live=off by default.
734      */
735     bool live;
736 
737     /* Postcopy specific fields */
738     void *postcopy_data;
739     bool postcopy_preempt;
740     bool postcopy_recovery_test_fail;
741 } MigrateCommon;
742 
743 static int test_migrate_start(QTestState **from, QTestState **to,
744                               const char *uri, MigrateStart *args)
745 {
746     g_autofree gchar *arch_source = NULL;
747     g_autofree gchar *arch_target = NULL;
748     /* options for source and target */
749     g_autofree gchar *arch_opts = NULL;
750     g_autofree gchar *cmd_source = NULL;
751     g_autofree gchar *cmd_target = NULL;
752     const gchar *ignore_stderr;
753     g_autofree char *shmem_opts = NULL;
754     g_autofree char *shmem_path = NULL;
755     const char *kvm_opts = NULL;
756     const char *arch = qtest_get_arch();
757     const char *memory_size;
758     const char *machine_alias, *machine_opts = "";
759     g_autofree char *machine = NULL;
760 
761     if (args->use_shmem) {
762         if (!g_file_test("/dev/shm", G_FILE_TEST_IS_DIR)) {
763             g_test_skip("/dev/shm is not supported");
764             return -1;
765         }
766     }
767 
768     dst_state = (QTestMigrationState) { };
769     src_state = (QTestMigrationState) { };
770     if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) {
771         memory_size = "150M";
772 
773         if (g_str_equal(arch, "i386")) {
774             machine_alias = "pc";
775         } else {
776             machine_alias = "q35";
777         }
778         arch_opts = g_strdup_printf(
779             "-drive if=none,id=d0,file=%s,format=raw "
780             "-device ide-hd,drive=d0,secs=1,cyls=1,heads=1", bootpath);
781         start_address = X86_TEST_MEM_START;
782         end_address = X86_TEST_MEM_END;
783     } else if (g_str_equal(arch, "s390x")) {
784         memory_size = "128M";
785         machine_alias = "s390-ccw-virtio";
786         arch_opts = g_strdup_printf("-bios %s", bootpath);
787         start_address = S390_TEST_MEM_START;
788         end_address = S390_TEST_MEM_END;
789     } else if (strcmp(arch, "ppc64") == 0) {
790         memory_size = "256M";
791         start_address = PPC_TEST_MEM_START;
792         end_address = PPC_TEST_MEM_END;
793         arch_source = g_strdup_printf("-prom-env 'use-nvramrc?=true' -prom-env "
794                                       "'nvramrc=hex .\" _\" begin %x %x "
795                                       "do i c@ 1 + i c! 1000 +loop .\" B\" 0 "
796                                       "until'", end_address, start_address);
797         machine_alias = "pseries";
798         machine_opts = "vsmt=8";
799         arch_opts = g_strdup("-nodefaults");
800     } else if (strcmp(arch, "aarch64") == 0) {
801         memory_size = "150M";
802         machine_alias = "virt";
803         machine_opts = "gic-version=max";
804         arch_opts = g_strdup_printf("-cpu max -kernel %s", bootpath);
805         start_address = ARM_TEST_MEM_START;
806         end_address = ARM_TEST_MEM_END;
807     } else {
808         g_assert_not_reached();
809     }
810 
811     if (!getenv("QTEST_LOG") && args->hide_stderr) {
812 #ifndef _WIN32
813         ignore_stderr = "2>/dev/null";
814 #else
815         /*
816          * On Windows the QEMU executable is created via CreateProcess() and
817          * IO redirection does not work, so don't bother adding IO redirection
818          * to the command line.
819          */
820         ignore_stderr = "";
821 #endif
822     } else {
823         ignore_stderr = "";
824     }
825 
826     if (args->use_shmem) {
827         shmem_path = g_strdup_printf("/dev/shm/qemu-%d", getpid());
828         shmem_opts = g_strdup_printf(
829             "-object memory-backend-file,id=mem0,size=%s"
830             ",mem-path=%s,share=on -numa node,memdev=mem0",
831             memory_size, shmem_path);
832     }
833 
834     if (args->use_dirty_ring) {
835         kvm_opts = ",dirty-ring-size=4096";
836     }
837 
838     machine = resolve_machine_version(machine_alias, QEMU_ENV_SRC,
839                                       QEMU_ENV_DST);
840 
841     g_test_message("Using machine type: %s", machine);
842 
843     cmd_source = g_strdup_printf("-accel kvm%s -accel tcg "
844                                  "-machine %s,%s "
845                                  "-name source,debug-threads=on "
846                                  "-m %s "
847                                  "-serial file:%s/src_serial "
848                                  "%s %s %s %s %s",
849                                  kvm_opts ? kvm_opts : "",
850                                  machine, machine_opts,
851                                  memory_size, tmpfs,
852                                  arch_opts ? arch_opts : "",
853                                  arch_source ? arch_source : "",
854                                  shmem_opts ? shmem_opts : "",
855                                  args->opts_source ? args->opts_source : "",
856                                  ignore_stderr);
857     if (!args->only_target) {
858         *from = qtest_init_with_env(QEMU_ENV_SRC, cmd_source);
859         qtest_qmp_set_event_callback(*from,
860                                      migrate_watch_for_events,
861                                      &src_state);
862     }
863 
864     cmd_target = g_strdup_printf("-accel kvm%s -accel tcg "
865                                  "-machine %s,%s "
866                                  "-name target,debug-threads=on "
867                                  "-m %s "
868                                  "-serial file:%s/dest_serial "
869                                  "-incoming %s "
870                                  "%s %s %s %s %s",
871                                  kvm_opts ? kvm_opts : "",
872                                  machine, machine_opts,
873                                  memory_size, tmpfs, uri,
874                                  arch_opts ? arch_opts : "",
875                                  arch_target ? arch_target : "",
876                                  shmem_opts ? shmem_opts : "",
877                                  args->opts_target ? args->opts_target : "",
878                                  ignore_stderr);
879     *to = qtest_init_with_env(QEMU_ENV_DST, cmd_target);
880     qtest_qmp_set_event_callback(*to,
881                                  migrate_watch_for_events,
882                                  &dst_state);
883 
884     /*
885      * Remove shmem file immediately to avoid memory leak in test failed case.
886      * It's valid because QEMU has already opened this file
887      */
888     if (args->use_shmem) {
889         unlink(shmem_path);
890     }
891 
892     return 0;
893 }
894 
895 static void test_migrate_end(QTestState *from, QTestState *to, bool test_dest)
896 {
897     unsigned char dest_byte_a, dest_byte_b, dest_byte_c, dest_byte_d;
898 
899     qtest_quit(from);
900 
901     if (test_dest) {
902         qtest_memread(to, start_address, &dest_byte_a, 1);
903 
904         /* Destination still running, wait for a byte to change */
905         do {
906             qtest_memread(to, start_address, &dest_byte_b, 1);
907             usleep(1000 * 10);
908         } while (dest_byte_a == dest_byte_b);
909 
910         qtest_qmp_assert_success(to, "{ 'execute' : 'stop'}");
911 
912         /* With it stopped, check nothing changes */
913         qtest_memread(to, start_address, &dest_byte_c, 1);
914         usleep(1000 * 200);
915         qtest_memread(to, start_address, &dest_byte_d, 1);
916         g_assert_cmpint(dest_byte_c, ==, dest_byte_d);
917 
918         check_guests_ram(to);
919     }
920 
921     qtest_quit(to);
922 
923     cleanup("migsocket");
924     cleanup("src_serial");
925     cleanup("dest_serial");
926     cleanup(FILE_TEST_FILENAME);
927 }
928 
929 #ifdef CONFIG_GNUTLS
930 struct TestMigrateTLSPSKData {
931     char *workdir;
932     char *workdiralt;
933     char *pskfile;
934     char *pskfilealt;
935 };
936 
937 static void *
938 test_migrate_tls_psk_start_common(QTestState *from,
939                                   QTestState *to,
940                                   bool mismatch)
941 {
942     struct TestMigrateTLSPSKData *data =
943         g_new0(struct TestMigrateTLSPSKData, 1);
944 
945     data->workdir = g_strdup_printf("%s/tlscredspsk0", tmpfs);
946     data->pskfile = g_strdup_printf("%s/%s", data->workdir,
947                                     QCRYPTO_TLS_CREDS_PSKFILE);
948     g_mkdir_with_parents(data->workdir, 0700);
949     test_tls_psk_init(data->pskfile);
950 
951     if (mismatch) {
952         data->workdiralt = g_strdup_printf("%s/tlscredspskalt0", tmpfs);
953         data->pskfilealt = g_strdup_printf("%s/%s", data->workdiralt,
954                                            QCRYPTO_TLS_CREDS_PSKFILE);
955         g_mkdir_with_parents(data->workdiralt, 0700);
956         test_tls_psk_init_alt(data->pskfilealt);
957     }
958 
959     qtest_qmp_assert_success(from,
960                              "{ 'execute': 'object-add',"
961                              "  'arguments': { 'qom-type': 'tls-creds-psk',"
962                              "                 'id': 'tlscredspsk0',"
963                              "                 'endpoint': 'client',"
964                              "                 'dir': %s,"
965                              "                 'username': 'qemu'} }",
966                              data->workdir);
967 
968     qtest_qmp_assert_success(to,
969                              "{ 'execute': 'object-add',"
970                              "  'arguments': { 'qom-type': 'tls-creds-psk',"
971                              "                 'id': 'tlscredspsk0',"
972                              "                 'endpoint': 'server',"
973                              "                 'dir': %s } }",
974                              mismatch ? data->workdiralt : data->workdir);
975 
976     migrate_set_parameter_str(from, "tls-creds", "tlscredspsk0");
977     migrate_set_parameter_str(to, "tls-creds", "tlscredspsk0");
978 
979     return data;
980 }
981 
982 static void *
983 test_migrate_tls_psk_start_match(QTestState *from,
984                                  QTestState *to)
985 {
986     return test_migrate_tls_psk_start_common(from, to, false);
987 }
988 
989 static void *
990 test_migrate_tls_psk_start_mismatch(QTestState *from,
991                                     QTestState *to)
992 {
993     return test_migrate_tls_psk_start_common(from, to, true);
994 }
995 
996 static void
997 test_migrate_tls_psk_finish(QTestState *from,
998                             QTestState *to,
999                             void *opaque)
1000 {
1001     struct TestMigrateTLSPSKData *data = opaque;
1002 
1003     test_tls_psk_cleanup(data->pskfile);
1004     if (data->pskfilealt) {
1005         test_tls_psk_cleanup(data->pskfilealt);
1006     }
1007     rmdir(data->workdir);
1008     if (data->workdiralt) {
1009         rmdir(data->workdiralt);
1010     }
1011 
1012     g_free(data->workdiralt);
1013     g_free(data->pskfilealt);
1014     g_free(data->workdir);
1015     g_free(data->pskfile);
1016     g_free(data);
1017 }
1018 
1019 #ifdef CONFIG_TASN1
1020 typedef struct {
1021     char *workdir;
1022     char *keyfile;
1023     char *cacert;
1024     char *servercert;
1025     char *serverkey;
1026     char *clientcert;
1027     char *clientkey;
1028 } TestMigrateTLSX509Data;
1029 
1030 typedef struct {
1031     bool verifyclient;
1032     bool clientcert;
1033     bool hostileclient;
1034     bool authzclient;
1035     const char *certhostname;
1036     const char *certipaddr;
1037 } TestMigrateTLSX509;
1038 
1039 static void *
1040 test_migrate_tls_x509_start_common(QTestState *from,
1041                                    QTestState *to,
1042                                    TestMigrateTLSX509 *args)
1043 {
1044     TestMigrateTLSX509Data *data = g_new0(TestMigrateTLSX509Data, 1);
1045 
1046     data->workdir = g_strdup_printf("%s/tlscredsx5090", tmpfs);
1047     data->keyfile = g_strdup_printf("%s/key.pem", data->workdir);
1048 
1049     data->cacert = g_strdup_printf("%s/ca-cert.pem", data->workdir);
1050     data->serverkey = g_strdup_printf("%s/server-key.pem", data->workdir);
1051     data->servercert = g_strdup_printf("%s/server-cert.pem", data->workdir);
1052     if (args->clientcert) {
1053         data->clientkey = g_strdup_printf("%s/client-key.pem", data->workdir);
1054         data->clientcert = g_strdup_printf("%s/client-cert.pem", data->workdir);
1055     }
1056 
1057     g_mkdir_with_parents(data->workdir, 0700);
1058 
1059     test_tls_init(data->keyfile);
1060 #ifndef _WIN32
1061     g_assert(link(data->keyfile, data->serverkey) == 0);
1062 #else
1063     g_assert(CreateHardLink(data->serverkey, data->keyfile, NULL) != 0);
1064 #endif
1065     if (args->clientcert) {
1066 #ifndef _WIN32
1067         g_assert(link(data->keyfile, data->clientkey) == 0);
1068 #else
1069         g_assert(CreateHardLink(data->clientkey, data->keyfile, NULL) != 0);
1070 #endif
1071     }
1072 
1073     TLS_ROOT_REQ_SIMPLE(cacertreq, data->cacert);
1074     if (args->clientcert) {
1075         TLS_CERT_REQ_SIMPLE_CLIENT(servercertreq, cacertreq,
1076                                    args->hostileclient ?
1077                                    QCRYPTO_TLS_TEST_CLIENT_HOSTILE_NAME :
1078                                    QCRYPTO_TLS_TEST_CLIENT_NAME,
1079                                    data->clientcert);
1080     }
1081 
1082     TLS_CERT_REQ_SIMPLE_SERVER(clientcertreq, cacertreq,
1083                                data->servercert,
1084                                args->certhostname,
1085                                args->certipaddr);
1086 
1087     qtest_qmp_assert_success(from,
1088                              "{ 'execute': 'object-add',"
1089                              "  'arguments': { 'qom-type': 'tls-creds-x509',"
1090                              "                 'id': 'tlscredsx509client0',"
1091                              "                 'endpoint': 'client',"
1092                              "                 'dir': %s,"
1093                              "                 'sanity-check': true,"
1094                              "                 'verify-peer': true} }",
1095                              data->workdir);
1096     migrate_set_parameter_str(from, "tls-creds", "tlscredsx509client0");
1097     if (args->certhostname) {
1098         migrate_set_parameter_str(from, "tls-hostname", args->certhostname);
1099     }
1100 
1101     qtest_qmp_assert_success(to,
1102                              "{ 'execute': 'object-add',"
1103                              "  'arguments': { 'qom-type': 'tls-creds-x509',"
1104                              "                 'id': 'tlscredsx509server0',"
1105                              "                 'endpoint': 'server',"
1106                              "                 'dir': %s,"
1107                              "                 'sanity-check': true,"
1108                              "                 'verify-peer': %i} }",
1109                              data->workdir, args->verifyclient);
1110     migrate_set_parameter_str(to, "tls-creds", "tlscredsx509server0");
1111 
1112     if (args->authzclient) {
1113         qtest_qmp_assert_success(to,
1114                                  "{ 'execute': 'object-add',"
1115                                  "  'arguments': { 'qom-type': 'authz-simple',"
1116                                  "                 'id': 'tlsauthz0',"
1117                                  "                 'identity': %s} }",
1118                                  "CN=" QCRYPTO_TLS_TEST_CLIENT_NAME);
1119         migrate_set_parameter_str(to, "tls-authz", "tlsauthz0");
1120     }
1121 
1122     return data;
1123 }
1124 
1125 /*
1126  * The normal case: match server's cert hostname against
1127  * whatever host we were telling QEMU to connect to (if any)
1128  */
1129 static void *
1130 test_migrate_tls_x509_start_default_host(QTestState *from,
1131                                          QTestState *to)
1132 {
1133     TestMigrateTLSX509 args = {
1134         .verifyclient = true,
1135         .clientcert = true,
1136         .certipaddr = "127.0.0.1"
1137     };
1138     return test_migrate_tls_x509_start_common(from, to, &args);
1139 }
1140 
1141 /*
1142  * The unusual case: the server's cert is different from
1143  * the address we're telling QEMU to connect to (if any),
1144  * so we must give QEMU an explicit hostname to validate
1145  */
1146 static void *
1147 test_migrate_tls_x509_start_override_host(QTestState *from,
1148                                           QTestState *to)
1149 {
1150     TestMigrateTLSX509 args = {
1151         .verifyclient = true,
1152         .clientcert = true,
1153         .certhostname = "qemu.org",
1154     };
1155     return test_migrate_tls_x509_start_common(from, to, &args);
1156 }
1157 
1158 /*
1159  * The unusual case: the server's cert is different from
1160  * the address we're telling QEMU to connect to, and so we
1161  * expect the client to reject the server
1162  */
1163 static void *
1164 test_migrate_tls_x509_start_mismatch_host(QTestState *from,
1165                                           QTestState *to)
1166 {
1167     TestMigrateTLSX509 args = {
1168         .verifyclient = true,
1169         .clientcert = true,
1170         .certipaddr = "10.0.0.1",
1171     };
1172     return test_migrate_tls_x509_start_common(from, to, &args);
1173 }
1174 
1175 static void *
1176 test_migrate_tls_x509_start_friendly_client(QTestState *from,
1177                                             QTestState *to)
1178 {
1179     TestMigrateTLSX509 args = {
1180         .verifyclient = true,
1181         .clientcert = true,
1182         .authzclient = true,
1183         .certipaddr = "127.0.0.1",
1184     };
1185     return test_migrate_tls_x509_start_common(from, to, &args);
1186 }
1187 
1188 static void *
1189 test_migrate_tls_x509_start_hostile_client(QTestState *from,
1190                                            QTestState *to)
1191 {
1192     TestMigrateTLSX509 args = {
1193         .verifyclient = true,
1194         .clientcert = true,
1195         .hostileclient = true,
1196         .authzclient = true,
1197         .certipaddr = "127.0.0.1",
1198     };
1199     return test_migrate_tls_x509_start_common(from, to, &args);
1200 }
1201 
1202 /*
1203  * The case with no client certificate presented,
1204  * and no server verification
1205  */
1206 static void *
1207 test_migrate_tls_x509_start_allow_anon_client(QTestState *from,
1208                                               QTestState *to)
1209 {
1210     TestMigrateTLSX509 args = {
1211         .certipaddr = "127.0.0.1",
1212     };
1213     return test_migrate_tls_x509_start_common(from, to, &args);
1214 }
1215 
1216 /*
1217  * The case with no client certificate presented,
1218  * and server verification rejecting
1219  */
1220 static void *
1221 test_migrate_tls_x509_start_reject_anon_client(QTestState *from,
1222                                                QTestState *to)
1223 {
1224     TestMigrateTLSX509 args = {
1225         .verifyclient = true,
1226         .certipaddr = "127.0.0.1",
1227     };
1228     return test_migrate_tls_x509_start_common(from, to, &args);
1229 }
1230 
1231 static void
1232 test_migrate_tls_x509_finish(QTestState *from,
1233                              QTestState *to,
1234                              void *opaque)
1235 {
1236     TestMigrateTLSX509Data *data = opaque;
1237 
1238     test_tls_cleanup(data->keyfile);
1239     g_free(data->keyfile);
1240 
1241     unlink(data->cacert);
1242     g_free(data->cacert);
1243     unlink(data->servercert);
1244     g_free(data->servercert);
1245     unlink(data->serverkey);
1246     g_free(data->serverkey);
1247 
1248     if (data->clientcert) {
1249         unlink(data->clientcert);
1250         g_free(data->clientcert);
1251     }
1252     if (data->clientkey) {
1253         unlink(data->clientkey);
1254         g_free(data->clientkey);
1255     }
1256 
1257     rmdir(data->workdir);
1258     g_free(data->workdir);
1259 
1260     g_free(data);
1261 }
1262 #endif /* CONFIG_TASN1 */
1263 #endif /* CONFIG_GNUTLS */
1264 
1265 static void *
1266 test_migrate_compress_start(QTestState *from,
1267                             QTestState *to)
1268 {
1269     migrate_set_parameter_int(from, "compress-level", 1);
1270     migrate_set_parameter_int(from, "compress-threads", 4);
1271     migrate_set_parameter_bool(from, "compress-wait-thread", true);
1272     migrate_set_parameter_int(to, "decompress-threads", 4);
1273 
1274     migrate_set_capability(from, "compress", true);
1275     migrate_set_capability(to, "compress", true);
1276 
1277     return NULL;
1278 }
1279 
1280 static void *
1281 test_migrate_compress_nowait_start(QTestState *from,
1282                                    QTestState *to)
1283 {
1284     migrate_set_parameter_int(from, "compress-level", 9);
1285     migrate_set_parameter_int(from, "compress-threads", 1);
1286     migrate_set_parameter_bool(from, "compress-wait-thread", false);
1287     migrate_set_parameter_int(to, "decompress-threads", 1);
1288 
1289     migrate_set_capability(from, "compress", true);
1290     migrate_set_capability(to, "compress", true);
1291 
1292     return NULL;
1293 }
1294 
1295 static int migrate_postcopy_prepare(QTestState **from_ptr,
1296                                     QTestState **to_ptr,
1297                                     MigrateCommon *args)
1298 {
1299     QTestState *from, *to;
1300 
1301     if (test_migrate_start(&from, &to, "defer", &args->start)) {
1302         return -1;
1303     }
1304 
1305     if (args->start_hook) {
1306         args->postcopy_data = args->start_hook(from, to);
1307     }
1308 
1309     migrate_set_capability(from, "postcopy-ram", true);
1310     migrate_set_capability(to, "postcopy-ram", true);
1311     migrate_set_capability(to, "postcopy-blocktime", true);
1312 
1313     if (args->postcopy_preempt) {
1314         migrate_set_capability(from, "postcopy-preempt", true);
1315         migrate_set_capability(to, "postcopy-preempt", true);
1316     }
1317 
1318     migrate_ensure_non_converge(from);
1319 
1320     migrate_prepare_for_dirty_mem(from);
1321     qtest_qmp_assert_success(to, "{ 'execute': 'migrate-incoming',"
1322                              "  'arguments': { "
1323                              "      'channels': [ { 'channel-type': 'main',"
1324                              "      'addr': { 'transport': 'socket',"
1325                              "                'type': 'inet',"
1326                              "                'host': '127.0.0.1',"
1327                              "                'port': '0' } } ] } }");
1328 
1329     /* Wait for the first serial output from the source */
1330     wait_for_serial("src_serial");
1331 
1332     g_autofree char *uri = migrate_get_socket_address(to, "socket-address");
1333     migrate_qmp(from, uri, "{}");
1334 
1335     migrate_wait_for_dirty_mem(from, to);
1336 
1337     *from_ptr = from;
1338     *to_ptr = to;
1339 
1340     return 0;
1341 }
1342 
1343 static void migrate_postcopy_complete(QTestState *from, QTestState *to,
1344                                       MigrateCommon *args)
1345 {
1346     wait_for_migration_complete(from);
1347 
1348     /* Make sure we get at least one "B" on destination */
1349     wait_for_serial("dest_serial");
1350 
1351     if (uffd_feature_thread_id) {
1352         read_blocktime(to);
1353     }
1354 
1355     if (args->finish_hook) {
1356         args->finish_hook(from, to, args->postcopy_data);
1357         args->postcopy_data = NULL;
1358     }
1359 
1360     test_migrate_end(from, to, true);
1361 }
1362 
1363 static void test_postcopy_common(MigrateCommon *args)
1364 {
1365     QTestState *from, *to;
1366 
1367     if (migrate_postcopy_prepare(&from, &to, args)) {
1368         return;
1369     }
1370     migrate_postcopy_start(from, to);
1371     migrate_postcopy_complete(from, to, args);
1372 }
1373 
1374 static void test_postcopy(void)
1375 {
1376     MigrateCommon args = { };
1377 
1378     test_postcopy_common(&args);
1379 }
1380 
1381 static void test_postcopy_compress(void)
1382 {
1383     MigrateCommon args = {
1384         .start_hook = test_migrate_compress_start
1385     };
1386 
1387     test_postcopy_common(&args);
1388 }
1389 
1390 static void test_postcopy_preempt(void)
1391 {
1392     MigrateCommon args = {
1393         .postcopy_preempt = true,
1394     };
1395 
1396     test_postcopy_common(&args);
1397 }
1398 
1399 #ifdef CONFIG_GNUTLS
1400 static void test_postcopy_tls_psk(void)
1401 {
1402     MigrateCommon args = {
1403         .start_hook = test_migrate_tls_psk_start_match,
1404         .finish_hook = test_migrate_tls_psk_finish,
1405     };
1406 
1407     test_postcopy_common(&args);
1408 }
1409 
1410 static void test_postcopy_preempt_tls_psk(void)
1411 {
1412     MigrateCommon args = {
1413         .postcopy_preempt = true,
1414         .start_hook = test_migrate_tls_psk_start_match,
1415         .finish_hook = test_migrate_tls_psk_finish,
1416     };
1417 
1418     test_postcopy_common(&args);
1419 }
1420 #endif
1421 
1422 static void wait_for_postcopy_status(QTestState *one, const char *status)
1423 {
1424     wait_for_migration_status(one, status,
1425                               (const char * []) { "failed", "active",
1426                                                   "completed", NULL });
1427 }
1428 
1429 #ifndef _WIN32
1430 static void postcopy_recover_fail(QTestState *from, QTestState *to)
1431 {
1432     int ret, pair1[2], pair2[2];
1433     char c;
1434 
1435     /* Create two unrelated socketpairs */
1436     ret = qemu_socketpair(PF_LOCAL, SOCK_STREAM, 0, pair1);
1437     g_assert_cmpint(ret, ==, 0);
1438 
1439     ret = qemu_socketpair(PF_LOCAL, SOCK_STREAM, 0, pair2);
1440     g_assert_cmpint(ret, ==, 0);
1441 
1442     /*
1443      * Give the guests unpaired ends of the sockets, so they'll all blocked
1444      * at reading.  This mimics a wrong channel established.
1445      */
1446     qtest_qmp_fds_assert_success(from, &pair1[0], 1,
1447                                  "{ 'execute': 'getfd',"
1448                                  "  'arguments': { 'fdname': 'fd-mig' }}");
1449     qtest_qmp_fds_assert_success(to, &pair2[0], 1,
1450                                  "{ 'execute': 'getfd',"
1451                                  "  'arguments': { 'fdname': 'fd-mig' }}");
1452 
1453     /*
1454      * Write the 1st byte as QEMU_VM_COMMAND (0x8) for the dest socket, to
1455      * emulate the 1st byte of a real recovery, but stops from there to
1456      * keep dest QEMU in RECOVER.  This is needed so that we can kick off
1457      * the recover process on dest QEMU (by triggering the G_IO_IN event).
1458      *
1459      * NOTE: this trick is not needed on src QEMUs, because src doesn't
1460      * rely on an pre-existing G_IO_IN event, so it will always trigger the
1461      * upcoming recovery anyway even if it can read nothing.
1462      */
1463 #define QEMU_VM_COMMAND              0x08
1464     c = QEMU_VM_COMMAND;
1465     ret = send(pair2[1], &c, 1, 0);
1466     g_assert_cmpint(ret, ==, 1);
1467 
1468     migrate_recover(to, "fd:fd-mig");
1469     migrate_qmp(from, "fd:fd-mig", "{'resume': true}");
1470 
1471     /*
1472      * Make sure both QEMU instances will go into RECOVER stage, then test
1473      * kicking them out using migrate-pause.
1474      */
1475     wait_for_postcopy_status(from, "postcopy-recover");
1476     wait_for_postcopy_status(to, "postcopy-recover");
1477 
1478     /*
1479      * This would be issued by the admin upon noticing the hang, we should
1480      * make sure we're able to kick this out.
1481      */
1482     migrate_pause(from);
1483     wait_for_postcopy_status(from, "postcopy-paused");
1484 
1485     /* Do the same test on dest */
1486     migrate_pause(to);
1487     wait_for_postcopy_status(to, "postcopy-paused");
1488 
1489     close(pair1[0]);
1490     close(pair1[1]);
1491     close(pair2[0]);
1492     close(pair2[1]);
1493 }
1494 #endif /* _WIN32 */
1495 
1496 static void test_postcopy_recovery_common(MigrateCommon *args)
1497 {
1498     QTestState *from, *to;
1499     g_autofree char *uri = NULL;
1500 
1501     /* Always hide errors for postcopy recover tests since they're expected */
1502     args->start.hide_stderr = true;
1503 
1504     if (migrate_postcopy_prepare(&from, &to, args)) {
1505         return;
1506     }
1507 
1508     /* Turn postcopy speed down, 4K/s is slow enough on any machines */
1509     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 4096);
1510 
1511     /* Now we start the postcopy */
1512     migrate_postcopy_start(from, to);
1513 
1514     /*
1515      * Wait until postcopy is really started; we can only run the
1516      * migrate-pause command during a postcopy
1517      */
1518     wait_for_migration_status(from, "postcopy-active", NULL);
1519 
1520     /*
1521      * Manually stop the postcopy migration. This emulates a network
1522      * failure with the migration socket
1523      */
1524     migrate_pause(from);
1525 
1526     /*
1527      * Wait for destination side to reach postcopy-paused state.  The
1528      * migrate-recover command can only succeed if destination machine
1529      * is in the paused state
1530      */
1531     wait_for_postcopy_status(to, "postcopy-paused");
1532     wait_for_postcopy_status(from, "postcopy-paused");
1533 
1534 #ifndef _WIN32
1535     if (args->postcopy_recovery_test_fail) {
1536         /*
1537          * Test when a wrong socket specified for recover, and then the
1538          * ability to kick it out, and continue with a correct socket.
1539          */
1540         postcopy_recover_fail(from, to);
1541         /* continue with a good recovery */
1542     }
1543 #endif /* _WIN32 */
1544 
1545     /*
1546      * Create a new socket to emulate a new channel that is different
1547      * from the broken migration channel; tell the destination to
1548      * listen to the new port
1549      */
1550     uri = g_strdup_printf("unix:%s/migsocket-recover", tmpfs);
1551     migrate_recover(to, uri);
1552 
1553     /*
1554      * Try to rebuild the migration channel using the resume flag and
1555      * the newly created channel
1556      */
1557     migrate_qmp(from, uri, "{'resume': true}");
1558 
1559     /* Restore the postcopy bandwidth to unlimited */
1560     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 0);
1561 
1562     migrate_postcopy_complete(from, to, args);
1563 }
1564 
1565 static void test_postcopy_recovery(void)
1566 {
1567     MigrateCommon args = { };
1568 
1569     test_postcopy_recovery_common(&args);
1570 }
1571 
1572 static void test_postcopy_recovery_compress(void)
1573 {
1574     MigrateCommon args = {
1575         .start_hook = test_migrate_compress_start
1576     };
1577 
1578     test_postcopy_recovery_common(&args);
1579 }
1580 
1581 #ifndef _WIN32
1582 static void test_postcopy_recovery_double_fail(void)
1583 {
1584     MigrateCommon args = {
1585         .postcopy_recovery_test_fail = true,
1586     };
1587 
1588     test_postcopy_recovery_common(&args);
1589 }
1590 #endif /* _WIN32 */
1591 
1592 #ifdef CONFIG_GNUTLS
1593 static void test_postcopy_recovery_tls_psk(void)
1594 {
1595     MigrateCommon args = {
1596         .start_hook = test_migrate_tls_psk_start_match,
1597         .finish_hook = test_migrate_tls_psk_finish,
1598     };
1599 
1600     test_postcopy_recovery_common(&args);
1601 }
1602 #endif
1603 
1604 static void test_postcopy_preempt_recovery(void)
1605 {
1606     MigrateCommon args = {
1607         .postcopy_preempt = true,
1608     };
1609 
1610     test_postcopy_recovery_common(&args);
1611 }
1612 
1613 #ifdef CONFIG_GNUTLS
1614 /* This contains preempt+recovery+tls test altogether */
1615 static void test_postcopy_preempt_all(void)
1616 {
1617     MigrateCommon args = {
1618         .postcopy_preempt = true,
1619         .start_hook = test_migrate_tls_psk_start_match,
1620         .finish_hook = test_migrate_tls_psk_finish,
1621     };
1622 
1623     test_postcopy_recovery_common(&args);
1624 }
1625 
1626 #endif
1627 
1628 static void test_baddest(void)
1629 {
1630     MigrateStart args = {
1631         .hide_stderr = true
1632     };
1633     QTestState *from, *to;
1634 
1635     if (test_migrate_start(&from, &to, "tcp:127.0.0.1:0", &args)) {
1636         return;
1637     }
1638     migrate_qmp(from, "tcp:127.0.0.1:0", "{}");
1639     wait_for_migration_fail(from, false);
1640     test_migrate_end(from, to, false);
1641 }
1642 
1643 #ifndef _WIN32
1644 static void test_analyze_script(void)
1645 {
1646     MigrateStart args = {
1647         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
1648     };
1649     QTestState *from, *to;
1650     g_autofree char *uri = NULL;
1651     g_autofree char *file = NULL;
1652     int pid, wstatus;
1653     const char *python = g_getenv("PYTHON");
1654 
1655     if (!python) {
1656         g_test_skip("PYTHON variable not set");
1657         return;
1658     }
1659 
1660     /* dummy url */
1661     if (test_migrate_start(&from, &to, "tcp:127.0.0.1:0", &args)) {
1662         return;
1663     }
1664 
1665     /*
1666      * Setting these two capabilities causes the "configuration"
1667      * vmstate to include subsections for them. The script needs to
1668      * parse those subsections properly.
1669      */
1670     migrate_set_capability(from, "validate-uuid", true);
1671     migrate_set_capability(from, "x-ignore-shared", true);
1672 
1673     file = g_strdup_printf("%s/migfile", tmpfs);
1674     uri = g_strdup_printf("exec:cat > %s", file);
1675 
1676     migrate_ensure_converge(from);
1677     migrate_qmp(from, uri, "{}");
1678     wait_for_migration_complete(from);
1679 
1680     pid = fork();
1681     if (!pid) {
1682         close(1);
1683         open("/dev/null", O_WRONLY);
1684         execl(python, python, ANALYZE_SCRIPT, "-f", file, NULL);
1685         g_assert_not_reached();
1686     }
1687 
1688     g_assert(waitpid(pid, &wstatus, 0) == pid);
1689     if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0) {
1690         g_test_message("Failed to analyze the migration stream");
1691         g_test_fail();
1692     }
1693     test_migrate_end(from, to, false);
1694     cleanup("migfile");
1695 }
1696 #endif
1697 
1698 static void test_precopy_common(MigrateCommon *args)
1699 {
1700     QTestState *from, *to;
1701     void *data_hook = NULL;
1702     g_autofree char *connect_uri = NULL;
1703 
1704     if (test_migrate_start(&from, &to, args->listen_uri, &args->start)) {
1705         return;
1706     }
1707 
1708     if (args->start_hook) {
1709         data_hook = args->start_hook(from, to);
1710     }
1711 
1712     /* Wait for the first serial output from the source */
1713     if (args->result == MIG_TEST_SUCCEED) {
1714         wait_for_serial("src_serial");
1715     }
1716 
1717     if (args->live) {
1718         migrate_ensure_non_converge(from);
1719         migrate_prepare_for_dirty_mem(from);
1720     } else {
1721         /*
1722          * Testing non-live migration, we allow it to run at
1723          * full speed to ensure short test case duration.
1724          * For tests expected to fail, we don't need to
1725          * change anything.
1726          */
1727         if (args->result == MIG_TEST_SUCCEED) {
1728             qtest_qmp_assert_success(from, "{ 'execute' : 'stop'}");
1729             wait_for_stop(from, &src_state);
1730             migrate_ensure_converge(from);
1731         }
1732     }
1733 
1734     if (!args->connect_uri) {
1735         connect_uri = migrate_get_socket_address(to, "socket-address");
1736     } else {
1737         connect_uri = g_strdup(args->connect_uri);
1738     }
1739 
1740     if (args->result == MIG_TEST_QMP_ERROR) {
1741         migrate_qmp_fail(from, connect_uri, "{}");
1742         goto finish;
1743     }
1744 
1745     migrate_qmp(from, connect_uri, "{}");
1746 
1747     if (args->result != MIG_TEST_SUCCEED) {
1748         bool allow_active = args->result == MIG_TEST_FAIL;
1749         wait_for_migration_fail(from, allow_active);
1750 
1751         if (args->result == MIG_TEST_FAIL_DEST_QUIT_ERR) {
1752             qtest_set_expected_status(to, EXIT_FAILURE);
1753         }
1754     } else {
1755         if (args->live) {
1756             /*
1757              * For initial iteration(s) we must do a full pass,
1758              * but for the final iteration, we need only wait
1759              * for some dirty mem before switching to converge
1760              */
1761             while (args->iterations > 1) {
1762                 wait_for_migration_pass(from);
1763                 args->iterations--;
1764             }
1765             migrate_wait_for_dirty_mem(from, to);
1766 
1767             migrate_ensure_converge(from);
1768 
1769             /*
1770              * We do this first, as it has a timeout to stop us
1771              * hanging forever if migration didn't converge
1772              */
1773             wait_for_migration_complete(from);
1774 
1775             wait_for_stop(from, &src_state);
1776 
1777         } else {
1778             wait_for_migration_complete(from);
1779             /*
1780              * Must wait for dst to finish reading all incoming
1781              * data on the socket before issuing 'cont' otherwise
1782              * it'll be ignored
1783              */
1784             wait_for_migration_complete(to);
1785 
1786             qtest_qmp_assert_success(to, "{ 'execute' : 'cont'}");
1787         }
1788 
1789         wait_for_resume(to, &dst_state);
1790 
1791         wait_for_serial("dest_serial");
1792     }
1793 
1794 finish:
1795     if (args->finish_hook) {
1796         args->finish_hook(from, to, data_hook);
1797     }
1798 
1799     test_migrate_end(from, to, args->result == MIG_TEST_SUCCEED);
1800 }
1801 
1802 static void test_file_common(MigrateCommon *args, bool stop_src)
1803 {
1804     QTestState *from, *to;
1805     void *data_hook = NULL;
1806     g_autofree char *connect_uri = g_strdup(args->connect_uri);
1807 
1808     if (test_migrate_start(&from, &to, args->listen_uri, &args->start)) {
1809         return;
1810     }
1811 
1812     /*
1813      * File migration is never live. We can keep the source VM running
1814      * during migration, but the destination will not be running
1815      * concurrently.
1816      */
1817     g_assert_false(args->live);
1818 
1819     if (args->start_hook) {
1820         data_hook = args->start_hook(from, to);
1821     }
1822 
1823     migrate_ensure_converge(from);
1824     wait_for_serial("src_serial");
1825 
1826     if (stop_src) {
1827         qtest_qmp_assert_success(from, "{ 'execute' : 'stop'}");
1828         wait_for_stop(from, &src_state);
1829     }
1830 
1831     if (args->result == MIG_TEST_QMP_ERROR) {
1832         migrate_qmp_fail(from, connect_uri, "{}");
1833         goto finish;
1834     }
1835 
1836     migrate_qmp(from, connect_uri, "{}");
1837     wait_for_migration_complete(from);
1838 
1839     /*
1840      * We need to wait for the source to finish before starting the
1841      * destination.
1842      */
1843     migrate_incoming_qmp(to, connect_uri, "{}");
1844     wait_for_migration_complete(to);
1845 
1846     if (stop_src) {
1847         qtest_qmp_assert_success(to, "{ 'execute' : 'cont'}");
1848     }
1849     wait_for_resume(to, &dst_state);
1850 
1851     wait_for_serial("dest_serial");
1852 
1853 finish:
1854     if (args->finish_hook) {
1855         args->finish_hook(from, to, data_hook);
1856     }
1857 
1858     test_migrate_end(from, to, args->result == MIG_TEST_SUCCEED);
1859 }
1860 
1861 static void test_precopy_unix_plain(void)
1862 {
1863     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1864     MigrateCommon args = {
1865         .listen_uri = uri,
1866         .connect_uri = uri,
1867         /*
1868          * The simplest use case of precopy, covering smoke tests of
1869          * get-dirty-log dirty tracking.
1870          */
1871         .live = true,
1872     };
1873 
1874     test_precopy_common(&args);
1875 }
1876 
1877 
1878 static void test_precopy_unix_dirty_ring(void)
1879 {
1880     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1881     MigrateCommon args = {
1882         .start = {
1883             .use_dirty_ring = true,
1884         },
1885         .listen_uri = uri,
1886         .connect_uri = uri,
1887         /*
1888          * Besides the precopy/unix basic test, cover dirty ring interface
1889          * rather than get-dirty-log.
1890          */
1891         .live = true,
1892     };
1893 
1894     test_precopy_common(&args);
1895 }
1896 
1897 #ifdef CONFIG_GNUTLS
1898 static void test_precopy_unix_tls_psk(void)
1899 {
1900     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1901     MigrateCommon args = {
1902         .connect_uri = uri,
1903         .listen_uri = uri,
1904         .start_hook = test_migrate_tls_psk_start_match,
1905         .finish_hook = test_migrate_tls_psk_finish,
1906     };
1907 
1908     test_precopy_common(&args);
1909 }
1910 
1911 #ifdef CONFIG_TASN1
1912 static void test_precopy_unix_tls_x509_default_host(void)
1913 {
1914     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1915     MigrateCommon args = {
1916         .start = {
1917             .hide_stderr = true,
1918         },
1919         .connect_uri = uri,
1920         .listen_uri = uri,
1921         .start_hook = test_migrate_tls_x509_start_default_host,
1922         .finish_hook = test_migrate_tls_x509_finish,
1923         .result = MIG_TEST_FAIL_DEST_QUIT_ERR,
1924     };
1925 
1926     test_precopy_common(&args);
1927 }
1928 
1929 static void test_precopy_unix_tls_x509_override_host(void)
1930 {
1931     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1932     MigrateCommon args = {
1933         .connect_uri = uri,
1934         .listen_uri = uri,
1935         .start_hook = test_migrate_tls_x509_start_override_host,
1936         .finish_hook = test_migrate_tls_x509_finish,
1937     };
1938 
1939     test_precopy_common(&args);
1940 }
1941 #endif /* CONFIG_TASN1 */
1942 #endif /* CONFIG_GNUTLS */
1943 
1944 #if 0
1945 /* Currently upset on aarch64 TCG */
1946 static void test_ignore_shared(void)
1947 {
1948     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1949     QTestState *from, *to;
1950 
1951     if (test_migrate_start(&from, &to, uri, false, true, NULL, NULL)) {
1952         return;
1953     }
1954 
1955     migrate_ensure_non_converge(from);
1956     migrate_prepare_for_dirty_mem(from);
1957 
1958     migrate_set_capability(from, "x-ignore-shared", true);
1959     migrate_set_capability(to, "x-ignore-shared", true);
1960 
1961     /* Wait for the first serial output from the source */
1962     wait_for_serial("src_serial");
1963 
1964     migrate_qmp(from, uri, "{}");
1965 
1966     migrate_wait_for_dirty_mem(from, to);
1967 
1968     wait_for_stop(from, &src_state);
1969 
1970     qtest_qmp_eventwait(to, "RESUME");
1971 
1972     wait_for_serial("dest_serial");
1973     wait_for_migration_complete(from);
1974 
1975     /* Check whether shared RAM has been really skipped */
1976     g_assert_cmpint(read_ram_property_int(from, "transferred"), <, 1024 * 1024);
1977 
1978     test_migrate_end(from, to, true);
1979 }
1980 #endif
1981 
1982 static void *
1983 test_migrate_xbzrle_start(QTestState *from,
1984                           QTestState *to)
1985 {
1986     migrate_set_parameter_int(from, "xbzrle-cache-size", 33554432);
1987 
1988     migrate_set_capability(from, "xbzrle", true);
1989     migrate_set_capability(to, "xbzrle", true);
1990 
1991     return NULL;
1992 }
1993 
1994 static void test_precopy_unix_xbzrle(void)
1995 {
1996     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1997     MigrateCommon args = {
1998         .connect_uri = uri,
1999         .listen_uri = uri,
2000         .start_hook = test_migrate_xbzrle_start,
2001         .iterations = 2,
2002         /*
2003          * XBZRLE needs pages to be modified when doing the 2nd+ round
2004          * iteration to have real data pushed to the stream.
2005          */
2006         .live = true,
2007     };
2008 
2009     test_precopy_common(&args);
2010 }
2011 
2012 static void test_precopy_unix_compress(void)
2013 {
2014     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
2015     MigrateCommon args = {
2016         .connect_uri = uri,
2017         .listen_uri = uri,
2018         .start_hook = test_migrate_compress_start,
2019         /*
2020          * Test that no invalid thread state is left over from
2021          * the previous iteration.
2022          */
2023         .iterations = 2,
2024         /*
2025          * We make sure the compressor can always work well even if guest
2026          * memory is changing.  See commit 34ab9e9743 where we used to fix
2027          * a bug when only trigger-able with guest memory changing.
2028          */
2029         .live = true,
2030     };
2031 
2032     test_precopy_common(&args);
2033 }
2034 
2035 static void test_precopy_unix_compress_nowait(void)
2036 {
2037     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
2038     MigrateCommon args = {
2039         .connect_uri = uri,
2040         .listen_uri = uri,
2041         .start_hook = test_migrate_compress_nowait_start,
2042         /*
2043          * Test that no invalid thread state is left over from
2044          * the previous iteration.
2045          */
2046         .iterations = 2,
2047         /* Same reason for the wait version of precopy compress test */
2048         .live = true,
2049     };
2050 
2051     test_precopy_common(&args);
2052 }
2053 
2054 static void test_precopy_file(void)
2055 {
2056     g_autofree char *uri = g_strdup_printf("file:%s/%s", tmpfs,
2057                                            FILE_TEST_FILENAME);
2058     MigrateCommon args = {
2059         .connect_uri = uri,
2060         .listen_uri = "defer",
2061     };
2062 
2063     test_file_common(&args, true);
2064 }
2065 
2066 static void file_offset_finish_hook(QTestState *from, QTestState *to,
2067                                     void *opaque)
2068 {
2069 #if defined(__linux__)
2070     g_autofree char *path = g_strdup_printf("%s/%s", tmpfs, FILE_TEST_FILENAME);
2071     size_t size = FILE_TEST_OFFSET + sizeof(QEMU_VM_FILE_MAGIC);
2072     uintptr_t *addr, *p;
2073     int fd;
2074 
2075     fd = open(path, O_RDONLY);
2076     g_assert(fd != -1);
2077     addr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
2078     g_assert(addr != MAP_FAILED);
2079 
2080     /*
2081      * Ensure the skipped offset contains zeros and the migration
2082      * stream starts at the right place.
2083      */
2084     p = addr;
2085     while (p < addr + FILE_TEST_OFFSET / sizeof(uintptr_t)) {
2086         g_assert(*p == 0);
2087         p++;
2088     }
2089     g_assert_cmpint(cpu_to_be64(*p) >> 32, ==, QEMU_VM_FILE_MAGIC);
2090 
2091     munmap(addr, size);
2092     close(fd);
2093 #endif
2094 }
2095 
2096 static void test_precopy_file_offset(void)
2097 {
2098     g_autofree char *uri = g_strdup_printf("file:%s/%s,offset=%d", tmpfs,
2099                                            FILE_TEST_FILENAME,
2100                                            FILE_TEST_OFFSET);
2101     MigrateCommon args = {
2102         .connect_uri = uri,
2103         .listen_uri = "defer",
2104         .finish_hook = file_offset_finish_hook,
2105     };
2106 
2107     test_file_common(&args, false);
2108 }
2109 
2110 static void test_precopy_file_offset_bad(void)
2111 {
2112     /* using a value not supported by qemu_strtosz() */
2113     g_autofree char *uri = g_strdup_printf("file:%s/%s,offset=0x20M",
2114                                            tmpfs, FILE_TEST_FILENAME);
2115     MigrateCommon args = {
2116         .connect_uri = uri,
2117         .listen_uri = "defer",
2118         .result = MIG_TEST_QMP_ERROR,
2119     };
2120 
2121     test_file_common(&args, false);
2122 }
2123 
2124 static void *test_mode_reboot_start(QTestState *from, QTestState *to)
2125 {
2126     migrate_set_parameter_str(from, "mode", "cpr-reboot");
2127     migrate_set_parameter_str(to, "mode", "cpr-reboot");
2128 
2129     migrate_set_capability(from, "x-ignore-shared", true);
2130     migrate_set_capability(to, "x-ignore-shared", true);
2131 
2132     return NULL;
2133 }
2134 
2135 static void test_mode_reboot(void)
2136 {
2137     g_autofree char *uri = g_strdup_printf("file:%s/%s", tmpfs,
2138                                            FILE_TEST_FILENAME);
2139     MigrateCommon args = {
2140         .start.use_shmem = true,
2141         .connect_uri = uri,
2142         .listen_uri = "defer",
2143         .start_hook = test_mode_reboot_start
2144     };
2145 
2146     test_file_common(&args, true);
2147 }
2148 
2149 static void test_precopy_tcp_plain(void)
2150 {
2151     MigrateCommon args = {
2152         .listen_uri = "tcp:127.0.0.1:0",
2153     };
2154 
2155     test_precopy_common(&args);
2156 }
2157 
2158 static void *test_migrate_switchover_ack_start(QTestState *from, QTestState *to)
2159 {
2160 
2161     migrate_set_capability(from, "return-path", true);
2162     migrate_set_capability(to, "return-path", true);
2163 
2164     migrate_set_capability(from, "switchover-ack", true);
2165     migrate_set_capability(to, "switchover-ack", true);
2166 
2167     return NULL;
2168 }
2169 
2170 static void test_precopy_tcp_switchover_ack(void)
2171 {
2172     MigrateCommon args = {
2173         .listen_uri = "tcp:127.0.0.1:0",
2174         .start_hook = test_migrate_switchover_ack_start,
2175         /*
2176          * Source VM must be running in order to consider the switchover ACK
2177          * when deciding to do switchover or not.
2178          */
2179         .live = true,
2180     };
2181 
2182     test_precopy_common(&args);
2183 }
2184 
2185 #ifdef CONFIG_GNUTLS
2186 static void test_precopy_tcp_tls_psk_match(void)
2187 {
2188     MigrateCommon args = {
2189         .listen_uri = "tcp:127.0.0.1:0",
2190         .start_hook = test_migrate_tls_psk_start_match,
2191         .finish_hook = test_migrate_tls_psk_finish,
2192     };
2193 
2194     test_precopy_common(&args);
2195 }
2196 
2197 static void test_precopy_tcp_tls_psk_mismatch(void)
2198 {
2199     MigrateCommon args = {
2200         .start = {
2201             .hide_stderr = true,
2202         },
2203         .listen_uri = "tcp:127.0.0.1:0",
2204         .start_hook = test_migrate_tls_psk_start_mismatch,
2205         .finish_hook = test_migrate_tls_psk_finish,
2206         .result = MIG_TEST_FAIL,
2207     };
2208 
2209     test_precopy_common(&args);
2210 }
2211 
2212 #ifdef CONFIG_TASN1
2213 static void test_precopy_tcp_tls_x509_default_host(void)
2214 {
2215     MigrateCommon args = {
2216         .listen_uri = "tcp:127.0.0.1:0",
2217         .start_hook = test_migrate_tls_x509_start_default_host,
2218         .finish_hook = test_migrate_tls_x509_finish,
2219     };
2220 
2221     test_precopy_common(&args);
2222 }
2223 
2224 static void test_precopy_tcp_tls_x509_override_host(void)
2225 {
2226     MigrateCommon args = {
2227         .listen_uri = "tcp:127.0.0.1:0",
2228         .start_hook = test_migrate_tls_x509_start_override_host,
2229         .finish_hook = test_migrate_tls_x509_finish,
2230     };
2231 
2232     test_precopy_common(&args);
2233 }
2234 
2235 static void test_precopy_tcp_tls_x509_mismatch_host(void)
2236 {
2237     MigrateCommon args = {
2238         .start = {
2239             .hide_stderr = true,
2240         },
2241         .listen_uri = "tcp:127.0.0.1:0",
2242         .start_hook = test_migrate_tls_x509_start_mismatch_host,
2243         .finish_hook = test_migrate_tls_x509_finish,
2244         .result = MIG_TEST_FAIL_DEST_QUIT_ERR,
2245     };
2246 
2247     test_precopy_common(&args);
2248 }
2249 
2250 static void test_precopy_tcp_tls_x509_friendly_client(void)
2251 {
2252     MigrateCommon args = {
2253         .listen_uri = "tcp:127.0.0.1:0",
2254         .start_hook = test_migrate_tls_x509_start_friendly_client,
2255         .finish_hook = test_migrate_tls_x509_finish,
2256     };
2257 
2258     test_precopy_common(&args);
2259 }
2260 
2261 static void test_precopy_tcp_tls_x509_hostile_client(void)
2262 {
2263     MigrateCommon args = {
2264         .start = {
2265             .hide_stderr = true,
2266         },
2267         .listen_uri = "tcp:127.0.0.1:0",
2268         .start_hook = test_migrate_tls_x509_start_hostile_client,
2269         .finish_hook = test_migrate_tls_x509_finish,
2270         .result = MIG_TEST_FAIL,
2271     };
2272 
2273     test_precopy_common(&args);
2274 }
2275 
2276 static void test_precopy_tcp_tls_x509_allow_anon_client(void)
2277 {
2278     MigrateCommon args = {
2279         .listen_uri = "tcp:127.0.0.1:0",
2280         .start_hook = test_migrate_tls_x509_start_allow_anon_client,
2281         .finish_hook = test_migrate_tls_x509_finish,
2282     };
2283 
2284     test_precopy_common(&args);
2285 }
2286 
2287 static void test_precopy_tcp_tls_x509_reject_anon_client(void)
2288 {
2289     MigrateCommon args = {
2290         .start = {
2291             .hide_stderr = true,
2292         },
2293         .listen_uri = "tcp:127.0.0.1:0",
2294         .start_hook = test_migrate_tls_x509_start_reject_anon_client,
2295         .finish_hook = test_migrate_tls_x509_finish,
2296         .result = MIG_TEST_FAIL,
2297     };
2298 
2299     test_precopy_common(&args);
2300 }
2301 #endif /* CONFIG_TASN1 */
2302 #endif /* CONFIG_GNUTLS */
2303 
2304 #ifndef _WIN32
2305 static void *test_migrate_fd_start_hook(QTestState *from,
2306                                         QTestState *to)
2307 {
2308     int ret;
2309     int pair[2];
2310 
2311     /* Create two connected sockets for migration */
2312     ret = qemu_socketpair(PF_LOCAL, SOCK_STREAM, 0, pair);
2313     g_assert_cmpint(ret, ==, 0);
2314 
2315     /* Send the 1st socket to the target */
2316     qtest_qmp_fds_assert_success(to, &pair[0], 1,
2317                                  "{ 'execute': 'getfd',"
2318                                  "  'arguments': { 'fdname': 'fd-mig' }}");
2319     close(pair[0]);
2320 
2321     /* Start incoming migration from the 1st socket */
2322     migrate_incoming_qmp(to, "fd:fd-mig", "{}");
2323 
2324     /* Send the 2nd socket to the target */
2325     qtest_qmp_fds_assert_success(from, &pair[1], 1,
2326                                  "{ 'execute': 'getfd',"
2327                                  "  'arguments': { 'fdname': 'fd-mig' }}");
2328     close(pair[1]);
2329 
2330     return NULL;
2331 }
2332 
2333 static void test_migrate_fd_finish_hook(QTestState *from,
2334                                         QTestState *to,
2335                                         void *opaque)
2336 {
2337     QDict *rsp;
2338     const char *error_desc;
2339 
2340     /* Test closing fds */
2341     /* We assume, that QEMU removes named fd from its list,
2342      * so this should fail */
2343     rsp = qtest_qmp(from, "{ 'execute': 'closefd',"
2344                           "  'arguments': { 'fdname': 'fd-mig' }}");
2345     g_assert_true(qdict_haskey(rsp, "error"));
2346     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
2347     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
2348     qobject_unref(rsp);
2349 
2350     rsp = qtest_qmp(to, "{ 'execute': 'closefd',"
2351                         "  'arguments': { 'fdname': 'fd-mig' }}");
2352     g_assert_true(qdict_haskey(rsp, "error"));
2353     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
2354     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
2355     qobject_unref(rsp);
2356 }
2357 
2358 static void test_migrate_fd_proto(void)
2359 {
2360     MigrateCommon args = {
2361         .listen_uri = "defer",
2362         .connect_uri = "fd:fd-mig",
2363         .start_hook = test_migrate_fd_start_hook,
2364         .finish_hook = test_migrate_fd_finish_hook
2365     };
2366     test_precopy_common(&args);
2367 }
2368 #endif /* _WIN32 */
2369 
2370 static void do_test_validate_uuid(MigrateStart *args, bool should_fail)
2371 {
2372     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
2373     QTestState *from, *to;
2374 
2375     if (test_migrate_start(&from, &to, uri, args)) {
2376         return;
2377     }
2378 
2379     /*
2380      * UUID validation is at the begin of migration. So, the main process of
2381      * migration is not interesting for us here. Thus, set huge downtime for
2382      * very fast migration.
2383      */
2384     migrate_set_parameter_int(from, "downtime-limit", 1000000);
2385     migrate_set_capability(from, "validate-uuid", true);
2386 
2387     /* Wait for the first serial output from the source */
2388     wait_for_serial("src_serial");
2389 
2390     migrate_qmp(from, uri, "{}");
2391 
2392     if (should_fail) {
2393         qtest_set_expected_status(to, EXIT_FAILURE);
2394         wait_for_migration_fail(from, true);
2395     } else {
2396         wait_for_migration_complete(from);
2397     }
2398 
2399     test_migrate_end(from, to, false);
2400 }
2401 
2402 static void test_validate_uuid(void)
2403 {
2404     MigrateStart args = {
2405         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
2406         .opts_target = "-uuid 11111111-1111-1111-1111-111111111111",
2407     };
2408 
2409     do_test_validate_uuid(&args, false);
2410 }
2411 
2412 static void test_validate_uuid_error(void)
2413 {
2414     MigrateStart args = {
2415         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
2416         .opts_target = "-uuid 22222222-2222-2222-2222-222222222222",
2417         .hide_stderr = true,
2418     };
2419 
2420     do_test_validate_uuid(&args, true);
2421 }
2422 
2423 static void test_validate_uuid_src_not_set(void)
2424 {
2425     MigrateStart args = {
2426         .opts_target = "-uuid 22222222-2222-2222-2222-222222222222",
2427         .hide_stderr = true,
2428     };
2429 
2430     do_test_validate_uuid(&args, false);
2431 }
2432 
2433 static void test_validate_uuid_dst_not_set(void)
2434 {
2435     MigrateStart args = {
2436         .opts_source = "-uuid 11111111-1111-1111-1111-111111111111",
2437         .hide_stderr = true,
2438     };
2439 
2440     do_test_validate_uuid(&args, false);
2441 }
2442 
2443 /*
2444  * The way auto_converge works, we need to do too many passes to
2445  * run this test.  Auto_converge logic is only run once every
2446  * three iterations, so:
2447  *
2448  * - 3 iterations without auto_converge enabled
2449  * - 3 iterations with pct = 5
2450  * - 3 iterations with pct = 30
2451  * - 3 iterations with pct = 55
2452  * - 3 iterations with pct = 80
2453  * - 3 iterations with pct = 95 (max(95, 80 + 25))
2454  *
2455  * To make things even worse, we need to run the initial stage at
2456  * 3MB/s so we enter autoconverge even when host is (over)loaded.
2457  */
2458 static void test_migrate_auto_converge(void)
2459 {
2460     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
2461     MigrateStart args = {};
2462     QTestState *from, *to;
2463     int64_t percentage;
2464 
2465     /*
2466      * We want the test to be stable and as fast as possible.
2467      * E.g., with 1Gb/s bandwidth migration may pass without throttling,
2468      * so we need to decrease a bandwidth.
2469      */
2470     const int64_t init_pct = 5, inc_pct = 25, max_pct = 95;
2471 
2472     if (test_migrate_start(&from, &to, uri, &args)) {
2473         return;
2474     }
2475 
2476     migrate_set_capability(from, "auto-converge", true);
2477     migrate_set_parameter_int(from, "cpu-throttle-initial", init_pct);
2478     migrate_set_parameter_int(from, "cpu-throttle-increment", inc_pct);
2479     migrate_set_parameter_int(from, "max-cpu-throttle", max_pct);
2480 
2481     /*
2482      * Set the initial parameters so that the migration could not converge
2483      * without throttling.
2484      */
2485     migrate_ensure_non_converge(from);
2486 
2487     /* To check remaining size after precopy */
2488     migrate_set_capability(from, "pause-before-switchover", true);
2489 
2490     /* Wait for the first serial output from the source */
2491     wait_for_serial("src_serial");
2492 
2493     migrate_qmp(from, uri, "{}");
2494 
2495     /* Wait for throttling begins */
2496     percentage = 0;
2497     do {
2498         percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
2499         if (percentage != 0) {
2500             break;
2501         }
2502         usleep(20);
2503         g_assert_false(src_state.stop_seen);
2504     } while (true);
2505     /* The first percentage of throttling should be at least init_pct */
2506     g_assert_cmpint(percentage, >=, init_pct);
2507     /* Now, when we tested that throttling works, let it converge */
2508     migrate_ensure_converge(from);
2509 
2510     /*
2511      * Wait for pre-switchover status to check last throttle percentage
2512      * and remaining. These values will be zeroed later
2513      */
2514     wait_for_migration_status(from, "pre-switchover", NULL);
2515 
2516     /* The final percentage of throttling shouldn't be greater than max_pct */
2517     percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
2518     g_assert_cmpint(percentage, <=, max_pct);
2519     migrate_continue(from, "pre-switchover");
2520 
2521     qtest_qmp_eventwait(to, "RESUME");
2522 
2523     wait_for_serial("dest_serial");
2524     wait_for_migration_complete(from);
2525 
2526     test_migrate_end(from, to, true);
2527 }
2528 
2529 static void *
2530 test_migrate_precopy_tcp_multifd_start_common(QTestState *from,
2531                                               QTestState *to,
2532                                               const char *method)
2533 {
2534     migrate_set_parameter_int(from, "multifd-channels", 16);
2535     migrate_set_parameter_int(to, "multifd-channels", 16);
2536 
2537     migrate_set_parameter_str(from, "multifd-compression", method);
2538     migrate_set_parameter_str(to, "multifd-compression", method);
2539 
2540     migrate_set_capability(from, "multifd", true);
2541     migrate_set_capability(to, "multifd", true);
2542 
2543     /* Start incoming migration from the 1st socket */
2544     migrate_incoming_qmp(to, "tcp:127.0.0.1:0", "{}");
2545 
2546     return NULL;
2547 }
2548 
2549 static void *
2550 test_migrate_precopy_tcp_multifd_start(QTestState *from,
2551                                        QTestState *to)
2552 {
2553     return test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2554 }
2555 
2556 static void *
2557 test_migrate_precopy_tcp_multifd_zlib_start(QTestState *from,
2558                                             QTestState *to)
2559 {
2560     return test_migrate_precopy_tcp_multifd_start_common(from, to, "zlib");
2561 }
2562 
2563 #ifdef CONFIG_ZSTD
2564 static void *
2565 test_migrate_precopy_tcp_multifd_zstd_start(QTestState *from,
2566                                             QTestState *to)
2567 {
2568     return test_migrate_precopy_tcp_multifd_start_common(from, to, "zstd");
2569 }
2570 #endif /* CONFIG_ZSTD */
2571 
2572 static void test_multifd_tcp_none(void)
2573 {
2574     MigrateCommon args = {
2575         .listen_uri = "defer",
2576         .start_hook = test_migrate_precopy_tcp_multifd_start,
2577         /*
2578          * Multifd is more complicated than most of the features, it
2579          * directly takes guest page buffers when sending, make sure
2580          * everything will work alright even if guest page is changing.
2581          */
2582         .live = true,
2583     };
2584     test_precopy_common(&args);
2585 }
2586 
2587 static void test_multifd_tcp_zlib(void)
2588 {
2589     MigrateCommon args = {
2590         .listen_uri = "defer",
2591         .start_hook = test_migrate_precopy_tcp_multifd_zlib_start,
2592     };
2593     test_precopy_common(&args);
2594 }
2595 
2596 #ifdef CONFIG_ZSTD
2597 static void test_multifd_tcp_zstd(void)
2598 {
2599     MigrateCommon args = {
2600         .listen_uri = "defer",
2601         .start_hook = test_migrate_precopy_tcp_multifd_zstd_start,
2602     };
2603     test_precopy_common(&args);
2604 }
2605 #endif
2606 
2607 #ifdef CONFIG_GNUTLS
2608 static void *
2609 test_migrate_multifd_tcp_tls_psk_start_match(QTestState *from,
2610                                              QTestState *to)
2611 {
2612     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2613     return test_migrate_tls_psk_start_match(from, to);
2614 }
2615 
2616 static void *
2617 test_migrate_multifd_tcp_tls_psk_start_mismatch(QTestState *from,
2618                                                 QTestState *to)
2619 {
2620     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2621     return test_migrate_tls_psk_start_mismatch(from, to);
2622 }
2623 
2624 #ifdef CONFIG_TASN1
2625 static void *
2626 test_migrate_multifd_tls_x509_start_default_host(QTestState *from,
2627                                                  QTestState *to)
2628 {
2629     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2630     return test_migrate_tls_x509_start_default_host(from, to);
2631 }
2632 
2633 static void *
2634 test_migrate_multifd_tls_x509_start_override_host(QTestState *from,
2635                                                   QTestState *to)
2636 {
2637     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2638     return test_migrate_tls_x509_start_override_host(from, to);
2639 }
2640 
2641 static void *
2642 test_migrate_multifd_tls_x509_start_mismatch_host(QTestState *from,
2643                                                   QTestState *to)
2644 {
2645     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2646     return test_migrate_tls_x509_start_mismatch_host(from, to);
2647 }
2648 
2649 static void *
2650 test_migrate_multifd_tls_x509_start_allow_anon_client(QTestState *from,
2651                                                       QTestState *to)
2652 {
2653     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2654     return test_migrate_tls_x509_start_allow_anon_client(from, to);
2655 }
2656 
2657 static void *
2658 test_migrate_multifd_tls_x509_start_reject_anon_client(QTestState *from,
2659                                                        QTestState *to)
2660 {
2661     test_migrate_precopy_tcp_multifd_start_common(from, to, "none");
2662     return test_migrate_tls_x509_start_reject_anon_client(from, to);
2663 }
2664 #endif /* CONFIG_TASN1 */
2665 
2666 static void test_multifd_tcp_tls_psk_match(void)
2667 {
2668     MigrateCommon args = {
2669         .listen_uri = "defer",
2670         .start_hook = test_migrate_multifd_tcp_tls_psk_start_match,
2671         .finish_hook = test_migrate_tls_psk_finish,
2672     };
2673     test_precopy_common(&args);
2674 }
2675 
2676 static void test_multifd_tcp_tls_psk_mismatch(void)
2677 {
2678     MigrateCommon args = {
2679         .start = {
2680             .hide_stderr = true,
2681         },
2682         .listen_uri = "defer",
2683         .start_hook = test_migrate_multifd_tcp_tls_psk_start_mismatch,
2684         .finish_hook = test_migrate_tls_psk_finish,
2685         .result = MIG_TEST_FAIL,
2686     };
2687     test_precopy_common(&args);
2688 }
2689 
2690 #ifdef CONFIG_TASN1
2691 static void test_multifd_tcp_tls_x509_default_host(void)
2692 {
2693     MigrateCommon args = {
2694         .listen_uri = "defer",
2695         .start_hook = test_migrate_multifd_tls_x509_start_default_host,
2696         .finish_hook = test_migrate_tls_x509_finish,
2697     };
2698     test_precopy_common(&args);
2699 }
2700 
2701 static void test_multifd_tcp_tls_x509_override_host(void)
2702 {
2703     MigrateCommon args = {
2704         .listen_uri = "defer",
2705         .start_hook = test_migrate_multifd_tls_x509_start_override_host,
2706         .finish_hook = test_migrate_tls_x509_finish,
2707     };
2708     test_precopy_common(&args);
2709 }
2710 
2711 static void test_multifd_tcp_tls_x509_mismatch_host(void)
2712 {
2713     /*
2714      * This has different behaviour to the non-multifd case.
2715      *
2716      * In non-multifd case when client aborts due to mismatched
2717      * cert host, the server has already started trying to load
2718      * migration state, and so it exits with I/O failure.
2719      *
2720      * In multifd case when client aborts due to mismatched
2721      * cert host, the server is still waiting for the other
2722      * multifd connections to arrive so hasn't started trying
2723      * to load migration state, and thus just aborts the migration
2724      * without exiting.
2725      */
2726     MigrateCommon args = {
2727         .start = {
2728             .hide_stderr = true,
2729         },
2730         .listen_uri = "defer",
2731         .start_hook = test_migrate_multifd_tls_x509_start_mismatch_host,
2732         .finish_hook = test_migrate_tls_x509_finish,
2733         .result = MIG_TEST_FAIL,
2734     };
2735     test_precopy_common(&args);
2736 }
2737 
2738 static void test_multifd_tcp_tls_x509_allow_anon_client(void)
2739 {
2740     MigrateCommon args = {
2741         .listen_uri = "defer",
2742         .start_hook = test_migrate_multifd_tls_x509_start_allow_anon_client,
2743         .finish_hook = test_migrate_tls_x509_finish,
2744     };
2745     test_precopy_common(&args);
2746 }
2747 
2748 static void test_multifd_tcp_tls_x509_reject_anon_client(void)
2749 {
2750     MigrateCommon args = {
2751         .start = {
2752             .hide_stderr = true,
2753         },
2754         .listen_uri = "defer",
2755         .start_hook = test_migrate_multifd_tls_x509_start_reject_anon_client,
2756         .finish_hook = test_migrate_tls_x509_finish,
2757         .result = MIG_TEST_FAIL,
2758     };
2759     test_precopy_common(&args);
2760 }
2761 #endif /* CONFIG_TASN1 */
2762 #endif /* CONFIG_GNUTLS */
2763 
2764 /*
2765  * This test does:
2766  *  source               target
2767  *                       migrate_incoming
2768  *     migrate
2769  *     migrate_cancel
2770  *                       launch another target
2771  *     migrate
2772  *
2773  *  And see that it works
2774  */
2775 static void test_multifd_tcp_cancel(void)
2776 {
2777     MigrateStart args = {
2778         .hide_stderr = true,
2779     };
2780     QTestState *from, *to, *to2;
2781     g_autofree char *uri = NULL;
2782 
2783     if (test_migrate_start(&from, &to, "defer", &args)) {
2784         return;
2785     }
2786 
2787     migrate_ensure_non_converge(from);
2788     migrate_prepare_for_dirty_mem(from);
2789 
2790     migrate_set_parameter_int(from, "multifd-channels", 16);
2791     migrate_set_parameter_int(to, "multifd-channels", 16);
2792 
2793     migrate_set_capability(from, "multifd", true);
2794     migrate_set_capability(to, "multifd", true);
2795 
2796     /* Start incoming migration from the 1st socket */
2797     migrate_incoming_qmp(to, "tcp:127.0.0.1:0", "{}");
2798 
2799     /* Wait for the first serial output from the source */
2800     wait_for_serial("src_serial");
2801 
2802     uri = migrate_get_socket_address(to, "socket-address");
2803 
2804     migrate_qmp(from, uri, "{}");
2805 
2806     migrate_wait_for_dirty_mem(from, to);
2807 
2808     migrate_cancel(from);
2809 
2810     /* Make sure QEMU process "to" exited */
2811     qtest_set_expected_status(to, EXIT_FAILURE);
2812     qtest_wait_qemu(to);
2813 
2814     args = (MigrateStart){
2815         .only_target = true,
2816     };
2817 
2818     if (test_migrate_start(&from, &to2, "defer", &args)) {
2819         return;
2820     }
2821 
2822     migrate_set_parameter_int(to2, "multifd-channels", 16);
2823 
2824     migrate_set_capability(to2, "multifd", true);
2825 
2826     /* Start incoming migration from the 1st socket */
2827     migrate_incoming_qmp(to2, "tcp:127.0.0.1:0", "{}");
2828 
2829     g_free(uri);
2830     uri = migrate_get_socket_address(to2, "socket-address");
2831 
2832     wait_for_migration_status(from, "cancelled", NULL);
2833 
2834     migrate_ensure_non_converge(from);
2835 
2836     migrate_qmp(from, uri, "{}");
2837 
2838     migrate_wait_for_dirty_mem(from, to2);
2839 
2840     migrate_ensure_converge(from);
2841 
2842     wait_for_stop(from, &src_state);
2843     qtest_qmp_eventwait(to2, "RESUME");
2844 
2845     wait_for_serial("dest_serial");
2846     wait_for_migration_complete(from);
2847     test_migrate_end(from, to2, true);
2848 }
2849 
2850 static void calc_dirty_rate(QTestState *who, uint64_t calc_time)
2851 {
2852     qtest_qmp_assert_success(who,
2853                              "{ 'execute': 'calc-dirty-rate',"
2854                              "'arguments': { "
2855                              "'calc-time': %" PRIu64 ","
2856                              "'mode': 'dirty-ring' }}",
2857                              calc_time);
2858 }
2859 
2860 static QDict *query_dirty_rate(QTestState *who)
2861 {
2862     return qtest_qmp_assert_success_ref(who,
2863                                         "{ 'execute': 'query-dirty-rate' }");
2864 }
2865 
2866 static void dirtylimit_set_all(QTestState *who, uint64_t dirtyrate)
2867 {
2868     qtest_qmp_assert_success(who,
2869                              "{ 'execute': 'set-vcpu-dirty-limit',"
2870                              "'arguments': { "
2871                              "'dirty-rate': %" PRIu64 " } }",
2872                              dirtyrate);
2873 }
2874 
2875 static void cancel_vcpu_dirty_limit(QTestState *who)
2876 {
2877     qtest_qmp_assert_success(who,
2878                              "{ 'execute': 'cancel-vcpu-dirty-limit' }");
2879 }
2880 
2881 static QDict *query_vcpu_dirty_limit(QTestState *who)
2882 {
2883     QDict *rsp;
2884 
2885     rsp = qtest_qmp(who, "{ 'execute': 'query-vcpu-dirty-limit' }");
2886     g_assert(!qdict_haskey(rsp, "error"));
2887     g_assert(qdict_haskey(rsp, "return"));
2888 
2889     return rsp;
2890 }
2891 
2892 static bool calc_dirtyrate_ready(QTestState *who)
2893 {
2894     QDict *rsp_return;
2895     gchar *status;
2896 
2897     rsp_return = query_dirty_rate(who);
2898     g_assert(rsp_return);
2899 
2900     status = g_strdup(qdict_get_str(rsp_return, "status"));
2901     g_assert(status);
2902 
2903     return g_strcmp0(status, "measuring");
2904 }
2905 
2906 static void wait_for_calc_dirtyrate_complete(QTestState *who,
2907                                              int64_t time_s)
2908 {
2909     int max_try_count = 10000;
2910     usleep(time_s * 1000000);
2911 
2912     while (!calc_dirtyrate_ready(who) && max_try_count--) {
2913         usleep(1000);
2914     }
2915 
2916     /*
2917      * Set the timeout with 10 s(max_try_count * 1000us),
2918      * if dirtyrate measurement not complete, fail test.
2919      */
2920     g_assert_cmpint(max_try_count, !=, 0);
2921 }
2922 
2923 static int64_t get_dirty_rate(QTestState *who)
2924 {
2925     QDict *rsp_return;
2926     gchar *status;
2927     QList *rates;
2928     const QListEntry *entry;
2929     QDict *rate;
2930     int64_t dirtyrate;
2931 
2932     rsp_return = query_dirty_rate(who);
2933     g_assert(rsp_return);
2934 
2935     status = g_strdup(qdict_get_str(rsp_return, "status"));
2936     g_assert(status);
2937     g_assert_cmpstr(status, ==, "measured");
2938 
2939     rates = qdict_get_qlist(rsp_return, "vcpu-dirty-rate");
2940     g_assert(rates && !qlist_empty(rates));
2941 
2942     entry = qlist_first(rates);
2943     g_assert(entry);
2944 
2945     rate = qobject_to(QDict, qlist_entry_obj(entry));
2946     g_assert(rate);
2947 
2948     dirtyrate = qdict_get_try_int(rate, "dirty-rate", -1);
2949 
2950     qobject_unref(rsp_return);
2951     return dirtyrate;
2952 }
2953 
2954 static int64_t get_limit_rate(QTestState *who)
2955 {
2956     QDict *rsp_return;
2957     QList *rates;
2958     const QListEntry *entry;
2959     QDict *rate;
2960     int64_t dirtyrate;
2961 
2962     rsp_return = query_vcpu_dirty_limit(who);
2963     g_assert(rsp_return);
2964 
2965     rates = qdict_get_qlist(rsp_return, "return");
2966     g_assert(rates && !qlist_empty(rates));
2967 
2968     entry = qlist_first(rates);
2969     g_assert(entry);
2970 
2971     rate = qobject_to(QDict, qlist_entry_obj(entry));
2972     g_assert(rate);
2973 
2974     dirtyrate = qdict_get_try_int(rate, "limit-rate", -1);
2975 
2976     qobject_unref(rsp_return);
2977     return dirtyrate;
2978 }
2979 
2980 static QTestState *dirtylimit_start_vm(void)
2981 {
2982     QTestState *vm = NULL;
2983     g_autofree gchar *
2984     cmd = g_strdup_printf("-accel kvm,dirty-ring-size=4096 "
2985                           "-name dirtylimit-test,debug-threads=on "
2986                           "-m 150M -smp 1 "
2987                           "-serial file:%s/vm_serial "
2988                           "-drive file=%s,format=raw ",
2989                           tmpfs, bootpath);
2990 
2991     vm = qtest_init(cmd);
2992     return vm;
2993 }
2994 
2995 static void dirtylimit_stop_vm(QTestState *vm)
2996 {
2997     qtest_quit(vm);
2998     cleanup("vm_serial");
2999 }
3000 
3001 static void test_vcpu_dirty_limit(void)
3002 {
3003     QTestState *vm;
3004     int64_t origin_rate;
3005     int64_t quota_rate;
3006     int64_t rate ;
3007     int max_try_count = 20;
3008     int hit = 0;
3009 
3010     /* Start vm for vcpu dirtylimit test */
3011     vm = dirtylimit_start_vm();
3012 
3013     /* Wait for the first serial output from the vm*/
3014     wait_for_serial("vm_serial");
3015 
3016     /* Do dirtyrate measurement with calc time equals 1s */
3017     calc_dirty_rate(vm, 1);
3018 
3019     /* Sleep calc time and wait for calc dirtyrate complete */
3020     wait_for_calc_dirtyrate_complete(vm, 1);
3021 
3022     /* Query original dirty page rate */
3023     origin_rate = get_dirty_rate(vm);
3024 
3025     /* VM booted from bootsect should dirty memory steadily */
3026     assert(origin_rate != 0);
3027 
3028     /* Setup quota dirty page rate at half of origin */
3029     quota_rate = origin_rate / 2;
3030 
3031     /* Set dirtylimit */
3032     dirtylimit_set_all(vm, quota_rate);
3033 
3034     /*
3035      * Check if set-vcpu-dirty-limit and query-vcpu-dirty-limit
3036      * works literally
3037      */
3038     g_assert_cmpint(quota_rate, ==, get_limit_rate(vm));
3039 
3040     /* Sleep a bit to check if it take effect */
3041     usleep(2000000);
3042 
3043     /*
3044      * Check if dirtylimit take effect realistically, set the
3045      * timeout with 20 s(max_try_count * 1s), if dirtylimit
3046      * doesn't take effect, fail test.
3047      */
3048     while (--max_try_count) {
3049         calc_dirty_rate(vm, 1);
3050         wait_for_calc_dirtyrate_complete(vm, 1);
3051         rate = get_dirty_rate(vm);
3052 
3053         /*
3054          * Assume hitting if current rate is less
3055          * than quota rate (within accepting error)
3056          */
3057         if (rate < (quota_rate + DIRTYLIMIT_TOLERANCE_RANGE)) {
3058             hit = 1;
3059             break;
3060         }
3061     }
3062 
3063     g_assert_cmpint(hit, ==, 1);
3064 
3065     hit = 0;
3066     max_try_count = 20;
3067 
3068     /* Check if dirtylimit cancellation take effect */
3069     cancel_vcpu_dirty_limit(vm);
3070     while (--max_try_count) {
3071         calc_dirty_rate(vm, 1);
3072         wait_for_calc_dirtyrate_complete(vm, 1);
3073         rate = get_dirty_rate(vm);
3074 
3075         /*
3076          * Assume dirtylimit be canceled if current rate is
3077          * greater than quota rate (within accepting error)
3078          */
3079         if (rate > (quota_rate + DIRTYLIMIT_TOLERANCE_RANGE)) {
3080             hit = 1;
3081             break;
3082         }
3083     }
3084 
3085     g_assert_cmpint(hit, ==, 1);
3086     dirtylimit_stop_vm(vm);
3087 }
3088 
3089 static void migrate_dirty_limit_wait_showup(QTestState *from,
3090                                             const int64_t period,
3091                                             const int64_t value)
3092 {
3093     /* Enable dirty limit capability */
3094     migrate_set_capability(from, "dirty-limit", true);
3095 
3096     /* Set dirty limit parameters */
3097     migrate_set_parameter_int(from, "x-vcpu-dirty-limit-period", period);
3098     migrate_set_parameter_int(from, "vcpu-dirty-limit", value);
3099 
3100     /* Make sure migrate can't converge */
3101     migrate_ensure_non_converge(from);
3102 
3103     /* To check limit rate after precopy */
3104     migrate_set_capability(from, "pause-before-switchover", true);
3105 
3106     /* Wait for the serial output from the source */
3107     wait_for_serial("src_serial");
3108 }
3109 
3110 /*
3111  * This test does:
3112  *  source                          destination
3113  *  start vm
3114  *                                  start incoming vm
3115  *  migrate
3116  *  wait dirty limit to begin
3117  *  cancel migrate
3118  *  cancellation check
3119  *                                  restart incoming vm
3120  *  migrate
3121  *  wait dirty limit to begin
3122  *  wait pre-switchover event
3123  *  convergence condition check
3124  *
3125  * And see if dirty limit migration works correctly.
3126  * This test case involves many passes, so it runs in slow mode only.
3127  */
3128 static void test_migrate_dirty_limit(void)
3129 {
3130     g_autofree char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
3131     QTestState *from, *to;
3132     int64_t remaining;
3133     uint64_t throttle_us_per_full;
3134     /*
3135      * We want the test to be stable and as fast as possible.
3136      * E.g., with 1Gb/s bandwidth migration may pass without dirty limit,
3137      * so we need to decrease a bandwidth.
3138      */
3139     const int64_t dirtylimit_period = 1000, dirtylimit_value = 50;
3140     const int64_t max_bandwidth = 400000000; /* ~400Mb/s */
3141     const int64_t downtime_limit = 250; /* 250ms */
3142     /*
3143      * We migrate through unix-socket (> 500Mb/s).
3144      * Thus, expected migration speed ~= bandwidth limit (< 500Mb/s).
3145      * So, we can predict expected_threshold
3146      */
3147     const int64_t expected_threshold = max_bandwidth * downtime_limit / 1000;
3148     int max_try_count = 10;
3149     MigrateCommon args = {
3150         .start = {
3151             .hide_stderr = true,
3152             .use_dirty_ring = true,
3153         },
3154         .listen_uri = uri,
3155         .connect_uri = uri,
3156     };
3157 
3158     /* Start src, dst vm */
3159     if (test_migrate_start(&from, &to, args.listen_uri, &args.start)) {
3160         return;
3161     }
3162 
3163     /* Prepare for dirty limit migration and wait src vm show up */
3164     migrate_dirty_limit_wait_showup(from, dirtylimit_period, dirtylimit_value);
3165 
3166     /* Start migrate */
3167     migrate_qmp(from, uri, "{}");
3168 
3169     /* Wait for dirty limit throttle begin */
3170     throttle_us_per_full = 0;
3171     while (throttle_us_per_full == 0) {
3172         throttle_us_per_full =
3173         read_migrate_property_int(from, "dirty-limit-throttle-time-per-round");
3174         usleep(100);
3175         g_assert_false(src_state.stop_seen);
3176     }
3177 
3178     /* Now cancel migrate and wait for dirty limit throttle switch off */
3179     migrate_cancel(from);
3180     wait_for_migration_status(from, "cancelled", NULL);
3181 
3182     /* Check if dirty limit throttle switched off, set timeout 1ms */
3183     do {
3184         throttle_us_per_full =
3185         read_migrate_property_int(from, "dirty-limit-throttle-time-per-round");
3186         usleep(100);
3187         g_assert_false(src_state.stop_seen);
3188     } while (throttle_us_per_full != 0 && --max_try_count);
3189 
3190     /* Assert dirty limit is not in service */
3191     g_assert_cmpint(throttle_us_per_full, ==, 0);
3192 
3193     args = (MigrateCommon) {
3194         .start = {
3195             .only_target = true,
3196             .use_dirty_ring = true,
3197         },
3198         .listen_uri = uri,
3199         .connect_uri = uri,
3200     };
3201 
3202     /* Restart dst vm, src vm already show up so we needn't wait anymore */
3203     if (test_migrate_start(&from, &to, args.listen_uri, &args.start)) {
3204         return;
3205     }
3206 
3207     /* Start migrate */
3208     migrate_qmp(from, uri, "{}");
3209 
3210     /* Wait for dirty limit throttle begin */
3211     throttle_us_per_full = 0;
3212     while (throttle_us_per_full == 0) {
3213         throttle_us_per_full =
3214         read_migrate_property_int(from, "dirty-limit-throttle-time-per-round");
3215         usleep(100);
3216         g_assert_false(src_state.stop_seen);
3217     }
3218 
3219     /*
3220      * The dirty limit rate should equals the return value of
3221      * query-vcpu-dirty-limit if dirty limit cap set
3222      */
3223     g_assert_cmpint(dirtylimit_value, ==, get_limit_rate(from));
3224 
3225     /* Now, we have tested if dirty limit works, let it converge */
3226     migrate_set_parameter_int(from, "downtime-limit", downtime_limit);
3227     migrate_set_parameter_int(from, "max-bandwidth", max_bandwidth);
3228 
3229     /*
3230      * Wait for pre-switchover status to check if migration
3231      * satisfy the convergence condition
3232      */
3233     wait_for_migration_status(from, "pre-switchover", NULL);
3234 
3235     remaining = read_ram_property_int(from, "remaining");
3236     g_assert_cmpint(remaining, <,
3237                     (expected_threshold + expected_threshold / 100));
3238 
3239     migrate_continue(from, "pre-switchover");
3240 
3241     qtest_qmp_eventwait(to, "RESUME");
3242 
3243     wait_for_serial("dest_serial");
3244     wait_for_migration_complete(from);
3245 
3246     test_migrate_end(from, to, true);
3247 }
3248 
3249 static bool kvm_dirty_ring_supported(void)
3250 {
3251 #if defined(__linux__) && defined(HOST_X86_64)
3252     int ret, kvm_fd = open("/dev/kvm", O_RDONLY);
3253 
3254     if (kvm_fd < 0) {
3255         return false;
3256     }
3257 
3258     ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING);
3259     close(kvm_fd);
3260 
3261     /* We test with 4096 slots */
3262     if (ret < 4096) {
3263         return false;
3264     }
3265 
3266     return true;
3267 #else
3268     return false;
3269 #endif
3270 }
3271 
3272 int main(int argc, char **argv)
3273 {
3274     bool has_kvm, has_tcg;
3275     bool has_uffd;
3276     const char *arch;
3277     g_autoptr(GError) err = NULL;
3278     const char *qemu_src = getenv(QEMU_ENV_SRC);
3279     const char *qemu_dst = getenv(QEMU_ENV_DST);
3280     int ret;
3281 
3282     g_test_init(&argc, &argv, NULL);
3283 
3284     /*
3285      * The default QTEST_QEMU_BINARY must always be provided because
3286      * that is what helpers use to query the accel type and
3287      * architecture.
3288      */
3289     if (qemu_src && qemu_dst) {
3290         g_test_message("Only one of %s, %s is allowed",
3291                        QEMU_ENV_SRC, QEMU_ENV_DST);
3292         exit(1);
3293     }
3294 
3295     has_kvm = qtest_has_accel("kvm");
3296     has_tcg = qtest_has_accel("tcg");
3297 
3298     if (!has_tcg && !has_kvm) {
3299         g_test_skip("No KVM or TCG accelerator available");
3300         return 0;
3301     }
3302 
3303     has_uffd = ufd_version_check();
3304     arch = qtest_get_arch();
3305 
3306     /*
3307      * On ppc64, the test only works with kvm-hv, but not with kvm-pr and TCG
3308      * is touchy due to race conditions on dirty bits (especially on PPC for
3309      * some reason)
3310      */
3311     if (g_str_equal(arch, "ppc64") &&
3312         (!has_kvm || access("/sys/module/kvm_hv", F_OK))) {
3313         g_test_message("Skipping test: kvm_hv not available");
3314         return g_test_run();
3315     }
3316 
3317     /*
3318      * Similar to ppc64, s390x seems to be touchy with TCG, so disable it
3319      * there until the problems are resolved
3320      */
3321     if (g_str_equal(arch, "s390x") && !has_kvm) {
3322         g_test_message("Skipping test: s390x host with KVM is required");
3323         return g_test_run();
3324     }
3325 
3326     tmpfs = g_dir_make_tmp("migration-test-XXXXXX", &err);
3327     if (!tmpfs) {
3328         g_test_message("Can't create temporary directory in %s: %s",
3329                        g_get_tmp_dir(), err->message);
3330     }
3331     g_assert(tmpfs);
3332     bootfile_create(tmpfs);
3333 
3334     module_call_init(MODULE_INIT_QOM);
3335 
3336     if (has_uffd) {
3337         qtest_add_func("/migration/postcopy/plain", test_postcopy);
3338         qtest_add_func("/migration/postcopy/recovery/plain",
3339                        test_postcopy_recovery);
3340         qtest_add_func("/migration/postcopy/preempt/plain", test_postcopy_preempt);
3341         qtest_add_func("/migration/postcopy/preempt/recovery/plain",
3342                        test_postcopy_preempt_recovery);
3343         if (getenv("QEMU_TEST_FLAKY_TESTS")) {
3344             qtest_add_func("/migration/postcopy/compress/plain",
3345                            test_postcopy_compress);
3346             qtest_add_func("/migration/postcopy/recovery/compress/plain",
3347                            test_postcopy_recovery_compress);
3348         }
3349 #ifndef _WIN32
3350         qtest_add_func("/migration/postcopy/recovery/double-failures",
3351                        test_postcopy_recovery_double_fail);
3352 #endif /* _WIN32 */
3353 
3354     }
3355 
3356     qtest_add_func("/migration/bad_dest", test_baddest);
3357 #ifndef _WIN32
3358     qtest_add_func("/migration/analyze-script", test_analyze_script);
3359 #endif
3360     qtest_add_func("/migration/precopy/unix/plain", test_precopy_unix_plain);
3361     qtest_add_func("/migration/precopy/unix/xbzrle", test_precopy_unix_xbzrle);
3362     /*
3363      * Compression fails from time to time.
3364      * Put test here but don't enable it until everything is fixed.
3365      */
3366     if (getenv("QEMU_TEST_FLAKY_TESTS")) {
3367         qtest_add_func("/migration/precopy/unix/compress/wait",
3368                        test_precopy_unix_compress);
3369         qtest_add_func("/migration/precopy/unix/compress/nowait",
3370                        test_precopy_unix_compress_nowait);
3371     }
3372 
3373     qtest_add_func("/migration/precopy/file",
3374                    test_precopy_file);
3375     qtest_add_func("/migration/precopy/file/offset",
3376                    test_precopy_file_offset);
3377     qtest_add_func("/migration/precopy/file/offset/bad",
3378                    test_precopy_file_offset_bad);
3379 
3380     /*
3381      * Our CI system has problems with shared memory.
3382      * Don't run this test until we find a workaround.
3383      */
3384     if (getenv("QEMU_TEST_FLAKY_TESTS")) {
3385         qtest_add_func("/migration/mode/reboot", test_mode_reboot);
3386     }
3387 
3388 #ifdef CONFIG_GNUTLS
3389     qtest_add_func("/migration/precopy/unix/tls/psk",
3390                    test_precopy_unix_tls_psk);
3391 
3392     if (has_uffd) {
3393         /*
3394          * NOTE: psk test is enough for postcopy, as other types of TLS
3395          * channels are tested under precopy.  Here what we want to test is the
3396          * general postcopy path that has TLS channel enabled.
3397          */
3398         qtest_add_func("/migration/postcopy/tls/psk", test_postcopy_tls_psk);
3399         qtest_add_func("/migration/postcopy/recovery/tls/psk",
3400                        test_postcopy_recovery_tls_psk);
3401         qtest_add_func("/migration/postcopy/preempt/tls/psk",
3402                        test_postcopy_preempt_tls_psk);
3403         qtest_add_func("/migration/postcopy/preempt/recovery/tls/psk",
3404                        test_postcopy_preempt_all);
3405     }
3406 #ifdef CONFIG_TASN1
3407     qtest_add_func("/migration/precopy/unix/tls/x509/default-host",
3408                    test_precopy_unix_tls_x509_default_host);
3409     qtest_add_func("/migration/precopy/unix/tls/x509/override-host",
3410                    test_precopy_unix_tls_x509_override_host);
3411 #endif /* CONFIG_TASN1 */
3412 #endif /* CONFIG_GNUTLS */
3413 
3414     qtest_add_func("/migration/precopy/tcp/plain", test_precopy_tcp_plain);
3415 
3416     qtest_add_func("/migration/precopy/tcp/plain/switchover-ack",
3417                    test_precopy_tcp_switchover_ack);
3418 
3419 #ifdef CONFIG_GNUTLS
3420     qtest_add_func("/migration/precopy/tcp/tls/psk/match",
3421                    test_precopy_tcp_tls_psk_match);
3422     qtest_add_func("/migration/precopy/tcp/tls/psk/mismatch",
3423                    test_precopy_tcp_tls_psk_mismatch);
3424 #ifdef CONFIG_TASN1
3425     qtest_add_func("/migration/precopy/tcp/tls/x509/default-host",
3426                    test_precopy_tcp_tls_x509_default_host);
3427     qtest_add_func("/migration/precopy/tcp/tls/x509/override-host",
3428                    test_precopy_tcp_tls_x509_override_host);
3429     qtest_add_func("/migration/precopy/tcp/tls/x509/mismatch-host",
3430                    test_precopy_tcp_tls_x509_mismatch_host);
3431     qtest_add_func("/migration/precopy/tcp/tls/x509/friendly-client",
3432                    test_precopy_tcp_tls_x509_friendly_client);
3433     qtest_add_func("/migration/precopy/tcp/tls/x509/hostile-client",
3434                    test_precopy_tcp_tls_x509_hostile_client);
3435     qtest_add_func("/migration/precopy/tcp/tls/x509/allow-anon-client",
3436                    test_precopy_tcp_tls_x509_allow_anon_client);
3437     qtest_add_func("/migration/precopy/tcp/tls/x509/reject-anon-client",
3438                    test_precopy_tcp_tls_x509_reject_anon_client);
3439 #endif /* CONFIG_TASN1 */
3440 #endif /* CONFIG_GNUTLS */
3441 
3442     /* qtest_add_func("/migration/ignore_shared", test_ignore_shared); */
3443 #ifndef _WIN32
3444     qtest_add_func("/migration/fd_proto", test_migrate_fd_proto);
3445 #endif
3446     qtest_add_func("/migration/validate_uuid", test_validate_uuid);
3447     qtest_add_func("/migration/validate_uuid_error", test_validate_uuid_error);
3448     qtest_add_func("/migration/validate_uuid_src_not_set",
3449                    test_validate_uuid_src_not_set);
3450     qtest_add_func("/migration/validate_uuid_dst_not_set",
3451                    test_validate_uuid_dst_not_set);
3452     /*
3453      * See explanation why this test is slow on function definition
3454      */
3455     if (g_test_slow()) {
3456         qtest_add_func("/migration/auto_converge", test_migrate_auto_converge);
3457         if (g_str_equal(arch, "x86_64") &&
3458             has_kvm && kvm_dirty_ring_supported()) {
3459             qtest_add_func("/migration/dirty_limit", test_migrate_dirty_limit);
3460         }
3461     }
3462     qtest_add_func("/migration/multifd/tcp/plain/none",
3463                    test_multifd_tcp_none);
3464     /*
3465      * This test is flaky and sometimes fails in CI and otherwise:
3466      * don't run unless user opts in via environment variable.
3467      */
3468     if (getenv("QEMU_TEST_FLAKY_TESTS")) {
3469         qtest_add_func("/migration/multifd/tcp/plain/cancel",
3470                        test_multifd_tcp_cancel);
3471     }
3472     qtest_add_func("/migration/multifd/tcp/plain/zlib",
3473                    test_multifd_tcp_zlib);
3474 #ifdef CONFIG_ZSTD
3475     qtest_add_func("/migration/multifd/tcp/plain/zstd",
3476                    test_multifd_tcp_zstd);
3477 #endif
3478 #ifdef CONFIG_GNUTLS
3479     qtest_add_func("/migration/multifd/tcp/tls/psk/match",
3480                    test_multifd_tcp_tls_psk_match);
3481     qtest_add_func("/migration/multifd/tcp/tls/psk/mismatch",
3482                    test_multifd_tcp_tls_psk_mismatch);
3483 #ifdef CONFIG_TASN1
3484     qtest_add_func("/migration/multifd/tcp/tls/x509/default-host",
3485                    test_multifd_tcp_tls_x509_default_host);
3486     qtest_add_func("/migration/multifd/tcp/tls/x509/override-host",
3487                    test_multifd_tcp_tls_x509_override_host);
3488     qtest_add_func("/migration/multifd/tcp/tls/x509/mismatch-host",
3489                    test_multifd_tcp_tls_x509_mismatch_host);
3490     qtest_add_func("/migration/multifd/tcp/tls/x509/allow-anon-client",
3491                    test_multifd_tcp_tls_x509_allow_anon_client);
3492     qtest_add_func("/migration/multifd/tcp/tls/x509/reject-anon-client",
3493                    test_multifd_tcp_tls_x509_reject_anon_client);
3494 #endif /* CONFIG_TASN1 */
3495 #endif /* CONFIG_GNUTLS */
3496 
3497     if (g_str_equal(arch, "x86_64") && has_kvm && kvm_dirty_ring_supported()) {
3498         qtest_add_func("/migration/dirty_ring",
3499                        test_precopy_unix_dirty_ring);
3500         qtest_add_func("/migration/vcpu_dirty_limit",
3501                        test_vcpu_dirty_limit);
3502     }
3503 
3504     ret = g_test_run();
3505 
3506     g_assert_cmpint(ret, ==, 0);
3507 
3508     bootfile_delete();
3509     ret = rmdir(tmpfs);
3510     if (ret != 0) {
3511         g_test_message("unable to rmdir: path (%s): %s",
3512                        tmpfs, strerror(errno));
3513     }
3514     g_free(tmpfs);
3515 
3516     return ret;
3517 }
3518