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