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