xref: /qemu/tests/qtest/migration-test.c (revision 71920809)
1 /*
2  * QTest testcase for migration
3  *
4  * Copyright (c) 2016-2018 Red Hat, Inc. and/or its affiliates
5  *   based on the vhost-user-test.c that is:
6  *      Copyright (c) 2014 Virtual Open Systems Sarl.
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  *
11  */
12 
13 #include "qemu/osdep.h"
14 
15 #include "libqtest.h"
16 #include "qapi/qmp/qdict.h"
17 #include "qemu/module.h"
18 #include "qemu/option.h"
19 #include "qemu/range.h"
20 #include "qemu/sockets.h"
21 #include "chardev/char.h"
22 #include "qapi/qapi-visit-sockets.h"
23 #include "qapi/qobject-input-visitor.h"
24 #include "qapi/qobject-output-visitor.h"
25 
26 #include "migration-helpers.h"
27 #include "migration/migration-test.h"
28 
29 /* TODO actually test the results and get rid of this */
30 #define qtest_qmp_discard_response(...) qobject_unref(qtest_qmp(__VA_ARGS__))
31 
32 unsigned start_address;
33 unsigned end_address;
34 static bool uffd_feature_thread_id;
35 
36 #if defined(__linux__)
37 #include <sys/syscall.h>
38 #include <sys/vfs.h>
39 #endif
40 
41 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
42 #include <sys/eventfd.h>
43 #include <sys/ioctl.h>
44 #include <linux/userfaultfd.h>
45 
46 static bool ufd_version_check(void)
47 {
48     struct uffdio_api api_struct;
49     uint64_t ioctl_mask;
50 
51     int ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
52 
53     if (ufd == -1) {
54         g_test_message("Skipping test: userfaultfd not available");
55         return false;
56     }
57 
58     api_struct.api = UFFD_API;
59     api_struct.features = 0;
60     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
61         g_test_message("Skipping test: UFFDIO_API failed");
62         return false;
63     }
64     uffd_feature_thread_id = api_struct.features & UFFD_FEATURE_THREAD_ID;
65 
66     ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
67                  (__u64)1 << _UFFDIO_UNREGISTER;
68     if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
69         g_test_message("Skipping test: Missing userfault feature");
70         return false;
71     }
72 
73     return true;
74 }
75 
76 #else
77 static bool ufd_version_check(void)
78 {
79     g_test_message("Skipping test: Userfault not available (builtdtime)");
80     return false;
81 }
82 
83 #endif
84 
85 static const char *tmpfs;
86 
87 /* The boot file modifies memory area in [start_address, end_address)
88  * repeatedly. It outputs a 'B' at a fixed rate while it's still running.
89  */
90 #include "tests/migration/i386/a-b-bootblock.h"
91 #include "tests/migration/aarch64/a-b-kernel.h"
92 #include "tests/migration/s390x/a-b-bios.h"
93 
94 static void init_bootfile(const char *bootpath, void *content, size_t len)
95 {
96     FILE *bootfile = fopen(bootpath, "wb");
97 
98     g_assert_cmpint(fwrite(content, len, 1, bootfile), ==, 1);
99     fclose(bootfile);
100 }
101 
102 /*
103  * Wait for some output in the serial output file,
104  * we get an 'A' followed by an endless string of 'B's
105  * but on the destination we won't have the A.
106  */
107 static void wait_for_serial(const char *side)
108 {
109     char *serialpath = g_strdup_printf("%s/%s", tmpfs, side);
110     FILE *serialfile = fopen(serialpath, "r");
111     const char *arch = qtest_get_arch();
112     int started = (strcmp(side, "src_serial") == 0 &&
113                    strcmp(arch, "ppc64") == 0) ? 0 : 1;
114 
115     g_free(serialpath);
116     do {
117         int readvalue = fgetc(serialfile);
118 
119         if (!started) {
120             /* SLOF prints its banner before starting test,
121              * to ignore it, mark the start of the test with '_',
122              * ignore all characters until this marker
123              */
124             switch (readvalue) {
125             case '_':
126                 started = 1;
127                 break;
128             case EOF:
129                 fseek(serialfile, 0, SEEK_SET);
130                 usleep(1000);
131                 break;
132             }
133             continue;
134         }
135         switch (readvalue) {
136         case 'A':
137             /* Fine */
138             break;
139 
140         case 'B':
141             /* It's alive! */
142             fclose(serialfile);
143             return;
144 
145         case EOF:
146             started = (strcmp(side, "src_serial") == 0 &&
147                        strcmp(arch, "ppc64") == 0) ? 0 : 1;
148             fseek(serialfile, 0, SEEK_SET);
149             usleep(1000);
150             break;
151 
152         default:
153             fprintf(stderr, "Unexpected %d on %s serial\n", readvalue, side);
154             g_assert_not_reached();
155         }
156     } while (true);
157 }
158 
159 /*
160  * It's tricky to use qemu's migration event capability with qtest,
161  * events suddenly appearing confuse the qmp()/hmp() responses.
162  */
163 
164 static int64_t read_ram_property_int(QTestState *who, const char *property)
165 {
166     QDict *rsp_return, *rsp_ram;
167     int64_t result;
168 
169     rsp_return = migrate_query(who);
170     if (!qdict_haskey(rsp_return, "ram")) {
171         /* Still in setup */
172         result = 0;
173     } else {
174         rsp_ram = qdict_get_qdict(rsp_return, "ram");
175         result = qdict_get_try_int(rsp_ram, property, 0);
176     }
177     qobject_unref(rsp_return);
178     return result;
179 }
180 
181 static int64_t read_migrate_property_int(QTestState *who, const char *property)
182 {
183     QDict *rsp_return;
184     int64_t result;
185 
186     rsp_return = migrate_query(who);
187     result = qdict_get_try_int(rsp_return, property, 0);
188     qobject_unref(rsp_return);
189     return result;
190 }
191 
192 static uint64_t get_migration_pass(QTestState *who)
193 {
194     return read_ram_property_int(who, "dirty-sync-count");
195 }
196 
197 static void read_blocktime(QTestState *who)
198 {
199     QDict *rsp_return;
200 
201     rsp_return = migrate_query(who);
202     g_assert(qdict_haskey(rsp_return, "postcopy-blocktime"));
203     qobject_unref(rsp_return);
204 }
205 
206 static void wait_for_migration_pass(QTestState *who)
207 {
208     uint64_t initial_pass = get_migration_pass(who);
209     uint64_t pass;
210 
211     /* Wait for the 1st sync */
212     while (!got_stop && !initial_pass) {
213         usleep(1000);
214         initial_pass = get_migration_pass(who);
215     }
216 
217     do {
218         usleep(1000);
219         pass = get_migration_pass(who);
220     } while (pass == initial_pass && !got_stop);
221 }
222 
223 static void check_guests_ram(QTestState *who)
224 {
225     /* Our ASM test will have been incrementing one byte from each page from
226      * start_address to < end_address in order. This gives us a constraint
227      * that any page's byte should be equal or less than the previous pages
228      * byte (mod 256); and they should all be equal except for one transition
229      * at the point where we meet the incrementer. (We're running this with
230      * the guest stopped).
231      */
232     unsigned address;
233     uint8_t first_byte;
234     uint8_t last_byte;
235     bool hit_edge = false;
236     int bad = 0;
237 
238     qtest_memread(who, start_address, &first_byte, 1);
239     last_byte = first_byte;
240 
241     for (address = start_address + TEST_MEM_PAGE_SIZE; address < end_address;
242          address += TEST_MEM_PAGE_SIZE)
243     {
244         uint8_t b;
245         qtest_memread(who, address, &b, 1);
246         if (b != last_byte) {
247             if (((b + 1) % 256) == last_byte && !hit_edge) {
248                 /* This is OK, the guest stopped at the point of
249                  * incrementing the previous page but didn't get
250                  * to us yet.
251                  */
252                 hit_edge = true;
253                 last_byte = b;
254             } else {
255                 bad++;
256                 if (bad <= 10) {
257                     fprintf(stderr, "Memory content inconsistency at %x"
258                             " first_byte = %x last_byte = %x current = %x"
259                             " hit_edge = %x\n",
260                             address, first_byte, last_byte, b, hit_edge);
261                 }
262             }
263         }
264     }
265     if (bad >= 10) {
266         fprintf(stderr, "and in another %d pages", bad - 10);
267     }
268     g_assert(bad == 0);
269 }
270 
271 static void cleanup(const char *filename)
272 {
273     char *path = g_strdup_printf("%s/%s", tmpfs, filename);
274 
275     unlink(path);
276     g_free(path);
277 }
278 
279 static char *SocketAddress_to_str(SocketAddress *addr)
280 {
281     switch (addr->type) {
282     case SOCKET_ADDRESS_TYPE_INET:
283         return g_strdup_printf("tcp:%s:%s",
284                                addr->u.inet.host,
285                                addr->u.inet.port);
286     case SOCKET_ADDRESS_TYPE_UNIX:
287         return g_strdup_printf("unix:%s",
288                                addr->u.q_unix.path);
289     case SOCKET_ADDRESS_TYPE_FD:
290         return g_strdup_printf("fd:%s", addr->u.fd.str);
291     case SOCKET_ADDRESS_TYPE_VSOCK:
292         return g_strdup_printf("tcp:%s:%s",
293                                addr->u.vsock.cid,
294                                addr->u.vsock.port);
295     default:
296         return g_strdup("unknown address type");
297     }
298 }
299 
300 static char *migrate_get_socket_address(QTestState *who, const char *parameter)
301 {
302     QDict *rsp;
303     char *result;
304     Error *local_err = NULL;
305     SocketAddressList *addrs;
306     Visitor *iv = NULL;
307     QObject *object;
308 
309     rsp = migrate_query(who);
310     object = qdict_get(rsp, parameter);
311 
312     iv = qobject_input_visitor_new(object);
313     visit_type_SocketAddressList(iv, NULL, &addrs, &local_err);
314     visit_free(iv);
315 
316     /* we are only using a single address */
317     result = SocketAddress_to_str(addrs->value);
318 
319     qapi_free_SocketAddressList(addrs);
320     qobject_unref(rsp);
321     return result;
322 }
323 
324 static long long migrate_get_parameter_int(QTestState *who,
325                                            const char *parameter)
326 {
327     QDict *rsp;
328     long long result;
329 
330     rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");
331     result = qdict_get_int(rsp, parameter);
332     qobject_unref(rsp);
333     return result;
334 }
335 
336 static void migrate_check_parameter_int(QTestState *who, const char *parameter,
337                                         long long value)
338 {
339     long long result;
340 
341     result = migrate_get_parameter_int(who, parameter);
342     g_assert_cmpint(result, ==, value);
343 }
344 
345 static void migrate_set_parameter_int(QTestState *who, const char *parameter,
346                                       long long value)
347 {
348     QDict *rsp;
349 
350     rsp = qtest_qmp(who,
351                     "{ 'execute': 'migrate-set-parameters',"
352                     "'arguments': { %s: %lld } }",
353                     parameter, value);
354     g_assert(qdict_haskey(rsp, "return"));
355     qobject_unref(rsp);
356     migrate_check_parameter_int(who, parameter, value);
357 }
358 
359 static char *migrate_get_parameter_str(QTestState *who,
360                                        const char *parameter)
361 {
362     QDict *rsp;
363     char *result;
364 
365     rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");
366     result = g_strdup(qdict_get_str(rsp, parameter));
367     qobject_unref(rsp);
368     return result;
369 }
370 
371 static void migrate_check_parameter_str(QTestState *who, const char *parameter,
372                                         const char *value)
373 {
374     char *result;
375 
376     result = migrate_get_parameter_str(who, parameter);
377     g_assert_cmpstr(result, ==, value);
378     g_free(result);
379 }
380 
381 __attribute__((unused))
382 static void migrate_set_parameter_str(QTestState *who, const char *parameter,
383                                       const char *value)
384 {
385     QDict *rsp;
386 
387     rsp = qtest_qmp(who,
388                     "{ 'execute': 'migrate-set-parameters',"
389                     "'arguments': { %s: %s } }",
390                     parameter, value);
391     g_assert(qdict_haskey(rsp, "return"));
392     qobject_unref(rsp);
393     migrate_check_parameter_str(who, parameter, value);
394 }
395 
396 static void migrate_pause(QTestState *who)
397 {
398     QDict *rsp;
399 
400     rsp = wait_command(who, "{ 'execute': 'migrate-pause' }");
401     qobject_unref(rsp);
402 }
403 
404 static void migrate_continue(QTestState *who, const char *state)
405 {
406     QDict *rsp;
407 
408     rsp = wait_command(who,
409                        "{ 'execute': 'migrate-continue',"
410                        "  'arguments': { 'state': %s } }",
411                        state);
412     qobject_unref(rsp);
413 }
414 
415 static void migrate_recover(QTestState *who, const char *uri)
416 {
417     QDict *rsp;
418 
419     rsp = wait_command(who,
420                        "{ 'execute': 'migrate-recover', "
421                        "  'id': 'recover-cmd', "
422                        "  'arguments': { 'uri': %s } }",
423                        uri);
424     qobject_unref(rsp);
425 }
426 
427 static void migrate_set_capability(QTestState *who, const char *capability,
428                                    bool value)
429 {
430     QDict *rsp;
431 
432     rsp = qtest_qmp(who,
433                     "{ 'execute': 'migrate-set-capabilities',"
434                     "'arguments': { "
435                     "'capabilities': [ { "
436                     "'capability': %s, 'state': %i } ] } }",
437                     capability, value);
438     g_assert(qdict_haskey(rsp, "return"));
439     qobject_unref(rsp);
440 }
441 
442 static void migrate_postcopy_start(QTestState *from, QTestState *to)
443 {
444     QDict *rsp;
445 
446     rsp = wait_command(from, "{ 'execute': 'migrate-start-postcopy' }");
447     qobject_unref(rsp);
448 
449     if (!got_stop) {
450         qtest_qmp_eventwait(from, "STOP");
451     }
452 
453     qtest_qmp_eventwait(to, "RESUME");
454 }
455 
456 typedef struct {
457     bool hide_stderr;
458     bool use_shmem;
459     char *opts_source;
460     char *opts_target;
461 } MigrateStart;
462 
463 static MigrateStart *migrate_start_new(void)
464 {
465     MigrateStart *args = g_new0(MigrateStart, 1);
466 
467     args->opts_source = g_strdup("");
468     args->opts_target = g_strdup("");
469     return args;
470 }
471 
472 static void migrate_start_destroy(MigrateStart *args)
473 {
474     g_free(args->opts_source);
475     g_free(args->opts_target);
476     g_free(args);
477 }
478 
479 static int test_migrate_start(QTestState **from, QTestState **to,
480                               const char *uri, MigrateStart *args)
481 {
482     gchar *arch_source, *arch_target;
483     gchar *cmd_source, *cmd_target;
484     const gchar *ignore_stderr;
485     char *bootpath = NULL;
486     char *shmem_opts;
487     char *shmem_path;
488     const char *arch = qtest_get_arch();
489     const char *machine_opts = NULL;
490     const char *memory_size;
491 
492     if (args->use_shmem) {
493         if (!g_file_test("/dev/shm", G_FILE_TEST_IS_DIR)) {
494             g_test_skip("/dev/shm is not supported");
495             return -1;
496         }
497     }
498 
499     got_stop = false;
500     bootpath = g_strdup_printf("%s/bootsect", tmpfs);
501     if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) {
502         /* the assembled x86 boot sector should be exactly one sector large */
503         assert(sizeof(x86_bootsect) == 512);
504         init_bootfile(bootpath, x86_bootsect, sizeof(x86_bootsect));
505         memory_size = "150M";
506         arch_source = g_strdup_printf("-drive file=%s,format=raw", bootpath);
507         arch_target = g_strdup(arch_source);
508         start_address = X86_TEST_MEM_START;
509         end_address = X86_TEST_MEM_END;
510     } else if (g_str_equal(arch, "s390x")) {
511         init_bootfile(bootpath, s390x_elf, sizeof(s390x_elf));
512         memory_size = "128M";
513         arch_source = g_strdup_printf("-bios %s", bootpath);
514         arch_target = g_strdup(arch_source);
515         start_address = S390_TEST_MEM_START;
516         end_address = S390_TEST_MEM_END;
517     } else if (strcmp(arch, "ppc64") == 0) {
518         machine_opts = "vsmt=8";
519         memory_size = "256M";
520         start_address = PPC_TEST_MEM_START;
521         end_address = PPC_TEST_MEM_END;
522         arch_source = g_strdup_printf("-nodefaults "
523                                       "-prom-env 'use-nvramrc?=true' -prom-env "
524                                       "'nvramrc=hex .\" _\" begin %x %x "
525                                       "do i c@ 1 + i c! 1000 +loop .\" B\" 0 "
526                                       "until'", end_address, start_address);
527         arch_target = g_strdup("");
528     } else if (strcmp(arch, "aarch64") == 0) {
529         init_bootfile(bootpath, aarch64_kernel, sizeof(aarch64_kernel));
530         machine_opts = "virt,gic-version=max";
531         memory_size = "150M";
532         arch_source = g_strdup_printf("-cpu max "
533                                       "-kernel %s",
534                                       bootpath);
535         arch_target = g_strdup(arch_source);
536         start_address = ARM_TEST_MEM_START;
537         end_address = ARM_TEST_MEM_END;
538 
539         g_assert(sizeof(aarch64_kernel) <= ARM_TEST_MAX_KERNEL_SIZE);
540     } else {
541         g_assert_not_reached();
542     }
543 
544     g_free(bootpath);
545 
546     if (args->hide_stderr) {
547         ignore_stderr = "2>/dev/null";
548     } else {
549         ignore_stderr = "";
550     }
551 
552     if (args->use_shmem) {
553         shmem_path = g_strdup_printf("/dev/shm/qemu-%d", getpid());
554         shmem_opts = g_strdup_printf(
555             "-object memory-backend-file,id=mem0,size=%s"
556             ",mem-path=%s,share=on -numa node,memdev=mem0",
557             memory_size, shmem_path);
558     } else {
559         shmem_path = NULL;
560         shmem_opts = g_strdup("");
561     }
562 
563     cmd_source = g_strdup_printf("-accel kvm -accel tcg%s%s "
564                                  "-name source,debug-threads=on "
565                                  "-m %s "
566                                  "-serial file:%s/src_serial "
567                                  "%s %s %s %s",
568                                  machine_opts ? " -machine " : "",
569                                  machine_opts ? machine_opts : "",
570                                  memory_size, tmpfs,
571                                  arch_source, shmem_opts, args->opts_source,
572                                  ignore_stderr);
573     g_free(arch_source);
574     *from = qtest_init(cmd_source);
575     g_free(cmd_source);
576 
577     cmd_target = g_strdup_printf("-accel kvm -accel tcg%s%s "
578                                  "-name target,debug-threads=on "
579                                  "-m %s "
580                                  "-serial file:%s/dest_serial "
581                                  "-incoming %s "
582                                  "%s %s %s %s",
583                                  machine_opts ? " -machine " : "",
584                                  machine_opts ? machine_opts : "",
585                                  memory_size, tmpfs, uri,
586                                  arch_target, shmem_opts,
587                                  args->opts_target, ignore_stderr);
588     g_free(arch_target);
589     *to = qtest_init(cmd_target);
590     g_free(cmd_target);
591 
592     g_free(shmem_opts);
593     /*
594      * Remove shmem file immediately to avoid memory leak in test failed case.
595      * It's valid becase QEMU has already opened this file
596      */
597     if (args->use_shmem) {
598         unlink(shmem_path);
599         g_free(shmem_path);
600     }
601 
602     migrate_start_destroy(args);
603     return 0;
604 }
605 
606 static void test_migrate_end(QTestState *from, QTestState *to, bool test_dest)
607 {
608     unsigned char dest_byte_a, dest_byte_b, dest_byte_c, dest_byte_d;
609 
610     qtest_quit(from);
611 
612     if (test_dest) {
613         qtest_memread(to, start_address, &dest_byte_a, 1);
614 
615         /* Destination still running, wait for a byte to change */
616         do {
617             qtest_memread(to, start_address, &dest_byte_b, 1);
618             usleep(1000 * 10);
619         } while (dest_byte_a == dest_byte_b);
620 
621         qtest_qmp_discard_response(to, "{ 'execute' : 'stop'}");
622 
623         /* With it stopped, check nothing changes */
624         qtest_memread(to, start_address, &dest_byte_c, 1);
625         usleep(1000 * 200);
626         qtest_memread(to, start_address, &dest_byte_d, 1);
627         g_assert_cmpint(dest_byte_c, ==, dest_byte_d);
628 
629         check_guests_ram(to);
630     }
631 
632     qtest_quit(to);
633 
634     cleanup("bootsect");
635     cleanup("migsocket");
636     cleanup("src_serial");
637     cleanup("dest_serial");
638 }
639 
640 static void deprecated_set_downtime(QTestState *who, const double value)
641 {
642     QDict *rsp;
643 
644     rsp = qtest_qmp(who,
645                     "{ 'execute': 'migrate_set_downtime',"
646                     " 'arguments': { 'value': %f } }", value);
647     g_assert(qdict_haskey(rsp, "return"));
648     qobject_unref(rsp);
649     migrate_check_parameter_int(who, "downtime-limit", value * 1000);
650 }
651 
652 static void deprecated_set_speed(QTestState *who, long long value)
653 {
654     QDict *rsp;
655 
656     rsp = qtest_qmp(who, "{ 'execute': 'migrate_set_speed',"
657                           "'arguments': { 'value': %lld } }", value);
658     g_assert(qdict_haskey(rsp, "return"));
659     qobject_unref(rsp);
660     migrate_check_parameter_int(who, "max-bandwidth", value);
661 }
662 
663 static void deprecated_set_cache_size(QTestState *who, long long value)
664 {
665     QDict *rsp;
666 
667     rsp = qtest_qmp(who, "{ 'execute': 'migrate-set-cache-size',"
668                          "'arguments': { 'value': %lld } }", value);
669     g_assert(qdict_haskey(rsp, "return"));
670     qobject_unref(rsp);
671     migrate_check_parameter_int(who, "xbzrle-cache-size", value);
672 }
673 
674 static void test_deprecated(void)
675 {
676     QTestState *from;
677 
678     from = qtest_init("-machine none");
679 
680     deprecated_set_downtime(from, 0.12345);
681     deprecated_set_speed(from, 12345);
682     deprecated_set_cache_size(from, 4096);
683 
684     qtest_quit(from);
685 }
686 
687 static int migrate_postcopy_prepare(QTestState **from_ptr,
688                                     QTestState **to_ptr,
689                                     MigrateStart *args)
690 {
691     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
692     QTestState *from, *to;
693 
694     if (test_migrate_start(&from, &to, uri, args)) {
695         return -1;
696     }
697 
698     migrate_set_capability(from, "postcopy-ram", true);
699     migrate_set_capability(to, "postcopy-ram", true);
700     migrate_set_capability(to, "postcopy-blocktime", true);
701 
702     /* We want to pick a speed slow enough that the test completes
703      * quickly, but that it doesn't complete precopy even on a slow
704      * machine, so also set the downtime.
705      */
706     migrate_set_parameter_int(from, "max-bandwidth", 30000000);
707     migrate_set_parameter_int(from, "downtime-limit", 1);
708 
709     /* Wait for the first serial output from the source */
710     wait_for_serial("src_serial");
711 
712     migrate_qmp(from, uri, "{}");
713     g_free(uri);
714 
715     wait_for_migration_pass(from);
716 
717     *from_ptr = from;
718     *to_ptr = to;
719 
720     return 0;
721 }
722 
723 static void migrate_postcopy_complete(QTestState *from, QTestState *to)
724 {
725     wait_for_migration_complete(from);
726 
727     /* Make sure we get at least one "B" on destination */
728     wait_for_serial("dest_serial");
729 
730     if (uffd_feature_thread_id) {
731         read_blocktime(to);
732     }
733 
734     test_migrate_end(from, to, true);
735 }
736 
737 static void test_postcopy(void)
738 {
739     MigrateStart *args = migrate_start_new();
740     QTestState *from, *to;
741 
742     if (migrate_postcopy_prepare(&from, &to, args)) {
743         return;
744     }
745     migrate_postcopy_start(from, to);
746     migrate_postcopy_complete(from, to);
747 }
748 
749 static void test_postcopy_recovery(void)
750 {
751     MigrateStart *args = migrate_start_new();
752     QTestState *from, *to;
753     char *uri;
754 
755     args->hide_stderr = true;
756 
757     if (migrate_postcopy_prepare(&from, &to, args)) {
758         return;
759     }
760 
761     /* Turn postcopy speed down, 4K/s is slow enough on any machines */
762     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 4096);
763 
764     /* Now we start the postcopy */
765     migrate_postcopy_start(from, to);
766 
767     /*
768      * Wait until postcopy is really started; we can only run the
769      * migrate-pause command during a postcopy
770      */
771     wait_for_migration_status(from, "postcopy-active", NULL);
772 
773     /*
774      * Manually stop the postcopy migration. This emulates a network
775      * failure with the migration socket
776      */
777     migrate_pause(from);
778 
779     /*
780      * Wait for destination side to reach postcopy-paused state.  The
781      * migrate-recover command can only succeed if destination machine
782      * is in the paused state
783      */
784     wait_for_migration_status(to, "postcopy-paused",
785                               (const char * []) { "failed", "active",
786                                                   "completed", NULL });
787 
788     /*
789      * Create a new socket to emulate a new channel that is different
790      * from the broken migration channel; tell the destination to
791      * listen to the new port
792      */
793     uri = g_strdup_printf("unix:%s/migsocket-recover", tmpfs);
794     migrate_recover(to, uri);
795 
796     /*
797      * Try to rebuild the migration channel using the resume flag and
798      * the newly created channel
799      */
800     wait_for_migration_status(from, "postcopy-paused",
801                               (const char * []) { "failed", "active",
802                                                   "completed", NULL });
803     migrate_qmp(from, uri, "{'resume': true}");
804     g_free(uri);
805 
806     /* Restore the postcopy bandwidth to unlimited */
807     migrate_set_parameter_int(from, "max-postcopy-bandwidth", 0);
808 
809     migrate_postcopy_complete(from, to);
810 }
811 
812 static void test_baddest(void)
813 {
814     MigrateStart *args = migrate_start_new();
815     QTestState *from, *to;
816 
817     args->hide_stderr = true;
818 
819     if (test_migrate_start(&from, &to, "tcp:0:0", args)) {
820         return;
821     }
822     migrate_qmp(from, "tcp:0:0", "{}");
823     wait_for_migration_fail(from, false);
824     test_migrate_end(from, to, false);
825 }
826 
827 static void test_precopy_unix(void)
828 {
829     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
830     MigrateStart *args = migrate_start_new();
831     QTestState *from, *to;
832 
833     if (test_migrate_start(&from, &to, uri, args)) {
834         return;
835     }
836 
837     /* We want to pick a speed slow enough that the test completes
838      * quickly, but that it doesn't complete precopy even on a slow
839      * machine, so also set the downtime.
840      */
841     /* 1 ms should make it not converge*/
842     migrate_set_parameter_int(from, "downtime-limit", 1);
843     /* 1GB/s */
844     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
845 
846     /* Wait for the first serial output from the source */
847     wait_for_serial("src_serial");
848 
849     migrate_qmp(from, uri, "{}");
850 
851     wait_for_migration_pass(from);
852 
853     /* 300 ms should converge */
854     migrate_set_parameter_int(from, "downtime-limit", 300);
855 
856     if (!got_stop) {
857         qtest_qmp_eventwait(from, "STOP");
858     }
859 
860     qtest_qmp_eventwait(to, "RESUME");
861 
862     wait_for_serial("dest_serial");
863     wait_for_migration_complete(from);
864 
865     test_migrate_end(from, to, true);
866     g_free(uri);
867 }
868 
869 #if 0
870 /* Currently upset on aarch64 TCG */
871 static void test_ignore_shared(void)
872 {
873     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
874     QTestState *from, *to;
875 
876     if (test_migrate_start(&from, &to, uri, false, true, NULL, NULL)) {
877         return;
878     }
879 
880     migrate_set_capability(from, "x-ignore-shared", true);
881     migrate_set_capability(to, "x-ignore-shared", true);
882 
883     /* Wait for the first serial output from the source */
884     wait_for_serial("src_serial");
885 
886     migrate_qmp(from, uri, "{}");
887 
888     wait_for_migration_pass(from);
889 
890     if (!got_stop) {
891         qtest_qmp_eventwait(from, "STOP");
892     }
893 
894     qtest_qmp_eventwait(to, "RESUME");
895 
896     wait_for_serial("dest_serial");
897     wait_for_migration_complete(from);
898 
899     /* Check whether shared RAM has been really skipped */
900     g_assert_cmpint(read_ram_property_int(from, "transferred"), <, 1024 * 1024);
901 
902     test_migrate_end(from, to, true);
903     g_free(uri);
904 }
905 #endif
906 
907 static void test_xbzrle(const char *uri)
908 {
909     MigrateStart *args = migrate_start_new();
910     QTestState *from, *to;
911 
912     if (test_migrate_start(&from, &to, uri, args)) {
913         return;
914     }
915 
916     /*
917      * We want to pick a speed slow enough that the test completes
918      * quickly, but that it doesn't complete precopy even on a slow
919      * machine, so also set the downtime.
920      */
921     /* 1 ms should make it not converge*/
922     migrate_set_parameter_int(from, "downtime-limit", 1);
923     /* 1GB/s */
924     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
925 
926     migrate_set_parameter_int(from, "xbzrle-cache-size", 33554432);
927 
928     migrate_set_capability(from, "xbzrle", "true");
929     migrate_set_capability(to, "xbzrle", "true");
930     /* Wait for the first serial output from the source */
931     wait_for_serial("src_serial");
932 
933     migrate_qmp(from, uri, "{}");
934 
935     wait_for_migration_pass(from);
936 
937     /* 300ms should converge */
938     migrate_set_parameter_int(from, "downtime-limit", 300);
939 
940     if (!got_stop) {
941         qtest_qmp_eventwait(from, "STOP");
942     }
943     qtest_qmp_eventwait(to, "RESUME");
944 
945     wait_for_serial("dest_serial");
946     wait_for_migration_complete(from);
947 
948     test_migrate_end(from, to, true);
949 }
950 
951 static void test_xbzrle_unix(void)
952 {
953     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
954 
955     test_xbzrle(uri);
956     g_free(uri);
957 }
958 
959 static void test_precopy_tcp(void)
960 {
961     MigrateStart *args = migrate_start_new();
962     char *uri;
963     QTestState *from, *to;
964 
965     if (test_migrate_start(&from, &to, "tcp:127.0.0.1:0", args)) {
966         return;
967     }
968 
969     /*
970      * We want to pick a speed slow enough that the test completes
971      * quickly, but that it doesn't complete precopy even on a slow
972      * machine, so also set the downtime.
973      */
974     /* 1 ms should make it not converge*/
975     migrate_set_parameter_int(from, "downtime-limit", 1);
976     /* 1GB/s */
977     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
978 
979     /* Wait for the first serial output from the source */
980     wait_for_serial("src_serial");
981 
982     uri = migrate_get_socket_address(to, "socket-address");
983 
984     migrate_qmp(from, uri, "{}");
985 
986     wait_for_migration_pass(from);
987 
988     /* 300ms should converge */
989     migrate_set_parameter_int(from, "downtime-limit", 300);
990 
991     if (!got_stop) {
992         qtest_qmp_eventwait(from, "STOP");
993     }
994     qtest_qmp_eventwait(to, "RESUME");
995 
996     wait_for_serial("dest_serial");
997     wait_for_migration_complete(from);
998 
999     test_migrate_end(from, to, true);
1000     g_free(uri);
1001 }
1002 
1003 static void test_migrate_fd_proto(void)
1004 {
1005     MigrateStart *args = migrate_start_new();
1006     QTestState *from, *to;
1007     int ret;
1008     int pair[2];
1009     QDict *rsp;
1010     const char *error_desc;
1011 
1012     if (test_migrate_start(&from, &to, "defer", args)) {
1013         return;
1014     }
1015 
1016     /*
1017      * We want to pick a speed slow enough that the test completes
1018      * quickly, but that it doesn't complete precopy even on a slow
1019      * machine, so also set the downtime.
1020      */
1021     /* 1 ms should make it not converge */
1022     migrate_set_parameter_int(from, "downtime-limit", 1);
1023     /* 1GB/s */
1024     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
1025 
1026     /* Wait for the first serial output from the source */
1027     wait_for_serial("src_serial");
1028 
1029     /* Create two connected sockets for migration */
1030     ret = socketpair(PF_LOCAL, SOCK_STREAM, 0, pair);
1031     g_assert_cmpint(ret, ==, 0);
1032 
1033     /* Send the 1st socket to the target */
1034     rsp = wait_command_fd(to, pair[0],
1035                           "{ 'execute': 'getfd',"
1036                           "  'arguments': { 'fdname': 'fd-mig' }}");
1037     qobject_unref(rsp);
1038     close(pair[0]);
1039 
1040     /* Start incoming migration from the 1st socket */
1041     rsp = wait_command(to, "{ 'execute': 'migrate-incoming',"
1042                            "  'arguments': { 'uri': 'fd:fd-mig' }}");
1043     qobject_unref(rsp);
1044 
1045     /* Send the 2nd socket to the target */
1046     rsp = wait_command_fd(from, pair[1],
1047                           "{ 'execute': 'getfd',"
1048                           "  'arguments': { 'fdname': 'fd-mig' }}");
1049     qobject_unref(rsp);
1050     close(pair[1]);
1051 
1052     /* Start migration to the 2nd socket*/
1053     migrate_qmp(from, "fd:fd-mig", "{}");
1054 
1055     wait_for_migration_pass(from);
1056 
1057     /* 300ms should converge */
1058     migrate_set_parameter_int(from, "downtime-limit", 300);
1059 
1060     if (!got_stop) {
1061         qtest_qmp_eventwait(from, "STOP");
1062     }
1063     qtest_qmp_eventwait(to, "RESUME");
1064 
1065     /* Test closing fds */
1066     /* We assume, that QEMU removes named fd from its list,
1067      * so this should fail */
1068     rsp = qtest_qmp(from, "{ 'execute': 'closefd',"
1069                           "  'arguments': { 'fdname': 'fd-mig' }}");
1070     g_assert_true(qdict_haskey(rsp, "error"));
1071     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
1072     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
1073     qobject_unref(rsp);
1074 
1075     rsp = qtest_qmp(to, "{ 'execute': 'closefd',"
1076                         "  'arguments': { 'fdname': 'fd-mig' }}");
1077     g_assert_true(qdict_haskey(rsp, "error"));
1078     error_desc = qdict_get_str(qdict_get_qdict(rsp, "error"), "desc");
1079     g_assert_cmpstr(error_desc, ==, "File descriptor named 'fd-mig' not found");
1080     qobject_unref(rsp);
1081 
1082     /* Complete migration */
1083     wait_for_serial("dest_serial");
1084     wait_for_migration_complete(from);
1085     test_migrate_end(from, to, true);
1086 }
1087 
1088 static void do_test_validate_uuid(MigrateStart *args, bool should_fail)
1089 {
1090     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1091     QTestState *from, *to;
1092 
1093     if (test_migrate_start(&from, &to, uri, args)) {
1094         return;
1095     }
1096 
1097     /*
1098      * UUID validation is at the begin of migration. So, the main process of
1099      * migration is not interesting for us here. Thus, set huge downtime for
1100      * very fast migration.
1101      */
1102     migrate_set_parameter_int(from, "downtime-limit", 1000000);
1103     migrate_set_capability(from, "validate-uuid", true);
1104 
1105     /* Wait for the first serial output from the source */
1106     wait_for_serial("src_serial");
1107 
1108     migrate_qmp(from, uri, "{}");
1109 
1110     if (should_fail) {
1111         qtest_set_expected_status(to, 1);
1112         wait_for_migration_fail(from, true);
1113     } else {
1114         wait_for_migration_complete(from);
1115     }
1116 
1117     test_migrate_end(from, to, false);
1118     g_free(uri);
1119 }
1120 
1121 static void test_validate_uuid(void)
1122 {
1123     MigrateStart *args = migrate_start_new();
1124 
1125     args->opts_source = g_strdup("-uuid 11111111-1111-1111-1111-111111111111");
1126     args->opts_target = g_strdup("-uuid 11111111-1111-1111-1111-111111111111");
1127     do_test_validate_uuid(args, false);
1128 }
1129 
1130 static void test_validate_uuid_error(void)
1131 {
1132     MigrateStart *args = migrate_start_new();
1133 
1134     args->opts_source = g_strdup("-uuid 11111111-1111-1111-1111-111111111111");
1135     args->opts_target = g_strdup("-uuid 22222222-2222-2222-2222-222222222222");
1136     args->hide_stderr = true;
1137     do_test_validate_uuid(args, true);
1138 }
1139 
1140 static void test_validate_uuid_src_not_set(void)
1141 {
1142     MigrateStart *args = migrate_start_new();
1143 
1144     args->opts_target = g_strdup("-uuid 22222222-2222-2222-2222-222222222222");
1145     args->hide_stderr = true;
1146     do_test_validate_uuid(args, false);
1147 }
1148 
1149 static void test_validate_uuid_dst_not_set(void)
1150 {
1151     MigrateStart *args = migrate_start_new();
1152 
1153     args->opts_source = g_strdup("-uuid 11111111-1111-1111-1111-111111111111");
1154     args->hide_stderr = true;
1155     do_test_validate_uuid(args, false);
1156 }
1157 
1158 static void test_migrate_auto_converge(void)
1159 {
1160     char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);
1161     MigrateStart *args = migrate_start_new();
1162     QTestState *from, *to;
1163     int64_t remaining, percentage;
1164 
1165     /*
1166      * We want the test to be stable and as fast as possible.
1167      * E.g., with 1Gb/s bandwith migration may pass without throttling,
1168      * so we need to decrease a bandwidth.
1169      */
1170     const int64_t init_pct = 5, inc_pct = 50, max_pct = 95;
1171     const int64_t max_bandwidth = 400000000; /* ~400Mb/s */
1172     const int64_t downtime_limit = 250; /* 250ms */
1173     /*
1174      * We migrate through unix-socket (> 500Mb/s).
1175      * Thus, expected migration speed ~= bandwidth limit (< 500Mb/s).
1176      * So, we can predict expected_threshold
1177      */
1178     const int64_t expected_threshold = max_bandwidth * downtime_limit / 1000;
1179 
1180     if (test_migrate_start(&from, &to, uri, args)) {
1181         return;
1182     }
1183 
1184     migrate_set_capability(from, "auto-converge", true);
1185     migrate_set_parameter_int(from, "cpu-throttle-initial", init_pct);
1186     migrate_set_parameter_int(from, "cpu-throttle-increment", inc_pct);
1187     migrate_set_parameter_int(from, "max-cpu-throttle", max_pct);
1188 
1189     /*
1190      * Set the initial parameters so that the migration could not converge
1191      * without throttling.
1192      */
1193     migrate_set_parameter_int(from, "downtime-limit", 1);
1194     migrate_set_parameter_int(from, "max-bandwidth", 100000000); /* ~100Mb/s */
1195 
1196     /* To check remaining size after precopy */
1197     migrate_set_capability(from, "pause-before-switchover", true);
1198 
1199     /* Wait for the first serial output from the source */
1200     wait_for_serial("src_serial");
1201 
1202     migrate_qmp(from, uri, "{}");
1203 
1204     /* Wait for throttling begins */
1205     percentage = 0;
1206     while (percentage == 0) {
1207         percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
1208         usleep(100);
1209         g_assert_false(got_stop);
1210     }
1211     /* The first percentage of throttling should be equal to init_pct */
1212     g_assert_cmpint(percentage, ==, init_pct);
1213     /* Now, when we tested that throttling works, let it converge */
1214     migrate_set_parameter_int(from, "downtime-limit", downtime_limit);
1215     migrate_set_parameter_int(from, "max-bandwidth", max_bandwidth);
1216 
1217     /*
1218      * Wait for pre-switchover status to check last throttle percentage
1219      * and remaining. These values will be zeroed later
1220      */
1221     wait_for_migration_status(from, "pre-switchover", NULL);
1222 
1223     /* The final percentage of throttling shouldn't be greater than max_pct */
1224     percentage = read_migrate_property_int(from, "cpu-throttle-percentage");
1225     g_assert_cmpint(percentage, <=, max_pct);
1226 
1227     remaining = read_ram_property_int(from, "remaining");
1228     g_assert_cmpint(remaining, <, expected_threshold);
1229 
1230     migrate_continue(from, "pre-switchover");
1231 
1232     qtest_qmp_eventwait(to, "RESUME");
1233 
1234     wait_for_serial("dest_serial");
1235     wait_for_migration_complete(from);
1236 
1237     g_free(uri);
1238 
1239     test_migrate_end(from, to, true);
1240 }
1241 
1242 static void test_multifd_tcp(void)
1243 {
1244     MigrateStart *args = migrate_start_new();
1245     QTestState *from, *to;
1246     QDict *rsp;
1247     char *uri;
1248 
1249     if (test_migrate_start(&from, &to, "defer", args)) {
1250         return;
1251     }
1252 
1253     /*
1254      * We want to pick a speed slow enough that the test completes
1255      * quickly, but that it doesn't complete precopy even on a slow
1256      * machine, so also set the downtime.
1257      */
1258     /* 1 ms should make it not converge*/
1259     migrate_set_parameter_int(from, "downtime-limit", 1);
1260     /* 1GB/s */
1261     migrate_set_parameter_int(from, "max-bandwidth", 1000000000);
1262 
1263     migrate_set_parameter_int(from, "multifd-channels", 16);
1264     migrate_set_parameter_int(to, "multifd-channels", 16);
1265 
1266     migrate_set_capability(from, "multifd", "true");
1267     migrate_set_capability(to, "multifd", "true");
1268 
1269     /* Start incoming migration from the 1st socket */
1270     rsp = wait_command(to, "{ 'execute': 'migrate-incoming',"
1271                            "  'arguments': { 'uri': 'tcp:127.0.0.1:0' }}");
1272     qobject_unref(rsp);
1273 
1274     /* Wait for the first serial output from the source */
1275     wait_for_serial("src_serial");
1276 
1277     uri = migrate_get_socket_address(to, "socket-address");
1278 
1279     migrate_qmp(from, uri, "{}");
1280 
1281     wait_for_migration_pass(from);
1282 
1283     /* 300ms it should converge */
1284     migrate_set_parameter_int(from, "downtime-limit", 300);
1285 
1286     if (!got_stop) {
1287         qtest_qmp_eventwait(from, "STOP");
1288     }
1289     qtest_qmp_eventwait(to, "RESUME");
1290 
1291     wait_for_serial("dest_serial");
1292     wait_for_migration_complete(from);
1293     test_migrate_end(from, to, true);
1294     free(uri);
1295 }
1296 
1297 int main(int argc, char **argv)
1298 {
1299     char template[] = "/tmp/migration-test-XXXXXX";
1300     int ret;
1301 
1302     g_test_init(&argc, &argv, NULL);
1303 
1304     if (!ufd_version_check()) {
1305         return g_test_run();
1306     }
1307 
1308     /*
1309      * On ppc64, the test only works with kvm-hv, but not with kvm-pr and TCG
1310      * is touchy due to race conditions on dirty bits (especially on PPC for
1311      * some reason)
1312      */
1313     if (g_str_equal(qtest_get_arch(), "ppc64") &&
1314         (access("/sys/module/kvm_hv", F_OK) ||
1315          access("/dev/kvm", R_OK | W_OK))) {
1316         g_test_message("Skipping test: kvm_hv not available");
1317         return g_test_run();
1318     }
1319 
1320     /*
1321      * Similar to ppc64, s390x seems to be touchy with TCG, so disable it
1322      * there until the problems are resolved
1323      */
1324     if (g_str_equal(qtest_get_arch(), "s390x")) {
1325 #if defined(HOST_S390X)
1326         if (access("/dev/kvm", R_OK | W_OK)) {
1327             g_test_message("Skipping test: kvm not available");
1328             return g_test_run();
1329         }
1330 #else
1331         g_test_message("Skipping test: Need s390x host to work properly");
1332         return g_test_run();
1333 #endif
1334     }
1335 
1336     tmpfs = mkdtemp(template);
1337     if (!tmpfs) {
1338         g_test_message("mkdtemp on path (%s): %s", template, strerror(errno));
1339     }
1340     g_assert(tmpfs);
1341 
1342     module_call_init(MODULE_INIT_QOM);
1343 
1344     qtest_add_func("/migration/postcopy/unix", test_postcopy);
1345     qtest_add_func("/migration/postcopy/recovery", test_postcopy_recovery);
1346     qtest_add_func("/migration/deprecated", test_deprecated);
1347     qtest_add_func("/migration/bad_dest", test_baddest);
1348     qtest_add_func("/migration/precopy/unix", test_precopy_unix);
1349     qtest_add_func("/migration/precopy/tcp", test_precopy_tcp);
1350     /* qtest_add_func("/migration/ignore_shared", test_ignore_shared); */
1351     qtest_add_func("/migration/xbzrle/unix", test_xbzrle_unix);
1352     qtest_add_func("/migration/fd_proto", test_migrate_fd_proto);
1353     qtest_add_func("/migration/validate_uuid", test_validate_uuid);
1354     qtest_add_func("/migration/validate_uuid_error", test_validate_uuid_error);
1355     qtest_add_func("/migration/validate_uuid_src_not_set",
1356                    test_validate_uuid_src_not_set);
1357     qtest_add_func("/migration/validate_uuid_dst_not_set",
1358                    test_validate_uuid_dst_not_set);
1359 
1360     qtest_add_func("/migration/auto_converge", test_migrate_auto_converge);
1361     qtest_add_func("/migration/multifd/tcp", test_multifd_tcp);
1362 
1363     ret = g_test_run();
1364 
1365     g_assert_cmpint(ret, ==, 0);
1366 
1367     ret = rmdir(tmpfs);
1368     if (ret != 0) {
1369         g_test_message("unable to rmdir: path (%s): %s",
1370                        tmpfs, strerror(errno));
1371     }
1372 
1373     return ret;
1374 }
1375