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