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