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