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