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