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