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