xref: /openbmc/qemu/migration/savevm.c (revision ce62df5378bd66963b3e096b86b31f342f001cfe)
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 "hw/xen/xen.h"
32 #include "net/net.h"
33 #include "migration.h"
34 #include "migration/snapshot.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
39 #include "ram.h"
40 #include "qemu-file-channel.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/qapi-commands-misc.h"
47 #include "qapi/qmp/qerror.h"
48 #include "qemu/error-report.h"
49 #include "sysemu/cpus.h"
50 #include "exec/memory.h"
51 #include "exec/target_page.h"
52 #include "trace.h"
53 #include "qemu/iov.h"
54 #include "qemu/main-loop.h"
55 #include "block/snapshot.h"
56 #include "qemu/cutils.h"
57 #include "io/channel-buffer.h"
58 #include "io/channel-file.h"
59 #include "sysemu/replay.h"
60 #include "sysemu/runstate.h"
61 #include "sysemu/sysemu.h"
62 #include "qjson.h"
63 #include "migration/colo.h"
64 #include "qemu/bitmap.h"
65 #include "net/announce.h"
66 
67 const unsigned int postcopy_ram_discard_version = 0;
68 
69 /* Subcommands for QEMU_VM_COMMAND */
70 enum qemu_vm_cmd {
71     MIG_CMD_INVALID = 0,   /* Must be 0 */
72     MIG_CMD_OPEN_RETURN_PATH,  /* Tell the dest to open the Return path */
73     MIG_CMD_PING,              /* Request a PONG on the RP */
74 
75     MIG_CMD_POSTCOPY_ADVISE,       /* Prior to any page transfers, just
76                                       warn we might want to do PC */
77     MIG_CMD_POSTCOPY_LISTEN,       /* Start listening for incoming
78                                       pages as it's running. */
79     MIG_CMD_POSTCOPY_RUN,          /* Start execution */
80 
81     MIG_CMD_POSTCOPY_RAM_DISCARD,  /* A list of pages to discard that
82                                       were previously sent during
83                                       precopy but are dirty. */
84     MIG_CMD_PACKAGED,          /* Send a wrapped stream within this stream */
85     MIG_CMD_ENABLE_COLO,       /* Enable COLO */
86     MIG_CMD_POSTCOPY_RESUME,   /* resume postcopy on dest */
87     MIG_CMD_RECV_BITMAP,       /* Request for recved bitmap on dst */
88     MIG_CMD_MAX
89 };
90 
91 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
92 static struct mig_cmd_args {
93     ssize_t     len; /* -1 = variable */
94     const char *name;
95 } mig_cmd_args[] = {
96     [MIG_CMD_INVALID]          = { .len = -1, .name = "INVALID" },
97     [MIG_CMD_OPEN_RETURN_PATH] = { .len =  0, .name = "OPEN_RETURN_PATH" },
98     [MIG_CMD_PING]             = { .len = sizeof(uint32_t), .name = "PING" },
99     [MIG_CMD_POSTCOPY_ADVISE]  = { .len = -1, .name = "POSTCOPY_ADVISE" },
100     [MIG_CMD_POSTCOPY_LISTEN]  = { .len =  0, .name = "POSTCOPY_LISTEN" },
101     [MIG_CMD_POSTCOPY_RUN]     = { .len =  0, .name = "POSTCOPY_RUN" },
102     [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
103                                    .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
104     [MIG_CMD_POSTCOPY_RESUME]  = { .len =  0, .name = "POSTCOPY_RESUME" },
105     [MIG_CMD_PACKAGED]         = { .len =  4, .name = "PACKAGED" },
106     [MIG_CMD_RECV_BITMAP]      = { .len = -1, .name = "RECV_BITMAP" },
107     [MIG_CMD_MAX]              = { .len = -1, .name = "MAX" },
108 };
109 
110 /* Note for MIG_CMD_POSTCOPY_ADVISE:
111  * The format of arguments is depending on postcopy mode:
112  * - postcopy RAM only
113  *   uint64_t host page size
114  *   uint64_t taget page size
115  *
116  * - postcopy RAM and postcopy dirty bitmaps
117  *   format is the same as for postcopy RAM only
118  *
119  * - postcopy dirty bitmaps only
120  *   Nothing. Command length field is 0.
121  *
122  * Be careful: adding a new postcopy entity with some other parameters should
123  * not break format self-description ability. Good way is to introduce some
124  * generic extendable format with an exception for two old entities.
125  */
126 
127 /***********************************************************/
128 /* savevm/loadvm support */
129 
130 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
131                                    int64_t pos, Error **errp)
132 {
133     int ret;
134     QEMUIOVector qiov;
135 
136     qemu_iovec_init_external(&qiov, iov, iovcnt);
137     ret = bdrv_writev_vmstate(opaque, &qiov, pos);
138     if (ret < 0) {
139         return ret;
140     }
141 
142     return qiov.size;
143 }
144 
145 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
146                                 size_t size, Error **errp)
147 {
148     return bdrv_load_vmstate(opaque, buf, pos, size);
149 }
150 
151 static int bdrv_fclose(void *opaque, Error **errp)
152 {
153     return bdrv_flush(opaque);
154 }
155 
156 static const QEMUFileOps bdrv_read_ops = {
157     .get_buffer = block_get_buffer,
158     .close =      bdrv_fclose
159 };
160 
161 static const QEMUFileOps bdrv_write_ops = {
162     .writev_buffer  = block_writev_buffer,
163     .close          = bdrv_fclose
164 };
165 
166 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
167 {
168     if (is_writable) {
169         return qemu_fopen_ops(bs, &bdrv_write_ops);
170     }
171     return qemu_fopen_ops(bs, &bdrv_read_ops);
172 }
173 
174 
175 /* QEMUFile timer support.
176  * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
177  */
178 
179 void timer_put(QEMUFile *f, QEMUTimer *ts)
180 {
181     uint64_t expire_time;
182 
183     expire_time = timer_expire_time_ns(ts);
184     qemu_put_be64(f, expire_time);
185 }
186 
187 void timer_get(QEMUFile *f, QEMUTimer *ts)
188 {
189     uint64_t expire_time;
190 
191     expire_time = qemu_get_be64(f);
192     if (expire_time != -1) {
193         timer_mod_ns(ts, expire_time);
194     } else {
195         timer_del(ts);
196     }
197 }
198 
199 
200 /* VMState timer support.
201  * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
202  */
203 
204 static int get_timer(QEMUFile *f, void *pv, size_t size,
205                      const VMStateField *field)
206 {
207     QEMUTimer *v = pv;
208     timer_get(f, v);
209     return 0;
210 }
211 
212 static int put_timer(QEMUFile *f, void *pv, size_t size,
213                      const VMStateField *field, QJSON *vmdesc)
214 {
215     QEMUTimer *v = pv;
216     timer_put(f, v);
217 
218     return 0;
219 }
220 
221 const VMStateInfo vmstate_info_timer = {
222     .name = "timer",
223     .get  = get_timer,
224     .put  = put_timer,
225 };
226 
227 
228 typedef struct CompatEntry {
229     char idstr[256];
230     int instance_id;
231 } CompatEntry;
232 
233 typedef struct SaveStateEntry {
234     QTAILQ_ENTRY(SaveStateEntry) entry;
235     char idstr[256];
236     int instance_id;
237     int alias_id;
238     int version_id;
239     /* version id read from the stream */
240     int load_version_id;
241     int section_id;
242     /* section id read from the stream */
243     int load_section_id;
244     const SaveVMHandlers *ops;
245     const VMStateDescription *vmsd;
246     void *opaque;
247     CompatEntry *compat;
248     int is_ram;
249 } SaveStateEntry;
250 
251 typedef struct SaveState {
252     QTAILQ_HEAD(, SaveStateEntry) handlers;
253     int global_section_id;
254     uint32_t len;
255     const char *name;
256     uint32_t target_page_bits;
257     uint32_t caps_count;
258     MigrationCapability *capabilities;
259 } SaveState;
260 
261 static SaveState savevm_state = {
262     .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
263     .global_section_id = 0,
264 };
265 
266 static bool should_validate_capability(int capability)
267 {
268     assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
269     /* Validate only new capabilities to keep compatibility. */
270     switch (capability) {
271     case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
272         return true;
273     default:
274         return false;
275     }
276 }
277 
278 static uint32_t get_validatable_capabilities_count(void)
279 {
280     MigrationState *s = migrate_get_current();
281     uint32_t result = 0;
282     int i;
283     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
284         if (should_validate_capability(i) && s->enabled_capabilities[i]) {
285             result++;
286         }
287     }
288     return result;
289 }
290 
291 static int configuration_pre_save(void *opaque)
292 {
293     SaveState *state = opaque;
294     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
295     MigrationState *s = migrate_get_current();
296     int i, j;
297 
298     state->len = strlen(current_name);
299     state->name = current_name;
300     state->target_page_bits = qemu_target_page_bits();
301 
302     state->caps_count = get_validatable_capabilities_count();
303     state->capabilities = g_renew(MigrationCapability, state->capabilities,
304                                   state->caps_count);
305     for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
306         if (should_validate_capability(i) && s->enabled_capabilities[i]) {
307             state->capabilities[j++] = i;
308         }
309     }
310 
311     return 0;
312 }
313 
314 static int configuration_pre_load(void *opaque)
315 {
316     SaveState *state = opaque;
317 
318     /* If there is no target-page-bits subsection it means the source
319      * predates the variable-target-page-bits support and is using the
320      * minimum possible value for this CPU.
321      */
322     state->target_page_bits = qemu_target_page_bits_min();
323     return 0;
324 }
325 
326 static bool configuration_validate_capabilities(SaveState *state)
327 {
328     bool ret = true;
329     MigrationState *s = migrate_get_current();
330     unsigned long *source_caps_bm;
331     int i;
332 
333     source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
334     for (i = 0; i < state->caps_count; i++) {
335         MigrationCapability capability = state->capabilities[i];
336         set_bit(capability, source_caps_bm);
337     }
338 
339     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
340         bool source_state, target_state;
341         if (!should_validate_capability(i)) {
342             continue;
343         }
344         source_state = test_bit(i, source_caps_bm);
345         target_state = s->enabled_capabilities[i];
346         if (source_state != target_state) {
347             error_report("Capability %s is %s, but received capability is %s",
348                          MigrationCapability_str(i),
349                          target_state ? "on" : "off",
350                          source_state ? "on" : "off");
351             ret = false;
352             /* Don't break here to report all failed capabilities */
353         }
354     }
355 
356     g_free(source_caps_bm);
357     return ret;
358 }
359 
360 static int configuration_post_load(void *opaque, int version_id)
361 {
362     SaveState *state = opaque;
363     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
364 
365     if (strncmp(state->name, current_name, state->len) != 0) {
366         error_report("Machine type received is '%.*s' and local is '%s'",
367                      (int) state->len, state->name, current_name);
368         return -EINVAL;
369     }
370 
371     if (state->target_page_bits != qemu_target_page_bits()) {
372         error_report("Received TARGET_PAGE_BITS is %d but local is %d",
373                      state->target_page_bits, qemu_target_page_bits());
374         return -EINVAL;
375     }
376 
377     if (!configuration_validate_capabilities(state)) {
378         return -EINVAL;
379     }
380 
381     return 0;
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, QJSON *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 = (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 = (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 const VMStateDescription vmstate_configuration = {
468     .name = "configuration",
469     .version_id = 1,
470     .pre_load = configuration_pre_load,
471     .post_load = configuration_post_load,
472     .pre_save = configuration_pre_save,
473     .fields = (VMStateField[]) {
474         VMSTATE_UINT32(len, SaveState),
475         VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
476         VMSTATE_END_OF_LIST()
477     },
478     .subsections = (const VMStateDescription*[]) {
479         &vmstate_target_page_bits,
480         &vmstate_capabilites,
481         NULL
482     }
483 };
484 
485 static void dump_vmstate_vmsd(FILE *out_file,
486                               const VMStateDescription *vmsd, int indent,
487                               bool is_subsection);
488 
489 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
490                               int indent)
491 {
492     fprintf(out_file, "%*s{\n", indent, "");
493     indent += 2;
494     fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
495     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
496             field->version_id);
497     fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
498             field->field_exists ? "true" : "false");
499     fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
500     if (field->vmsd != NULL) {
501         fprintf(out_file, ",\n");
502         dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
503     }
504     fprintf(out_file, "\n%*s}", indent - 2, "");
505 }
506 
507 static void dump_vmstate_vmss(FILE *out_file,
508                               const VMStateDescription **subsection,
509                               int indent)
510 {
511     if (*subsection != NULL) {
512         dump_vmstate_vmsd(out_file, *subsection, indent, true);
513     }
514 }
515 
516 static void dump_vmstate_vmsd(FILE *out_file,
517                               const VMStateDescription *vmsd, int indent,
518                               bool is_subsection)
519 {
520     if (is_subsection) {
521         fprintf(out_file, "%*s{\n", indent, "");
522     } else {
523         fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
524     }
525     indent += 2;
526     fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
527     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
528             vmsd->version_id);
529     fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
530             vmsd->minimum_version_id);
531     if (vmsd->fields != NULL) {
532         const VMStateField *field = vmsd->fields;
533         bool first;
534 
535         fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
536         first = true;
537         while (field->name != NULL) {
538             if (field->flags & VMS_MUST_EXIST) {
539                 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
540                 field++;
541                 continue;
542             }
543             if (!first) {
544                 fprintf(out_file, ",\n");
545             }
546             dump_vmstate_vmsf(out_file, field, indent + 2);
547             field++;
548             first = false;
549         }
550         fprintf(out_file, "\n%*s]", indent, "");
551     }
552     if (vmsd->subsections != NULL) {
553         const VMStateDescription **subsection = vmsd->subsections;
554         bool first;
555 
556         fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
557         first = true;
558         while (*subsection != NULL) {
559             if (!first) {
560                 fprintf(out_file, ",\n");
561             }
562             dump_vmstate_vmss(out_file, subsection, indent + 2);
563             subsection++;
564             first = false;
565         }
566         fprintf(out_file, "\n%*s]", indent, "");
567     }
568     fprintf(out_file, "\n%*s}", indent - 2, "");
569 }
570 
571 static void dump_machine_type(FILE *out_file)
572 {
573     MachineClass *mc;
574 
575     mc = MACHINE_GET_CLASS(current_machine);
576 
577     fprintf(out_file, "  \"vmschkmachine\": {\n");
578     fprintf(out_file, "    \"Name\": \"%s\"\n", mc->name);
579     fprintf(out_file, "  },\n");
580 }
581 
582 void dump_vmstate_json_to_file(FILE *out_file)
583 {
584     GSList *list, *elt;
585     bool first;
586 
587     fprintf(out_file, "{\n");
588     dump_machine_type(out_file);
589 
590     first = true;
591     list = object_class_get_list(TYPE_DEVICE, true);
592     for (elt = list; elt; elt = elt->next) {
593         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
594                                              TYPE_DEVICE);
595         const char *name;
596         int indent = 2;
597 
598         if (!dc->vmsd) {
599             continue;
600         }
601 
602         if (!first) {
603             fprintf(out_file, ",\n");
604         }
605         name = object_class_get_name(OBJECT_CLASS(dc));
606         fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
607         indent += 2;
608         fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
609         fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
610                 dc->vmsd->version_id);
611         fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
612                 dc->vmsd->minimum_version_id);
613 
614         dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
615 
616         fprintf(out_file, "\n%*s}", indent - 2, "");
617         first = false;
618     }
619     fprintf(out_file, "\n}\n");
620     fclose(out_file);
621 }
622 
623 static int calculate_new_instance_id(const char *idstr)
624 {
625     SaveStateEntry *se;
626     int instance_id = 0;
627 
628     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
629         if (strcmp(idstr, se->idstr) == 0
630             && instance_id <= se->instance_id) {
631             instance_id = se->instance_id + 1;
632         }
633     }
634     return instance_id;
635 }
636 
637 static int calculate_compat_instance_id(const char *idstr)
638 {
639     SaveStateEntry *se;
640     int instance_id = 0;
641 
642     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
643         if (!se->compat) {
644             continue;
645         }
646 
647         if (strcmp(idstr, se->compat->idstr) == 0
648             && instance_id <= se->compat->instance_id) {
649             instance_id = se->compat->instance_id + 1;
650         }
651     }
652     return instance_id;
653 }
654 
655 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
656 {
657     if (se->vmsd) {
658         return se->vmsd->priority;
659     }
660     return MIG_PRI_DEFAULT;
661 }
662 
663 static void savevm_state_handler_insert(SaveStateEntry *nse)
664 {
665     MigrationPriority priority = save_state_priority(nse);
666     SaveStateEntry *se;
667 
668     assert(priority <= MIG_PRI_MAX);
669 
670     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
671         if (save_state_priority(se) < priority) {
672             break;
673         }
674     }
675 
676     if (se) {
677         QTAILQ_INSERT_BEFORE(se, nse, entry);
678     } else {
679         QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
680     }
681 }
682 
683 /* TODO: Individual devices generally have very little idea about the rest
684    of the system, so instance_id should be removed/replaced.
685    Meanwhile pass -1 as instance_id if you do not already have a clearly
686    distinguishing id for all instances of your device class. */
687 int register_savevm_live(const char *idstr,
688                          int instance_id,
689                          int version_id,
690                          const SaveVMHandlers *ops,
691                          void *opaque)
692 {
693     SaveStateEntry *se;
694 
695     se = g_new0(SaveStateEntry, 1);
696     se->version_id = version_id;
697     se->section_id = savevm_state.global_section_id++;
698     se->ops = ops;
699     se->opaque = opaque;
700     se->vmsd = NULL;
701     /* if this is a live_savem then set is_ram */
702     if (ops->save_setup != NULL) {
703         se->is_ram = 1;
704     }
705 
706     pstrcat(se->idstr, sizeof(se->idstr), idstr);
707 
708     if (instance_id == -1) {
709         se->instance_id = calculate_new_instance_id(se->idstr);
710     } else {
711         se->instance_id = instance_id;
712     }
713     assert(!se->compat || se->instance_id == 0);
714     savevm_state_handler_insert(se);
715     return 0;
716 }
717 
718 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
719 {
720     SaveStateEntry *se, *new_se;
721     char id[256] = "";
722 
723     if (dev) {
724         char *path = qdev_get_dev_path(dev);
725         if (path) {
726             pstrcpy(id, sizeof(id), path);
727             pstrcat(id, sizeof(id), "/");
728             g_free(path);
729         }
730     }
731     pstrcat(id, sizeof(id), idstr);
732 
733     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
734         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
735             QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
736             g_free(se->compat);
737             g_free(se);
738         }
739     }
740 }
741 
742 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
743                                    const VMStateDescription *vmsd,
744                                    void *opaque, int alias_id,
745                                    int required_for_version,
746                                    Error **errp)
747 {
748     SaveStateEntry *se;
749 
750     /* If this triggers, alias support can be dropped for the vmsd. */
751     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
752 
753     se = g_new0(SaveStateEntry, 1);
754     se->version_id = vmsd->version_id;
755     se->section_id = savevm_state.global_section_id++;
756     se->opaque = opaque;
757     se->vmsd = vmsd;
758     se->alias_id = alias_id;
759 
760     if (dev) {
761         char *id = qdev_get_dev_path(dev);
762         if (id) {
763             if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
764                 sizeof(se->idstr)) {
765                 error_setg(errp, "Path too long for VMState (%s)", id);
766                 g_free(id);
767                 g_free(se);
768 
769                 return -1;
770             }
771             g_free(id);
772 
773             se->compat = g_new0(CompatEntry, 1);
774             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
775             se->compat->instance_id = instance_id == -1 ?
776                          calculate_compat_instance_id(vmsd->name) : instance_id;
777             instance_id = -1;
778         }
779     }
780     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
781 
782     if (instance_id == -1) {
783         se->instance_id = calculate_new_instance_id(se->idstr);
784     } else {
785         se->instance_id = instance_id;
786     }
787     assert(!se->compat || se->instance_id == 0);
788     savevm_state_handler_insert(se);
789     return 0;
790 }
791 
792 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
793                         void *opaque)
794 {
795     SaveStateEntry *se, *new_se;
796 
797     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
798         if (se->vmsd == vmsd && se->opaque == opaque) {
799             QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
800             g_free(se->compat);
801             g_free(se);
802         }
803     }
804 }
805 
806 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
807 {
808     trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
809     if (!se->vmsd) {         /* Old style */
810         return se->ops->load_state(f, se->opaque, se->load_version_id);
811     }
812     return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
813 }
814 
815 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
816 {
817     int64_t old_offset, size;
818 
819     old_offset = qemu_ftell_fast(f);
820     se->ops->save_state(f, se->opaque);
821     size = qemu_ftell_fast(f) - old_offset;
822 
823     if (vmdesc) {
824         json_prop_int(vmdesc, "size", size);
825         json_start_array(vmdesc, "fields");
826         json_start_object(vmdesc, NULL);
827         json_prop_str(vmdesc, "name", "data");
828         json_prop_int(vmdesc, "size", size);
829         json_prop_str(vmdesc, "type", "buffer");
830         json_end_object(vmdesc);
831         json_end_array(vmdesc);
832     }
833 }
834 
835 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
836 {
837     trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
838     if (!se->vmsd) {
839         vmstate_save_old_style(f, se, vmdesc);
840         return 0;
841     }
842     return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
843 }
844 
845 /*
846  * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
847  */
848 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
849                                 uint8_t section_type)
850 {
851     qemu_put_byte(f, section_type);
852     qemu_put_be32(f, se->section_id);
853 
854     if (section_type == QEMU_VM_SECTION_FULL ||
855         section_type == QEMU_VM_SECTION_START) {
856         /* ID string */
857         size_t len = strlen(se->idstr);
858         qemu_put_byte(f, len);
859         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
860 
861         qemu_put_be32(f, se->instance_id);
862         qemu_put_be32(f, se->version_id);
863     }
864 }
865 
866 /*
867  * Write a footer onto device sections that catches cases misformatted device
868  * sections.
869  */
870 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
871 {
872     if (migrate_get_current()->send_section_footer) {
873         qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
874         qemu_put_be32(f, se->section_id);
875     }
876 }
877 
878 /**
879  * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
880  *                           command and associated data.
881  *
882  * @f: File to send command on
883  * @command: Command type to send
884  * @len: Length of associated data
885  * @data: Data associated with command.
886  */
887 static void qemu_savevm_command_send(QEMUFile *f,
888                                      enum qemu_vm_cmd command,
889                                      uint16_t len,
890                                      uint8_t *data)
891 {
892     trace_savevm_command_send(command, len);
893     qemu_put_byte(f, QEMU_VM_COMMAND);
894     qemu_put_be16(f, (uint16_t)command);
895     qemu_put_be16(f, len);
896     qemu_put_buffer(f, data, len);
897     qemu_fflush(f);
898 }
899 
900 void qemu_savevm_send_colo_enable(QEMUFile *f)
901 {
902     trace_savevm_send_colo_enable();
903     qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
904 }
905 
906 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
907 {
908     uint32_t buf;
909 
910     trace_savevm_send_ping(value);
911     buf = cpu_to_be32(value);
912     qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
913 }
914 
915 void qemu_savevm_send_open_return_path(QEMUFile *f)
916 {
917     trace_savevm_send_open_return_path();
918     qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
919 }
920 
921 /* We have a buffer of data to send; we don't want that all to be loaded
922  * by the command itself, so the command contains just the length of the
923  * extra buffer that we then send straight after it.
924  * TODO: Must be a better way to organise that
925  *
926  * Returns:
927  *    0 on success
928  *    -ve on error
929  */
930 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
931 {
932     uint32_t tmp;
933 
934     if (len > MAX_VM_CMD_PACKAGED_SIZE) {
935         error_report("%s: Unreasonably large packaged state: %zu",
936                      __func__, len);
937         return -1;
938     }
939 
940     tmp = cpu_to_be32(len);
941 
942     trace_qemu_savevm_send_packaged();
943     qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
944 
945     qemu_put_buffer(f, buf, len);
946 
947     return 0;
948 }
949 
950 /* Send prior to any postcopy transfer */
951 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
952 {
953     if (migrate_postcopy_ram()) {
954         uint64_t tmp[2];
955         tmp[0] = cpu_to_be64(ram_pagesize_summary());
956         tmp[1] = cpu_to_be64(qemu_target_page_size());
957 
958         trace_qemu_savevm_send_postcopy_advise();
959         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
960                                  16, (uint8_t *)tmp);
961     } else {
962         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
963     }
964 }
965 
966 /* Sent prior to starting the destination running in postcopy, discard pages
967  * that have already been sent but redirtied on the source.
968  * CMD_POSTCOPY_RAM_DISCARD consist of:
969  *      byte   version (0)
970  *      byte   Length of name field (not including 0)
971  *  n x byte   RAM block name
972  *      byte   0 terminator (just for safety)
973  *  n x        Byte ranges within the named RAMBlock
974  *      be64   Start of the range
975  *      be64   Length
976  *
977  *  name:  RAMBlock name that these entries are part of
978  *  len: Number of page entries
979  *  start_list: 'len' addresses
980  *  length_list: 'len' addresses
981  *
982  */
983 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
984                                            uint16_t len,
985                                            uint64_t *start_list,
986                                            uint64_t *length_list)
987 {
988     uint8_t *buf;
989     uint16_t tmplen;
990     uint16_t t;
991     size_t name_len = strlen(name);
992 
993     trace_qemu_savevm_send_postcopy_ram_discard(name, len);
994     assert(name_len < 256);
995     buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
996     buf[0] = postcopy_ram_discard_version;
997     buf[1] = name_len;
998     memcpy(buf + 2, name, name_len);
999     tmplen = 2 + name_len;
1000     buf[tmplen++] = '\0';
1001 
1002     for (t = 0; t < len; t++) {
1003         stq_be_p(buf + tmplen, start_list[t]);
1004         tmplen += 8;
1005         stq_be_p(buf + tmplen, length_list[t]);
1006         tmplen += 8;
1007     }
1008     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1009     g_free(buf);
1010 }
1011 
1012 /* Get the destination into a state where it can receive postcopy data. */
1013 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1014 {
1015     trace_savevm_send_postcopy_listen();
1016     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1017 }
1018 
1019 /* Kick the destination into running */
1020 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1021 {
1022     trace_savevm_send_postcopy_run();
1023     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1024 }
1025 
1026 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1027 {
1028     trace_savevm_send_postcopy_resume();
1029     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1030 }
1031 
1032 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1033 {
1034     size_t len;
1035     char buf[256];
1036 
1037     trace_savevm_send_recv_bitmap(block_name);
1038 
1039     buf[0] = len = strlen(block_name);
1040     memcpy(buf + 1, block_name, len);
1041 
1042     qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1043 }
1044 
1045 bool qemu_savevm_state_blocked(Error **errp)
1046 {
1047     SaveStateEntry *se;
1048 
1049     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1050         if (se->vmsd && se->vmsd->unmigratable) {
1051             error_setg(errp, "State blocked by non-migratable device '%s'",
1052                        se->idstr);
1053             return true;
1054         }
1055     }
1056     return false;
1057 }
1058 
1059 void qemu_savevm_state_header(QEMUFile *f)
1060 {
1061     trace_savevm_state_header();
1062     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1063     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1064 
1065     if (migrate_get_current()->send_configuration) {
1066         qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1067         vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1068     }
1069 }
1070 
1071 void qemu_savevm_state_setup(QEMUFile *f)
1072 {
1073     SaveStateEntry *se;
1074     Error *local_err = NULL;
1075     int ret;
1076 
1077     trace_savevm_state_setup();
1078     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1079         if (!se->ops || !se->ops->save_setup) {
1080             continue;
1081         }
1082         if (se->ops->is_active) {
1083             if (!se->ops->is_active(se->opaque)) {
1084                 continue;
1085             }
1086         }
1087         save_section_header(f, se, QEMU_VM_SECTION_START);
1088 
1089         ret = se->ops->save_setup(f, se->opaque);
1090         save_section_footer(f, se);
1091         if (ret < 0) {
1092             qemu_file_set_error(f, ret);
1093             break;
1094         }
1095     }
1096 
1097     if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1098         error_report_err(local_err);
1099     }
1100 }
1101 
1102 int qemu_savevm_state_resume_prepare(MigrationState *s)
1103 {
1104     SaveStateEntry *se;
1105     int ret;
1106 
1107     trace_savevm_state_resume_prepare();
1108 
1109     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1110         if (!se->ops || !se->ops->resume_prepare) {
1111             continue;
1112         }
1113         if (se->ops->is_active) {
1114             if (!se->ops->is_active(se->opaque)) {
1115                 continue;
1116             }
1117         }
1118         ret = se->ops->resume_prepare(s, se->opaque);
1119         if (ret < 0) {
1120             return ret;
1121         }
1122     }
1123 
1124     return 0;
1125 }
1126 
1127 /*
1128  * this function has three return values:
1129  *   negative: there was one error, and we have -errno.
1130  *   0 : We haven't finished, caller have to go again
1131  *   1 : We have finished, we can go to complete phase
1132  */
1133 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1134 {
1135     SaveStateEntry *se;
1136     int ret = 1;
1137 
1138     trace_savevm_state_iterate();
1139     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1140         if (!se->ops || !se->ops->save_live_iterate) {
1141             continue;
1142         }
1143         if (se->ops->is_active &&
1144             !se->ops->is_active(se->opaque)) {
1145             continue;
1146         }
1147         if (se->ops->is_active_iterate &&
1148             !se->ops->is_active_iterate(se->opaque)) {
1149             continue;
1150         }
1151         /*
1152          * In the postcopy phase, any device that doesn't know how to
1153          * do postcopy should have saved it's state in the _complete
1154          * call that's already run, it might get confused if we call
1155          * iterate afterwards.
1156          */
1157         if (postcopy &&
1158             !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1159             continue;
1160         }
1161         if (qemu_file_rate_limit(f)) {
1162             return 0;
1163         }
1164         trace_savevm_section_start(se->idstr, se->section_id);
1165 
1166         save_section_header(f, se, QEMU_VM_SECTION_PART);
1167 
1168         ret = se->ops->save_live_iterate(f, se->opaque);
1169         trace_savevm_section_end(se->idstr, se->section_id, ret);
1170         save_section_footer(f, se);
1171 
1172         if (ret < 0) {
1173             qemu_file_set_error(f, ret);
1174         }
1175         if (ret <= 0) {
1176             /* Do not proceed to the next vmstate before this one reported
1177                completion of the current stage. This serializes the migration
1178                and reduces the probability that a faster changing state is
1179                synchronized over and over again. */
1180             break;
1181         }
1182     }
1183     return ret;
1184 }
1185 
1186 static bool should_send_vmdesc(void)
1187 {
1188     MachineState *machine = MACHINE(qdev_get_machine());
1189     bool in_postcopy = migration_in_postcopy();
1190     return !machine->suppress_vmdesc && !in_postcopy;
1191 }
1192 
1193 /*
1194  * Calls the save_live_complete_postcopy methods
1195  * causing the last few pages to be sent immediately and doing any associated
1196  * cleanup.
1197  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1198  * all the other devices, but that happens at the point we switch to postcopy.
1199  */
1200 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1201 {
1202     SaveStateEntry *se;
1203     int ret;
1204 
1205     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1206         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1207             continue;
1208         }
1209         if (se->ops->is_active) {
1210             if (!se->ops->is_active(se->opaque)) {
1211                 continue;
1212             }
1213         }
1214         trace_savevm_section_start(se->idstr, se->section_id);
1215         /* Section type */
1216         qemu_put_byte(f, QEMU_VM_SECTION_END);
1217         qemu_put_be32(f, se->section_id);
1218 
1219         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1220         trace_savevm_section_end(se->idstr, se->section_id, ret);
1221         save_section_footer(f, se);
1222         if (ret < 0) {
1223             qemu_file_set_error(f, ret);
1224             return;
1225         }
1226     }
1227 
1228     qemu_put_byte(f, QEMU_VM_EOF);
1229     qemu_fflush(f);
1230 }
1231 
1232 static
1233 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1234 {
1235     SaveStateEntry *se;
1236     int ret;
1237 
1238     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1239         if (!se->ops ||
1240             (in_postcopy && se->ops->has_postcopy &&
1241              se->ops->has_postcopy(se->opaque)) ||
1242             !se->ops->save_live_complete_precopy) {
1243             continue;
1244         }
1245 
1246         if (se->ops->is_active) {
1247             if (!se->ops->is_active(se->opaque)) {
1248                 continue;
1249             }
1250         }
1251         trace_savevm_section_start(se->idstr, se->section_id);
1252 
1253         save_section_header(f, se, QEMU_VM_SECTION_END);
1254 
1255         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1256         trace_savevm_section_end(se->idstr, se->section_id, ret);
1257         save_section_footer(f, se);
1258         if (ret < 0) {
1259             qemu_file_set_error(f, ret);
1260             return -1;
1261         }
1262     }
1263 
1264     return 0;
1265 }
1266 
1267 static
1268 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1269                                                     bool in_postcopy,
1270                                                     bool inactivate_disks)
1271 {
1272     QJSON *vmdesc;
1273     int vmdesc_len;
1274     SaveStateEntry *se;
1275     int ret;
1276 
1277     vmdesc = qjson_new();
1278     json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1279     json_start_array(vmdesc, "devices");
1280     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1281 
1282         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1283             continue;
1284         }
1285         if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1286             trace_savevm_section_skip(se->idstr, se->section_id);
1287             continue;
1288         }
1289 
1290         trace_savevm_section_start(se->idstr, se->section_id);
1291 
1292         json_start_object(vmdesc, NULL);
1293         json_prop_str(vmdesc, "name", se->idstr);
1294         json_prop_int(vmdesc, "instance_id", se->instance_id);
1295 
1296         save_section_header(f, se, QEMU_VM_SECTION_FULL);
1297         ret = vmstate_save(f, se, vmdesc);
1298         if (ret) {
1299             qemu_file_set_error(f, ret);
1300             return ret;
1301         }
1302         trace_savevm_section_end(se->idstr, se->section_id, 0);
1303         save_section_footer(f, se);
1304 
1305         json_end_object(vmdesc);
1306     }
1307 
1308     if (inactivate_disks) {
1309         /* Inactivate before sending QEMU_VM_EOF so that the
1310          * bdrv_invalidate_cache_all() on the other end won't fail. */
1311         ret = bdrv_inactivate_all();
1312         if (ret) {
1313             error_report("%s: bdrv_inactivate_all() failed (%d)",
1314                          __func__, ret);
1315             qemu_file_set_error(f, ret);
1316             return ret;
1317         }
1318     }
1319     if (!in_postcopy) {
1320         /* Postcopy stream will still be going */
1321         qemu_put_byte(f, QEMU_VM_EOF);
1322     }
1323 
1324     json_end_array(vmdesc);
1325     qjson_finish(vmdesc);
1326     vmdesc_len = strlen(qjson_get_str(vmdesc));
1327 
1328     if (should_send_vmdesc()) {
1329         qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1330         qemu_put_be32(f, vmdesc_len);
1331         qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1332     }
1333     qjson_destroy(vmdesc);
1334 
1335     return 0;
1336 }
1337 
1338 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1339                                        bool inactivate_disks)
1340 {
1341     int ret;
1342     Error *local_err = NULL;
1343     bool in_postcopy = migration_in_postcopy();
1344 
1345     if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1346         error_report_err(local_err);
1347     }
1348 
1349     trace_savevm_state_complete_precopy();
1350 
1351     cpu_synchronize_all_states();
1352 
1353     if (!in_postcopy || iterable_only) {
1354         ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1355         if (ret) {
1356             return ret;
1357         }
1358     }
1359 
1360     if (iterable_only) {
1361         goto flush;
1362     }
1363 
1364     ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1365                                                           inactivate_disks);
1366     if (ret) {
1367         return ret;
1368     }
1369 
1370 flush:
1371     qemu_fflush(f);
1372     return 0;
1373 }
1374 
1375 /* Give an estimate of the amount left to be transferred,
1376  * the result is split into the amount for units that can and
1377  * for units that can't do postcopy.
1378  */
1379 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1380                                uint64_t *res_precopy_only,
1381                                uint64_t *res_compatible,
1382                                uint64_t *res_postcopy_only)
1383 {
1384     SaveStateEntry *se;
1385 
1386     *res_precopy_only = 0;
1387     *res_compatible = 0;
1388     *res_postcopy_only = 0;
1389 
1390 
1391     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1392         if (!se->ops || !se->ops->save_live_pending) {
1393             continue;
1394         }
1395         if (se->ops->is_active) {
1396             if (!se->ops->is_active(se->opaque)) {
1397                 continue;
1398             }
1399         }
1400         se->ops->save_live_pending(f, se->opaque, threshold_size,
1401                                    res_precopy_only, res_compatible,
1402                                    res_postcopy_only);
1403     }
1404 }
1405 
1406 void qemu_savevm_state_cleanup(void)
1407 {
1408     SaveStateEntry *se;
1409     Error *local_err = NULL;
1410 
1411     if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1412         error_report_err(local_err);
1413     }
1414 
1415     trace_savevm_state_cleanup();
1416     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1417         if (se->ops && se->ops->save_cleanup) {
1418             se->ops->save_cleanup(se->opaque);
1419         }
1420     }
1421 }
1422 
1423 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1424 {
1425     int ret;
1426     MigrationState *ms = migrate_get_current();
1427     MigrationStatus status;
1428 
1429     if (migration_is_setup_or_active(ms->state) ||
1430         ms->state == MIGRATION_STATUS_CANCELLING ||
1431         ms->state == MIGRATION_STATUS_COLO) {
1432         error_setg(errp, QERR_MIGRATION_ACTIVE);
1433         return -EINVAL;
1434     }
1435 
1436     if (migrate_use_block()) {
1437         error_setg(errp, "Block migration and snapshots are incompatible");
1438         return -EINVAL;
1439     }
1440 
1441     migrate_init(ms);
1442     memset(&ram_counters, 0, sizeof(ram_counters));
1443     ms->to_dst_file = f;
1444 
1445     qemu_mutex_unlock_iothread();
1446     qemu_savevm_state_header(f);
1447     qemu_savevm_state_setup(f);
1448     qemu_mutex_lock_iothread();
1449 
1450     while (qemu_file_get_error(f) == 0) {
1451         if (qemu_savevm_state_iterate(f, false) > 0) {
1452             break;
1453         }
1454     }
1455 
1456     ret = qemu_file_get_error(f);
1457     if (ret == 0) {
1458         qemu_savevm_state_complete_precopy(f, false, false);
1459         ret = qemu_file_get_error(f);
1460     }
1461     qemu_savevm_state_cleanup();
1462     if (ret != 0) {
1463         error_setg_errno(errp, -ret, "Error while writing VM state");
1464     }
1465 
1466     if (ret != 0) {
1467         status = MIGRATION_STATUS_FAILED;
1468     } else {
1469         status = MIGRATION_STATUS_COMPLETED;
1470     }
1471     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1472 
1473     /* f is outer parameter, it should not stay in global migration state after
1474      * this function finished */
1475     ms->to_dst_file = NULL;
1476 
1477     return ret;
1478 }
1479 
1480 void qemu_savevm_live_state(QEMUFile *f)
1481 {
1482     /* save QEMU_VM_SECTION_END section */
1483     qemu_savevm_state_complete_precopy(f, true, false);
1484     qemu_put_byte(f, QEMU_VM_EOF);
1485 }
1486 
1487 int qemu_save_device_state(QEMUFile *f)
1488 {
1489     SaveStateEntry *se;
1490 
1491     if (!migration_in_colo_state()) {
1492         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1493         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1494     }
1495     cpu_synchronize_all_states();
1496 
1497     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1498         int ret;
1499 
1500         if (se->is_ram) {
1501             continue;
1502         }
1503         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1504             continue;
1505         }
1506         if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1507             continue;
1508         }
1509 
1510         save_section_header(f, se, QEMU_VM_SECTION_FULL);
1511 
1512         ret = vmstate_save(f, se, NULL);
1513         if (ret) {
1514             return ret;
1515         }
1516 
1517         save_section_footer(f, se);
1518     }
1519 
1520     qemu_put_byte(f, QEMU_VM_EOF);
1521 
1522     return qemu_file_get_error(f);
1523 }
1524 
1525 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1526 {
1527     SaveStateEntry *se;
1528 
1529     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1530         if (!strcmp(se->idstr, idstr) &&
1531             (instance_id == se->instance_id ||
1532              instance_id == se->alias_id))
1533             return se;
1534         /* Migrating from an older version? */
1535         if (strstr(se->idstr, idstr) && se->compat) {
1536             if (!strcmp(se->compat->idstr, idstr) &&
1537                 (instance_id == se->compat->instance_id ||
1538                  instance_id == se->alias_id))
1539                 return se;
1540         }
1541     }
1542     return NULL;
1543 }
1544 
1545 enum LoadVMExitCodes {
1546     /* Allow a command to quit all layers of nested loadvm loops */
1547     LOADVM_QUIT     =  1,
1548 };
1549 
1550 /* ------ incoming postcopy messages ------ */
1551 /* 'advise' arrives before any transfers just to tell us that a postcopy
1552  * *might* happen - it might be skipped if precopy transferred everything
1553  * quickly.
1554  */
1555 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1556                                          uint16_t len)
1557 {
1558     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1559     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1560     Error *local_err = NULL;
1561 
1562     trace_loadvm_postcopy_handle_advise();
1563     if (ps != POSTCOPY_INCOMING_NONE) {
1564         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1565         return -1;
1566     }
1567 
1568     switch (len) {
1569     case 0:
1570         if (migrate_postcopy_ram()) {
1571             error_report("RAM postcopy is enabled but have 0 byte advise");
1572             return -EINVAL;
1573         }
1574         return 0;
1575     case 8 + 8:
1576         if (!migrate_postcopy_ram()) {
1577             error_report("RAM postcopy is disabled but have 16 byte advise");
1578             return -EINVAL;
1579         }
1580         break;
1581     default:
1582         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1583         return -EINVAL;
1584     }
1585 
1586     if (!postcopy_ram_supported_by_host(mis)) {
1587         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1588         return -1;
1589     }
1590 
1591     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1592     local_pagesize_summary = ram_pagesize_summary();
1593 
1594     if (remote_pagesize_summary != local_pagesize_summary)  {
1595         /*
1596          * This detects two potential causes of mismatch:
1597          *   a) A mismatch in host page sizes
1598          *      Some combinations of mismatch are probably possible but it gets
1599          *      a bit more complicated.  In particular we need to place whole
1600          *      host pages on the dest at once, and we need to ensure that we
1601          *      handle dirtying to make sure we never end up sending part of
1602          *      a hostpage on it's own.
1603          *   b) The use of different huge page sizes on source/destination
1604          *      a more fine grain test is performed during RAM block migration
1605          *      but this test here causes a nice early clear failure, and
1606          *      also fails when passed to an older qemu that doesn't
1607          *      do huge pages.
1608          */
1609         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1610                                                              " d=%" PRIx64 ")",
1611                      remote_pagesize_summary, local_pagesize_summary);
1612         return -1;
1613     }
1614 
1615     remote_tps = qemu_get_be64(mis->from_src_file);
1616     if (remote_tps != qemu_target_page_size()) {
1617         /*
1618          * Again, some differences could be dealt with, but for now keep it
1619          * simple.
1620          */
1621         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1622                      (int)remote_tps, qemu_target_page_size());
1623         return -1;
1624     }
1625 
1626     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1627         error_report_err(local_err);
1628         return -1;
1629     }
1630 
1631     if (ram_postcopy_incoming_init(mis)) {
1632         return -1;
1633     }
1634 
1635     return 0;
1636 }
1637 
1638 /* After postcopy we will be told to throw some pages away since they're
1639  * dirty and will have to be demand fetched.  Must happen before CPU is
1640  * started.
1641  * There can be 0..many of these messages, each encoding multiple pages.
1642  */
1643 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1644                                               uint16_t len)
1645 {
1646     int tmp;
1647     char ramid[256];
1648     PostcopyState ps = postcopy_state_get();
1649 
1650     trace_loadvm_postcopy_ram_handle_discard();
1651 
1652     switch (ps) {
1653     case POSTCOPY_INCOMING_ADVISE:
1654         /* 1st discard */
1655         tmp = postcopy_ram_prepare_discard(mis);
1656         if (tmp) {
1657             return tmp;
1658         }
1659         break;
1660 
1661     case POSTCOPY_INCOMING_DISCARD:
1662         /* Expected state */
1663         break;
1664 
1665     default:
1666         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1667                      ps);
1668         return -1;
1669     }
1670     /* We're expecting a
1671      *    Version (0)
1672      *    a RAM ID string (length byte, name, 0 term)
1673      *    then at least 1 16 byte chunk
1674     */
1675     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1676         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1677         return -1;
1678     }
1679 
1680     tmp = qemu_get_byte(mis->from_src_file);
1681     if (tmp != postcopy_ram_discard_version) {
1682         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1683         return -1;
1684     }
1685 
1686     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1687         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1688         return -1;
1689     }
1690     tmp = qemu_get_byte(mis->from_src_file);
1691     if (tmp != 0) {
1692         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1693         return -1;
1694     }
1695 
1696     len -= 3 + strlen(ramid);
1697     if (len % 16) {
1698         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1699         return -1;
1700     }
1701     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1702     while (len) {
1703         uint64_t start_addr, block_length;
1704         start_addr = qemu_get_be64(mis->from_src_file);
1705         block_length = qemu_get_be64(mis->from_src_file);
1706 
1707         len -= 16;
1708         int ret = ram_discard_range(ramid, start_addr, block_length);
1709         if (ret) {
1710             return ret;
1711         }
1712     }
1713     trace_loadvm_postcopy_ram_handle_discard_end();
1714 
1715     return 0;
1716 }
1717 
1718 /*
1719  * Triggered by a postcopy_listen command; this thread takes over reading
1720  * the input stream, leaving the main thread free to carry on loading the rest
1721  * of the device state (from RAM).
1722  * (TODO:This could do with being in a postcopy file - but there again it's
1723  * just another input loop, not that postcopy specific)
1724  */
1725 static void *postcopy_ram_listen_thread(void *opaque)
1726 {
1727     MigrationIncomingState *mis = migration_incoming_get_current();
1728     QEMUFile *f = mis->from_src_file;
1729     int load_res;
1730 
1731     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1732                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
1733     qemu_sem_post(&mis->listen_thread_sem);
1734     trace_postcopy_ram_listen_thread_start();
1735 
1736     rcu_register_thread();
1737     /*
1738      * Because we're a thread and not a coroutine we can't yield
1739      * in qemu_file, and thus we must be blocking now.
1740      */
1741     qemu_file_set_blocking(f, true);
1742     load_res = qemu_loadvm_state_main(f, mis);
1743 
1744     /*
1745      * This is tricky, but, mis->from_src_file can change after it
1746      * returns, when postcopy recovery happened. In the future, we may
1747      * want a wrapper for the QEMUFile handle.
1748      */
1749     f = mis->from_src_file;
1750 
1751     /* And non-blocking again so we don't block in any cleanup */
1752     qemu_file_set_blocking(f, false);
1753 
1754     trace_postcopy_ram_listen_thread_exit();
1755     if (load_res < 0) {
1756         error_report("%s: loadvm failed: %d", __func__, load_res);
1757         qemu_file_set_error(f, load_res);
1758         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1759                                        MIGRATION_STATUS_FAILED);
1760     } else {
1761         /*
1762          * This looks good, but it's possible that the device loading in the
1763          * main thread hasn't finished yet, and so we might not be in 'RUN'
1764          * state yet; wait for the end of the main thread.
1765          */
1766         qemu_event_wait(&mis->main_thread_load_event);
1767     }
1768     postcopy_ram_incoming_cleanup(mis);
1769 
1770     if (load_res < 0) {
1771         /*
1772          * If something went wrong then we have a bad state so exit;
1773          * depending how far we got it might be possible at this point
1774          * to leave the guest running and fire MCEs for pages that never
1775          * arrived as a desperate recovery step.
1776          */
1777         rcu_unregister_thread();
1778         exit(EXIT_FAILURE);
1779     }
1780 
1781     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1782                                    MIGRATION_STATUS_COMPLETED);
1783     /*
1784      * If everything has worked fine, then the main thread has waited
1785      * for us to start, and we're the last use of the mis.
1786      * (If something broke then qemu will have to exit anyway since it's
1787      * got a bad migration state).
1788      */
1789     migration_incoming_state_destroy();
1790     qemu_loadvm_state_cleanup();
1791 
1792     rcu_unregister_thread();
1793     mis->have_listen_thread = false;
1794     return NULL;
1795 }
1796 
1797 /* After this message we must be able to immediately receive postcopy data */
1798 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1799 {
1800     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1801     trace_loadvm_postcopy_handle_listen();
1802     Error *local_err = NULL;
1803 
1804     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1805         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1806         return -1;
1807     }
1808     if (ps == POSTCOPY_INCOMING_ADVISE) {
1809         /*
1810          * A rare case, we entered listen without having to do any discards,
1811          * so do the setup that's normally done at the time of the 1st discard.
1812          */
1813         if (migrate_postcopy_ram()) {
1814             postcopy_ram_prepare_discard(mis);
1815         }
1816     }
1817 
1818     /*
1819      * Sensitise RAM - can now generate requests for blocks that don't exist
1820      * However, at this point the CPU shouldn't be running, and the IO
1821      * shouldn't be doing anything yet so don't actually expect requests
1822      */
1823     if (migrate_postcopy_ram()) {
1824         if (postcopy_ram_enable_notify(mis)) {
1825             postcopy_ram_incoming_cleanup(mis);
1826             return -1;
1827         }
1828     }
1829 
1830     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1831         error_report_err(local_err);
1832         return -1;
1833     }
1834 
1835     if (mis->have_listen_thread) {
1836         error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1837         return -1;
1838     }
1839 
1840     mis->have_listen_thread = true;
1841     /* Start up the listening thread and wait for it to signal ready */
1842     qemu_sem_init(&mis->listen_thread_sem, 0);
1843     qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1844                        postcopy_ram_listen_thread, NULL,
1845                        QEMU_THREAD_DETACHED);
1846     qemu_sem_wait(&mis->listen_thread_sem);
1847     qemu_sem_destroy(&mis->listen_thread_sem);
1848 
1849     return 0;
1850 }
1851 
1852 static void loadvm_postcopy_handle_run_bh(void *opaque)
1853 {
1854     Error *local_err = NULL;
1855     MigrationIncomingState *mis = opaque;
1856 
1857     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1858      * in migration.c
1859      */
1860     cpu_synchronize_all_post_init();
1861 
1862     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
1863 
1864     /* Make sure all file formats flush their mutable metadata.
1865      * If we get an error here, just don't restart the VM yet. */
1866     bdrv_invalidate_cache_all(&local_err);
1867     if (local_err) {
1868         error_report_err(local_err);
1869         local_err = NULL;
1870         autostart = false;
1871     }
1872 
1873     trace_loadvm_postcopy_handle_run_cpu_sync();
1874 
1875     trace_loadvm_postcopy_handle_run_vmstart();
1876 
1877     dirty_bitmap_mig_before_vm_start();
1878 
1879     if (autostart) {
1880         /* Hold onto your hats, starting the CPU */
1881         vm_start();
1882     } else {
1883         /* leave it paused and let management decide when to start the CPU */
1884         runstate_set(RUN_STATE_PAUSED);
1885     }
1886 
1887     qemu_bh_delete(mis->bh);
1888 }
1889 
1890 /* After all discards we can start running and asking for pages */
1891 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1892 {
1893     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1894 
1895     trace_loadvm_postcopy_handle_run();
1896     if (ps != POSTCOPY_INCOMING_LISTENING) {
1897         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1898         return -1;
1899     }
1900 
1901     mis->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, mis);
1902     qemu_bh_schedule(mis->bh);
1903 
1904     /* We need to finish reading the stream from the package
1905      * and also stop reading anything more from the stream that loaded the
1906      * package (since it's now being read by the listener thread).
1907      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1908      */
1909     return LOADVM_QUIT;
1910 }
1911 
1912 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
1913 {
1914     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
1915         error_report("%s: illegal resume received", __func__);
1916         /* Don't fail the load, only for this. */
1917         return 0;
1918     }
1919 
1920     /*
1921      * This means source VM is ready to resume the postcopy migration.
1922      * It's time to switch state and release the fault thread to
1923      * continue service page faults.
1924      */
1925     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1926                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
1927     qemu_sem_post(&mis->postcopy_pause_sem_fault);
1928 
1929     trace_loadvm_postcopy_handle_resume();
1930 
1931     /* Tell source that "we are ready" */
1932     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
1933 
1934     return 0;
1935 }
1936 
1937 /**
1938  * Immediately following this command is a blob of data containing an embedded
1939  * chunk of migration stream; read it and load it.
1940  *
1941  * @mis: Incoming state
1942  * @length: Length of packaged data to read
1943  *
1944  * Returns: Negative values on error
1945  *
1946  */
1947 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1948 {
1949     int ret;
1950     size_t length;
1951     QIOChannelBuffer *bioc;
1952 
1953     length = qemu_get_be32(mis->from_src_file);
1954     trace_loadvm_handle_cmd_packaged(length);
1955 
1956     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1957         error_report("Unreasonably large packaged state: %zu", length);
1958         return -1;
1959     }
1960 
1961     bioc = qio_channel_buffer_new(length);
1962     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1963     ret = qemu_get_buffer(mis->from_src_file,
1964                           bioc->data,
1965                           length);
1966     if (ret != length) {
1967         object_unref(OBJECT(bioc));
1968         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1969                      ret, length);
1970         return (ret < 0) ? ret : -EAGAIN;
1971     }
1972     bioc->usage += length;
1973     trace_loadvm_handle_cmd_packaged_received(ret);
1974 
1975     QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1976 
1977     ret = qemu_loadvm_state_main(packf, mis);
1978     trace_loadvm_handle_cmd_packaged_main(ret);
1979     qemu_fclose(packf);
1980     object_unref(OBJECT(bioc));
1981 
1982     return ret;
1983 }
1984 
1985 /*
1986  * Handle request that source requests for recved_bitmap on
1987  * destination. Payload format:
1988  *
1989  * len (1 byte) + ramblock_name (<255 bytes)
1990  */
1991 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
1992                                      uint16_t len)
1993 {
1994     QEMUFile *file = mis->from_src_file;
1995     RAMBlock *rb;
1996     char block_name[256];
1997     size_t cnt;
1998 
1999     cnt = qemu_get_counted_string(file, block_name);
2000     if (!cnt) {
2001         error_report("%s: failed to read block name", __func__);
2002         return -EINVAL;
2003     }
2004 
2005     /* Validate before using the data */
2006     if (qemu_file_get_error(file)) {
2007         return qemu_file_get_error(file);
2008     }
2009 
2010     if (len != cnt + 1) {
2011         error_report("%s: invalid payload length (%d)", __func__, len);
2012         return -EINVAL;
2013     }
2014 
2015     rb = qemu_ram_block_by_name(block_name);
2016     if (!rb) {
2017         error_report("%s: block '%s' not found", __func__, block_name);
2018         return -EINVAL;
2019     }
2020 
2021     migrate_send_rp_recv_bitmap(mis, block_name);
2022 
2023     trace_loadvm_handle_recv_bitmap(block_name);
2024 
2025     return 0;
2026 }
2027 
2028 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2029 {
2030     migration_incoming_enable_colo();
2031     return colo_init_ram_cache();
2032 }
2033 
2034 /*
2035  * Process an incoming 'QEMU_VM_COMMAND'
2036  * 0           just a normal return
2037  * LOADVM_QUIT All good, but exit the loop
2038  * <0          Error
2039  */
2040 static int loadvm_process_command(QEMUFile *f)
2041 {
2042     MigrationIncomingState *mis = migration_incoming_get_current();
2043     uint16_t cmd;
2044     uint16_t len;
2045     uint32_t tmp32;
2046 
2047     cmd = qemu_get_be16(f);
2048     len = qemu_get_be16(f);
2049 
2050     /* Check validity before continue processing of cmds */
2051     if (qemu_file_get_error(f)) {
2052         return qemu_file_get_error(f);
2053     }
2054 
2055     trace_loadvm_process_command(cmd, len);
2056     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2057         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2058         return -EINVAL;
2059     }
2060 
2061     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2062         error_report("%s received with bad length - expecting %zu, got %d",
2063                      mig_cmd_args[cmd].name,
2064                      (size_t)mig_cmd_args[cmd].len, len);
2065         return -ERANGE;
2066     }
2067 
2068     switch (cmd) {
2069     case MIG_CMD_OPEN_RETURN_PATH:
2070         if (mis->to_src_file) {
2071             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2072             /* Not really a problem, so don't give up */
2073             return 0;
2074         }
2075         mis->to_src_file = qemu_file_get_return_path(f);
2076         if (!mis->to_src_file) {
2077             error_report("CMD_OPEN_RETURN_PATH failed");
2078             return -1;
2079         }
2080         break;
2081 
2082     case MIG_CMD_PING:
2083         tmp32 = qemu_get_be32(f);
2084         trace_loadvm_process_command_ping(tmp32);
2085         if (!mis->to_src_file) {
2086             error_report("CMD_PING (0x%x) received with no return path",
2087                          tmp32);
2088             return -1;
2089         }
2090         migrate_send_rp_pong(mis, tmp32);
2091         break;
2092 
2093     case MIG_CMD_PACKAGED:
2094         return loadvm_handle_cmd_packaged(mis);
2095 
2096     case MIG_CMD_POSTCOPY_ADVISE:
2097         return loadvm_postcopy_handle_advise(mis, len);
2098 
2099     case MIG_CMD_POSTCOPY_LISTEN:
2100         return loadvm_postcopy_handle_listen(mis);
2101 
2102     case MIG_CMD_POSTCOPY_RUN:
2103         return loadvm_postcopy_handle_run(mis);
2104 
2105     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2106         return loadvm_postcopy_ram_handle_discard(mis, len);
2107 
2108     case MIG_CMD_POSTCOPY_RESUME:
2109         return loadvm_postcopy_handle_resume(mis);
2110 
2111     case MIG_CMD_RECV_BITMAP:
2112         return loadvm_handle_recv_bitmap(mis, len);
2113 
2114     case MIG_CMD_ENABLE_COLO:
2115         return loadvm_process_enable_colo(mis);
2116     }
2117 
2118     return 0;
2119 }
2120 
2121 /*
2122  * Read a footer off the wire and check that it matches the expected section
2123  *
2124  * Returns: true if the footer was good
2125  *          false if there is a problem (and calls error_report to say why)
2126  */
2127 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2128 {
2129     int ret;
2130     uint8_t read_mark;
2131     uint32_t read_section_id;
2132 
2133     if (!migrate_get_current()->send_section_footer) {
2134         /* No footer to check */
2135         return true;
2136     }
2137 
2138     read_mark = qemu_get_byte(f);
2139 
2140     ret = qemu_file_get_error(f);
2141     if (ret) {
2142         error_report("%s: Read section footer failed: %d",
2143                      __func__, ret);
2144         return false;
2145     }
2146 
2147     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2148         error_report("Missing section footer for %s", se->idstr);
2149         return false;
2150     }
2151 
2152     read_section_id = qemu_get_be32(f);
2153     if (read_section_id != se->load_section_id) {
2154         error_report("Mismatched section id in footer for %s -"
2155                      " read 0x%x expected 0x%x",
2156                      se->idstr, read_section_id, se->load_section_id);
2157         return false;
2158     }
2159 
2160     /* All good */
2161     return true;
2162 }
2163 
2164 static int
2165 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2166 {
2167     uint32_t instance_id, version_id, section_id;
2168     SaveStateEntry *se;
2169     char idstr[256];
2170     int ret;
2171 
2172     /* Read section start */
2173     section_id = qemu_get_be32(f);
2174     if (!qemu_get_counted_string(f, idstr)) {
2175         error_report("Unable to read ID string for section %u",
2176                      section_id);
2177         return -EINVAL;
2178     }
2179     instance_id = qemu_get_be32(f);
2180     version_id = qemu_get_be32(f);
2181 
2182     ret = qemu_file_get_error(f);
2183     if (ret) {
2184         error_report("%s: Failed to read instance/version ID: %d",
2185                      __func__, ret);
2186         return ret;
2187     }
2188 
2189     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2190             instance_id, version_id);
2191     /* Find savevm section */
2192     se = find_se(idstr, instance_id);
2193     if (se == NULL) {
2194         error_report("Unknown savevm section or instance '%s' %d. "
2195                      "Make sure that your current VM setup matches your "
2196                      "saved VM setup, including any hotplugged devices",
2197                      idstr, instance_id);
2198         return -EINVAL;
2199     }
2200 
2201     /* Validate version */
2202     if (version_id > se->version_id) {
2203         error_report("savevm: unsupported version %d for '%s' v%d",
2204                      version_id, idstr, se->version_id);
2205         return -EINVAL;
2206     }
2207     se->load_version_id = version_id;
2208     se->load_section_id = section_id;
2209 
2210     /* Validate if it is a device's state */
2211     if (xen_enabled() && se->is_ram) {
2212         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2213         return -EINVAL;
2214     }
2215 
2216     ret = vmstate_load(f, se);
2217     if (ret < 0) {
2218         error_report("error while loading state for instance 0x%x of"
2219                      " device '%s'", instance_id, idstr);
2220         return ret;
2221     }
2222     if (!check_section_footer(f, se)) {
2223         return -EINVAL;
2224     }
2225 
2226     return 0;
2227 }
2228 
2229 static int
2230 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2231 {
2232     uint32_t section_id;
2233     SaveStateEntry *se;
2234     int ret;
2235 
2236     section_id = qemu_get_be32(f);
2237 
2238     ret = qemu_file_get_error(f);
2239     if (ret) {
2240         error_report("%s: Failed to read section ID: %d",
2241                      __func__, ret);
2242         return ret;
2243     }
2244 
2245     trace_qemu_loadvm_state_section_partend(section_id);
2246     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2247         if (se->load_section_id == section_id) {
2248             break;
2249         }
2250     }
2251     if (se == NULL) {
2252         error_report("Unknown savevm section %d", section_id);
2253         return -EINVAL;
2254     }
2255 
2256     ret = vmstate_load(f, se);
2257     if (ret < 0) {
2258         error_report("error while loading state section id %d(%s)",
2259                      section_id, se->idstr);
2260         return ret;
2261     }
2262     if (!check_section_footer(f, se)) {
2263         return -EINVAL;
2264     }
2265 
2266     return 0;
2267 }
2268 
2269 static int qemu_loadvm_state_header(QEMUFile *f)
2270 {
2271     unsigned int v;
2272     int ret;
2273 
2274     v = qemu_get_be32(f);
2275     if (v != QEMU_VM_FILE_MAGIC) {
2276         error_report("Not a migration stream");
2277         return -EINVAL;
2278     }
2279 
2280     v = qemu_get_be32(f);
2281     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2282         error_report("SaveVM v2 format is obsolete and don't work anymore");
2283         return -ENOTSUP;
2284     }
2285     if (v != QEMU_VM_FILE_VERSION) {
2286         error_report("Unsupported migration stream version");
2287         return -ENOTSUP;
2288     }
2289 
2290     if (migrate_get_current()->send_configuration) {
2291         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2292             error_report("Configuration section missing");
2293             qemu_loadvm_state_cleanup();
2294             return -EINVAL;
2295         }
2296         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2297 
2298         if (ret) {
2299             qemu_loadvm_state_cleanup();
2300             return ret;
2301         }
2302     }
2303     return 0;
2304 }
2305 
2306 static int qemu_loadvm_state_setup(QEMUFile *f)
2307 {
2308     SaveStateEntry *se;
2309     int ret;
2310 
2311     trace_loadvm_state_setup();
2312     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2313         if (!se->ops || !se->ops->load_setup) {
2314             continue;
2315         }
2316         if (se->ops->is_active) {
2317             if (!se->ops->is_active(se->opaque)) {
2318                 continue;
2319             }
2320         }
2321 
2322         ret = se->ops->load_setup(f, se->opaque);
2323         if (ret < 0) {
2324             qemu_file_set_error(f, ret);
2325             error_report("Load state of device %s failed", se->idstr);
2326             return ret;
2327         }
2328     }
2329     return 0;
2330 }
2331 
2332 void qemu_loadvm_state_cleanup(void)
2333 {
2334     SaveStateEntry *se;
2335 
2336     trace_loadvm_state_cleanup();
2337     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2338         if (se->ops && se->ops->load_cleanup) {
2339             se->ops->load_cleanup(se->opaque);
2340         }
2341     }
2342 }
2343 
2344 /* Return true if we should continue the migration, or false. */
2345 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2346 {
2347     trace_postcopy_pause_incoming();
2348 
2349     /* Clear the triggered bit to allow one recovery */
2350     mis->postcopy_recover_triggered = false;
2351 
2352     assert(mis->from_src_file);
2353     qemu_file_shutdown(mis->from_src_file);
2354     qemu_fclose(mis->from_src_file);
2355     mis->from_src_file = NULL;
2356 
2357     assert(mis->to_src_file);
2358     qemu_file_shutdown(mis->to_src_file);
2359     qemu_mutex_lock(&mis->rp_mutex);
2360     qemu_fclose(mis->to_src_file);
2361     mis->to_src_file = NULL;
2362     qemu_mutex_unlock(&mis->rp_mutex);
2363 
2364     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2365                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2366 
2367     /* Notify the fault thread for the invalidated file handle */
2368     postcopy_fault_thread_notify(mis);
2369 
2370     error_report("Detected IO failure for postcopy. "
2371                  "Migration paused.");
2372 
2373     while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2374         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2375     }
2376 
2377     trace_postcopy_pause_incoming_continued();
2378 
2379     return true;
2380 }
2381 
2382 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2383 {
2384     uint8_t section_type;
2385     int ret = 0;
2386 
2387 retry:
2388     while (true) {
2389         section_type = qemu_get_byte(f);
2390 
2391         if (qemu_file_get_error(f)) {
2392             ret = qemu_file_get_error(f);
2393             break;
2394         }
2395 
2396         trace_qemu_loadvm_state_section(section_type);
2397         switch (section_type) {
2398         case QEMU_VM_SECTION_START:
2399         case QEMU_VM_SECTION_FULL:
2400             ret = qemu_loadvm_section_start_full(f, mis);
2401             if (ret < 0) {
2402                 goto out;
2403             }
2404             break;
2405         case QEMU_VM_SECTION_PART:
2406         case QEMU_VM_SECTION_END:
2407             ret = qemu_loadvm_section_part_end(f, mis);
2408             if (ret < 0) {
2409                 goto out;
2410             }
2411             break;
2412         case QEMU_VM_COMMAND:
2413             ret = loadvm_process_command(f);
2414             trace_qemu_loadvm_state_section_command(ret);
2415             if ((ret < 0) || (ret == LOADVM_QUIT)) {
2416                 goto out;
2417             }
2418             break;
2419         case QEMU_VM_EOF:
2420             /* This is the end of migration */
2421             goto out;
2422         default:
2423             error_report("Unknown savevm section type %d", section_type);
2424             ret = -EINVAL;
2425             goto out;
2426         }
2427     }
2428 
2429 out:
2430     if (ret < 0) {
2431         qemu_file_set_error(f, ret);
2432 
2433         /*
2434          * If we are during an active postcopy, then we pause instead
2435          * of bail out to at least keep the VM's dirty data.  Note
2436          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2437          * during which we're still receiving device states and we
2438          * still haven't yet started the VM on destination.
2439          */
2440         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2441             postcopy_pause_incoming(mis)) {
2442             /* Reset f to point to the newly created channel */
2443             f = mis->from_src_file;
2444             goto retry;
2445         }
2446     }
2447     return ret;
2448 }
2449 
2450 int qemu_loadvm_state(QEMUFile *f)
2451 {
2452     MigrationIncomingState *mis = migration_incoming_get_current();
2453     Error *local_err = NULL;
2454     int ret;
2455 
2456     if (qemu_savevm_state_blocked(&local_err)) {
2457         error_report_err(local_err);
2458         return -EINVAL;
2459     }
2460 
2461     ret = qemu_loadvm_state_header(f);
2462     if (ret) {
2463         return ret;
2464     }
2465 
2466     if (qemu_loadvm_state_setup(f) != 0) {
2467         return -EINVAL;
2468     }
2469 
2470     cpu_synchronize_all_pre_loadvm();
2471 
2472     ret = qemu_loadvm_state_main(f, mis);
2473     qemu_event_set(&mis->main_thread_load_event);
2474 
2475     trace_qemu_loadvm_state_post_main(ret);
2476 
2477     if (mis->have_listen_thread) {
2478         /* Listen thread still going, can't clean up yet */
2479         return ret;
2480     }
2481 
2482     if (ret == 0) {
2483         ret = qemu_file_get_error(f);
2484     }
2485 
2486     /*
2487      * Try to read in the VMDESC section as well, so that dumping tools that
2488      * intercept our migration stream have the chance to see it.
2489      */
2490 
2491     /* We've got to be careful; if we don't read the data and just shut the fd
2492      * then the sender can error if we close while it's still sending.
2493      * We also mustn't read data that isn't there; some transports (RDMA)
2494      * will stall waiting for that data when the source has already closed.
2495      */
2496     if (ret == 0 && should_send_vmdesc()) {
2497         uint8_t *buf;
2498         uint32_t size;
2499         uint8_t  section_type = qemu_get_byte(f);
2500 
2501         if (section_type != QEMU_VM_VMDESCRIPTION) {
2502             error_report("Expected vmdescription section, but got %d",
2503                          section_type);
2504             /*
2505              * It doesn't seem worth failing at this point since
2506              * we apparently have an otherwise valid VM state
2507              */
2508         } else {
2509             buf = g_malloc(0x1000);
2510             size = qemu_get_be32(f);
2511 
2512             while (size > 0) {
2513                 uint32_t read_chunk = MIN(size, 0x1000);
2514                 qemu_get_buffer(f, buf, read_chunk);
2515                 size -= read_chunk;
2516             }
2517             g_free(buf);
2518         }
2519     }
2520 
2521     qemu_loadvm_state_cleanup();
2522     cpu_synchronize_all_post_init();
2523 
2524     return ret;
2525 }
2526 
2527 int qemu_load_device_state(QEMUFile *f)
2528 {
2529     MigrationIncomingState *mis = migration_incoming_get_current();
2530     int ret;
2531 
2532     /* Load QEMU_VM_SECTION_FULL section */
2533     ret = qemu_loadvm_state_main(f, mis);
2534     if (ret < 0) {
2535         error_report("Failed to load device state: %d", ret);
2536         return ret;
2537     }
2538 
2539     cpu_synchronize_all_post_init();
2540     return 0;
2541 }
2542 
2543 int save_snapshot(const char *name, Error **errp)
2544 {
2545     BlockDriverState *bs, *bs1;
2546     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2547     int ret = -1;
2548     QEMUFile *f;
2549     int saved_vm_running;
2550     uint64_t vm_state_size;
2551     qemu_timeval tv;
2552     struct tm tm;
2553     AioContext *aio_context;
2554 
2555     if (migration_is_blocked(errp)) {
2556         return ret;
2557     }
2558 
2559     if (!replay_can_snapshot()) {
2560         error_setg(errp, "Record/replay does not allow making snapshot "
2561                    "right now. Try once more later.");
2562         return ret;
2563     }
2564 
2565     if (!bdrv_all_can_snapshot(&bs)) {
2566         error_setg(errp, "Device '%s' is writable but does not support "
2567                    "snapshots", bdrv_get_device_name(bs));
2568         return ret;
2569     }
2570 
2571     /* Delete old snapshots of the same name */
2572     if (name) {
2573         ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2574         if (ret < 0) {
2575             error_prepend(errp, "Error while deleting snapshot on device "
2576                           "'%s': ", bdrv_get_device_name(bs1));
2577             return ret;
2578         }
2579     }
2580 
2581     bs = bdrv_all_find_vmstate_bs();
2582     if (bs == NULL) {
2583         error_setg(errp, "No block device can accept snapshots");
2584         return ret;
2585     }
2586     aio_context = bdrv_get_aio_context(bs);
2587 
2588     saved_vm_running = runstate_is_running();
2589 
2590     ret = global_state_store();
2591     if (ret) {
2592         error_setg(errp, "Error saving global state");
2593         return ret;
2594     }
2595     vm_stop(RUN_STATE_SAVE_VM);
2596 
2597     bdrv_drain_all_begin();
2598 
2599     aio_context_acquire(aio_context);
2600 
2601     memset(sn, 0, sizeof(*sn));
2602 
2603     /* fill auxiliary fields */
2604     qemu_gettimeofday(&tv);
2605     sn->date_sec = tv.tv_sec;
2606     sn->date_nsec = tv.tv_usec * 1000;
2607     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2608 
2609     if (name) {
2610         ret = bdrv_snapshot_find(bs, old_sn, name);
2611         if (ret >= 0) {
2612             pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2613             pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2614         } else {
2615             pstrcpy(sn->name, sizeof(sn->name), name);
2616         }
2617     } else {
2618         /* cast below needed for OpenBSD where tv_sec is still 'long' */
2619         localtime_r((const time_t *)&tv.tv_sec, &tm);
2620         strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2621     }
2622 
2623     /* save the VM state */
2624     f = qemu_fopen_bdrv(bs, 1);
2625     if (!f) {
2626         error_setg(errp, "Could not open VM state file");
2627         goto the_end;
2628     }
2629     ret = qemu_savevm_state(f, errp);
2630     vm_state_size = qemu_ftell(f);
2631     qemu_fclose(f);
2632     if (ret < 0) {
2633         goto the_end;
2634     }
2635 
2636     /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2637      * for itself.  BDRV_POLL_WHILE() does not support nested locking because
2638      * it only releases the lock once.  Therefore synchronous I/O will deadlock
2639      * unless we release the AioContext before bdrv_all_create_snapshot().
2640      */
2641     aio_context_release(aio_context);
2642     aio_context = NULL;
2643 
2644     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2645     if (ret < 0) {
2646         error_setg(errp, "Error while creating snapshot on '%s'",
2647                    bdrv_get_device_name(bs));
2648         goto the_end;
2649     }
2650 
2651     ret = 0;
2652 
2653  the_end:
2654     if (aio_context) {
2655         aio_context_release(aio_context);
2656     }
2657 
2658     bdrv_drain_all_end();
2659 
2660     if (saved_vm_running) {
2661         vm_start();
2662     }
2663     return ret;
2664 }
2665 
2666 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2667                                 Error **errp)
2668 {
2669     QEMUFile *f;
2670     QIOChannelFile *ioc;
2671     int saved_vm_running;
2672     int ret;
2673 
2674     if (!has_live) {
2675         /* live default to true so old version of Xen tool stack can have a
2676          * successfull live migration */
2677         live = true;
2678     }
2679 
2680     saved_vm_running = runstate_is_running();
2681     vm_stop(RUN_STATE_SAVE_VM);
2682     global_state_store_running();
2683 
2684     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2685     if (!ioc) {
2686         goto the_end;
2687     }
2688     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2689     f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2690     object_unref(OBJECT(ioc));
2691     ret = qemu_save_device_state(f);
2692     if (ret < 0 || qemu_fclose(f) < 0) {
2693         error_setg(errp, QERR_IO_ERROR);
2694     } else {
2695         /* libxl calls the QMP command "stop" before calling
2696          * "xen-save-devices-state" and in case of migration failure, libxl
2697          * would call "cont".
2698          * So call bdrv_inactivate_all (release locks) here to let the other
2699          * side of the migration take controle of the images.
2700          */
2701         if (live && !saved_vm_running) {
2702             ret = bdrv_inactivate_all();
2703             if (ret) {
2704                 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2705                            __func__, ret);
2706             }
2707         }
2708     }
2709 
2710  the_end:
2711     if (saved_vm_running) {
2712         vm_start();
2713     }
2714 }
2715 
2716 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2717 {
2718     QEMUFile *f;
2719     QIOChannelFile *ioc;
2720     int ret;
2721 
2722     /* Guest must be paused before loading the device state; the RAM state
2723      * will already have been loaded by xc
2724      */
2725     if (runstate_is_running()) {
2726         error_setg(errp, "Cannot update device state while vm is running");
2727         return;
2728     }
2729     vm_stop(RUN_STATE_RESTORE_VM);
2730 
2731     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2732     if (!ioc) {
2733         return;
2734     }
2735     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2736     f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2737     object_unref(OBJECT(ioc));
2738 
2739     ret = qemu_loadvm_state(f);
2740     qemu_fclose(f);
2741     if (ret < 0) {
2742         error_setg(errp, QERR_IO_ERROR);
2743     }
2744     migration_incoming_state_destroy();
2745 }
2746 
2747 int load_snapshot(const char *name, Error **errp)
2748 {
2749     BlockDriverState *bs, *bs_vm_state;
2750     QEMUSnapshotInfo sn;
2751     QEMUFile *f;
2752     int ret;
2753     AioContext *aio_context;
2754     MigrationIncomingState *mis = migration_incoming_get_current();
2755 
2756     if (!replay_can_snapshot()) {
2757         error_setg(errp, "Record/replay does not allow loading snapshot "
2758                    "right now. Try once more later.");
2759         return -EINVAL;
2760     }
2761 
2762     if (!bdrv_all_can_snapshot(&bs)) {
2763         error_setg(errp,
2764                    "Device '%s' is writable but does not support snapshots",
2765                    bdrv_get_device_name(bs));
2766         return -ENOTSUP;
2767     }
2768     ret = bdrv_all_find_snapshot(name, &bs);
2769     if (ret < 0) {
2770         error_setg(errp,
2771                    "Device '%s' does not have the requested snapshot '%s'",
2772                    bdrv_get_device_name(bs), name);
2773         return ret;
2774     }
2775 
2776     bs_vm_state = bdrv_all_find_vmstate_bs();
2777     if (!bs_vm_state) {
2778         error_setg(errp, "No block device supports snapshots");
2779         return -ENOTSUP;
2780     }
2781     aio_context = bdrv_get_aio_context(bs_vm_state);
2782 
2783     /* Don't even try to load empty VM states */
2784     aio_context_acquire(aio_context);
2785     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2786     aio_context_release(aio_context);
2787     if (ret < 0) {
2788         return ret;
2789     } else if (sn.vm_state_size == 0) {
2790         error_setg(errp, "This is a disk-only snapshot. Revert to it "
2791                    " offline using qemu-img");
2792         return -EINVAL;
2793     }
2794 
2795     /* Flush all IO requests so they don't interfere with the new state.  */
2796     bdrv_drain_all_begin();
2797 
2798     ret = bdrv_all_goto_snapshot(name, &bs, errp);
2799     if (ret < 0) {
2800         error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
2801                       name, bdrv_get_device_name(bs));
2802         goto err_drain;
2803     }
2804 
2805     /* restore the VM state */
2806     f = qemu_fopen_bdrv(bs_vm_state, 0);
2807     if (!f) {
2808         error_setg(errp, "Could not open VM state file");
2809         ret = -EINVAL;
2810         goto err_drain;
2811     }
2812 
2813     qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2814     mis->from_src_file = f;
2815 
2816     aio_context_acquire(aio_context);
2817     ret = qemu_loadvm_state(f);
2818     migration_incoming_state_destroy();
2819     aio_context_release(aio_context);
2820 
2821     bdrv_drain_all_end();
2822 
2823     if (ret < 0) {
2824         error_setg(errp, "Error %d while loading VM state", ret);
2825         return ret;
2826     }
2827 
2828     return 0;
2829 
2830 err_drain:
2831     bdrv_drain_all_end();
2832     return ret;
2833 }
2834 
2835 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2836 {
2837     qemu_ram_set_idstr(mr->ram_block,
2838                        memory_region_name(mr), dev);
2839     qemu_ram_set_migratable(mr->ram_block);
2840 }
2841 
2842 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2843 {
2844     qemu_ram_unset_idstr(mr->ram_block);
2845     qemu_ram_unset_migratable(mr->ram_block);
2846 }
2847 
2848 void vmstate_register_ram_global(MemoryRegion *mr)
2849 {
2850     vmstate_register_ram(mr, NULL);
2851 }
2852 
2853 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2854 {
2855     /* check needed if --only-migratable is specified */
2856     if (!only_migratable) {
2857         return true;
2858     }
2859 
2860     return !(vmsd && vmsd->unmigratable);
2861 }
2862