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