xref: /openbmc/qemu/migration/savevm.c (revision 18eb55546a54e443d94a4c49286348176ad4b00a)
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 
1990     /* TODO: sanity check that only postcopiable data will be loaded here */
1991     load_res = qemu_loadvm_state_main(f, mis);
1992 
1993     /*
1994      * This is tricky, but, mis->from_src_file can change after it
1995      * returns, when postcopy recovery happened. In the future, we may
1996      * want a wrapper for the QEMUFile handle.
1997      */
1998     f = mis->from_src_file;
1999 
2000     /* And non-blocking again so we don't block in any cleanup */
2001     qemu_file_set_blocking(f, false);
2002 
2003     trace_postcopy_ram_listen_thread_exit();
2004     if (load_res < 0) {
2005         qemu_file_set_error(f, load_res);
2006         dirty_bitmap_mig_cancel_incoming();
2007         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2008             !migrate_postcopy_ram() && migrate_dirty_bitmaps())
2009         {
2010             error_report("%s: loadvm failed during postcopy: %d. All states "
2011                          "are migrated except dirty bitmaps. Some dirty "
2012                          "bitmaps may be lost, and present migrated dirty "
2013                          "bitmaps are correctly migrated and valid.",
2014                          __func__, load_res);
2015             load_res = 0; /* prevent further exit() */
2016         } else {
2017             error_report("%s: loadvm failed: %d", __func__, load_res);
2018             migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2019                                            MIGRATION_STATUS_FAILED);
2020         }
2021     }
2022     if (load_res >= 0) {
2023         /*
2024          * This looks good, but it's possible that the device loading in the
2025          * main thread hasn't finished yet, and so we might not be in 'RUN'
2026          * state yet; wait for the end of the main thread.
2027          */
2028         qemu_event_wait(&mis->main_thread_load_event);
2029     }
2030     postcopy_ram_incoming_cleanup(mis);
2031 
2032     if (load_res < 0) {
2033         /*
2034          * If something went wrong then we have a bad state so exit;
2035          * depending how far we got it might be possible at this point
2036          * to leave the guest running and fire MCEs for pages that never
2037          * arrived as a desperate recovery step.
2038          */
2039         rcu_unregister_thread();
2040         exit(EXIT_FAILURE);
2041     }
2042 
2043     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2044                                    MIGRATION_STATUS_COMPLETED);
2045     /*
2046      * If everything has worked fine, then the main thread has waited
2047      * for us to start, and we're the last use of the mis.
2048      * (If something broke then qemu will have to exit anyway since it's
2049      * got a bad migration state).
2050      */
2051     bql_lock();
2052     migration_incoming_state_destroy();
2053     bql_unlock();
2054 
2055     rcu_unregister_thread();
2056     mis->have_listen_thread = false;
2057     postcopy_state_set(POSTCOPY_INCOMING_END);
2058 
2059     object_unref(OBJECT(migr));
2060 
2061     return NULL;
2062 }
2063 
2064 /* After this message we must be able to immediately receive postcopy data */
2065 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2066 {
2067     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2068     Error *local_err = NULL;
2069 
2070     trace_loadvm_postcopy_handle_listen("enter");
2071 
2072     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2073         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2074         return -1;
2075     }
2076     if (ps == POSTCOPY_INCOMING_ADVISE) {
2077         /*
2078          * A rare case, we entered listen without having to do any discards,
2079          * so do the setup that's normally done at the time of the 1st discard.
2080          */
2081         if (migrate_postcopy_ram()) {
2082             postcopy_ram_prepare_discard(mis);
2083         }
2084     }
2085 
2086     trace_loadvm_postcopy_handle_listen("after discard");
2087 
2088     /*
2089      * Sensitise RAM - can now generate requests for blocks that don't exist
2090      * However, at this point the CPU shouldn't be running, and the IO
2091      * shouldn't be doing anything yet so don't actually expect requests
2092      */
2093     if (migrate_postcopy_ram()) {
2094         if (postcopy_ram_incoming_setup(mis)) {
2095             postcopy_ram_incoming_cleanup(mis);
2096             return -1;
2097         }
2098     }
2099 
2100     trace_loadvm_postcopy_handle_listen("after uffd");
2101 
2102     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2103         error_report_err(local_err);
2104         return -1;
2105     }
2106 
2107     mis->have_listen_thread = true;
2108     postcopy_thread_create(mis, &mis->listen_thread,
2109                            MIGRATION_THREAD_DST_LISTEN,
2110                            postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2111     trace_loadvm_postcopy_handle_listen("return");
2112 
2113     return 0;
2114 }
2115 
2116 static void loadvm_postcopy_handle_run_bh(void *opaque)
2117 {
2118     MigrationIncomingState *mis = opaque;
2119 
2120     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-enter");
2121 
2122     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2123      * in migration.c
2124      */
2125     cpu_synchronize_all_post_init();
2126 
2127     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cpu-synced");
2128 
2129     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2130 
2131     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-announced");
2132 
2133     dirty_bitmap_mig_before_vm_start();
2134 
2135     if (autostart) {
2136         /*
2137          * Make sure all file formats throw away their mutable metadata.
2138          * If we get an error here, just don't restart the VM yet.
2139          */
2140         bool success = migration_block_activate(NULL);
2141 
2142         trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cache-invalidated");
2143 
2144         if (success) {
2145             vm_start();
2146         }
2147     } else {
2148         /* leave it paused and let management decide when to start the CPU */
2149         runstate_set(RUN_STATE_PAUSED);
2150     }
2151 
2152     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-vm-started");
2153 }
2154 
2155 /* After all discards we can start running and asking for pages */
2156 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2157 {
2158     PostcopyState ps = postcopy_state_get();
2159 
2160     trace_loadvm_postcopy_handle_run();
2161     if (ps != POSTCOPY_INCOMING_LISTENING) {
2162         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2163         return -1;
2164     }
2165 
2166     postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2167     migration_bh_schedule(loadvm_postcopy_handle_run_bh, mis);
2168 
2169     /* We need to finish reading the stream from the package
2170      * and also stop reading anything more from the stream that loaded the
2171      * package (since it's now being read by the listener thread).
2172      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2173      */
2174     return LOADVM_QUIT;
2175 }
2176 
2177 /* We must be with page_request_mutex held */
2178 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2179                                        gpointer data)
2180 {
2181     MigrationIncomingState *mis = data;
2182     void *host_addr = (void *) key;
2183     ram_addr_t rb_offset;
2184     RAMBlock *rb;
2185     int ret;
2186 
2187     rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2188     if (!rb) {
2189         /*
2190          * This should _never_ happen.  However be nice for a migrating VM to
2191          * not crash/assert.  Post an error (note: intended to not use *_once
2192          * because we do want to see all the illegal addresses; and this can
2193          * never be triggered by the guest so we're safe) and move on next.
2194          */
2195         error_report("%s: illegal host addr %p", __func__, host_addr);
2196         /* Try the next entry */
2197         return FALSE;
2198     }
2199 
2200     ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2201     if (ret) {
2202         /* Please refer to above comment. */
2203         error_report("%s: send rp message failed for addr %p",
2204                      __func__, host_addr);
2205         return FALSE;
2206     }
2207 
2208     trace_postcopy_page_req_sync(host_addr);
2209 
2210     return FALSE;
2211 }
2212 
2213 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2214 {
2215     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2216         g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2217     }
2218 }
2219 
2220 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2221 {
2222     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2223         error_report("%s: illegal resume received", __func__);
2224         /* Don't fail the load, only for this. */
2225         return 0;
2226     }
2227 
2228     /*
2229      * Reset the last_rb before we resend any page req to source again, since
2230      * the source should have it reset already.
2231      */
2232     mis->last_rb = NULL;
2233 
2234     /*
2235      * This means source VM is ready to resume the postcopy migration.
2236      */
2237     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2238                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2239 
2240     trace_loadvm_postcopy_handle_resume();
2241 
2242     /* Tell source that "we are ready" */
2243     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2244 
2245     /*
2246      * After a postcopy recovery, the source should have lost the postcopy
2247      * queue, or potentially the requested pages could have been lost during
2248      * the network down phase.  Let's re-sync with the source VM by re-sending
2249      * all the pending pages that we eagerly need, so these threads won't get
2250      * blocked too long due to the recovery.
2251      *
2252      * Without this procedure, the faulted destination VM threads (waiting for
2253      * page requests right before the postcopy is interrupted) can keep hanging
2254      * until the pages are sent by the source during the background copying of
2255      * pages, or another thread faulted on the same address accidentally.
2256      */
2257     migrate_send_rp_req_pages_pending(mis);
2258 
2259     /*
2260      * It's time to switch state and release the fault thread to continue
2261      * service page faults.  Note that this should be explicitly after the
2262      * above call to migrate_send_rp_req_pages_pending().  In short:
2263      * migrate_send_rp_message_req_pages() is not thread safe, yet.
2264      */
2265     qemu_sem_post(&mis->postcopy_pause_sem_fault);
2266 
2267     if (migrate_postcopy_preempt()) {
2268         /*
2269          * The preempt channel will be created in async manner, now let's
2270          * wait for it and make sure it's created.
2271          */
2272         qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2273         assert(mis->postcopy_qemufile_dst);
2274         /* Kick the fast ram load thread too */
2275         qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2276     }
2277 
2278     return 0;
2279 }
2280 
2281 /**
2282  * Immediately following this command is a blob of data containing an embedded
2283  * chunk of migration stream; read it and load it.
2284  *
2285  * @mis: Incoming state
2286  * @length: Length of packaged data to read
2287  *
2288  * Returns: Negative values on error
2289  *
2290  */
2291 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2292 {
2293     int ret;
2294     size_t length;
2295     QIOChannelBuffer *bioc;
2296 
2297     length = qemu_get_be32(mis->from_src_file);
2298     trace_loadvm_handle_cmd_packaged(length);
2299 
2300     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2301         error_report("Unreasonably large packaged state: %zu", length);
2302         return -1;
2303     }
2304 
2305     bioc = qio_channel_buffer_new(length);
2306     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2307     ret = qemu_get_buffer(mis->from_src_file,
2308                           bioc->data,
2309                           length);
2310     if (ret != length) {
2311         object_unref(OBJECT(bioc));
2312         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2313                      ret, length);
2314         return (ret < 0) ? ret : -EAGAIN;
2315     }
2316     bioc->usage += length;
2317     trace_loadvm_handle_cmd_packaged_received(ret);
2318 
2319     QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2320 
2321     /*
2322      * Before loading the guest states, ensure that the preempt channel has
2323      * been ready to use, as some of the states (e.g. via virtio_load) might
2324      * trigger page faults that will be handled through the preempt channel.
2325      * So yield to the main thread in the case that the channel create event
2326      * hasn't been dispatched.
2327      *
2328      * TODO: if we can move migration loadvm out of main thread, then we
2329      * won't block main thread from polling the accept() fds.  We can drop
2330      * this as a whole when that is done.
2331      */
2332     do {
2333         if (!migrate_postcopy_preempt() || !qemu_in_coroutine() ||
2334             mis->postcopy_qemufile_dst) {
2335             break;
2336         }
2337 
2338         aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
2339         qemu_coroutine_yield();
2340     } while (1);
2341 
2342     ret = qemu_loadvm_state_main(packf, mis);
2343     trace_loadvm_handle_cmd_packaged_main(ret);
2344     qemu_fclose(packf);
2345     object_unref(OBJECT(bioc));
2346 
2347     return ret;
2348 }
2349 
2350 /*
2351  * Handle request that source requests for recved_bitmap on
2352  * destination. Payload format:
2353  *
2354  * len (1 byte) + ramblock_name (<255 bytes)
2355  */
2356 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2357                                      uint16_t len)
2358 {
2359     QEMUFile *file = mis->from_src_file;
2360     RAMBlock *rb;
2361     char block_name[256];
2362     size_t cnt;
2363 
2364     cnt = qemu_get_counted_string(file, block_name);
2365     if (!cnt) {
2366         error_report("%s: failed to read block name", __func__);
2367         return -EINVAL;
2368     }
2369 
2370     /* Validate before using the data */
2371     if (qemu_file_get_error(file)) {
2372         return qemu_file_get_error(file);
2373     }
2374 
2375     if (len != cnt + 1) {
2376         error_report("%s: invalid payload length (%d)", __func__, len);
2377         return -EINVAL;
2378     }
2379 
2380     rb = qemu_ram_block_by_name(block_name);
2381     if (!rb) {
2382         error_report("%s: block '%s' not found", __func__, block_name);
2383         return -EINVAL;
2384     }
2385 
2386     migrate_send_rp_recv_bitmap(mis, block_name);
2387 
2388     trace_loadvm_handle_recv_bitmap(block_name);
2389 
2390     return 0;
2391 }
2392 
2393 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2394 {
2395     int ret = migration_incoming_enable_colo();
2396 
2397     if (!ret) {
2398         ret = colo_init_ram_cache();
2399         if (ret) {
2400             migration_incoming_disable_colo();
2401         }
2402     }
2403     return ret;
2404 }
2405 
2406 static int loadvm_postcopy_handle_switchover_start(void)
2407 {
2408     SaveStateEntry *se;
2409 
2410     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2411         int ret;
2412 
2413         if (!se->ops || !se->ops->switchover_start) {
2414             continue;
2415         }
2416 
2417         ret = se->ops->switchover_start(se->opaque);
2418         if (ret < 0) {
2419             return ret;
2420         }
2421     }
2422 
2423     return 0;
2424 }
2425 
2426 /*
2427  * Process an incoming 'QEMU_VM_COMMAND'
2428  * 0           just a normal return
2429  * LOADVM_QUIT All good, but exit the loop
2430  * <0          Error
2431  */
2432 static int loadvm_process_command(QEMUFile *f)
2433 {
2434     MigrationIncomingState *mis = migration_incoming_get_current();
2435     uint16_t cmd;
2436     uint16_t len;
2437     uint32_t tmp32;
2438 
2439     cmd = qemu_get_be16(f);
2440     len = qemu_get_be16(f);
2441 
2442     /* Check validity before continue processing of cmds */
2443     if (qemu_file_get_error(f)) {
2444         return qemu_file_get_error(f);
2445     }
2446 
2447     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2448         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2449         return -EINVAL;
2450     }
2451 
2452     trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2453 
2454     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2455         error_report("%s received with bad length - expecting %zu, got %d",
2456                      mig_cmd_args[cmd].name,
2457                      (size_t)mig_cmd_args[cmd].len, len);
2458         return -ERANGE;
2459     }
2460 
2461     switch (cmd) {
2462     case MIG_CMD_OPEN_RETURN_PATH:
2463         if (mis->to_src_file) {
2464             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2465             /* Not really a problem, so don't give up */
2466             return 0;
2467         }
2468         mis->to_src_file = qemu_file_get_return_path(f);
2469         if (!mis->to_src_file) {
2470             error_report("CMD_OPEN_RETURN_PATH failed");
2471             return -1;
2472         }
2473 
2474         /*
2475          * Switchover ack is enabled but no device uses it, so send an ACK to
2476          * source that it's OK to switchover. Do it here, after return path has
2477          * been created.
2478          */
2479         if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2480             int ret = migrate_send_rp_switchover_ack(mis);
2481             if (ret) {
2482                 error_report(
2483                     "Could not send switchover ack RP MSG, err %d (%s)", ret,
2484                     strerror(-ret));
2485                 return ret;
2486             }
2487         }
2488         break;
2489 
2490     case MIG_CMD_PING:
2491         tmp32 = qemu_get_be32(f);
2492         trace_loadvm_process_command_ping(tmp32);
2493         if (!mis->to_src_file) {
2494             error_report("CMD_PING (0x%x) received with no return path",
2495                          tmp32);
2496             return -1;
2497         }
2498         migrate_send_rp_pong(mis, tmp32);
2499         break;
2500 
2501     case MIG_CMD_PACKAGED:
2502         return loadvm_handle_cmd_packaged(mis);
2503 
2504     case MIG_CMD_POSTCOPY_ADVISE:
2505         return loadvm_postcopy_handle_advise(mis, len);
2506 
2507     case MIG_CMD_POSTCOPY_LISTEN:
2508         return loadvm_postcopy_handle_listen(mis);
2509 
2510     case MIG_CMD_POSTCOPY_RUN:
2511         return loadvm_postcopy_handle_run(mis);
2512 
2513     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2514         return loadvm_postcopy_ram_handle_discard(mis, len);
2515 
2516     case MIG_CMD_POSTCOPY_RESUME:
2517         return loadvm_postcopy_handle_resume(mis);
2518 
2519     case MIG_CMD_RECV_BITMAP:
2520         return loadvm_handle_recv_bitmap(mis, len);
2521 
2522     case MIG_CMD_ENABLE_COLO:
2523         return loadvm_process_enable_colo(mis);
2524 
2525     case MIG_CMD_SWITCHOVER_START:
2526         return loadvm_postcopy_handle_switchover_start();
2527     }
2528 
2529     return 0;
2530 }
2531 
2532 /*
2533  * Read a footer off the wire and check that it matches the expected section
2534  *
2535  * Returns: true if the footer was good
2536  *          false if there is a problem (and calls error_report to say why)
2537  */
2538 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2539 {
2540     int ret;
2541     uint8_t read_mark;
2542     uint32_t read_section_id;
2543 
2544     if (!migrate_get_current()->send_section_footer) {
2545         /* No footer to check */
2546         return true;
2547     }
2548 
2549     read_mark = qemu_get_byte(f);
2550 
2551     ret = qemu_file_get_error(f);
2552     if (ret) {
2553         error_report("%s: Read section footer failed: %d",
2554                      __func__, ret);
2555         return false;
2556     }
2557 
2558     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2559         error_report("Missing section footer for %s", se->idstr);
2560         return false;
2561     }
2562 
2563     read_section_id = qemu_get_be32(f);
2564     if (read_section_id != se->load_section_id) {
2565         error_report("Mismatched section id in footer for %s -"
2566                      " read 0x%x expected 0x%x",
2567                      se->idstr, read_section_id, se->load_section_id);
2568         return false;
2569     }
2570 
2571     /* All good */
2572     return true;
2573 }
2574 
2575 static int
2576 qemu_loadvm_section_start_full(QEMUFile *f, uint8_t type)
2577 {
2578     bool trace_downtime = (type == QEMU_VM_SECTION_FULL);
2579     uint32_t instance_id, version_id, section_id;
2580     int64_t start_ts, end_ts;
2581     SaveStateEntry *se;
2582     char idstr[256];
2583     int ret;
2584 
2585     /* Read section start */
2586     section_id = qemu_get_be32(f);
2587     if (!qemu_get_counted_string(f, idstr)) {
2588         error_report("Unable to read ID string for section %u",
2589                      section_id);
2590         return -EINVAL;
2591     }
2592     instance_id = qemu_get_be32(f);
2593     version_id = qemu_get_be32(f);
2594 
2595     ret = qemu_file_get_error(f);
2596     if (ret) {
2597         error_report("%s: Failed to read instance/version ID: %d",
2598                      __func__, ret);
2599         return ret;
2600     }
2601 
2602     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2603             instance_id, version_id);
2604     /* Find savevm section */
2605     se = find_se(idstr, instance_id);
2606     if (se == NULL) {
2607         error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2608                      "Make sure that your current VM setup matches your "
2609                      "saved VM setup, including any hotplugged devices",
2610                      idstr, instance_id);
2611         return -EINVAL;
2612     }
2613 
2614     /* Validate version */
2615     if (version_id > se->version_id) {
2616         error_report("savevm: unsupported version %d for '%s' v%d",
2617                      version_id, idstr, se->version_id);
2618         return -EINVAL;
2619     }
2620     se->load_version_id = version_id;
2621     se->load_section_id = section_id;
2622 
2623     /* Validate if it is a device's state */
2624     if (xen_enabled() && se->is_ram) {
2625         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2626         return -EINVAL;
2627     }
2628 
2629     if (trace_downtime) {
2630         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2631     }
2632 
2633     ret = vmstate_load(f, se);
2634     if (ret < 0) {
2635         error_report("error while loading state for instance 0x%"PRIx32" of"
2636                      " device '%s'", instance_id, idstr);
2637         return ret;
2638     }
2639 
2640     if (trace_downtime) {
2641         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2642         trace_vmstate_downtime_load("non-iterable", se->idstr,
2643                                     se->instance_id, end_ts - start_ts);
2644     }
2645 
2646     if (!check_section_footer(f, se)) {
2647         return -EINVAL;
2648     }
2649 
2650     return 0;
2651 }
2652 
2653 static int
2654 qemu_loadvm_section_part_end(QEMUFile *f, uint8_t type)
2655 {
2656     bool trace_downtime = (type == QEMU_VM_SECTION_END);
2657     int64_t start_ts, end_ts;
2658     uint32_t section_id;
2659     SaveStateEntry *se;
2660     int ret;
2661 
2662     section_id = qemu_get_be32(f);
2663 
2664     ret = qemu_file_get_error(f);
2665     if (ret) {
2666         error_report("%s: Failed to read section ID: %d",
2667                      __func__, ret);
2668         return ret;
2669     }
2670 
2671     trace_qemu_loadvm_state_section_partend(section_id);
2672     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2673         if (se->load_section_id == section_id) {
2674             break;
2675         }
2676     }
2677     if (se == NULL) {
2678         error_report("Unknown savevm section %d", section_id);
2679         return -EINVAL;
2680     }
2681 
2682     if (trace_downtime) {
2683         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2684     }
2685 
2686     ret = vmstate_load(f, se);
2687     if (ret < 0) {
2688         error_report("error while loading state section id %d(%s)",
2689                      section_id, se->idstr);
2690         return ret;
2691     }
2692 
2693     if (trace_downtime) {
2694         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2695         trace_vmstate_downtime_load("iterable", se->idstr,
2696                                     se->instance_id, end_ts - start_ts);
2697     }
2698 
2699     if (!check_section_footer(f, se)) {
2700         return -EINVAL;
2701     }
2702 
2703     return 0;
2704 }
2705 
2706 static int qemu_loadvm_state_header(QEMUFile *f)
2707 {
2708     unsigned int v;
2709     int ret;
2710 
2711     v = qemu_get_be32(f);
2712     if (v != QEMU_VM_FILE_MAGIC) {
2713         error_report("Not a migration stream");
2714         return -EINVAL;
2715     }
2716 
2717     v = qemu_get_be32(f);
2718     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2719         error_report("SaveVM v2 format is obsolete and don't work anymore");
2720         return -ENOTSUP;
2721     }
2722     if (v != QEMU_VM_FILE_VERSION) {
2723         error_report("Unsupported migration stream version");
2724         return -ENOTSUP;
2725     }
2726 
2727     if (migrate_get_current()->send_configuration) {
2728         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2729             error_report("Configuration section missing");
2730             return -EINVAL;
2731         }
2732         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2733 
2734         if (ret) {
2735             return ret;
2736         }
2737     }
2738     return 0;
2739 }
2740 
2741 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2742 {
2743     SaveStateEntry *se;
2744 
2745     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2746         if (!se->ops || !se->ops->switchover_ack_needed) {
2747             continue;
2748         }
2749 
2750         if (se->ops->switchover_ack_needed(se->opaque)) {
2751             mis->switchover_ack_pending_num++;
2752         }
2753     }
2754 
2755     trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2756 }
2757 
2758 static int qemu_loadvm_state_setup(QEMUFile *f, Error **errp)
2759 {
2760     ERRP_GUARD();
2761     SaveStateEntry *se;
2762     int ret;
2763 
2764     trace_loadvm_state_setup();
2765     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2766         if (!se->ops || !se->ops->load_setup) {
2767             continue;
2768         }
2769         if (se->ops->is_active) {
2770             if (!se->ops->is_active(se->opaque)) {
2771                 continue;
2772             }
2773         }
2774 
2775         ret = se->ops->load_setup(f, se->opaque, errp);
2776         if (ret < 0) {
2777             error_prepend(errp, "Load state of device %s failed: ",
2778                           se->idstr);
2779             qemu_file_set_error(f, ret);
2780             return ret;
2781         }
2782     }
2783     return 0;
2784 }
2785 
2786 void qemu_loadvm_state_cleanup(void)
2787 {
2788     SaveStateEntry *se;
2789 
2790     trace_loadvm_state_cleanup();
2791     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2792         if (se->ops && se->ops->load_cleanup) {
2793             se->ops->load_cleanup(se->opaque);
2794         }
2795     }
2796 }
2797 
2798 /* Return true if we should continue the migration, or false. */
2799 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2800 {
2801     int i;
2802 
2803     trace_postcopy_pause_incoming();
2804 
2805     assert(migrate_postcopy_ram());
2806 
2807     /*
2808      * Unregister yank with either from/to src would work, since ioc behind it
2809      * is the same
2810      */
2811     migration_ioc_unregister_yank_from_file(mis->from_src_file);
2812 
2813     assert(mis->from_src_file);
2814     qemu_file_shutdown(mis->from_src_file);
2815     qemu_fclose(mis->from_src_file);
2816     mis->from_src_file = NULL;
2817 
2818     assert(mis->to_src_file);
2819     qemu_file_shutdown(mis->to_src_file);
2820     qemu_mutex_lock(&mis->rp_mutex);
2821     qemu_fclose(mis->to_src_file);
2822     mis->to_src_file = NULL;
2823     qemu_mutex_unlock(&mis->rp_mutex);
2824 
2825     /*
2826      * NOTE: this must happen before reset the PostcopyTmpPages below,
2827      * otherwise it's racy to reset those fields when the fast load thread
2828      * can be accessing it in parallel.
2829      */
2830     if (mis->postcopy_qemufile_dst) {
2831         qemu_file_shutdown(mis->postcopy_qemufile_dst);
2832         /* Take the mutex to make sure the fast ram load thread halted */
2833         qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2834         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2835         qemu_fclose(mis->postcopy_qemufile_dst);
2836         mis->postcopy_qemufile_dst = NULL;
2837         qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2838     }
2839 
2840     /* Current state can be either ACTIVE or RECOVER */
2841     migrate_set_state(&mis->state, mis->state,
2842                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2843 
2844     /* Notify the fault thread for the invalidated file handle */
2845     postcopy_fault_thread_notify(mis);
2846 
2847     /*
2848      * If network is interrupted, any temp page we received will be useless
2849      * because we didn't mark them as "received" in receivedmap.  After a
2850      * proper recovery later (which will sync src dirty bitmap with receivedmap
2851      * on dest) these cached small pages will be resent again.
2852      */
2853     for (i = 0; i < mis->postcopy_channels; i++) {
2854         postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2855     }
2856 
2857     error_report("Detected IO failure for postcopy. "
2858                  "Migration paused.");
2859 
2860     do {
2861         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2862     } while (postcopy_is_paused(mis->state));
2863 
2864     trace_postcopy_pause_incoming_continued();
2865 
2866     return true;
2867 }
2868 
2869 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2870 {
2871     uint8_t section_type;
2872     int ret = 0;
2873 
2874 retry:
2875     while (true) {
2876         section_type = qemu_get_byte(f);
2877 
2878         ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2879         if (ret) {
2880             break;
2881         }
2882 
2883         trace_qemu_loadvm_state_section(section_type);
2884         switch (section_type) {
2885         case QEMU_VM_SECTION_START:
2886         case QEMU_VM_SECTION_FULL:
2887             ret = qemu_loadvm_section_start_full(f, section_type);
2888             if (ret < 0) {
2889                 goto out;
2890             }
2891             break;
2892         case QEMU_VM_SECTION_PART:
2893         case QEMU_VM_SECTION_END:
2894             ret = qemu_loadvm_section_part_end(f, section_type);
2895             if (ret < 0) {
2896                 goto out;
2897             }
2898             break;
2899         case QEMU_VM_COMMAND:
2900             ret = loadvm_process_command(f);
2901             trace_qemu_loadvm_state_section_command(ret);
2902             if ((ret < 0) || (ret == LOADVM_QUIT)) {
2903                 goto out;
2904             }
2905             break;
2906         case QEMU_VM_EOF:
2907             /* This is the end of migration */
2908             goto out;
2909         default:
2910             error_report("Unknown savevm section type %d", section_type);
2911             ret = -EINVAL;
2912             goto out;
2913         }
2914     }
2915 
2916 out:
2917     if (ret < 0) {
2918         qemu_file_set_error(f, ret);
2919 
2920         /* Cancel bitmaps incoming regardless of recovery */
2921         dirty_bitmap_mig_cancel_incoming();
2922 
2923         /*
2924          * If we are during an active postcopy, then we pause instead
2925          * of bail out to at least keep the VM's dirty data.  Note
2926          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2927          * during which we're still receiving device states and we
2928          * still haven't yet started the VM on destination.
2929          *
2930          * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2931          * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2932          * recovering.
2933          */
2934         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2935             migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2936             /* Reset f to point to the newly created channel */
2937             f = mis->from_src_file;
2938             goto retry;
2939         }
2940     }
2941     return ret;
2942 }
2943 
2944 int qemu_loadvm_state(QEMUFile *f)
2945 {
2946     MigrationIncomingState *mis = migration_incoming_get_current();
2947     Error *local_err = NULL;
2948     int ret;
2949 
2950     if (qemu_savevm_state_blocked(&local_err)) {
2951         error_report_err(local_err);
2952         return -EINVAL;
2953     }
2954 
2955     ret = qemu_loadvm_state_header(f);
2956     if (ret) {
2957         return ret;
2958     }
2959 
2960     if (qemu_loadvm_state_setup(f, &local_err) != 0) {
2961         error_report_err(local_err);
2962         return -EINVAL;
2963     }
2964 
2965     if (migrate_switchover_ack()) {
2966         qemu_loadvm_state_switchover_ack_needed(mis);
2967     }
2968 
2969     cpu_synchronize_all_pre_loadvm();
2970 
2971     ret = qemu_loadvm_state_main(f, mis);
2972     qemu_event_set(&mis->main_thread_load_event);
2973 
2974     trace_qemu_loadvm_state_post_main(ret);
2975 
2976     if (mis->have_listen_thread) {
2977         /*
2978          * Postcopy listen thread still going, don't synchronize the
2979          * cpus yet.
2980          */
2981         return ret;
2982     }
2983 
2984     /* When reaching here, it must be precopy */
2985     if (ret == 0) {
2986         if (migrate_has_error(migrate_get_current())) {
2987             ret = -EINVAL;
2988         } else {
2989             ret = qemu_file_get_error(f);
2990         }
2991     }
2992 
2993     /*
2994      * Try to read in the VMDESC section as well, so that dumping tools that
2995      * intercept our migration stream have the chance to see it.
2996      */
2997 
2998     /* We've got to be careful; if we don't read the data and just shut the fd
2999      * then the sender can error if we close while it's still sending.
3000      * We also mustn't read data that isn't there; some transports (RDMA)
3001      * will stall waiting for that data when the source has already closed.
3002      */
3003     if (ret == 0 && should_send_vmdesc()) {
3004         uint8_t *buf;
3005         uint32_t size;
3006         uint8_t  section_type = qemu_get_byte(f);
3007 
3008         if (section_type != QEMU_VM_VMDESCRIPTION) {
3009             error_report("Expected vmdescription section, but got %d",
3010                          section_type);
3011             /*
3012              * It doesn't seem worth failing at this point since
3013              * we apparently have an otherwise valid VM state
3014              */
3015         } else {
3016             buf = g_malloc(0x1000);
3017             size = qemu_get_be32(f);
3018 
3019             while (size > 0) {
3020                 uint32_t read_chunk = MIN(size, 0x1000);
3021                 qemu_get_buffer(f, buf, read_chunk);
3022                 size -= read_chunk;
3023             }
3024             g_free(buf);
3025         }
3026     }
3027 
3028     cpu_synchronize_all_post_init();
3029 
3030     return ret;
3031 }
3032 
3033 int qemu_load_device_state(QEMUFile *f)
3034 {
3035     MigrationIncomingState *mis = migration_incoming_get_current();
3036     int ret;
3037 
3038     /* Load QEMU_VM_SECTION_FULL section */
3039     ret = qemu_loadvm_state_main(f, mis);
3040     if (ret < 0) {
3041         error_report("Failed to load device state: %d", ret);
3042         return ret;
3043     }
3044 
3045     cpu_synchronize_all_post_init();
3046     return 0;
3047 }
3048 
3049 int qemu_loadvm_approve_switchover(void)
3050 {
3051     MigrationIncomingState *mis = migration_incoming_get_current();
3052 
3053     if (!mis->switchover_ack_pending_num) {
3054         return -EINVAL;
3055     }
3056 
3057     mis->switchover_ack_pending_num--;
3058     trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
3059 
3060     if (mis->switchover_ack_pending_num) {
3061         return 0;
3062     }
3063 
3064     return migrate_send_rp_switchover_ack(mis);
3065 }
3066 
3067 bool qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
3068                                    char *buf, size_t len, Error **errp)
3069 {
3070     SaveStateEntry *se;
3071 
3072     se = find_se(idstr, instance_id);
3073     if (!se) {
3074         error_setg(errp,
3075                    "Unknown idstr %s or instance id %u for load state buffer",
3076                    idstr, instance_id);
3077         return false;
3078     }
3079 
3080     if (!se->ops || !se->ops->load_state_buffer) {
3081         error_setg(errp,
3082                    "idstr %s / instance %u has no load state buffer operation",
3083                    idstr, instance_id);
3084         return false;
3085     }
3086 
3087     return se->ops->load_state_buffer(se->opaque, buf, len, errp);
3088 }
3089 
3090 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
3091                   bool has_devices, strList *devices, Error **errp)
3092 {
3093     BlockDriverState *bs;
3094     QEMUSnapshotInfo sn1, *sn = &sn1;
3095     int ret = -1, ret2;
3096     QEMUFile *f;
3097     RunState saved_state = runstate_get();
3098     uint64_t vm_state_size;
3099     g_autoptr(GDateTime) now = g_date_time_new_now_local();
3100 
3101     GLOBAL_STATE_CODE();
3102 
3103     if (migration_is_blocked(errp)) {
3104         return false;
3105     }
3106 
3107     if (!replay_can_snapshot()) {
3108         error_setg(errp, "Record/replay does not allow making snapshot "
3109                    "right now. Try once more later.");
3110         return false;
3111     }
3112 
3113     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3114         return false;
3115     }
3116 
3117     /* Delete old snapshots of the same name */
3118     if (name) {
3119         if (overwrite) {
3120             if (bdrv_all_delete_snapshot(name, has_devices,
3121                                          devices, errp) < 0) {
3122                 return false;
3123             }
3124         } else {
3125             ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3126             if (ret2 < 0) {
3127                 return false;
3128             }
3129             if (ret2 == 1) {
3130                 error_setg(errp,
3131                            "Snapshot '%s' already exists in one or more devices",
3132                            name);
3133                 return false;
3134             }
3135         }
3136     }
3137 
3138     bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3139     if (bs == NULL) {
3140         return false;
3141     }
3142 
3143     global_state_store();
3144     vm_stop(RUN_STATE_SAVE_VM);
3145 
3146     bdrv_drain_all_begin();
3147 
3148     memset(sn, 0, sizeof(*sn));
3149 
3150     /* fill auxiliary fields */
3151     sn->date_sec = g_date_time_to_unix(now);
3152     sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3153     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3154     if (replay_mode != REPLAY_MODE_NONE) {
3155         sn->icount = replay_get_current_icount();
3156     } else {
3157         sn->icount = -1ULL;
3158     }
3159 
3160     if (name) {
3161         pstrcpy(sn->name, sizeof(sn->name), name);
3162     } else {
3163         g_autofree char *autoname = g_date_time_format(now,  "vm-%Y%m%d%H%M%S");
3164         pstrcpy(sn->name, sizeof(sn->name), autoname);
3165     }
3166 
3167     /* save the VM state */
3168     f = qemu_fopen_bdrv(bs, 1);
3169     if (!f) {
3170         error_setg(errp, "Could not open VM state file");
3171         goto the_end;
3172     }
3173     ret = qemu_savevm_state(f, errp);
3174     vm_state_size = qemu_file_transferred(f);
3175     ret2 = qemu_fclose(f);
3176     if (ret < 0) {
3177         goto the_end;
3178     }
3179     if (ret2 < 0) {
3180         ret = ret2;
3181         goto the_end;
3182     }
3183 
3184     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3185                                    has_devices, devices, errp);
3186     if (ret < 0) {
3187         bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3188         goto the_end;
3189     }
3190 
3191     ret = 0;
3192 
3193  the_end:
3194     bdrv_drain_all_end();
3195 
3196     vm_resume(saved_state);
3197     return ret == 0;
3198 }
3199 
3200 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3201                                 Error **errp)
3202 {
3203     QEMUFile *f;
3204     QIOChannelFile *ioc;
3205     int saved_vm_running;
3206     int ret;
3207 
3208     if (!has_live) {
3209         /* live default to true so old version of Xen tool stack can have a
3210          * successful live migration */
3211         live = true;
3212     }
3213 
3214     saved_vm_running = runstate_is_running();
3215     vm_stop(RUN_STATE_SAVE_VM);
3216     global_state_store_running();
3217 
3218     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3219                                     0660, errp);
3220     if (!ioc) {
3221         goto the_end;
3222     }
3223     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3224     f = qemu_file_new_output(QIO_CHANNEL(ioc));
3225     object_unref(OBJECT(ioc));
3226     ret = qemu_save_device_state(f);
3227     if (ret < 0 || qemu_fclose(f) < 0) {
3228         error_setg(errp, "saving Xen device state failed");
3229     } else {
3230         /* libxl calls the QMP command "stop" before calling
3231          * "xen-save-devices-state" and in case of migration failure, libxl
3232          * would call "cont".
3233          * So call bdrv_inactivate_all (release locks) here to let the other
3234          * side of the migration take control of the images.
3235          */
3236         if (live && !saved_vm_running) {
3237             migration_block_inactivate();
3238         }
3239     }
3240 
3241  the_end:
3242     if (saved_vm_running) {
3243         vm_start();
3244     }
3245 }
3246 
3247 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3248 {
3249     QEMUFile *f;
3250     QIOChannelFile *ioc;
3251     int ret;
3252 
3253     /* Guest must be paused before loading the device state; the RAM state
3254      * will already have been loaded by xc
3255      */
3256     if (runstate_is_running()) {
3257         error_setg(errp, "Cannot update device state while vm is running");
3258         return;
3259     }
3260     vm_stop(RUN_STATE_RESTORE_VM);
3261 
3262     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3263     if (!ioc) {
3264         return;
3265     }
3266     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3267     f = qemu_file_new_input(QIO_CHANNEL(ioc));
3268     object_unref(OBJECT(ioc));
3269 
3270     ret = qemu_loadvm_state(f);
3271     qemu_fclose(f);
3272     if (ret < 0) {
3273         error_setg(errp, "loading Xen device state failed");
3274     }
3275     migration_incoming_state_destroy();
3276 }
3277 
3278 bool load_snapshot(const char *name, const char *vmstate,
3279                    bool has_devices, strList *devices, Error **errp)
3280 {
3281     BlockDriverState *bs_vm_state;
3282     QEMUSnapshotInfo sn;
3283     QEMUFile *f;
3284     int ret;
3285     MigrationIncomingState *mis = migration_incoming_get_current();
3286 
3287     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3288         return false;
3289     }
3290     ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3291     if (ret < 0) {
3292         return false;
3293     }
3294     if (ret == 0) {
3295         error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3296                    name);
3297         return false;
3298     }
3299 
3300     bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3301     if (!bs_vm_state) {
3302         return false;
3303     }
3304 
3305     /* Don't even try to load empty VM states */
3306     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3307     if (ret < 0) {
3308         error_setg(errp, "Snapshot can not be found");
3309         return false;
3310     } else if (sn.vm_state_size == 0) {
3311         error_setg(errp, "This is a disk-only snapshot. Revert to it "
3312                    " offline using qemu-img");
3313         return false;
3314     }
3315 
3316     /*
3317      * Flush the record/replay queue. Now the VM state is going
3318      * to change. Therefore we don't need to preserve its consistency
3319      */
3320     replay_flush_events();
3321 
3322     /* Flush all IO requests so they don't interfere with the new state.  */
3323     bdrv_drain_all_begin();
3324 
3325     ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3326     if (ret < 0) {
3327         goto err_drain;
3328     }
3329 
3330     /* restore the VM state */
3331     f = qemu_fopen_bdrv(bs_vm_state, 0);
3332     if (!f) {
3333         error_setg(errp, "Could not open VM state file");
3334         goto err_drain;
3335     }
3336 
3337     qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3338     mis->from_src_file = f;
3339 
3340     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3341         ret = -EINVAL;
3342         goto err_drain;
3343     }
3344     ret = qemu_loadvm_state(f);
3345     migration_incoming_state_destroy();
3346 
3347     bdrv_drain_all_end();
3348 
3349     if (ret < 0) {
3350         error_setg(errp, "Error %d while loading VM state", ret);
3351         return false;
3352     }
3353 
3354     return true;
3355 
3356 err_drain:
3357     bdrv_drain_all_end();
3358     return false;
3359 }
3360 
3361 void load_snapshot_resume(RunState state)
3362 {
3363     vm_resume(state);
3364     if (state == RUN_STATE_RUNNING && runstate_get() == RUN_STATE_SUSPENDED) {
3365         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, &error_abort);
3366     }
3367 }
3368 
3369 bool delete_snapshot(const char *name, bool has_devices,
3370                      strList *devices, Error **errp)
3371 {
3372     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3373         return false;
3374     }
3375 
3376     if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3377         return false;
3378     }
3379 
3380     return true;
3381 }
3382 
3383 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3384 {
3385     qemu_ram_set_idstr(mr->ram_block,
3386                        memory_region_name(mr), dev);
3387     qemu_ram_set_migratable(mr->ram_block);
3388 }
3389 
3390 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3391 {
3392     qemu_ram_unset_idstr(mr->ram_block);
3393     qemu_ram_unset_migratable(mr->ram_block);
3394 }
3395 
3396 void vmstate_register_ram_global(MemoryRegion *mr)
3397 {
3398     vmstate_register_ram(mr, NULL);
3399 }
3400 
3401 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3402 {
3403     /* check needed if --only-migratable is specified */
3404     if (!only_migratable) {
3405         return true;
3406     }
3407 
3408     return !(vmsd && vmsd->unmigratable);
3409 }
3410 
3411 typedef struct SnapshotJob {
3412     Job common;
3413     char *tag;
3414     char *vmstate;
3415     strList *devices;
3416     Coroutine *co;
3417     Error **errp;
3418     bool ret;
3419 } SnapshotJob;
3420 
3421 static void qmp_snapshot_job_free(SnapshotJob *s)
3422 {
3423     g_free(s->tag);
3424     g_free(s->vmstate);
3425     qapi_free_strList(s->devices);
3426 }
3427 
3428 
3429 static void snapshot_load_job_bh(void *opaque)
3430 {
3431     Job *job = opaque;
3432     SnapshotJob *s = container_of(job, SnapshotJob, common);
3433     RunState orig_state = runstate_get();
3434 
3435     job_progress_set_remaining(&s->common, 1);
3436 
3437     vm_stop(RUN_STATE_RESTORE_VM);
3438 
3439     s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3440     if (s->ret) {
3441         load_snapshot_resume(orig_state);
3442     }
3443 
3444     job_progress_update(&s->common, 1);
3445 
3446     qmp_snapshot_job_free(s);
3447     aio_co_wake(s->co);
3448 }
3449 
3450 static void snapshot_save_job_bh(void *opaque)
3451 {
3452     Job *job = opaque;
3453     SnapshotJob *s = container_of(job, SnapshotJob, common);
3454 
3455     job_progress_set_remaining(&s->common, 1);
3456     s->ret = save_snapshot(s->tag, false, s->vmstate,
3457                            true, s->devices, s->errp);
3458     job_progress_update(&s->common, 1);
3459 
3460     qmp_snapshot_job_free(s);
3461     aio_co_wake(s->co);
3462 }
3463 
3464 static void snapshot_delete_job_bh(void *opaque)
3465 {
3466     Job *job = opaque;
3467     SnapshotJob *s = container_of(job, SnapshotJob, common);
3468 
3469     job_progress_set_remaining(&s->common, 1);
3470     s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3471     job_progress_update(&s->common, 1);
3472 
3473     qmp_snapshot_job_free(s);
3474     aio_co_wake(s->co);
3475 }
3476 
3477 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3478 {
3479     SnapshotJob *s = container_of(job, SnapshotJob, common);
3480     s->errp = errp;
3481     s->co = qemu_coroutine_self();
3482     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3483                             snapshot_save_job_bh, job);
3484     qemu_coroutine_yield();
3485     return s->ret ? 0 : -1;
3486 }
3487 
3488 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3489 {
3490     SnapshotJob *s = container_of(job, SnapshotJob, common);
3491     s->errp = errp;
3492     s->co = qemu_coroutine_self();
3493     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3494                             snapshot_load_job_bh, job);
3495     qemu_coroutine_yield();
3496     return s->ret ? 0 : -1;
3497 }
3498 
3499 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3500 {
3501     SnapshotJob *s = container_of(job, SnapshotJob, common);
3502     s->errp = errp;
3503     s->co = qemu_coroutine_self();
3504     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3505                             snapshot_delete_job_bh, job);
3506     qemu_coroutine_yield();
3507     return s->ret ? 0 : -1;
3508 }
3509 
3510 
3511 static const JobDriver snapshot_load_job_driver = {
3512     .instance_size = sizeof(SnapshotJob),
3513     .job_type      = JOB_TYPE_SNAPSHOT_LOAD,
3514     .run           = snapshot_load_job_run,
3515 };
3516 
3517 static const JobDriver snapshot_save_job_driver = {
3518     .instance_size = sizeof(SnapshotJob),
3519     .job_type      = JOB_TYPE_SNAPSHOT_SAVE,
3520     .run           = snapshot_save_job_run,
3521 };
3522 
3523 static const JobDriver snapshot_delete_job_driver = {
3524     .instance_size = sizeof(SnapshotJob),
3525     .job_type      = JOB_TYPE_SNAPSHOT_DELETE,
3526     .run           = snapshot_delete_job_run,
3527 };
3528 
3529 
3530 void qmp_snapshot_save(const char *job_id,
3531                        const char *tag,
3532                        const char *vmstate,
3533                        strList *devices,
3534                        Error **errp)
3535 {
3536     SnapshotJob *s;
3537 
3538     s = job_create(job_id, &snapshot_save_job_driver, NULL,
3539                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3540                    NULL, NULL, errp);
3541     if (!s) {
3542         return;
3543     }
3544 
3545     s->tag = g_strdup(tag);
3546     s->vmstate = g_strdup(vmstate);
3547     s->devices = QAPI_CLONE(strList, devices);
3548 
3549     job_start(&s->common);
3550 }
3551 
3552 void qmp_snapshot_load(const char *job_id,
3553                        const char *tag,
3554                        const char *vmstate,
3555                        strList *devices,
3556                        Error **errp)
3557 {
3558     SnapshotJob *s;
3559 
3560     s = job_create(job_id, &snapshot_load_job_driver, NULL,
3561                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3562                    NULL, NULL, errp);
3563     if (!s) {
3564         return;
3565     }
3566 
3567     s->tag = g_strdup(tag);
3568     s->vmstate = g_strdup(vmstate);
3569     s->devices = QAPI_CLONE(strList, devices);
3570 
3571     job_start(&s->common);
3572 }
3573 
3574 void qmp_snapshot_delete(const char *job_id,
3575                          const char *tag,
3576                          strList *devices,
3577                          Error **errp)
3578 {
3579     SnapshotJob *s;
3580 
3581     s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3582                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3583                    NULL, NULL, errp);
3584     if (!s) {
3585         return;
3586     }
3587 
3588     s->tag = g_strdup(tag);
3589     s->devices = QAPI_CLONE(strList, devices);
3590 
3591     job_start(&s->common);
3592 }
3593