xref: /openbmc/qemu/migration/savevm.c (revision 4e55cb3cdeb099cb65f75f5d3b061e3e1319cf3b)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2009-2015 Red Hat Inc
6  *
7  * Authors:
8  *  Juan Quintela <quintela@redhat.com>
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a copy
11  * of this software and associated documentation files (the "Software"), to deal
12  * in the Software without restriction, including without limitation the rights
13  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14  * copies of the Software, and to permit persons to whom the Software is
15  * furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26  * THE SOFTWARE.
27  */
28 
29 #include "qemu/osdep.h"
30 #include "hw/boards.h"
31 #include "net/net.h"
32 #include "migration.h"
33 #include "migration/snapshot.h"
34 #include "migration-stats.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
39 #include "migration/channel-block.h"
40 #include "ram.h"
41 #include "qemu-file.h"
42 #include "savevm.h"
43 #include "postcopy-ram.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/clone-visitor.h"
47 #include "qapi/qapi-builtin-visit.h"
48 #include "qemu/error-report.h"
49 #include "system/cpus.h"
50 #include "exec/memory.h"
51 #include "exec/target_page.h"
52 #include "trace.h"
53 #include "qemu/iov.h"
54 #include "qemu/job.h"
55 #include "qemu/main-loop.h"
56 #include "block/snapshot.h"
57 #include "qemu/cutils.h"
58 #include "io/channel-buffer.h"
59 #include "io/channel-file.h"
60 #include "system/replay.h"
61 #include "system/runstate.h"
62 #include "system/system.h"
63 #include "system/xen.h"
64 #include "migration/colo.h"
65 #include "qemu/bitmap.h"
66 #include "net/announce.h"
67 #include "qemu/yank.h"
68 #include "yank_functions.h"
69 #include "system/qtest.h"
70 #include "options.h"
71 
72 const unsigned int postcopy_ram_discard_version;
73 
74 /* Subcommands for QEMU_VM_COMMAND */
75 enum qemu_vm_cmd {
76     MIG_CMD_INVALID = 0,   /* Must be 0 */
77     MIG_CMD_OPEN_RETURN_PATH,  /* Tell the dest to open the Return path */
78     MIG_CMD_PING,              /* Request a PONG on the RP */
79 
80     MIG_CMD_POSTCOPY_ADVISE,       /* Prior to any page transfers, just
81                                       warn we might want to do PC */
82     MIG_CMD_POSTCOPY_LISTEN,       /* Start listening for incoming
83                                       pages as it's running. */
84     MIG_CMD_POSTCOPY_RUN,          /* Start execution */
85 
86     MIG_CMD_POSTCOPY_RAM_DISCARD,  /* A list of pages to discard that
87                                       were previously sent during
88                                       precopy but are dirty. */
89     MIG_CMD_PACKAGED,          /* Send a wrapped stream within this stream */
90     MIG_CMD_ENABLE_COLO,       /* Enable COLO */
91     MIG_CMD_POSTCOPY_RESUME,   /* resume postcopy on dest */
92     MIG_CMD_RECV_BITMAP,       /* Request for recved bitmap on dst */
93     MIG_CMD_SWITCHOVER_START,  /* Switchover start notification */
94     MIG_CMD_MAX
95 };
96 
97 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
98 static struct mig_cmd_args {
99     ssize_t     len; /* -1 = variable */
100     const char *name;
101 } mig_cmd_args[] = {
102     [MIG_CMD_INVALID]          = { .len = -1, .name = "INVALID" },
103     [MIG_CMD_OPEN_RETURN_PATH] = { .len =  0, .name = "OPEN_RETURN_PATH" },
104     [MIG_CMD_PING]             = { .len = sizeof(uint32_t), .name = "PING" },
105     [MIG_CMD_POSTCOPY_ADVISE]  = { .len = -1, .name = "POSTCOPY_ADVISE" },
106     [MIG_CMD_POSTCOPY_LISTEN]  = { .len =  0, .name = "POSTCOPY_LISTEN" },
107     [MIG_CMD_POSTCOPY_RUN]     = { .len =  0, .name = "POSTCOPY_RUN" },
108     [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
109                                    .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
110     [MIG_CMD_POSTCOPY_RESUME]  = { .len =  0, .name = "POSTCOPY_RESUME" },
111     [MIG_CMD_PACKAGED]         = { .len =  4, .name = "PACKAGED" },
112     [MIG_CMD_RECV_BITMAP]      = { .len = -1, .name = "RECV_BITMAP" },
113     [MIG_CMD_SWITCHOVER_START] = { .len =  0, .name = "SWITCHOVER_START" },
114     [MIG_CMD_MAX]              = { .len = -1, .name = "MAX" },
115 };
116 
117 /* Note for MIG_CMD_POSTCOPY_ADVISE:
118  * The format of arguments is depending on postcopy mode:
119  * - postcopy RAM only
120  *   uint64_t host page size
121  *   uint64_t target page size
122  *
123  * - postcopy RAM and postcopy dirty bitmaps
124  *   format is the same as for postcopy RAM only
125  *
126  * - postcopy dirty bitmaps only
127  *   Nothing. Command length field is 0.
128  *
129  * Be careful: adding a new postcopy entity with some other parameters should
130  * not break format self-description ability. Good way is to introduce some
131  * generic extendable format with an exception for two old entities.
132  */
133 
134 /***********************************************************/
135 /* savevm/loadvm support */
136 
137 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
138 {
139     if (is_writable) {
140         return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
141     } else {
142         return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
143     }
144 }
145 
146 
147 /* QEMUFile timer support.
148  * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
149  */
150 
151 void timer_put(QEMUFile *f, QEMUTimer *ts)
152 {
153     uint64_t expire_time;
154 
155     expire_time = timer_expire_time_ns(ts);
156     qemu_put_be64(f, expire_time);
157 }
158 
159 void timer_get(QEMUFile *f, QEMUTimer *ts)
160 {
161     uint64_t expire_time;
162 
163     expire_time = qemu_get_be64(f);
164     if (expire_time != -1) {
165         timer_mod_ns(ts, expire_time);
166     } else {
167         timer_del(ts);
168     }
169 }
170 
171 
172 /* VMState timer support.
173  * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
174  */
175 
176 static int get_timer(QEMUFile *f, void *pv, size_t size,
177                      const VMStateField *field)
178 {
179     QEMUTimer *v = pv;
180     timer_get(f, v);
181     return 0;
182 }
183 
184 static int put_timer(QEMUFile *f, void *pv, size_t size,
185                      const VMStateField *field, JSONWriter *vmdesc)
186 {
187     QEMUTimer *v = pv;
188     timer_put(f, v);
189 
190     return 0;
191 }
192 
193 const VMStateInfo vmstate_info_timer = {
194     .name = "timer",
195     .get  = get_timer,
196     .put  = put_timer,
197 };
198 
199 
200 typedef struct CompatEntry {
201     char idstr[256];
202     int instance_id;
203 } CompatEntry;
204 
205 typedef struct SaveStateEntry {
206     QTAILQ_ENTRY(SaveStateEntry) entry;
207     char idstr[256];
208     uint32_t instance_id;
209     int alias_id;
210     int version_id;
211     /* version id read from the stream */
212     int load_version_id;
213     int section_id;
214     /* section id read from the stream */
215     int load_section_id;
216     const SaveVMHandlers *ops;
217     const VMStateDescription *vmsd;
218     void *opaque;
219     CompatEntry *compat;
220     int is_ram;
221 } SaveStateEntry;
222 
223 typedef struct SaveState {
224     QTAILQ_HEAD(, SaveStateEntry) handlers;
225     SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
226     int global_section_id;
227     uint32_t len;
228     const char *name;
229     uint32_t target_page_bits;
230     uint32_t caps_count;
231     MigrationCapability *capabilities;
232     QemuUUID uuid;
233 } SaveState;
234 
235 static SaveState savevm_state = {
236     .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
237     .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
238     .global_section_id = 0,
239 };
240 
241 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id);
242 
243 static bool should_validate_capability(int capability)
244 {
245     assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
246     /* Validate only new capabilities to keep compatibility. */
247     switch (capability) {
248     case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
249     case MIGRATION_CAPABILITY_MAPPED_RAM:
250         return true;
251     default:
252         return false;
253     }
254 }
255 
256 static uint32_t get_validatable_capabilities_count(void)
257 {
258     MigrationState *s = migrate_get_current();
259     uint32_t result = 0;
260     int i;
261     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
262         if (should_validate_capability(i) && s->capabilities[i]) {
263             result++;
264         }
265     }
266     return result;
267 }
268 
269 static int configuration_pre_save(void *opaque)
270 {
271     SaveState *state = opaque;
272     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
273     MigrationState *s = migrate_get_current();
274     int i, j;
275 
276     state->len = strlen(current_name);
277     state->name = current_name;
278     state->target_page_bits = qemu_target_page_bits();
279 
280     state->caps_count = get_validatable_capabilities_count();
281     state->capabilities = g_renew(MigrationCapability, state->capabilities,
282                                   state->caps_count);
283     for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
284         if (should_validate_capability(i) && s->capabilities[i]) {
285             state->capabilities[j++] = i;
286         }
287     }
288     state->uuid = qemu_uuid;
289 
290     return 0;
291 }
292 
293 static int configuration_post_save(void *opaque)
294 {
295     SaveState *state = opaque;
296 
297     g_free(state->capabilities);
298     state->capabilities = NULL;
299     state->caps_count = 0;
300     return 0;
301 }
302 
303 static int configuration_pre_load(void *opaque)
304 {
305     SaveState *state = opaque;
306 
307     /* If there is no target-page-bits subsection it means the source
308      * predates the variable-target-page-bits support and is using the
309      * minimum possible value for this CPU.
310      */
311     state->target_page_bits = qemu_target_page_bits_min();
312     return 0;
313 }
314 
315 static bool configuration_validate_capabilities(SaveState *state)
316 {
317     bool ret = true;
318     MigrationState *s = migrate_get_current();
319     unsigned long *source_caps_bm;
320     int i;
321 
322     source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
323     for (i = 0; i < state->caps_count; i++) {
324         MigrationCapability capability = state->capabilities[i];
325         set_bit(capability, source_caps_bm);
326     }
327 
328     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
329         bool source_state, target_state;
330         if (!should_validate_capability(i)) {
331             continue;
332         }
333         source_state = test_bit(i, source_caps_bm);
334         target_state = s->capabilities[i];
335         if (source_state != target_state) {
336             error_report("Capability %s is %s, but received capability is %s",
337                          MigrationCapability_str(i),
338                          target_state ? "on" : "off",
339                          source_state ? "on" : "off");
340             ret = false;
341             /* Don't break here to report all failed capabilities */
342         }
343     }
344 
345     g_free(source_caps_bm);
346     return ret;
347 }
348 
349 static int configuration_post_load(void *opaque, int version_id)
350 {
351     SaveState *state = opaque;
352     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
353     int ret = 0;
354 
355     if (strncmp(state->name, current_name, state->len) != 0) {
356         error_report("Machine type received is '%.*s' and local is '%s'",
357                      (int) state->len, state->name, current_name);
358         ret = -EINVAL;
359         goto out;
360     }
361 
362     if (state->target_page_bits != qemu_target_page_bits()) {
363         error_report("Received TARGET_PAGE_BITS is %d but local is %d",
364                      state->target_page_bits, qemu_target_page_bits());
365         ret = -EINVAL;
366         goto out;
367     }
368 
369     if (!configuration_validate_capabilities(state)) {
370         ret = -EINVAL;
371         goto out;
372     }
373 
374 out:
375     g_free((void *)state->name);
376     state->name = NULL;
377     state->len = 0;
378     g_free(state->capabilities);
379     state->capabilities = NULL;
380     state->caps_count = 0;
381 
382     return ret;
383 }
384 
385 static int get_capability(QEMUFile *f, void *pv, size_t size,
386                           const VMStateField *field)
387 {
388     MigrationCapability *capability = pv;
389     char capability_str[UINT8_MAX + 1];
390     uint8_t len;
391     int i;
392 
393     len = qemu_get_byte(f);
394     qemu_get_buffer(f, (uint8_t *)capability_str, len);
395     capability_str[len] = '\0';
396     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
397         if (!strcmp(MigrationCapability_str(i), capability_str)) {
398             *capability = i;
399             return 0;
400         }
401     }
402     error_report("Received unknown capability %s", capability_str);
403     return -EINVAL;
404 }
405 
406 static int put_capability(QEMUFile *f, void *pv, size_t size,
407                           const VMStateField *field, JSONWriter *vmdesc)
408 {
409     MigrationCapability *capability = pv;
410     const char *capability_str = MigrationCapability_str(*capability);
411     size_t len = strlen(capability_str);
412     assert(len <= UINT8_MAX);
413 
414     qemu_put_byte(f, len);
415     qemu_put_buffer(f, (uint8_t *)capability_str, len);
416     return 0;
417 }
418 
419 static const VMStateInfo vmstate_info_capability = {
420     .name = "capability",
421     .get  = get_capability,
422     .put  = put_capability,
423 };
424 
425 /* The target-page-bits subsection is present only if the
426  * target page size is not the same as the default (ie the
427  * minimum page size for a variable-page-size guest CPU).
428  * If it is present then it contains the actual target page
429  * bits for the machine, and migration will fail if the
430  * two ends don't agree about it.
431  */
432 static bool vmstate_target_page_bits_needed(void *opaque)
433 {
434     return qemu_target_page_bits()
435         > qemu_target_page_bits_min();
436 }
437 
438 static const VMStateDescription vmstate_target_page_bits = {
439     .name = "configuration/target-page-bits",
440     .version_id = 1,
441     .minimum_version_id = 1,
442     .needed = vmstate_target_page_bits_needed,
443     .fields = (const VMStateField[]) {
444         VMSTATE_UINT32(target_page_bits, SaveState),
445         VMSTATE_END_OF_LIST()
446     }
447 };
448 
449 static bool vmstate_capabilites_needed(void *opaque)
450 {
451     return get_validatable_capabilities_count() > 0;
452 }
453 
454 static const VMStateDescription vmstate_capabilites = {
455     .name = "configuration/capabilities",
456     .version_id = 1,
457     .minimum_version_id = 1,
458     .needed = vmstate_capabilites_needed,
459     .fields = (const VMStateField[]) {
460         VMSTATE_UINT32_V(caps_count, SaveState, 1),
461         VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
462                                     vmstate_info_capability,
463                                     MigrationCapability),
464         VMSTATE_END_OF_LIST()
465     }
466 };
467 
468 static bool vmstate_uuid_needed(void *opaque)
469 {
470     return qemu_uuid_set && migrate_validate_uuid();
471 }
472 
473 static int vmstate_uuid_post_load(void *opaque, int version_id)
474 {
475     SaveState *state = opaque;
476     char uuid_src[UUID_STR_LEN];
477     char uuid_dst[UUID_STR_LEN];
478 
479     if (!qemu_uuid_set) {
480         /*
481          * It's warning because user might not know UUID in some cases,
482          * e.g. load an old snapshot
483          */
484         qemu_uuid_unparse(&state->uuid, uuid_src);
485         warn_report("UUID is received %s, but local uuid isn't set",
486                      uuid_src);
487         return 0;
488     }
489     if (!qemu_uuid_is_equal(&state->uuid, &qemu_uuid)) {
490         qemu_uuid_unparse(&state->uuid, uuid_src);
491         qemu_uuid_unparse(&qemu_uuid, uuid_dst);
492         error_report("UUID received is %s and local is %s", uuid_src, uuid_dst);
493         return -EINVAL;
494     }
495     return 0;
496 }
497 
498 static const VMStateDescription vmstate_uuid = {
499     .name = "configuration/uuid",
500     .version_id = 1,
501     .minimum_version_id = 1,
502     .needed = vmstate_uuid_needed,
503     .post_load = vmstate_uuid_post_load,
504     .fields = (const VMStateField[]) {
505         VMSTATE_UINT8_ARRAY_V(uuid.data, SaveState, sizeof(QemuUUID), 1),
506         VMSTATE_END_OF_LIST()
507     }
508 };
509 
510 static const VMStateDescription vmstate_configuration = {
511     .name = "configuration",
512     .version_id = 1,
513     .pre_load = configuration_pre_load,
514     .post_load = configuration_post_load,
515     .pre_save = configuration_pre_save,
516     .post_save = configuration_post_save,
517     .fields = (const VMStateField[]) {
518         VMSTATE_UINT32(len, SaveState),
519         VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
520         VMSTATE_END_OF_LIST()
521     },
522     .subsections = (const VMStateDescription * const []) {
523         &vmstate_target_page_bits,
524         &vmstate_capabilites,
525         &vmstate_uuid,
526         NULL
527     }
528 };
529 
530 static void dump_vmstate_vmsd(FILE *out_file,
531                               const VMStateDescription *vmsd, int indent,
532                               bool is_subsection);
533 
534 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
535                               int indent)
536 {
537     fprintf(out_file, "%*s{\n", indent, "");
538     indent += 2;
539     fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
540     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
541             field->version_id);
542     fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
543             field->field_exists ? "true" : "false");
544     if (field->flags & VMS_ARRAY) {
545         fprintf(out_file, "%*s\"num\": %d,\n", indent, "", field->num);
546     }
547     fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
548     if (field->vmsd != NULL) {
549         fprintf(out_file, ",\n");
550         dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
551     }
552     fprintf(out_file, "\n%*s}", indent - 2, "");
553 }
554 
555 static void dump_vmstate_vmss(FILE *out_file,
556                               const VMStateDescription *subsection,
557                               int indent)
558 {
559     if (subsection != NULL) {
560         dump_vmstate_vmsd(out_file, subsection, indent, true);
561     }
562 }
563 
564 static void dump_vmstate_vmsd(FILE *out_file,
565                               const VMStateDescription *vmsd, int indent,
566                               bool is_subsection)
567 {
568     if (is_subsection) {
569         fprintf(out_file, "%*s{\n", indent, "");
570     } else {
571         fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
572     }
573     indent += 2;
574     fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
575     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
576             vmsd->version_id);
577     fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
578             vmsd->minimum_version_id);
579     if (vmsd->fields != NULL) {
580         const VMStateField *field = vmsd->fields;
581         bool first;
582 
583         fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
584         first = true;
585         while (field->name != NULL) {
586             if (field->flags & VMS_MUST_EXIST) {
587                 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
588                 field++;
589                 continue;
590             }
591             if (!first) {
592                 fprintf(out_file, ",\n");
593             }
594             dump_vmstate_vmsf(out_file, field, indent + 2);
595             field++;
596             first = false;
597         }
598         assert(field->flags == VMS_END);
599         fprintf(out_file, "\n%*s]", indent, "");
600     }
601     if (vmsd->subsections != NULL) {
602         const VMStateDescription * const *subsection = vmsd->subsections;
603         bool first;
604 
605         fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
606         first = true;
607         while (*subsection != NULL) {
608             if (!first) {
609                 fprintf(out_file, ",\n");
610             }
611             dump_vmstate_vmss(out_file, *subsection, indent + 2);
612             subsection++;
613             first = false;
614         }
615         fprintf(out_file, "\n%*s]", indent, "");
616     }
617     fprintf(out_file, "\n%*s}", indent - 2, "");
618 }
619 
620 static void dump_machine_type(FILE *out_file)
621 {
622     MachineClass *mc;
623 
624     mc = MACHINE_GET_CLASS(current_machine);
625 
626     fprintf(out_file, "  \"vmschkmachine\": {\n");
627     fprintf(out_file, "    \"Name\": \"%s\"\n", mc->name);
628     fprintf(out_file, "  },\n");
629 }
630 
631 void dump_vmstate_json_to_file(FILE *out_file)
632 {
633     GSList *list, *elt;
634     bool first;
635 
636     fprintf(out_file, "{\n");
637     dump_machine_type(out_file);
638 
639     first = true;
640     list = object_class_get_list(TYPE_DEVICE, true);
641     for (elt = list; elt; elt = elt->next) {
642         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
643                                              TYPE_DEVICE);
644         const char *name;
645         int indent = 2;
646 
647         if (!dc->vmsd) {
648             continue;
649         }
650 
651         if (!first) {
652             fprintf(out_file, ",\n");
653         }
654         name = object_class_get_name(OBJECT_CLASS(dc));
655         fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
656         indent += 2;
657         fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
658         fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
659                 dc->vmsd->version_id);
660         fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
661                 dc->vmsd->minimum_version_id);
662 
663         dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
664 
665         fprintf(out_file, "\n%*s}", indent - 2, "");
666         first = false;
667     }
668     fprintf(out_file, "\n}\n");
669     fclose(out_file);
670     g_slist_free(list);
671 }
672 
673 static uint32_t calculate_new_instance_id(const char *idstr)
674 {
675     SaveStateEntry *se;
676     uint32_t instance_id = 0;
677 
678     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
679         if (strcmp(idstr, se->idstr) == 0
680             && instance_id <= se->instance_id) {
681             instance_id = se->instance_id + 1;
682         }
683     }
684     /* Make sure we never loop over without being noticed */
685     assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
686     return instance_id;
687 }
688 
689 static int calculate_compat_instance_id(const char *idstr)
690 {
691     SaveStateEntry *se;
692     int instance_id = 0;
693 
694     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
695         if (!se->compat) {
696             continue;
697         }
698 
699         if (strcmp(idstr, se->compat->idstr) == 0
700             && instance_id <= se->compat->instance_id) {
701             instance_id = se->compat->instance_id + 1;
702         }
703     }
704     return instance_id;
705 }
706 
707 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
708 {
709     if (se->vmsd) {
710         return se->vmsd->priority;
711     }
712     return MIG_PRI_DEFAULT;
713 }
714 
715 static void savevm_state_handler_insert(SaveStateEntry *nse)
716 {
717     MigrationPriority priority = save_state_priority(nse);
718     SaveStateEntry *se;
719     int i;
720 
721     assert(priority <= MIG_PRI_MAX);
722 
723     /*
724      * This should never happen otherwise migration will probably fail
725      * silently somewhere because we can be wrongly applying one
726      * object properties upon another one.  Bail out ASAP.
727      */
728     if (find_se(nse->idstr, nse->instance_id)) {
729         error_report("%s: Detected duplicate SaveStateEntry: "
730                      "id=%s, instance_id=0x%"PRIx32, __func__,
731                      nse->idstr, nse->instance_id);
732         exit(EXIT_FAILURE);
733     }
734 
735     for (i = priority - 1; i >= 0; i--) {
736         se = savevm_state.handler_pri_head[i];
737         if (se != NULL) {
738             assert(save_state_priority(se) < priority);
739             break;
740         }
741     }
742 
743     if (i >= 0) {
744         QTAILQ_INSERT_BEFORE(se, nse, entry);
745     } else {
746         QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
747     }
748 
749     if (savevm_state.handler_pri_head[priority] == NULL) {
750         savevm_state.handler_pri_head[priority] = nse;
751     }
752 }
753 
754 static void savevm_state_handler_remove(SaveStateEntry *se)
755 {
756     SaveStateEntry *next;
757     MigrationPriority priority = save_state_priority(se);
758 
759     if (se == savevm_state.handler_pri_head[priority]) {
760         next = QTAILQ_NEXT(se, entry);
761         if (next != NULL && save_state_priority(next) == priority) {
762             savevm_state.handler_pri_head[priority] = next;
763         } else {
764             savevm_state.handler_pri_head[priority] = NULL;
765         }
766     }
767     QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
768 }
769 
770 /* TODO: Individual devices generally have very little idea about the rest
771    of the system, so instance_id should be removed/replaced.
772    Meanwhile pass -1 as instance_id if you do not already have a clearly
773    distinguishing id for all instances of your device class. */
774 int register_savevm_live(const char *idstr,
775                          uint32_t instance_id,
776                          int version_id,
777                          const SaveVMHandlers *ops,
778                          void *opaque)
779 {
780     SaveStateEntry *se;
781 
782     se = g_new0(SaveStateEntry, 1);
783     se->version_id = version_id;
784     se->section_id = savevm_state.global_section_id++;
785     se->ops = ops;
786     se->opaque = opaque;
787     se->vmsd = NULL;
788     /* if this is a live_savem then set is_ram */
789     if (ops->save_setup != NULL) {
790         se->is_ram = 1;
791     }
792 
793     pstrcat(se->idstr, sizeof(se->idstr), idstr);
794 
795     if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
796         se->instance_id = calculate_new_instance_id(se->idstr);
797     } else {
798         se->instance_id = instance_id;
799     }
800     assert(!se->compat || se->instance_id == 0);
801     savevm_state_handler_insert(se);
802     return 0;
803 }
804 
805 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
806 {
807     SaveStateEntry *se, *new_se;
808     char id[256] = "";
809 
810     if (obj) {
811         char *oid = vmstate_if_get_id(obj);
812         if (oid) {
813             pstrcpy(id, sizeof(id), oid);
814             pstrcat(id, sizeof(id), "/");
815             g_free(oid);
816         }
817     }
818     pstrcat(id, sizeof(id), idstr);
819 
820     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
821         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
822             savevm_state_handler_remove(se);
823             g_free(se->compat);
824             g_free(se);
825         }
826     }
827 }
828 
829 /*
830  * Perform some basic checks on vmsd's at registration
831  * time.
832  */
833 static void vmstate_check(const VMStateDescription *vmsd)
834 {
835     const VMStateField *field = vmsd->fields;
836     const VMStateDescription * const *subsection = vmsd->subsections;
837 
838     if (field) {
839         while (field->name) {
840             if (field->flags & (VMS_STRUCT | VMS_VSTRUCT)) {
841                 /* Recurse to sub structures */
842                 vmstate_check(field->vmsd);
843             }
844             /* Carry on */
845             field++;
846         }
847         /* Check for the end of field list canary */
848         if (field->flags != VMS_END) {
849             error_report("VMSTATE not ending with VMS_END: %s", vmsd->name);
850             g_assert_not_reached();
851         }
852     }
853 
854     while (subsection && *subsection) {
855         /*
856          * The name of a subsection should start with the name of the
857          * current object.
858          */
859         assert(!strncmp(vmsd->name, (*subsection)->name, strlen(vmsd->name)));
860         vmstate_check(*subsection);
861         subsection++;
862     }
863 }
864 
865 
866 int vmstate_register_with_alias_id(VMStateIf *obj, uint32_t instance_id,
867                                    const VMStateDescription *vmsd,
868                                    void *opaque, int alias_id,
869                                    int required_for_version,
870                                    Error **errp)
871 {
872     SaveStateEntry *se;
873 
874     /* If this triggers, alias support can be dropped for the vmsd. */
875     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
876 
877     se = g_new0(SaveStateEntry, 1);
878     se->version_id = vmsd->version_id;
879     se->section_id = savevm_state.global_section_id++;
880     se->opaque = opaque;
881     se->vmsd = vmsd;
882     se->alias_id = alias_id;
883 
884     if (obj) {
885         char *id = vmstate_if_get_id(obj);
886         if (id) {
887             if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
888                 sizeof(se->idstr)) {
889                 error_setg(errp, "Path too long for VMState (%s)", id);
890                 g_free(id);
891                 g_free(se);
892 
893                 return -1;
894             }
895             g_free(id);
896 
897             se->compat = g_new0(CompatEntry, 1);
898             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
899             se->compat->instance_id = instance_id == VMSTATE_INSTANCE_ID_ANY ?
900                          calculate_compat_instance_id(vmsd->name) : instance_id;
901             instance_id = VMSTATE_INSTANCE_ID_ANY;
902         }
903     }
904     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
905 
906     if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
907         se->instance_id = calculate_new_instance_id(se->idstr);
908     } else {
909         se->instance_id = instance_id;
910     }
911 
912     /* Perform a recursive sanity check during the test runs */
913     if (qtest_enabled()) {
914         vmstate_check(vmsd);
915     }
916     assert(!se->compat || se->instance_id == 0);
917     savevm_state_handler_insert(se);
918     return 0;
919 }
920 
921 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
922                         void *opaque)
923 {
924     SaveStateEntry *se, *new_se;
925 
926     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
927         if (se->vmsd == vmsd && se->opaque == opaque) {
928             savevm_state_handler_remove(se);
929             g_free(se->compat);
930             g_free(se);
931         }
932     }
933 }
934 
935 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
936 {
937     trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
938     if (!se->vmsd) {         /* Old style */
939         return se->ops->load_state(f, se->opaque, se->load_version_id);
940     }
941     return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
942 }
943 
944 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
945                                    JSONWriter *vmdesc)
946 {
947     uint64_t old_offset = qemu_file_transferred(f);
948     se->ops->save_state(f, se->opaque);
949     uint64_t size = qemu_file_transferred(f) - old_offset;
950 
951     if (vmdesc) {
952         json_writer_int64(vmdesc, "size", size);
953         json_writer_start_array(vmdesc, "fields");
954         json_writer_start_object(vmdesc, NULL);
955         json_writer_str(vmdesc, "name", "data");
956         json_writer_int64(vmdesc, "size", size);
957         json_writer_str(vmdesc, "type", "buffer");
958         json_writer_end_object(vmdesc);
959         json_writer_end_array(vmdesc);
960     }
961 }
962 
963 /*
964  * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
965  */
966 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
967                                 uint8_t section_type)
968 {
969     qemu_put_byte(f, section_type);
970     qemu_put_be32(f, se->section_id);
971 
972     if (section_type == QEMU_VM_SECTION_FULL ||
973         section_type == QEMU_VM_SECTION_START) {
974         /* ID string */
975         size_t len = strlen(se->idstr);
976         qemu_put_byte(f, len);
977         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
978 
979         qemu_put_be32(f, se->instance_id);
980         qemu_put_be32(f, se->version_id);
981     }
982 }
983 
984 /*
985  * Write a footer onto device sections that catches cases misformatted device
986  * sections.
987  */
988 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
989 {
990     if (migrate_get_current()->send_section_footer) {
991         qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
992         qemu_put_be32(f, se->section_id);
993     }
994 }
995 
996 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, JSONWriter *vmdesc,
997                         Error **errp)
998 {
999     int ret;
1000 
1001     if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1002         return 0;
1003     }
1004     if (se->vmsd && !vmstate_section_needed(se->vmsd, se->opaque)) {
1005         trace_savevm_section_skip(se->idstr, se->section_id);
1006         return 0;
1007     }
1008 
1009     trace_savevm_section_start(se->idstr, se->section_id);
1010     save_section_header(f, se, QEMU_VM_SECTION_FULL);
1011     if (vmdesc) {
1012         json_writer_start_object(vmdesc, NULL);
1013         json_writer_str(vmdesc, "name", se->idstr);
1014         json_writer_int64(vmdesc, "instance_id", se->instance_id);
1015     }
1016 
1017     trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
1018     if (!se->vmsd) {
1019         vmstate_save_old_style(f, se, vmdesc);
1020     } else {
1021         ret = vmstate_save_state_with_err(f, se->vmsd, se->opaque, vmdesc,
1022                                           errp);
1023         if (ret) {
1024             return ret;
1025         }
1026     }
1027 
1028     trace_savevm_section_end(se->idstr, se->section_id, 0);
1029     save_section_footer(f, se);
1030     if (vmdesc) {
1031         json_writer_end_object(vmdesc);
1032     }
1033     return 0;
1034 }
1035 /**
1036  * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
1037  *                           command and associated data.
1038  *
1039  * @f: File to send command on
1040  * @command: Command type to send
1041  * @len: Length of associated data
1042  * @data: Data associated with command.
1043  */
1044 static void qemu_savevm_command_send(QEMUFile *f,
1045                                      enum qemu_vm_cmd command,
1046                                      uint16_t len,
1047                                      uint8_t *data)
1048 {
1049     trace_savevm_command_send(command, len);
1050     qemu_put_byte(f, QEMU_VM_COMMAND);
1051     qemu_put_be16(f, (uint16_t)command);
1052     qemu_put_be16(f, len);
1053     qemu_put_buffer(f, data, len);
1054     qemu_fflush(f);
1055 }
1056 
1057 void qemu_savevm_send_colo_enable(QEMUFile *f)
1058 {
1059     trace_savevm_send_colo_enable();
1060     qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
1061 }
1062 
1063 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
1064 {
1065     uint32_t buf;
1066 
1067     trace_savevm_send_ping(value);
1068     buf = cpu_to_be32(value);
1069     qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
1070 }
1071 
1072 void qemu_savevm_send_open_return_path(QEMUFile *f)
1073 {
1074     trace_savevm_send_open_return_path();
1075     qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
1076 }
1077 
1078 /* We have a buffer of data to send; we don't want that all to be loaded
1079  * by the command itself, so the command contains just the length of the
1080  * extra buffer that we then send straight after it.
1081  * TODO: Must be a better way to organise that
1082  *
1083  * Returns:
1084  *    0 on success
1085  *    -ve on error
1086  */
1087 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
1088 {
1089     uint32_t tmp;
1090     MigrationState *ms = migrate_get_current();
1091     Error *local_err = NULL;
1092 
1093     if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1094         error_setg(&local_err, "%s: Unreasonably large packaged state: %zu",
1095                      __func__, len);
1096         migrate_set_error(ms, local_err);
1097         error_report_err(local_err);
1098         return -1;
1099     }
1100 
1101     tmp = cpu_to_be32(len);
1102 
1103     trace_qemu_savevm_send_packaged();
1104     qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1105 
1106     qemu_put_buffer(f, buf, len);
1107 
1108     return 0;
1109 }
1110 
1111 /* Send prior to any postcopy transfer */
1112 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1113 {
1114     if (migrate_postcopy_ram()) {
1115         uint64_t tmp[2];
1116         tmp[0] = cpu_to_be64(ram_pagesize_summary());
1117         tmp[1] = cpu_to_be64(qemu_target_page_size());
1118 
1119         trace_qemu_savevm_send_postcopy_advise();
1120         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1121                                  16, (uint8_t *)tmp);
1122     } else {
1123         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1124     }
1125 }
1126 
1127 /* Sent prior to starting the destination running in postcopy, discard pages
1128  * that have already been sent but redirtied on the source.
1129  * CMD_POSTCOPY_RAM_DISCARD consist of:
1130  *      byte   version (0)
1131  *      byte   Length of name field (not including 0)
1132  *  n x byte   RAM block name
1133  *      byte   0 terminator (just for safety)
1134  *  n x        Byte ranges within the named RAMBlock
1135  *      be64   Start of the range
1136  *      be64   Length
1137  *
1138  *  name:  RAMBlock name that these entries are part of
1139  *  len: Number of page entries
1140  *  start_list: 'len' addresses
1141  *  length_list: 'len' addresses
1142  *
1143  */
1144 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1145                                            uint16_t len,
1146                                            uint64_t *start_list,
1147                                            uint64_t *length_list)
1148 {
1149     uint8_t *buf;
1150     uint16_t tmplen;
1151     uint16_t t;
1152     size_t name_len = strlen(name);
1153 
1154     trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1155     assert(name_len < 256);
1156     buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1157     buf[0] = postcopy_ram_discard_version;
1158     buf[1] = name_len;
1159     memcpy(buf + 2, name, name_len);
1160     tmplen = 2 + name_len;
1161     buf[tmplen++] = '\0';
1162 
1163     for (t = 0; t < len; t++) {
1164         stq_be_p(buf + tmplen, start_list[t]);
1165         tmplen += 8;
1166         stq_be_p(buf + tmplen, length_list[t]);
1167         tmplen += 8;
1168     }
1169     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1170     g_free(buf);
1171 }
1172 
1173 /* Get the destination into a state where it can receive postcopy data. */
1174 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1175 {
1176     trace_savevm_send_postcopy_listen();
1177     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1178 }
1179 
1180 /* Kick the destination into running */
1181 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1182 {
1183     trace_savevm_send_postcopy_run();
1184     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1185 }
1186 
1187 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1188 {
1189     trace_savevm_send_postcopy_resume();
1190     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1191 }
1192 
1193 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1194 {
1195     size_t len;
1196     char buf[256];
1197 
1198     trace_savevm_send_recv_bitmap(block_name);
1199 
1200     buf[0] = len = strlen(block_name);
1201     memcpy(buf + 1, block_name, len);
1202 
1203     qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1204 }
1205 
1206 static void qemu_savevm_send_switchover_start(QEMUFile *f)
1207 {
1208     trace_savevm_send_switchover_start();
1209     qemu_savevm_command_send(f, MIG_CMD_SWITCHOVER_START, 0, NULL);
1210 }
1211 
1212 void qemu_savevm_maybe_send_switchover_start(QEMUFile *f)
1213 {
1214     if (migrate_send_switchover_start()) {
1215         qemu_savevm_send_switchover_start(f);
1216     }
1217 }
1218 
1219 bool qemu_savevm_state_blocked(Error **errp)
1220 {
1221     SaveStateEntry *se;
1222 
1223     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1224         if (se->vmsd && se->vmsd->unmigratable) {
1225             error_setg(errp, "State blocked by non-migratable device '%s'",
1226                        se->idstr);
1227             return true;
1228         }
1229     }
1230     return false;
1231 }
1232 
1233 void qemu_savevm_non_migratable_list(strList **reasons)
1234 {
1235     SaveStateEntry *se;
1236 
1237     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1238         if (se->vmsd && se->vmsd->unmigratable) {
1239             QAPI_LIST_PREPEND(*reasons,
1240                               g_strdup_printf("non-migratable device: %s",
1241                                               se->idstr));
1242         }
1243     }
1244 }
1245 
1246 void qemu_savevm_state_header(QEMUFile *f)
1247 {
1248     MigrationState *s = migrate_get_current();
1249     JSONWriter *vmdesc = s->vmdesc;
1250 
1251     trace_savevm_state_header();
1252     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1253     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1254 
1255     if (s->send_configuration) {
1256         qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1257 
1258         if (vmdesc) {
1259             /*
1260              * This starts the main json object and is paired with the
1261              * json_writer_end_object in
1262              * qemu_savevm_state_complete_precopy_non_iterable
1263              */
1264             json_writer_start_object(vmdesc, NULL);
1265             json_writer_start_object(vmdesc, "configuration");
1266         }
1267 
1268         vmstate_save_state(f, &vmstate_configuration, &savevm_state, vmdesc);
1269 
1270         if (vmdesc) {
1271             json_writer_end_object(vmdesc);
1272         }
1273     }
1274 }
1275 
1276 bool qemu_savevm_state_guest_unplug_pending(void)
1277 {
1278     SaveStateEntry *se;
1279 
1280     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1281         if (se->vmsd && se->vmsd->dev_unplug_pending &&
1282             se->vmsd->dev_unplug_pending(se->opaque)) {
1283             return true;
1284         }
1285     }
1286 
1287     return false;
1288 }
1289 
1290 int qemu_savevm_state_prepare(Error **errp)
1291 {
1292     SaveStateEntry *se;
1293     int ret;
1294 
1295     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1296         if (!se->ops || !se->ops->save_prepare) {
1297             continue;
1298         }
1299         if (se->ops->is_active) {
1300             if (!se->ops->is_active(se->opaque)) {
1301                 continue;
1302             }
1303         }
1304 
1305         ret = se->ops->save_prepare(se->opaque, errp);
1306         if (ret < 0) {
1307             return ret;
1308         }
1309     }
1310 
1311     return 0;
1312 }
1313 
1314 int qemu_savevm_state_setup(QEMUFile *f, Error **errp)
1315 {
1316     ERRP_GUARD();
1317     MigrationState *ms = migrate_get_current();
1318     JSONWriter *vmdesc = ms->vmdesc;
1319     SaveStateEntry *se;
1320     int ret = 0;
1321 
1322     if (vmdesc) {
1323         json_writer_int64(vmdesc, "page_size", qemu_target_page_size());
1324         json_writer_start_array(vmdesc, "devices");
1325     }
1326 
1327     trace_savevm_state_setup();
1328     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1329         if (se->vmsd && se->vmsd->early_setup) {
1330             ret = vmstate_save(f, se, vmdesc, errp);
1331             if (ret) {
1332                 migrate_set_error(ms, *errp);
1333                 qemu_file_set_error(f, ret);
1334                 break;
1335             }
1336             continue;
1337         }
1338 
1339         if (!se->ops || !se->ops->save_setup) {
1340             continue;
1341         }
1342         if (se->ops->is_active) {
1343             if (!se->ops->is_active(se->opaque)) {
1344                 continue;
1345             }
1346         }
1347         save_section_header(f, se, QEMU_VM_SECTION_START);
1348 
1349         ret = se->ops->save_setup(f, se->opaque, errp);
1350         save_section_footer(f, se);
1351         if (ret < 0) {
1352             qemu_file_set_error(f, ret);
1353             break;
1354         }
1355     }
1356 
1357     if (ret) {
1358         return ret;
1359     }
1360 
1361     /* TODO: Should we check that errp is set in case of failure ? */
1362     return precopy_notify(PRECOPY_NOTIFY_SETUP, errp);
1363 }
1364 
1365 int qemu_savevm_state_resume_prepare(MigrationState *s)
1366 {
1367     SaveStateEntry *se;
1368     int ret;
1369 
1370     trace_savevm_state_resume_prepare();
1371 
1372     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1373         if (!se->ops || !se->ops->resume_prepare) {
1374             continue;
1375         }
1376         if (se->ops->is_active) {
1377             if (!se->ops->is_active(se->opaque)) {
1378                 continue;
1379             }
1380         }
1381         ret = se->ops->resume_prepare(s, se->opaque);
1382         if (ret < 0) {
1383             return ret;
1384         }
1385     }
1386 
1387     return 0;
1388 }
1389 
1390 /*
1391  * this function has three return values:
1392  *   negative: there was one error, and we have -errno.
1393  *   0 : We haven't finished, caller have to go again
1394  *   1 : We have finished, we can go to complete phase
1395  */
1396 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1397 {
1398     SaveStateEntry *se;
1399     bool all_finished = true;
1400     int ret;
1401 
1402     trace_savevm_state_iterate();
1403     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1404         if (!se->ops || !se->ops->save_live_iterate) {
1405             continue;
1406         }
1407         if (se->ops->is_active &&
1408             !se->ops->is_active(se->opaque)) {
1409             continue;
1410         }
1411         if (se->ops->is_active_iterate &&
1412             !se->ops->is_active_iterate(se->opaque)) {
1413             continue;
1414         }
1415         /*
1416          * In the postcopy phase, any device that doesn't know how to
1417          * do postcopy should have saved it's state in the _complete
1418          * call that's already run, it might get confused if we call
1419          * iterate afterwards.
1420          */
1421         if (postcopy &&
1422             !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1423             continue;
1424         }
1425         if (migration_rate_exceeded(f)) {
1426             return 0;
1427         }
1428         trace_savevm_section_start(se->idstr, se->section_id);
1429 
1430         save_section_header(f, se, QEMU_VM_SECTION_PART);
1431 
1432         ret = se->ops->save_live_iterate(f, se->opaque);
1433         trace_savevm_section_end(se->idstr, se->section_id, ret);
1434         save_section_footer(f, se);
1435 
1436         if (ret < 0) {
1437             error_report("failed to save SaveStateEntry with id(name): "
1438                          "%d(%s): %d",
1439                          se->section_id, se->idstr, ret);
1440             qemu_file_set_error(f, ret);
1441             return ret;
1442         } else if (!ret) {
1443             all_finished = false;
1444         }
1445     }
1446     return all_finished;
1447 }
1448 
1449 bool should_send_vmdesc(void)
1450 {
1451     MachineState *machine = MACHINE(qdev_get_machine());
1452 
1453     return !machine->suppress_vmdesc;
1454 }
1455 
1456 /*
1457  * Calls the save_live_complete_postcopy methods
1458  * causing the last few pages to be sent immediately and doing any associated
1459  * cleanup.
1460  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1461  * all the other devices, but that happens at the point we switch to postcopy.
1462  */
1463 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1464 {
1465     SaveStateEntry *se;
1466     int ret;
1467 
1468     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1469         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1470             continue;
1471         }
1472         if (se->ops->is_active) {
1473             if (!se->ops->is_active(se->opaque)) {
1474                 continue;
1475             }
1476         }
1477         trace_savevm_section_start(se->idstr, se->section_id);
1478         /* Section type */
1479         qemu_put_byte(f, QEMU_VM_SECTION_END);
1480         qemu_put_be32(f, se->section_id);
1481 
1482         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1483         trace_savevm_section_end(se->idstr, se->section_id, ret);
1484         save_section_footer(f, se);
1485         if (ret < 0) {
1486             qemu_file_set_error(f, ret);
1487             return;
1488         }
1489     }
1490 
1491     qemu_put_byte(f, QEMU_VM_EOF);
1492     qemu_fflush(f);
1493 }
1494 
1495 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1496 {
1497     int64_t start_ts_each, end_ts_each;
1498     SaveStateEntry *se;
1499     int ret;
1500 
1501     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1502         if (!se->ops ||
1503             (in_postcopy && se->ops->has_postcopy &&
1504              se->ops->has_postcopy(se->opaque)) ||
1505             !se->ops->save_live_complete_precopy) {
1506             continue;
1507         }
1508 
1509         if (se->ops->is_active) {
1510             if (!se->ops->is_active(se->opaque)) {
1511                 continue;
1512             }
1513         }
1514 
1515         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1516         trace_savevm_section_start(se->idstr, se->section_id);
1517 
1518         save_section_header(f, se, QEMU_VM_SECTION_END);
1519 
1520         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1521         trace_savevm_section_end(se->idstr, se->section_id, ret);
1522         save_section_footer(f, se);
1523         if (ret < 0) {
1524             qemu_file_set_error(f, ret);
1525             return -1;
1526         }
1527         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1528         trace_vmstate_downtime_save("iterable", se->idstr, se->instance_id,
1529                                     end_ts_each - start_ts_each);
1530     }
1531 
1532     trace_vmstate_downtime_checkpoint("src-iterable-saved");
1533 
1534     return 0;
1535 }
1536 
1537 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1538                                                     bool in_postcopy)
1539 {
1540     MigrationState *ms = migrate_get_current();
1541     int64_t start_ts_each, end_ts_each;
1542     JSONWriter *vmdesc = ms->vmdesc;
1543     int vmdesc_len;
1544     SaveStateEntry *se;
1545     Error *local_err = NULL;
1546     int ret;
1547 
1548     /* Making sure cpu states are synchronized before saving non-iterable */
1549     cpu_synchronize_all_states();
1550 
1551     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1552         if (se->vmsd && se->vmsd->early_setup) {
1553             /* Already saved during qemu_savevm_state_setup(). */
1554             continue;
1555         }
1556 
1557         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1558 
1559         ret = vmstate_save(f, se, vmdesc, &local_err);
1560         if (ret) {
1561             migrate_set_error(ms, local_err);
1562             error_report_err(local_err);
1563             qemu_file_set_error(f, ret);
1564             return ret;
1565         }
1566 
1567         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1568         trace_vmstate_downtime_save("non-iterable", se->idstr, se->instance_id,
1569                                     end_ts_each - start_ts_each);
1570     }
1571 
1572     if (!in_postcopy) {
1573         /* Postcopy stream will still be going */
1574         qemu_put_byte(f, QEMU_VM_EOF);
1575 
1576         if (vmdesc) {
1577             json_writer_end_array(vmdesc);
1578             json_writer_end_object(vmdesc);
1579             vmdesc_len = strlen(json_writer_get(vmdesc));
1580 
1581             qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1582             qemu_put_be32(f, vmdesc_len);
1583             qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1584         }
1585     }
1586 
1587     trace_vmstate_downtime_checkpoint("src-non-iterable-saved");
1588 
1589     return 0;
1590 }
1591 
1592 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only)
1593 {
1594     int ret;
1595 
1596     ret = qemu_savevm_state_complete_precopy_iterable(f, false);
1597     if (ret) {
1598         return ret;
1599     }
1600 
1601     if (!iterable_only) {
1602         ret = qemu_savevm_state_complete_precopy_non_iterable(f, false);
1603         if (ret) {
1604             return ret;
1605         }
1606     }
1607 
1608     return qemu_fflush(f);
1609 }
1610 
1611 /* Give an estimate of the amount left to be transferred,
1612  * the result is split into the amount for units that can and
1613  * for units that can't do postcopy.
1614  */
1615 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1616                                         uint64_t *can_postcopy)
1617 {
1618     SaveStateEntry *se;
1619 
1620     *must_precopy = 0;
1621     *can_postcopy = 0;
1622 
1623     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1624         if (!se->ops || !se->ops->state_pending_estimate) {
1625             continue;
1626         }
1627         if (se->ops->is_active) {
1628             if (!se->ops->is_active(se->opaque)) {
1629                 continue;
1630             }
1631         }
1632         se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1633     }
1634 }
1635 
1636 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1637                                      uint64_t *can_postcopy)
1638 {
1639     SaveStateEntry *se;
1640 
1641     *must_precopy = 0;
1642     *can_postcopy = 0;
1643 
1644     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1645         if (!se->ops || !se->ops->state_pending_exact) {
1646             continue;
1647         }
1648         if (se->ops->is_active) {
1649             if (!se->ops->is_active(se->opaque)) {
1650                 continue;
1651             }
1652         }
1653         se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1654     }
1655 }
1656 
1657 void qemu_savevm_state_cleanup(void)
1658 {
1659     SaveStateEntry *se;
1660     Error *local_err = NULL;
1661 
1662     if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1663         error_report_err(local_err);
1664     }
1665 
1666     trace_savevm_state_cleanup();
1667     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1668         if (se->ops && se->ops->save_cleanup) {
1669             se->ops->save_cleanup(se->opaque);
1670         }
1671     }
1672 }
1673 
1674 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1675 {
1676     int ret;
1677     MigrationState *ms = migrate_get_current();
1678     MigrationStatus status;
1679 
1680     if (migration_is_running()) {
1681         error_setg(errp, "There's a migration process in progress");
1682         return -EINVAL;
1683     }
1684 
1685     ret = migrate_init(ms, errp);
1686     if (ret) {
1687         return ret;
1688     }
1689     ms->to_dst_file = f;
1690 
1691     qemu_savevm_state_header(f);
1692     ret = qemu_savevm_state_setup(f, errp);
1693     if (ret) {
1694         goto cleanup;
1695     }
1696 
1697     while (qemu_file_get_error(f) == 0) {
1698         if (qemu_savevm_state_iterate(f, false) > 0) {
1699             break;
1700         }
1701     }
1702 
1703     ret = qemu_file_get_error(f);
1704     if (ret == 0) {
1705         qemu_savevm_maybe_send_switchover_start(f);
1706         qemu_savevm_state_complete_precopy(f, false);
1707         ret = qemu_file_get_error(f);
1708     }
1709     if (ret != 0) {
1710         error_setg_errno(errp, -ret, "Error while writing VM state");
1711     }
1712 cleanup:
1713     qemu_savevm_state_cleanup();
1714 
1715     if (ret != 0) {
1716         status = MIGRATION_STATUS_FAILED;
1717     } else {
1718         status = MIGRATION_STATUS_COMPLETED;
1719     }
1720     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1721 
1722     /* f is outer parameter, it should not stay in global migration state after
1723      * this function finished */
1724     ms->to_dst_file = NULL;
1725 
1726     return ret;
1727 }
1728 
1729 void qemu_savevm_live_state(QEMUFile *f)
1730 {
1731     /* save QEMU_VM_SECTION_END section */
1732     qemu_savevm_state_complete_precopy(f, true);
1733     qemu_put_byte(f, QEMU_VM_EOF);
1734 }
1735 
1736 int qemu_save_device_state(QEMUFile *f)
1737 {
1738     MigrationState *ms = migrate_get_current();
1739     Error *local_err = NULL;
1740     SaveStateEntry *se;
1741 
1742     if (!migration_in_colo_state()) {
1743         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1744         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1745     }
1746     cpu_synchronize_all_states();
1747 
1748     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1749         int ret;
1750 
1751         if (se->is_ram) {
1752             continue;
1753         }
1754         ret = vmstate_save(f, se, NULL, &local_err);
1755         if (ret) {
1756             migrate_set_error(ms, local_err);
1757             error_report_err(local_err);
1758             return ret;
1759         }
1760     }
1761 
1762     qemu_put_byte(f, QEMU_VM_EOF);
1763 
1764     return qemu_file_get_error(f);
1765 }
1766 
1767 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1768 {
1769     SaveStateEntry *se;
1770 
1771     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1772         if (!strcmp(se->idstr, idstr) &&
1773             (instance_id == se->instance_id ||
1774              instance_id == se->alias_id))
1775             return se;
1776         /* Migrating from an older version? */
1777         if (strstr(se->idstr, idstr) && se->compat) {
1778             if (!strcmp(se->compat->idstr, idstr) &&
1779                 (instance_id == se->compat->instance_id ||
1780                  instance_id == se->alias_id))
1781                 return se;
1782         }
1783     }
1784     return NULL;
1785 }
1786 
1787 enum LoadVMExitCodes {
1788     /* Allow a command to quit all layers of nested loadvm loops */
1789     LOADVM_QUIT     =  1,
1790 };
1791 
1792 /* ------ incoming postcopy messages ------ */
1793 /* 'advise' arrives before any transfers just to tell us that a postcopy
1794  * *might* happen - it might be skipped if precopy transferred everything
1795  * quickly.
1796  */
1797 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1798                                          uint16_t len)
1799 {
1800     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1801     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1802     size_t page_size = qemu_target_page_size();
1803     Error *local_err = NULL;
1804 
1805     trace_loadvm_postcopy_handle_advise();
1806     if (ps != POSTCOPY_INCOMING_NONE) {
1807         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1808         return -1;
1809     }
1810 
1811     switch (len) {
1812     case 0:
1813         if (migrate_postcopy_ram()) {
1814             error_report("RAM postcopy is enabled but have 0 byte advise");
1815             return -EINVAL;
1816         }
1817         return 0;
1818     case 8 + 8:
1819         if (!migrate_postcopy_ram()) {
1820             error_report("RAM postcopy is disabled but have 16 byte advise");
1821             return -EINVAL;
1822         }
1823         break;
1824     default:
1825         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1826         return -EINVAL;
1827     }
1828 
1829     if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1830         error_report_err(local_err);
1831         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1832         return -1;
1833     }
1834 
1835     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1836     local_pagesize_summary = ram_pagesize_summary();
1837 
1838     if (remote_pagesize_summary != local_pagesize_summary)  {
1839         /*
1840          * This detects two potential causes of mismatch:
1841          *   a) A mismatch in host page sizes
1842          *      Some combinations of mismatch are probably possible but it gets
1843          *      a bit more complicated.  In particular we need to place whole
1844          *      host pages on the dest at once, and we need to ensure that we
1845          *      handle dirtying to make sure we never end up sending part of
1846          *      a hostpage on it's own.
1847          *   b) The use of different huge page sizes on source/destination
1848          *      a more fine grain test is performed during RAM block migration
1849          *      but this test here causes a nice early clear failure, and
1850          *      also fails when passed to an older qemu that doesn't
1851          *      do huge pages.
1852          */
1853         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1854                                                              " d=%" PRIx64 ")",
1855                      remote_pagesize_summary, local_pagesize_summary);
1856         return -1;
1857     }
1858 
1859     remote_tps = qemu_get_be64(mis->from_src_file);
1860     if (remote_tps != page_size) {
1861         /*
1862          * Again, some differences could be dealt with, but for now keep it
1863          * simple.
1864          */
1865         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1866                      (int)remote_tps, page_size);
1867         return -1;
1868     }
1869 
1870     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1871         error_report_err(local_err);
1872         return -1;
1873     }
1874 
1875     if (ram_postcopy_incoming_init(mis)) {
1876         return -1;
1877     }
1878 
1879     return 0;
1880 }
1881 
1882 /* After postcopy we will be told to throw some pages away since they're
1883  * dirty and will have to be demand fetched.  Must happen before CPU is
1884  * started.
1885  * There can be 0..many of these messages, each encoding multiple pages.
1886  */
1887 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1888                                               uint16_t len)
1889 {
1890     int tmp;
1891     char ramid[256];
1892     PostcopyState ps = postcopy_state_get();
1893 
1894     trace_loadvm_postcopy_ram_handle_discard();
1895 
1896     switch (ps) {
1897     case POSTCOPY_INCOMING_ADVISE:
1898         /* 1st discard */
1899         tmp = postcopy_ram_prepare_discard(mis);
1900         if (tmp) {
1901             return tmp;
1902         }
1903         break;
1904 
1905     case POSTCOPY_INCOMING_DISCARD:
1906         /* Expected state */
1907         break;
1908 
1909     default:
1910         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1911                      ps);
1912         return -1;
1913     }
1914     /* We're expecting a
1915      *    Version (0)
1916      *    a RAM ID string (length byte, name, 0 term)
1917      *    then at least 1 16 byte chunk
1918     */
1919     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1920         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1921         return -1;
1922     }
1923 
1924     tmp = qemu_get_byte(mis->from_src_file);
1925     if (tmp != postcopy_ram_discard_version) {
1926         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1927         return -1;
1928     }
1929 
1930     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1931         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1932         return -1;
1933     }
1934     tmp = qemu_get_byte(mis->from_src_file);
1935     if (tmp != 0) {
1936         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1937         return -1;
1938     }
1939 
1940     len -= 3 + strlen(ramid);
1941     if (len % 16) {
1942         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1943         return -1;
1944     }
1945     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1946     while (len) {
1947         uint64_t start_addr, block_length;
1948         start_addr = qemu_get_be64(mis->from_src_file);
1949         block_length = qemu_get_be64(mis->from_src_file);
1950 
1951         len -= 16;
1952         int ret = ram_discard_range(ramid, start_addr, block_length);
1953         if (ret) {
1954             return ret;
1955         }
1956     }
1957     trace_loadvm_postcopy_ram_handle_discard_end();
1958 
1959     return 0;
1960 }
1961 
1962 /*
1963  * Triggered by a postcopy_listen command; this thread takes over reading
1964  * the input stream, leaving the main thread free to carry on loading the rest
1965  * of the device state (from RAM).
1966  * (TODO:This could do with being in a postcopy file - but there again it's
1967  * just another input loop, not that postcopy specific)
1968  */
1969 static void *postcopy_ram_listen_thread(void *opaque)
1970 {
1971     MigrationIncomingState *mis = migration_incoming_get_current();
1972     QEMUFile *f = mis->from_src_file;
1973     int load_res;
1974     MigrationState *migr = migrate_get_current();
1975 
1976     object_ref(OBJECT(migr));
1977 
1978     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1979                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
1980     qemu_sem_post(&mis->thread_sync_sem);
1981     trace_postcopy_ram_listen_thread_start();
1982 
1983     rcu_register_thread();
1984     /*
1985      * Because we're a thread and not a coroutine we can't yield
1986      * in qemu_file, and thus we must be blocking now.
1987      */
1988     qemu_file_set_blocking(f, true);
1989     load_res = qemu_loadvm_state_main(f, mis);
1990 
1991     /*
1992      * This is tricky, but, mis->from_src_file can change after it
1993      * returns, when postcopy recovery happened. In the future, we may
1994      * want a wrapper for the QEMUFile handle.
1995      */
1996     f = mis->from_src_file;
1997 
1998     /* And non-blocking again so we don't block in any cleanup */
1999     qemu_file_set_blocking(f, false);
2000 
2001     trace_postcopy_ram_listen_thread_exit();
2002     if (load_res < 0) {
2003         qemu_file_set_error(f, load_res);
2004         dirty_bitmap_mig_cancel_incoming();
2005         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2006             !migrate_postcopy_ram() && migrate_dirty_bitmaps())
2007         {
2008             error_report("%s: loadvm failed during postcopy: %d. All states "
2009                          "are migrated except dirty bitmaps. Some dirty "
2010                          "bitmaps may be lost, and present migrated dirty "
2011                          "bitmaps are correctly migrated and valid.",
2012                          __func__, load_res);
2013             load_res = 0; /* prevent further exit() */
2014         } else {
2015             error_report("%s: loadvm failed: %d", __func__, load_res);
2016             migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2017                                            MIGRATION_STATUS_FAILED);
2018         }
2019     }
2020     if (load_res >= 0) {
2021         /*
2022          * This looks good, but it's possible that the device loading in the
2023          * main thread hasn't finished yet, and so we might not be in 'RUN'
2024          * state yet; wait for the end of the main thread.
2025          */
2026         qemu_event_wait(&mis->main_thread_load_event);
2027     }
2028     postcopy_ram_incoming_cleanup(mis);
2029 
2030     if (load_res < 0) {
2031         /*
2032          * If something went wrong then we have a bad state so exit;
2033          * depending how far we got it might be possible at this point
2034          * to leave the guest running and fire MCEs for pages that never
2035          * arrived as a desperate recovery step.
2036          */
2037         rcu_unregister_thread();
2038         exit(EXIT_FAILURE);
2039     }
2040 
2041     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2042                                    MIGRATION_STATUS_COMPLETED);
2043     /*
2044      * If everything has worked fine, then the main thread has waited
2045      * for us to start, and we're the last use of the mis.
2046      * (If something broke then qemu will have to exit anyway since it's
2047      * got a bad migration state).
2048      */
2049     migration_incoming_state_destroy();
2050 
2051     rcu_unregister_thread();
2052     mis->have_listen_thread = false;
2053     postcopy_state_set(POSTCOPY_INCOMING_END);
2054 
2055     object_unref(OBJECT(migr));
2056 
2057     return NULL;
2058 }
2059 
2060 /* After this message we must be able to immediately receive postcopy data */
2061 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2062 {
2063     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2064     Error *local_err = NULL;
2065 
2066     trace_loadvm_postcopy_handle_listen("enter");
2067 
2068     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2069         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2070         return -1;
2071     }
2072     if (ps == POSTCOPY_INCOMING_ADVISE) {
2073         /*
2074          * A rare case, we entered listen without having to do any discards,
2075          * so do the setup that's normally done at the time of the 1st discard.
2076          */
2077         if (migrate_postcopy_ram()) {
2078             postcopy_ram_prepare_discard(mis);
2079         }
2080     }
2081 
2082     trace_loadvm_postcopy_handle_listen("after discard");
2083 
2084     /*
2085      * Sensitise RAM - can now generate requests for blocks that don't exist
2086      * However, at this point the CPU shouldn't be running, and the IO
2087      * shouldn't be doing anything yet so don't actually expect requests
2088      */
2089     if (migrate_postcopy_ram()) {
2090         if (postcopy_ram_incoming_setup(mis)) {
2091             postcopy_ram_incoming_cleanup(mis);
2092             return -1;
2093         }
2094     }
2095 
2096     trace_loadvm_postcopy_handle_listen("after uffd");
2097 
2098     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2099         error_report_err(local_err);
2100         return -1;
2101     }
2102 
2103     mis->have_listen_thread = true;
2104     postcopy_thread_create(mis, &mis->listen_thread,
2105                            MIGRATION_THREAD_DST_LISTEN,
2106                            postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2107     trace_loadvm_postcopy_handle_listen("return");
2108 
2109     return 0;
2110 }
2111 
2112 static void loadvm_postcopy_handle_run_bh(void *opaque)
2113 {
2114     MigrationIncomingState *mis = opaque;
2115 
2116     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-enter");
2117 
2118     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2119      * in migration.c
2120      */
2121     cpu_synchronize_all_post_init();
2122 
2123     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cpu-synced");
2124 
2125     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2126 
2127     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-announced");
2128 
2129     dirty_bitmap_mig_before_vm_start();
2130 
2131     if (autostart) {
2132         /*
2133          * Make sure all file formats throw away their mutable metadata.
2134          * If we get an error here, just don't restart the VM yet.
2135          */
2136         bool success = migration_block_activate(NULL);
2137 
2138         trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cache-invalidated");
2139 
2140         if (success) {
2141             vm_start();
2142         }
2143     } else {
2144         /* leave it paused and let management decide when to start the CPU */
2145         runstate_set(RUN_STATE_PAUSED);
2146     }
2147 
2148     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-vm-started");
2149 }
2150 
2151 /* After all discards we can start running and asking for pages */
2152 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2153 {
2154     PostcopyState ps = postcopy_state_get();
2155 
2156     trace_loadvm_postcopy_handle_run();
2157     if (ps != POSTCOPY_INCOMING_LISTENING) {
2158         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2159         return -1;
2160     }
2161 
2162     postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2163     migration_bh_schedule(loadvm_postcopy_handle_run_bh, mis);
2164 
2165     /* We need to finish reading the stream from the package
2166      * and also stop reading anything more from the stream that loaded the
2167      * package (since it's now being read by the listener thread).
2168      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2169      */
2170     return LOADVM_QUIT;
2171 }
2172 
2173 /* We must be with page_request_mutex held */
2174 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2175                                        gpointer data)
2176 {
2177     MigrationIncomingState *mis = data;
2178     void *host_addr = (void *) key;
2179     ram_addr_t rb_offset;
2180     RAMBlock *rb;
2181     int ret;
2182 
2183     rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2184     if (!rb) {
2185         /*
2186          * This should _never_ happen.  However be nice for a migrating VM to
2187          * not crash/assert.  Post an error (note: intended to not use *_once
2188          * because we do want to see all the illegal addresses; and this can
2189          * never be triggered by the guest so we're safe) and move on next.
2190          */
2191         error_report("%s: illegal host addr %p", __func__, host_addr);
2192         /* Try the next entry */
2193         return FALSE;
2194     }
2195 
2196     ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2197     if (ret) {
2198         /* Please refer to above comment. */
2199         error_report("%s: send rp message failed for addr %p",
2200                      __func__, host_addr);
2201         return FALSE;
2202     }
2203 
2204     trace_postcopy_page_req_sync(host_addr);
2205 
2206     return FALSE;
2207 }
2208 
2209 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2210 {
2211     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2212         g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2213     }
2214 }
2215 
2216 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2217 {
2218     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2219         error_report("%s: illegal resume received", __func__);
2220         /* Don't fail the load, only for this. */
2221         return 0;
2222     }
2223 
2224     /*
2225      * Reset the last_rb before we resend any page req to source again, since
2226      * the source should have it reset already.
2227      */
2228     mis->last_rb = NULL;
2229 
2230     /*
2231      * This means source VM is ready to resume the postcopy migration.
2232      */
2233     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2234                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2235 
2236     trace_loadvm_postcopy_handle_resume();
2237 
2238     /* Tell source that "we are ready" */
2239     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2240 
2241     /*
2242      * After a postcopy recovery, the source should have lost the postcopy
2243      * queue, or potentially the requested pages could have been lost during
2244      * the network down phase.  Let's re-sync with the source VM by re-sending
2245      * all the pending pages that we eagerly need, so these threads won't get
2246      * blocked too long due to the recovery.
2247      *
2248      * Without this procedure, the faulted destination VM threads (waiting for
2249      * page requests right before the postcopy is interrupted) can keep hanging
2250      * until the pages are sent by the source during the background copying of
2251      * pages, or another thread faulted on the same address accidentally.
2252      */
2253     migrate_send_rp_req_pages_pending(mis);
2254 
2255     /*
2256      * It's time to switch state and release the fault thread to continue
2257      * service page faults.  Note that this should be explicitly after the
2258      * above call to migrate_send_rp_req_pages_pending().  In short:
2259      * migrate_send_rp_message_req_pages() is not thread safe, yet.
2260      */
2261     qemu_sem_post(&mis->postcopy_pause_sem_fault);
2262 
2263     if (migrate_postcopy_preempt()) {
2264         /*
2265          * The preempt channel will be created in async manner, now let's
2266          * wait for it and make sure it's created.
2267          */
2268         qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2269         assert(mis->postcopy_qemufile_dst);
2270         /* Kick the fast ram load thread too */
2271         qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2272     }
2273 
2274     return 0;
2275 }
2276 
2277 /**
2278  * Immediately following this command is a blob of data containing an embedded
2279  * chunk of migration stream; read it and load it.
2280  *
2281  * @mis: Incoming state
2282  * @length: Length of packaged data to read
2283  *
2284  * Returns: Negative values on error
2285  *
2286  */
2287 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2288 {
2289     int ret;
2290     size_t length;
2291     QIOChannelBuffer *bioc;
2292 
2293     length = qemu_get_be32(mis->from_src_file);
2294     trace_loadvm_handle_cmd_packaged(length);
2295 
2296     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2297         error_report("Unreasonably large packaged state: %zu", length);
2298         return -1;
2299     }
2300 
2301     bioc = qio_channel_buffer_new(length);
2302     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2303     ret = qemu_get_buffer(mis->from_src_file,
2304                           bioc->data,
2305                           length);
2306     if (ret != length) {
2307         object_unref(OBJECT(bioc));
2308         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2309                      ret, length);
2310         return (ret < 0) ? ret : -EAGAIN;
2311     }
2312     bioc->usage += length;
2313     trace_loadvm_handle_cmd_packaged_received(ret);
2314 
2315     QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2316 
2317     /*
2318      * Before loading the guest states, ensure that the preempt channel has
2319      * been ready to use, as some of the states (e.g. via virtio_load) might
2320      * trigger page faults that will be handled through the preempt channel.
2321      * So yield to the main thread in the case that the channel create event
2322      * hasn't been dispatched.
2323      *
2324      * TODO: if we can move migration loadvm out of main thread, then we
2325      * won't block main thread from polling the accept() fds.  We can drop
2326      * this as a whole when that is done.
2327      */
2328     do {
2329         if (!migrate_postcopy_preempt() || !qemu_in_coroutine() ||
2330             mis->postcopy_qemufile_dst) {
2331             break;
2332         }
2333 
2334         aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
2335         qemu_coroutine_yield();
2336     } while (1);
2337 
2338     ret = qemu_loadvm_state_main(packf, mis);
2339     trace_loadvm_handle_cmd_packaged_main(ret);
2340     qemu_fclose(packf);
2341     object_unref(OBJECT(bioc));
2342 
2343     return ret;
2344 }
2345 
2346 /*
2347  * Handle request that source requests for recved_bitmap on
2348  * destination. Payload format:
2349  *
2350  * len (1 byte) + ramblock_name (<255 bytes)
2351  */
2352 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2353                                      uint16_t len)
2354 {
2355     QEMUFile *file = mis->from_src_file;
2356     RAMBlock *rb;
2357     char block_name[256];
2358     size_t cnt;
2359 
2360     cnt = qemu_get_counted_string(file, block_name);
2361     if (!cnt) {
2362         error_report("%s: failed to read block name", __func__);
2363         return -EINVAL;
2364     }
2365 
2366     /* Validate before using the data */
2367     if (qemu_file_get_error(file)) {
2368         return qemu_file_get_error(file);
2369     }
2370 
2371     if (len != cnt + 1) {
2372         error_report("%s: invalid payload length (%d)", __func__, len);
2373         return -EINVAL;
2374     }
2375 
2376     rb = qemu_ram_block_by_name(block_name);
2377     if (!rb) {
2378         error_report("%s: block '%s' not found", __func__, block_name);
2379         return -EINVAL;
2380     }
2381 
2382     migrate_send_rp_recv_bitmap(mis, block_name);
2383 
2384     trace_loadvm_handle_recv_bitmap(block_name);
2385 
2386     return 0;
2387 }
2388 
2389 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2390 {
2391     int ret = migration_incoming_enable_colo();
2392 
2393     if (!ret) {
2394         ret = colo_init_ram_cache();
2395         if (ret) {
2396             migration_incoming_disable_colo();
2397         }
2398     }
2399     return ret;
2400 }
2401 
2402 static int loadvm_postcopy_handle_switchover_start(void)
2403 {
2404     SaveStateEntry *se;
2405 
2406     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2407         int ret;
2408 
2409         if (!se->ops || !se->ops->switchover_start) {
2410             continue;
2411         }
2412 
2413         ret = se->ops->switchover_start(se->opaque);
2414         if (ret < 0) {
2415             return ret;
2416         }
2417     }
2418 
2419     return 0;
2420 }
2421 
2422 /*
2423  * Process an incoming 'QEMU_VM_COMMAND'
2424  * 0           just a normal return
2425  * LOADVM_QUIT All good, but exit the loop
2426  * <0          Error
2427  */
2428 static int loadvm_process_command(QEMUFile *f)
2429 {
2430     MigrationIncomingState *mis = migration_incoming_get_current();
2431     uint16_t cmd;
2432     uint16_t len;
2433     uint32_t tmp32;
2434 
2435     cmd = qemu_get_be16(f);
2436     len = qemu_get_be16(f);
2437 
2438     /* Check validity before continue processing of cmds */
2439     if (qemu_file_get_error(f)) {
2440         return qemu_file_get_error(f);
2441     }
2442 
2443     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2444         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2445         return -EINVAL;
2446     }
2447 
2448     trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2449 
2450     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2451         error_report("%s received with bad length - expecting %zu, got %d",
2452                      mig_cmd_args[cmd].name,
2453                      (size_t)mig_cmd_args[cmd].len, len);
2454         return -ERANGE;
2455     }
2456 
2457     switch (cmd) {
2458     case MIG_CMD_OPEN_RETURN_PATH:
2459         if (mis->to_src_file) {
2460             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2461             /* Not really a problem, so don't give up */
2462             return 0;
2463         }
2464         mis->to_src_file = qemu_file_get_return_path(f);
2465         if (!mis->to_src_file) {
2466             error_report("CMD_OPEN_RETURN_PATH failed");
2467             return -1;
2468         }
2469 
2470         /*
2471          * Switchover ack is enabled but no device uses it, so send an ACK to
2472          * source that it's OK to switchover. Do it here, after return path has
2473          * been created.
2474          */
2475         if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2476             int ret = migrate_send_rp_switchover_ack(mis);
2477             if (ret) {
2478                 error_report(
2479                     "Could not send switchover ack RP MSG, err %d (%s)", ret,
2480                     strerror(-ret));
2481                 return ret;
2482             }
2483         }
2484         break;
2485 
2486     case MIG_CMD_PING:
2487         tmp32 = qemu_get_be32(f);
2488         trace_loadvm_process_command_ping(tmp32);
2489         if (!mis->to_src_file) {
2490             error_report("CMD_PING (0x%x) received with no return path",
2491                          tmp32);
2492             return -1;
2493         }
2494         migrate_send_rp_pong(mis, tmp32);
2495         break;
2496 
2497     case MIG_CMD_PACKAGED:
2498         return loadvm_handle_cmd_packaged(mis);
2499 
2500     case MIG_CMD_POSTCOPY_ADVISE:
2501         return loadvm_postcopy_handle_advise(mis, len);
2502 
2503     case MIG_CMD_POSTCOPY_LISTEN:
2504         return loadvm_postcopy_handle_listen(mis);
2505 
2506     case MIG_CMD_POSTCOPY_RUN:
2507         return loadvm_postcopy_handle_run(mis);
2508 
2509     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2510         return loadvm_postcopy_ram_handle_discard(mis, len);
2511 
2512     case MIG_CMD_POSTCOPY_RESUME:
2513         return loadvm_postcopy_handle_resume(mis);
2514 
2515     case MIG_CMD_RECV_BITMAP:
2516         return loadvm_handle_recv_bitmap(mis, len);
2517 
2518     case MIG_CMD_ENABLE_COLO:
2519         return loadvm_process_enable_colo(mis);
2520 
2521     case MIG_CMD_SWITCHOVER_START:
2522         return loadvm_postcopy_handle_switchover_start();
2523     }
2524 
2525     return 0;
2526 }
2527 
2528 /*
2529  * Read a footer off the wire and check that it matches the expected section
2530  *
2531  * Returns: true if the footer was good
2532  *          false if there is a problem (and calls error_report to say why)
2533  */
2534 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2535 {
2536     int ret;
2537     uint8_t read_mark;
2538     uint32_t read_section_id;
2539 
2540     if (!migrate_get_current()->send_section_footer) {
2541         /* No footer to check */
2542         return true;
2543     }
2544 
2545     read_mark = qemu_get_byte(f);
2546 
2547     ret = qemu_file_get_error(f);
2548     if (ret) {
2549         error_report("%s: Read section footer failed: %d",
2550                      __func__, ret);
2551         return false;
2552     }
2553 
2554     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2555         error_report("Missing section footer for %s", se->idstr);
2556         return false;
2557     }
2558 
2559     read_section_id = qemu_get_be32(f);
2560     if (read_section_id != se->load_section_id) {
2561         error_report("Mismatched section id in footer for %s -"
2562                      " read 0x%x expected 0x%x",
2563                      se->idstr, read_section_id, se->load_section_id);
2564         return false;
2565     }
2566 
2567     /* All good */
2568     return true;
2569 }
2570 
2571 static int
2572 qemu_loadvm_section_start_full(QEMUFile *f, uint8_t type)
2573 {
2574     bool trace_downtime = (type == QEMU_VM_SECTION_FULL);
2575     uint32_t instance_id, version_id, section_id;
2576     int64_t start_ts, end_ts;
2577     SaveStateEntry *se;
2578     char idstr[256];
2579     int ret;
2580 
2581     /* Read section start */
2582     section_id = qemu_get_be32(f);
2583     if (!qemu_get_counted_string(f, idstr)) {
2584         error_report("Unable to read ID string for section %u",
2585                      section_id);
2586         return -EINVAL;
2587     }
2588     instance_id = qemu_get_be32(f);
2589     version_id = qemu_get_be32(f);
2590 
2591     ret = qemu_file_get_error(f);
2592     if (ret) {
2593         error_report("%s: Failed to read instance/version ID: %d",
2594                      __func__, ret);
2595         return ret;
2596     }
2597 
2598     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2599             instance_id, version_id);
2600     /* Find savevm section */
2601     se = find_se(idstr, instance_id);
2602     if (se == NULL) {
2603         error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2604                      "Make sure that your current VM setup matches your "
2605                      "saved VM setup, including any hotplugged devices",
2606                      idstr, instance_id);
2607         return -EINVAL;
2608     }
2609 
2610     /* Validate version */
2611     if (version_id > se->version_id) {
2612         error_report("savevm: unsupported version %d for '%s' v%d",
2613                      version_id, idstr, se->version_id);
2614         return -EINVAL;
2615     }
2616     se->load_version_id = version_id;
2617     se->load_section_id = section_id;
2618 
2619     /* Validate if it is a device's state */
2620     if (xen_enabled() && se->is_ram) {
2621         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2622         return -EINVAL;
2623     }
2624 
2625     if (trace_downtime) {
2626         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2627     }
2628 
2629     ret = vmstate_load(f, se);
2630     if (ret < 0) {
2631         error_report("error while loading state for instance 0x%"PRIx32" of"
2632                      " device '%s'", instance_id, idstr);
2633         return ret;
2634     }
2635 
2636     if (trace_downtime) {
2637         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2638         trace_vmstate_downtime_load("non-iterable", se->idstr,
2639                                     se->instance_id, end_ts - start_ts);
2640     }
2641 
2642     if (!check_section_footer(f, se)) {
2643         return -EINVAL;
2644     }
2645 
2646     return 0;
2647 }
2648 
2649 static int
2650 qemu_loadvm_section_part_end(QEMUFile *f, uint8_t type)
2651 {
2652     bool trace_downtime = (type == QEMU_VM_SECTION_END);
2653     int64_t start_ts, end_ts;
2654     uint32_t section_id;
2655     SaveStateEntry *se;
2656     int ret;
2657 
2658     section_id = qemu_get_be32(f);
2659 
2660     ret = qemu_file_get_error(f);
2661     if (ret) {
2662         error_report("%s: Failed to read section ID: %d",
2663                      __func__, ret);
2664         return ret;
2665     }
2666 
2667     trace_qemu_loadvm_state_section_partend(section_id);
2668     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2669         if (se->load_section_id == section_id) {
2670             break;
2671         }
2672     }
2673     if (se == NULL) {
2674         error_report("Unknown savevm section %d", section_id);
2675         return -EINVAL;
2676     }
2677 
2678     if (trace_downtime) {
2679         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2680     }
2681 
2682     ret = vmstate_load(f, se);
2683     if (ret < 0) {
2684         error_report("error while loading state section id %d(%s)",
2685                      section_id, se->idstr);
2686         return ret;
2687     }
2688 
2689     if (trace_downtime) {
2690         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2691         trace_vmstate_downtime_load("iterable", se->idstr,
2692                                     se->instance_id, end_ts - start_ts);
2693     }
2694 
2695     if (!check_section_footer(f, se)) {
2696         return -EINVAL;
2697     }
2698 
2699     return 0;
2700 }
2701 
2702 static int qemu_loadvm_state_header(QEMUFile *f)
2703 {
2704     unsigned int v;
2705     int ret;
2706 
2707     v = qemu_get_be32(f);
2708     if (v != QEMU_VM_FILE_MAGIC) {
2709         error_report("Not a migration stream");
2710         return -EINVAL;
2711     }
2712 
2713     v = qemu_get_be32(f);
2714     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2715         error_report("SaveVM v2 format is obsolete and don't work anymore");
2716         return -ENOTSUP;
2717     }
2718     if (v != QEMU_VM_FILE_VERSION) {
2719         error_report("Unsupported migration stream version");
2720         return -ENOTSUP;
2721     }
2722 
2723     if (migrate_get_current()->send_configuration) {
2724         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2725             error_report("Configuration section missing");
2726             return -EINVAL;
2727         }
2728         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2729 
2730         if (ret) {
2731             return ret;
2732         }
2733     }
2734     return 0;
2735 }
2736 
2737 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2738 {
2739     SaveStateEntry *se;
2740 
2741     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2742         if (!se->ops || !se->ops->switchover_ack_needed) {
2743             continue;
2744         }
2745 
2746         if (se->ops->switchover_ack_needed(se->opaque)) {
2747             mis->switchover_ack_pending_num++;
2748         }
2749     }
2750 
2751     trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2752 }
2753 
2754 static int qemu_loadvm_state_setup(QEMUFile *f, Error **errp)
2755 {
2756     ERRP_GUARD();
2757     SaveStateEntry *se;
2758     int ret;
2759 
2760     trace_loadvm_state_setup();
2761     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2762         if (!se->ops || !se->ops->load_setup) {
2763             continue;
2764         }
2765         if (se->ops->is_active) {
2766             if (!se->ops->is_active(se->opaque)) {
2767                 continue;
2768             }
2769         }
2770 
2771         ret = se->ops->load_setup(f, se->opaque, errp);
2772         if (ret < 0) {
2773             error_prepend(errp, "Load state of device %s failed: ",
2774                           se->idstr);
2775             qemu_file_set_error(f, ret);
2776             return ret;
2777         }
2778     }
2779     return 0;
2780 }
2781 
2782 void qemu_loadvm_state_cleanup(void)
2783 {
2784     SaveStateEntry *se;
2785 
2786     trace_loadvm_state_cleanup();
2787     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2788         if (se->ops && se->ops->load_cleanup) {
2789             se->ops->load_cleanup(se->opaque);
2790         }
2791     }
2792 }
2793 
2794 /* Return true if we should continue the migration, or false. */
2795 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2796 {
2797     int i;
2798 
2799     trace_postcopy_pause_incoming();
2800 
2801     assert(migrate_postcopy_ram());
2802 
2803     /*
2804      * Unregister yank with either from/to src would work, since ioc behind it
2805      * is the same
2806      */
2807     migration_ioc_unregister_yank_from_file(mis->from_src_file);
2808 
2809     assert(mis->from_src_file);
2810     qemu_file_shutdown(mis->from_src_file);
2811     qemu_fclose(mis->from_src_file);
2812     mis->from_src_file = NULL;
2813 
2814     assert(mis->to_src_file);
2815     qemu_file_shutdown(mis->to_src_file);
2816     qemu_mutex_lock(&mis->rp_mutex);
2817     qemu_fclose(mis->to_src_file);
2818     mis->to_src_file = NULL;
2819     qemu_mutex_unlock(&mis->rp_mutex);
2820 
2821     /*
2822      * NOTE: this must happen before reset the PostcopyTmpPages below,
2823      * otherwise it's racy to reset those fields when the fast load thread
2824      * can be accessing it in parallel.
2825      */
2826     if (mis->postcopy_qemufile_dst) {
2827         qemu_file_shutdown(mis->postcopy_qemufile_dst);
2828         /* Take the mutex to make sure the fast ram load thread halted */
2829         qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2830         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2831         qemu_fclose(mis->postcopy_qemufile_dst);
2832         mis->postcopy_qemufile_dst = NULL;
2833         qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2834     }
2835 
2836     /* Current state can be either ACTIVE or RECOVER */
2837     migrate_set_state(&mis->state, mis->state,
2838                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2839 
2840     /* Notify the fault thread for the invalidated file handle */
2841     postcopy_fault_thread_notify(mis);
2842 
2843     /*
2844      * If network is interrupted, any temp page we received will be useless
2845      * because we didn't mark them as "received" in receivedmap.  After a
2846      * proper recovery later (which will sync src dirty bitmap with receivedmap
2847      * on dest) these cached small pages will be resent again.
2848      */
2849     for (i = 0; i < mis->postcopy_channels; i++) {
2850         postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2851     }
2852 
2853     error_report("Detected IO failure for postcopy. "
2854                  "Migration paused.");
2855 
2856     do {
2857         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2858     } while (postcopy_is_paused(mis->state));
2859 
2860     trace_postcopy_pause_incoming_continued();
2861 
2862     return true;
2863 }
2864 
2865 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2866 {
2867     uint8_t section_type;
2868     int ret = 0;
2869 
2870 retry:
2871     while (true) {
2872         section_type = qemu_get_byte(f);
2873 
2874         ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2875         if (ret) {
2876             break;
2877         }
2878 
2879         trace_qemu_loadvm_state_section(section_type);
2880         switch (section_type) {
2881         case QEMU_VM_SECTION_START:
2882         case QEMU_VM_SECTION_FULL:
2883             ret = qemu_loadvm_section_start_full(f, section_type);
2884             if (ret < 0) {
2885                 goto out;
2886             }
2887             break;
2888         case QEMU_VM_SECTION_PART:
2889         case QEMU_VM_SECTION_END:
2890             ret = qemu_loadvm_section_part_end(f, section_type);
2891             if (ret < 0) {
2892                 goto out;
2893             }
2894             break;
2895         case QEMU_VM_COMMAND:
2896             ret = loadvm_process_command(f);
2897             trace_qemu_loadvm_state_section_command(ret);
2898             if ((ret < 0) || (ret == LOADVM_QUIT)) {
2899                 goto out;
2900             }
2901             break;
2902         case QEMU_VM_EOF:
2903             /* This is the end of migration */
2904             goto out;
2905         default:
2906             error_report("Unknown savevm section type %d", section_type);
2907             ret = -EINVAL;
2908             goto out;
2909         }
2910     }
2911 
2912 out:
2913     if (ret < 0) {
2914         qemu_file_set_error(f, ret);
2915 
2916         /* Cancel bitmaps incoming regardless of recovery */
2917         dirty_bitmap_mig_cancel_incoming();
2918 
2919         /*
2920          * If we are during an active postcopy, then we pause instead
2921          * of bail out to at least keep the VM's dirty data.  Note
2922          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2923          * during which we're still receiving device states and we
2924          * still haven't yet started the VM on destination.
2925          *
2926          * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2927          * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2928          * recovering.
2929          */
2930         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2931             migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2932             /* Reset f to point to the newly created channel */
2933             f = mis->from_src_file;
2934             goto retry;
2935         }
2936     }
2937     return ret;
2938 }
2939 
2940 int qemu_loadvm_state(QEMUFile *f)
2941 {
2942     MigrationIncomingState *mis = migration_incoming_get_current();
2943     Error *local_err = NULL;
2944     int ret;
2945 
2946     if (qemu_savevm_state_blocked(&local_err)) {
2947         error_report_err(local_err);
2948         return -EINVAL;
2949     }
2950 
2951     ret = qemu_loadvm_state_header(f);
2952     if (ret) {
2953         return ret;
2954     }
2955 
2956     if (qemu_loadvm_state_setup(f, &local_err) != 0) {
2957         error_report_err(local_err);
2958         return -EINVAL;
2959     }
2960 
2961     if (migrate_switchover_ack()) {
2962         qemu_loadvm_state_switchover_ack_needed(mis);
2963     }
2964 
2965     cpu_synchronize_all_pre_loadvm();
2966 
2967     ret = qemu_loadvm_state_main(f, mis);
2968     qemu_event_set(&mis->main_thread_load_event);
2969 
2970     trace_qemu_loadvm_state_post_main(ret);
2971 
2972     if (mis->have_listen_thread) {
2973         /*
2974          * Postcopy listen thread still going, don't synchronize the
2975          * cpus yet.
2976          */
2977         return ret;
2978     }
2979 
2980     /* When reaching here, it must be precopy */
2981     if (ret == 0) {
2982         if (migrate_has_error(migrate_get_current())) {
2983             ret = -EINVAL;
2984         } else {
2985             ret = qemu_file_get_error(f);
2986         }
2987     }
2988 
2989     /*
2990      * Try to read in the VMDESC section as well, so that dumping tools that
2991      * intercept our migration stream have the chance to see it.
2992      */
2993 
2994     /* We've got to be careful; if we don't read the data and just shut the fd
2995      * then the sender can error if we close while it's still sending.
2996      * We also mustn't read data that isn't there; some transports (RDMA)
2997      * will stall waiting for that data when the source has already closed.
2998      */
2999     if (ret == 0 && should_send_vmdesc()) {
3000         uint8_t *buf;
3001         uint32_t size;
3002         uint8_t  section_type = qemu_get_byte(f);
3003 
3004         if (section_type != QEMU_VM_VMDESCRIPTION) {
3005             error_report("Expected vmdescription section, but got %d",
3006                          section_type);
3007             /*
3008              * It doesn't seem worth failing at this point since
3009              * we apparently have an otherwise valid VM state
3010              */
3011         } else {
3012             buf = g_malloc(0x1000);
3013             size = qemu_get_be32(f);
3014 
3015             while (size > 0) {
3016                 uint32_t read_chunk = MIN(size, 0x1000);
3017                 qemu_get_buffer(f, buf, read_chunk);
3018                 size -= read_chunk;
3019             }
3020             g_free(buf);
3021         }
3022     }
3023 
3024     cpu_synchronize_all_post_init();
3025 
3026     return ret;
3027 }
3028 
3029 int qemu_load_device_state(QEMUFile *f)
3030 {
3031     MigrationIncomingState *mis = migration_incoming_get_current();
3032     int ret;
3033 
3034     /* Load QEMU_VM_SECTION_FULL section */
3035     ret = qemu_loadvm_state_main(f, mis);
3036     if (ret < 0) {
3037         error_report("Failed to load device state: %d", ret);
3038         return ret;
3039     }
3040 
3041     cpu_synchronize_all_post_init();
3042     return 0;
3043 }
3044 
3045 int qemu_loadvm_approve_switchover(void)
3046 {
3047     MigrationIncomingState *mis = migration_incoming_get_current();
3048 
3049     if (!mis->switchover_ack_pending_num) {
3050         return -EINVAL;
3051     }
3052 
3053     mis->switchover_ack_pending_num--;
3054     trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
3055 
3056     if (mis->switchover_ack_pending_num) {
3057         return 0;
3058     }
3059 
3060     return migrate_send_rp_switchover_ack(mis);
3061 }
3062 
3063 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
3064                   bool has_devices, strList *devices, Error **errp)
3065 {
3066     BlockDriverState *bs;
3067     QEMUSnapshotInfo sn1, *sn = &sn1;
3068     int ret = -1, ret2;
3069     QEMUFile *f;
3070     RunState saved_state = runstate_get();
3071     uint64_t vm_state_size;
3072     g_autoptr(GDateTime) now = g_date_time_new_now_local();
3073 
3074     GLOBAL_STATE_CODE();
3075 
3076     if (migration_is_blocked(errp)) {
3077         return false;
3078     }
3079 
3080     if (!replay_can_snapshot()) {
3081         error_setg(errp, "Record/replay does not allow making snapshot "
3082                    "right now. Try once more later.");
3083         return false;
3084     }
3085 
3086     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3087         return false;
3088     }
3089 
3090     /* Delete old snapshots of the same name */
3091     if (name) {
3092         if (overwrite) {
3093             if (bdrv_all_delete_snapshot(name, has_devices,
3094                                          devices, errp) < 0) {
3095                 return false;
3096             }
3097         } else {
3098             ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3099             if (ret2 < 0) {
3100                 return false;
3101             }
3102             if (ret2 == 1) {
3103                 error_setg(errp,
3104                            "Snapshot '%s' already exists in one or more devices",
3105                            name);
3106                 return false;
3107             }
3108         }
3109     }
3110 
3111     bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3112     if (bs == NULL) {
3113         return false;
3114     }
3115 
3116     global_state_store();
3117     vm_stop(RUN_STATE_SAVE_VM);
3118 
3119     bdrv_drain_all_begin();
3120 
3121     memset(sn, 0, sizeof(*sn));
3122 
3123     /* fill auxiliary fields */
3124     sn->date_sec = g_date_time_to_unix(now);
3125     sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3126     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3127     if (replay_mode != REPLAY_MODE_NONE) {
3128         sn->icount = replay_get_current_icount();
3129     } else {
3130         sn->icount = -1ULL;
3131     }
3132 
3133     if (name) {
3134         pstrcpy(sn->name, sizeof(sn->name), name);
3135     } else {
3136         g_autofree char *autoname = g_date_time_format(now,  "vm-%Y%m%d%H%M%S");
3137         pstrcpy(sn->name, sizeof(sn->name), autoname);
3138     }
3139 
3140     /* save the VM state */
3141     f = qemu_fopen_bdrv(bs, 1);
3142     if (!f) {
3143         error_setg(errp, "Could not open VM state file");
3144         goto the_end;
3145     }
3146     ret = qemu_savevm_state(f, errp);
3147     vm_state_size = qemu_file_transferred(f);
3148     ret2 = qemu_fclose(f);
3149     if (ret < 0) {
3150         goto the_end;
3151     }
3152     if (ret2 < 0) {
3153         ret = ret2;
3154         goto the_end;
3155     }
3156 
3157     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3158                                    has_devices, devices, errp);
3159     if (ret < 0) {
3160         bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3161         goto the_end;
3162     }
3163 
3164     ret = 0;
3165 
3166  the_end:
3167     bdrv_drain_all_end();
3168 
3169     vm_resume(saved_state);
3170     return ret == 0;
3171 }
3172 
3173 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3174                                 Error **errp)
3175 {
3176     QEMUFile *f;
3177     QIOChannelFile *ioc;
3178     int saved_vm_running;
3179     int ret;
3180 
3181     if (!has_live) {
3182         /* live default to true so old version of Xen tool stack can have a
3183          * successful live migration */
3184         live = true;
3185     }
3186 
3187     saved_vm_running = runstate_is_running();
3188     vm_stop(RUN_STATE_SAVE_VM);
3189     global_state_store_running();
3190 
3191     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3192                                     0660, errp);
3193     if (!ioc) {
3194         goto the_end;
3195     }
3196     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3197     f = qemu_file_new_output(QIO_CHANNEL(ioc));
3198     object_unref(OBJECT(ioc));
3199     ret = qemu_save_device_state(f);
3200     if (ret < 0 || qemu_fclose(f) < 0) {
3201         error_setg(errp, "saving Xen device state failed");
3202     } else {
3203         /* libxl calls the QMP command "stop" before calling
3204          * "xen-save-devices-state" and in case of migration failure, libxl
3205          * would call "cont".
3206          * So call bdrv_inactivate_all (release locks) here to let the other
3207          * side of the migration take control of the images.
3208          */
3209         if (live && !saved_vm_running) {
3210             migration_block_inactivate();
3211         }
3212     }
3213 
3214  the_end:
3215     if (saved_vm_running) {
3216         vm_start();
3217     }
3218 }
3219 
3220 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3221 {
3222     QEMUFile *f;
3223     QIOChannelFile *ioc;
3224     int ret;
3225 
3226     /* Guest must be paused before loading the device state; the RAM state
3227      * will already have been loaded by xc
3228      */
3229     if (runstate_is_running()) {
3230         error_setg(errp, "Cannot update device state while vm is running");
3231         return;
3232     }
3233     vm_stop(RUN_STATE_RESTORE_VM);
3234 
3235     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3236     if (!ioc) {
3237         return;
3238     }
3239     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3240     f = qemu_file_new_input(QIO_CHANNEL(ioc));
3241     object_unref(OBJECT(ioc));
3242 
3243     ret = qemu_loadvm_state(f);
3244     qemu_fclose(f);
3245     if (ret < 0) {
3246         error_setg(errp, "loading Xen device state failed");
3247     }
3248     migration_incoming_state_destroy();
3249 }
3250 
3251 bool load_snapshot(const char *name, const char *vmstate,
3252                    bool has_devices, strList *devices, Error **errp)
3253 {
3254     BlockDriverState *bs_vm_state;
3255     QEMUSnapshotInfo sn;
3256     QEMUFile *f;
3257     int ret;
3258     MigrationIncomingState *mis = migration_incoming_get_current();
3259 
3260     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3261         return false;
3262     }
3263     ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3264     if (ret < 0) {
3265         return false;
3266     }
3267     if (ret == 0) {
3268         error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3269                    name);
3270         return false;
3271     }
3272 
3273     bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3274     if (!bs_vm_state) {
3275         return false;
3276     }
3277 
3278     /* Don't even try to load empty VM states */
3279     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3280     if (ret < 0) {
3281         error_setg(errp, "Snapshot can not be found");
3282         return false;
3283     } else if (sn.vm_state_size == 0) {
3284         error_setg(errp, "This is a disk-only snapshot. Revert to it "
3285                    " offline using qemu-img");
3286         return false;
3287     }
3288 
3289     /*
3290      * Flush the record/replay queue. Now the VM state is going
3291      * to change. Therefore we don't need to preserve its consistency
3292      */
3293     replay_flush_events();
3294 
3295     /* Flush all IO requests so they don't interfere with the new state.  */
3296     bdrv_drain_all_begin();
3297 
3298     ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3299     if (ret < 0) {
3300         goto err_drain;
3301     }
3302 
3303     /* restore the VM state */
3304     f = qemu_fopen_bdrv(bs_vm_state, 0);
3305     if (!f) {
3306         error_setg(errp, "Could not open VM state file");
3307         goto err_drain;
3308     }
3309 
3310     qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3311     mis->from_src_file = f;
3312 
3313     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3314         ret = -EINVAL;
3315         goto err_drain;
3316     }
3317     ret = qemu_loadvm_state(f);
3318     migration_incoming_state_destroy();
3319 
3320     bdrv_drain_all_end();
3321 
3322     if (ret < 0) {
3323         error_setg(errp, "Error %d while loading VM state", ret);
3324         return false;
3325     }
3326 
3327     return true;
3328 
3329 err_drain:
3330     bdrv_drain_all_end();
3331     return false;
3332 }
3333 
3334 void load_snapshot_resume(RunState state)
3335 {
3336     vm_resume(state);
3337     if (state == RUN_STATE_RUNNING && runstate_get() == RUN_STATE_SUSPENDED) {
3338         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, &error_abort);
3339     }
3340 }
3341 
3342 bool delete_snapshot(const char *name, bool has_devices,
3343                      strList *devices, Error **errp)
3344 {
3345     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3346         return false;
3347     }
3348 
3349     if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3350         return false;
3351     }
3352 
3353     return true;
3354 }
3355 
3356 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3357 {
3358     qemu_ram_set_idstr(mr->ram_block,
3359                        memory_region_name(mr), dev);
3360     qemu_ram_set_migratable(mr->ram_block);
3361 }
3362 
3363 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3364 {
3365     qemu_ram_unset_idstr(mr->ram_block);
3366     qemu_ram_unset_migratable(mr->ram_block);
3367 }
3368 
3369 void vmstate_register_ram_global(MemoryRegion *mr)
3370 {
3371     vmstate_register_ram(mr, NULL);
3372 }
3373 
3374 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3375 {
3376     /* check needed if --only-migratable is specified */
3377     if (!only_migratable) {
3378         return true;
3379     }
3380 
3381     return !(vmsd && vmsd->unmigratable);
3382 }
3383 
3384 typedef struct SnapshotJob {
3385     Job common;
3386     char *tag;
3387     char *vmstate;
3388     strList *devices;
3389     Coroutine *co;
3390     Error **errp;
3391     bool ret;
3392 } SnapshotJob;
3393 
3394 static void qmp_snapshot_job_free(SnapshotJob *s)
3395 {
3396     g_free(s->tag);
3397     g_free(s->vmstate);
3398     qapi_free_strList(s->devices);
3399 }
3400 
3401 
3402 static void snapshot_load_job_bh(void *opaque)
3403 {
3404     Job *job = opaque;
3405     SnapshotJob *s = container_of(job, SnapshotJob, common);
3406     RunState orig_state = runstate_get();
3407 
3408     job_progress_set_remaining(&s->common, 1);
3409 
3410     vm_stop(RUN_STATE_RESTORE_VM);
3411 
3412     s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3413     if (s->ret) {
3414         load_snapshot_resume(orig_state);
3415     }
3416 
3417     job_progress_update(&s->common, 1);
3418 
3419     qmp_snapshot_job_free(s);
3420     aio_co_wake(s->co);
3421 }
3422 
3423 static void snapshot_save_job_bh(void *opaque)
3424 {
3425     Job *job = opaque;
3426     SnapshotJob *s = container_of(job, SnapshotJob, common);
3427 
3428     job_progress_set_remaining(&s->common, 1);
3429     s->ret = save_snapshot(s->tag, false, s->vmstate,
3430                            true, s->devices, s->errp);
3431     job_progress_update(&s->common, 1);
3432 
3433     qmp_snapshot_job_free(s);
3434     aio_co_wake(s->co);
3435 }
3436 
3437 static void snapshot_delete_job_bh(void *opaque)
3438 {
3439     Job *job = opaque;
3440     SnapshotJob *s = container_of(job, SnapshotJob, common);
3441 
3442     job_progress_set_remaining(&s->common, 1);
3443     s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3444     job_progress_update(&s->common, 1);
3445 
3446     qmp_snapshot_job_free(s);
3447     aio_co_wake(s->co);
3448 }
3449 
3450 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3451 {
3452     SnapshotJob *s = container_of(job, SnapshotJob, common);
3453     s->errp = errp;
3454     s->co = qemu_coroutine_self();
3455     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3456                             snapshot_save_job_bh, job);
3457     qemu_coroutine_yield();
3458     return s->ret ? 0 : -1;
3459 }
3460 
3461 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3462 {
3463     SnapshotJob *s = container_of(job, SnapshotJob, common);
3464     s->errp = errp;
3465     s->co = qemu_coroutine_self();
3466     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3467                             snapshot_load_job_bh, job);
3468     qemu_coroutine_yield();
3469     return s->ret ? 0 : -1;
3470 }
3471 
3472 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3473 {
3474     SnapshotJob *s = container_of(job, SnapshotJob, common);
3475     s->errp = errp;
3476     s->co = qemu_coroutine_self();
3477     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3478                             snapshot_delete_job_bh, job);
3479     qemu_coroutine_yield();
3480     return s->ret ? 0 : -1;
3481 }
3482 
3483 
3484 static const JobDriver snapshot_load_job_driver = {
3485     .instance_size = sizeof(SnapshotJob),
3486     .job_type      = JOB_TYPE_SNAPSHOT_LOAD,
3487     .run           = snapshot_load_job_run,
3488 };
3489 
3490 static const JobDriver snapshot_save_job_driver = {
3491     .instance_size = sizeof(SnapshotJob),
3492     .job_type      = JOB_TYPE_SNAPSHOT_SAVE,
3493     .run           = snapshot_save_job_run,
3494 };
3495 
3496 static const JobDriver snapshot_delete_job_driver = {
3497     .instance_size = sizeof(SnapshotJob),
3498     .job_type      = JOB_TYPE_SNAPSHOT_DELETE,
3499     .run           = snapshot_delete_job_run,
3500 };
3501 
3502 
3503 void qmp_snapshot_save(const char *job_id,
3504                        const char *tag,
3505                        const char *vmstate,
3506                        strList *devices,
3507                        Error **errp)
3508 {
3509     SnapshotJob *s;
3510 
3511     s = job_create(job_id, &snapshot_save_job_driver, NULL,
3512                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3513                    NULL, NULL, errp);
3514     if (!s) {
3515         return;
3516     }
3517 
3518     s->tag = g_strdup(tag);
3519     s->vmstate = g_strdup(vmstate);
3520     s->devices = QAPI_CLONE(strList, devices);
3521 
3522     job_start(&s->common);
3523 }
3524 
3525 void qmp_snapshot_load(const char *job_id,
3526                        const char *tag,
3527                        const char *vmstate,
3528                        strList *devices,
3529                        Error **errp)
3530 {
3531     SnapshotJob *s;
3532 
3533     s = job_create(job_id, &snapshot_load_job_driver, NULL,
3534                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3535                    NULL, NULL, errp);
3536     if (!s) {
3537         return;
3538     }
3539 
3540     s->tag = g_strdup(tag);
3541     s->vmstate = g_strdup(vmstate);
3542     s->devices = QAPI_CLONE(strList, devices);
3543 
3544     job_start(&s->common);
3545 }
3546 
3547 void qmp_snapshot_delete(const char *job_id,
3548                          const char *tag,
3549                          strList *devices,
3550                          Error **errp)
3551 {
3552     SnapshotJob *s;
3553 
3554     s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3555                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3556                    NULL, NULL, errp);
3557     if (!s) {
3558         return;
3559     }
3560 
3561     s->tag = g_strdup(tag);
3562     s->devices = QAPI_CLONE(strList, devices);
3563 
3564     job_start(&s->common);
3565 }
3566