4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
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:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
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
29 #include "qemu/osdep.h"
30 #include "hw/boards.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"
39 #include "qemu-file-channel.h"
40 #include "qemu-file.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"
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"
67 const unsigned int postcopy_ram_discard_version;
69 /* Subcommands for QEMU_VM_COMMAND */
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 */
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 */
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 */
91 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
92 static struct mig_cmd_args {
93 ssize_t len; /* -1 = variable */
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" },
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
116 * - postcopy RAM and postcopy dirty bitmaps
117 * format is the same as for postcopy RAM only
119 * - postcopy dirty bitmaps only
120 * Nothing. Command length field is 0.
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.
127 /***********************************************************/
128 /* savevm/loadvm support */
130 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
131 int64_t pos, Error **errp)
136 qemu_iovec_init_external(&qiov, iov, iovcnt);
137 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
145 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
146 size_t size, Error **errp)
148 return bdrv_load_vmstate(opaque, buf, pos, size);
151 static int bdrv_fclose(void *opaque, Error **errp)
153 return bdrv_flush(opaque);
156 static const QEMUFileOps bdrv_read_ops = {
157 .get_buffer = block_get_buffer,
161 static const QEMUFileOps bdrv_write_ops = {
162 .writev_buffer = block_writev_buffer,
166 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
169 return qemu_fopen_ops(bs, &bdrv_write_ops);
171 return qemu_fopen_ops(bs, &bdrv_read_ops);
175 /* QEMUFile timer support.
176 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
179 void timer_put(QEMUFile *f, QEMUTimer *ts)
181 uint64_t expire_time;
183 expire_time = timer_expire_time_ns(ts);
184 qemu_put_be64(f, expire_time);
187 void timer_get(QEMUFile *f, QEMUTimer *ts)
189 uint64_t expire_time;
191 expire_time = qemu_get_be64(f);
192 if (expire_time != -1) {
193 timer_mod_ns(ts, expire_time);
200 /* VMState timer support.
201 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
204 static int get_timer(QEMUFile *f, void *pv, size_t size,
205 const VMStateField *field)
212 static int put_timer(QEMUFile *f, void *pv, size_t size,
213 const VMStateField *field, JSONWriter *vmdesc)
221 const VMStateInfo vmstate_info_timer = {
228 typedef struct CompatEntry {
233 typedef struct SaveStateEntry {
234 QTAILQ_ENTRY(SaveStateEntry) entry;
236 uint32_t instance_id;
239 /* version id read from the stream */
242 /* section id read from the stream */
244 const SaveVMHandlers *ops;
245 const VMStateDescription *vmsd;
251 typedef struct SaveState {
252 QTAILQ_HEAD(, SaveStateEntry) handlers;
253 SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
254 int global_section_id;
257 uint32_t target_page_bits;
259 MigrationCapability *capabilities;
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,
269 static bool should_validate_capability(int capability)
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:
281 static uint32_t get_validatable_capabilities_count(void)
283 MigrationState *s = migrate_get_current();
286 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
287 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
294 static int configuration_pre_save(void *opaque)
296 SaveState *state = opaque;
297 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
298 MigrationState *s = migrate_get_current();
301 state->len = strlen(current_name);
302 state->name = current_name;
303 state->target_page_bits = qemu_target_page_bits();
305 state->caps_count = get_validatable_capabilities_count();
306 state->capabilities = g_renew(MigrationCapability, state->capabilities,
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;
313 state->uuid = qemu_uuid;
318 static int configuration_post_save(void *opaque)
320 SaveState *state = opaque;
322 g_free(state->capabilities);
323 state->capabilities = NULL;
324 state->caps_count = 0;
328 static int configuration_pre_load(void *opaque)
330 SaveState *state = opaque;
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.
336 state->target_page_bits = qemu_target_page_bits_min();
340 static bool configuration_validate_capabilities(SaveState *state)
343 MigrationState *s = migrate_get_current();
344 unsigned long *source_caps_bm;
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);
353 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
354 bool source_state, target_state;
355 if (!should_validate_capability(i)) {
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");
366 /* Don't break here to report all failed capabilities */
370 g_free(source_caps_bm);
374 static int configuration_post_load(void *opaque, int version_id)
376 SaveState *state = opaque;
377 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
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);
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());
394 if (!configuration_validate_capabilities(state)) {
400 g_free((void *)state->name);
403 g_free(state->capabilities);
404 state->capabilities = NULL;
405 state->caps_count = 0;
410 static int get_capability(QEMUFile *f, void *pv, size_t size,
411 const VMStateField *field)
413 MigrationCapability *capability = pv;
414 char capability_str[UINT8_MAX + 1];
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)) {
427 error_report("Received unknown capability %s", capability_str);
431 static int put_capability(QEMUFile *f, void *pv, size_t size,
432 const VMStateField *field, JSONWriter *vmdesc)
434 MigrationCapability *capability = pv;
435 const char *capability_str = MigrationCapability_str(*capability);
436 size_t len = strlen(capability_str);
437 assert(len <= UINT8_MAX);
439 qemu_put_byte(f, len);
440 qemu_put_buffer(f, (uint8_t *)capability_str, len);
444 static const VMStateInfo vmstate_info_capability = {
445 .name = "capability",
446 .get = get_capability,
447 .put = put_capability,
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.
457 static bool vmstate_target_page_bits_needed(void *opaque)
459 return qemu_target_page_bits()
460 > qemu_target_page_bits_min();
463 static const VMStateDescription vmstate_target_page_bits = {
464 .name = "configuration/target-page-bits",
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()
474 static bool vmstate_capabilites_needed(void *opaque)
476 return get_validatable_capabilities_count() > 0;
479 static const VMStateDescription vmstate_capabilites = {
480 .name = "configuration/capabilities",
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()
493 static bool vmstate_uuid_needed(void *opaque)
495 return qemu_uuid_set && migrate_validate_uuid();
498 static int vmstate_uuid_post_load(void *opaque, int version_id)
500 SaveState *state = opaque;
501 char uuid_src[UUID_FMT_LEN + 1];
502 char uuid_dst[UUID_FMT_LEN + 1];
504 if (!qemu_uuid_set) {
506 * It's warning because user might not know UUID in some cases,
507 * e.g. load an old snapshot
509 qemu_uuid_unparse(&state->uuid, uuid_src);
510 warn_report("UUID is received %s, but local uuid isn't set",
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);
523 static const VMStateDescription vmstate_uuid = {
524 .name = "configuration/uuid",
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()
535 static const VMStateDescription vmstate_configuration = {
536 .name = "configuration",
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()
547 .subsections = (const VMStateDescription *[]) {
548 &vmstate_target_page_bits,
549 &vmstate_capabilites,
555 static void dump_vmstate_vmsd(FILE *out_file,
556 const VMStateDescription *vmsd, int indent,
559 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
562 fprintf(out_file, "%*s{\n", indent, "");
564 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
565 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
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);
574 fprintf(out_file, "\n%*s}", indent - 2, "");
577 static void dump_vmstate_vmss(FILE *out_file,
578 const VMStateDescription **subsection,
581 if (*subsection != NULL) {
582 dump_vmstate_vmsd(out_file, *subsection, indent, true);
586 static void dump_vmstate_vmsd(FILE *out_file,
587 const VMStateDescription *vmsd, int indent,
591 fprintf(out_file, "%*s{\n", indent, "");
593 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
596 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
597 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
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;
605 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
607 while (field->name != NULL) {
608 if (field->flags & VMS_MUST_EXIST) {
609 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
614 fprintf(out_file, ",\n");
616 dump_vmstate_vmsf(out_file, field, indent + 2);
620 fprintf(out_file, "\n%*s]", indent, "");
622 if (vmsd->subsections != NULL) {
623 const VMStateDescription **subsection = vmsd->subsections;
626 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
628 while (*subsection != NULL) {
630 fprintf(out_file, ",\n");
632 dump_vmstate_vmss(out_file, subsection, indent + 2);
636 fprintf(out_file, "\n%*s]", indent, "");
638 fprintf(out_file, "\n%*s}", indent - 2, "");
641 static void dump_machine_type(FILE *out_file)
645 mc = MACHINE_GET_CLASS(current_machine);
647 fprintf(out_file, " \"vmschkmachine\": {\n");
648 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
649 fprintf(out_file, " },\n");
652 void dump_vmstate_json_to_file(FILE *out_file)
657 fprintf(out_file, "{\n");
658 dump_machine_type(out_file);
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,
673 fprintf(out_file, ",\n");
675 name = object_class_get_name(OBJECT_CLASS(dc));
676 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
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);
684 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
686 fprintf(out_file, "\n%*s}", indent - 2, "");
689 fprintf(out_file, "\n}\n");
694 static uint32_t calculate_new_instance_id(const char *idstr)
697 uint32_t instance_id = 0;
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;
705 /* Make sure we never loop over without being noticed */
706 assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
710 static int calculate_compat_instance_id(const char *idstr)
715 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
720 if (strcmp(idstr, se->compat->idstr) == 0
721 && instance_id <= se->compat->instance_id) {
722 instance_id = se->compat->instance_id + 1;
728 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
731 return se->vmsd->priority;
733 return MIG_PRI_DEFAULT;
736 static void savevm_state_handler_insert(SaveStateEntry *nse)
738 MigrationPriority priority = save_state_priority(nse);
742 assert(priority <= MIG_PRI_MAX);
744 for (i = priority - 1; i >= 0; i--) {
745 se = savevm_state.handler_pri_head[i];
747 assert(save_state_priority(se) < priority);
753 QTAILQ_INSERT_BEFORE(se, nse, entry);
755 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
758 if (savevm_state.handler_pri_head[priority] == NULL) {
759 savevm_state.handler_pri_head[priority] = nse;
763 static void savevm_state_handler_remove(SaveStateEntry *se)
765 SaveStateEntry *next;
766 MigrationPriority priority = save_state_priority(se);
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;
773 savevm_state.handler_pri_head[priority] = NULL;
776 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
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,
786 const SaveVMHandlers *ops,
791 se = g_new0(SaveStateEntry, 1);
792 se->version_id = version_id;
793 se->section_id = savevm_state.global_section_id++;
797 /* if this is a live_savem then set is_ram */
798 if (ops->save_setup != NULL) {
802 pstrcat(se->idstr, sizeof(se->idstr), idstr);
804 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
805 se->instance_id = calculate_new_instance_id(se->idstr);
807 se->instance_id = instance_id;
809 assert(!se->compat || se->instance_id == 0);
810 savevm_state_handler_insert(se);
814 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
816 SaveStateEntry *se, *new_se;
820 char *oid = vmstate_if_get_id(obj);
822 pstrcpy(id, sizeof(id), oid);
823 pstrcat(id, sizeof(id), "/");
827 pstrcat(id, sizeof(id), idstr);
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);
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,
846 /* If this triggers, alias support can be dropped for the vmsd. */
847 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
849 se = g_new0(SaveStateEntry, 1);
850 se->version_id = vmsd->version_id;
851 se->section_id = savevm_state.global_section_id++;
854 se->alias_id = alias_id;
857 char *id = vmstate_if_get_id(obj);
859 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
861 error_setg(errp, "Path too long for VMState (%s)", id);
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;
876 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
878 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
879 se->instance_id = calculate_new_instance_id(se->idstr);
881 se->instance_id = instance_id;
883 assert(!se->compat || se->instance_id == 0);
884 savevm_state_handler_insert(se);
888 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
891 SaveStateEntry *se, *new_se;
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);
902 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
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);
908 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
911 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
914 int64_t old_offset, size;
916 old_offset = qemu_ftell_fast(f);
917 se->ops->save_state(f, se->opaque);
918 size = qemu_ftell_fast(f) - old_offset;
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);
932 static int vmstate_save(QEMUFile *f, SaveStateEntry *se,
935 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
937 vmstate_save_old_style(f, se, vmdesc);
940 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
944 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
946 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
947 uint8_t section_type)
949 qemu_put_byte(f, section_type);
950 qemu_put_be32(f, se->section_id);
952 if (section_type == QEMU_VM_SECTION_FULL ||
953 section_type == QEMU_VM_SECTION_START) {
955 size_t len = strlen(se->idstr);
956 qemu_put_byte(f, len);
957 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
959 qemu_put_be32(f, se->instance_id);
960 qemu_put_be32(f, se->version_id);
965 * Write a footer onto device sections that catches cases misformatted device
968 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
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);
977 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
978 * command and associated data.
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.
985 static void qemu_savevm_command_send(QEMUFile *f,
986 enum qemu_vm_cmd command,
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);
998 void qemu_savevm_send_colo_enable(QEMUFile *f)
1000 trace_savevm_send_colo_enable();
1001 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
1004 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
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);
1013 void qemu_savevm_send_open_return_path(QEMUFile *f)
1015 trace_savevm_send_open_return_path();
1016 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
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
1028 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
1032 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1033 error_report("%s: Unreasonably large packaged state: %zu",
1038 tmp = cpu_to_be32(len);
1040 trace_qemu_savevm_send_packaged();
1041 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1043 qemu_put_buffer(f, buf, len);
1048 /* Send prior to any postcopy transfer */
1049 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1051 if (migrate_postcopy_ram()) {
1053 tmp[0] = cpu_to_be64(ram_pagesize_summary());
1054 tmp[1] = cpu_to_be64(qemu_target_page_size());
1056 trace_qemu_savevm_send_postcopy_advise();
1057 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1058 16, (uint8_t *)tmp);
1060 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
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:
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
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
1081 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1083 uint64_t *start_list,
1084 uint64_t *length_list)
1089 size_t name_len = strlen(name);
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;
1096 memcpy(buf + 2, name, name_len);
1097 tmplen = 2 + name_len;
1098 buf[tmplen++] = '\0';
1100 for (t = 0; t < len; t++) {
1101 stq_be_p(buf + tmplen, start_list[t]);
1103 stq_be_p(buf + tmplen, length_list[t]);
1106 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1110 /* Get the destination into a state where it can receive postcopy data. */
1111 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1113 trace_savevm_send_postcopy_listen();
1114 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1117 /* Kick the destination into running */
1118 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1120 trace_savevm_send_postcopy_run();
1121 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1124 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1126 trace_savevm_send_postcopy_resume();
1127 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1130 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1135 trace_savevm_send_recv_bitmap(block_name);
1137 buf[0] = len = strlen(block_name);
1138 memcpy(buf + 1, block_name, len);
1140 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1143 bool qemu_savevm_state_blocked(Error **errp)
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'",
1157 void qemu_savevm_non_migratable_list(strList **reasons)
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",
1170 void qemu_savevm_state_header(QEMUFile *f)
1172 trace_savevm_state_header();
1173 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1174 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
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);
1182 bool qemu_savevm_state_guest_unplug_pending(void)
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)) {
1196 void qemu_savevm_state_setup(QEMUFile *f)
1199 Error *local_err = NULL;
1202 trace_savevm_state_setup();
1203 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1204 if (!se->ops || !se->ops->save_setup) {
1207 if (se->ops->is_active) {
1208 if (!se->ops->is_active(se->opaque)) {
1212 save_section_header(f, se, QEMU_VM_SECTION_START);
1214 ret = se->ops->save_setup(f, se->opaque);
1215 save_section_footer(f, se);
1217 qemu_file_set_error(f, ret);
1222 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1223 error_report_err(local_err);
1227 int qemu_savevm_state_resume_prepare(MigrationState *s)
1232 trace_savevm_state_resume_prepare();
1234 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1235 if (!se->ops || !se->ops->resume_prepare) {
1238 if (se->ops->is_active) {
1239 if (!se->ops->is_active(se->opaque)) {
1243 ret = se->ops->resume_prepare(s, se->opaque);
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
1258 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1263 trace_savevm_state_iterate();
1264 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1265 if (!se->ops || !se->ops->save_live_iterate) {
1268 if (se->ops->is_active &&
1269 !se->ops->is_active(se->opaque)) {
1272 if (se->ops->is_active_iterate &&
1273 !se->ops->is_active_iterate(se->opaque)) {
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.
1283 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1286 if (qemu_file_rate_limit(f)) {
1289 trace_savevm_section_start(se->idstr, se->section_id);
1291 save_section_header(f, se, QEMU_VM_SECTION_PART);
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);
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);
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. */
1313 static bool should_send_vmdesc(void)
1315 MachineState *machine = MACHINE(qdev_get_machine());
1316 bool in_postcopy = migration_in_postcopy();
1317 return !machine->suppress_vmdesc && !in_postcopy;
1321 * Calls the save_live_complete_postcopy methods
1322 * causing the last few pages to be sent immediately and doing any associated
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.
1327 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1332 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1333 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1336 if (se->ops->is_active) {
1337 if (!se->ops->is_active(se->opaque)) {
1341 trace_savevm_section_start(se->idstr, se->section_id);
1343 qemu_put_byte(f, QEMU_VM_SECTION_END);
1344 qemu_put_be32(f, se->section_id);
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);
1350 qemu_file_set_error(f, ret);
1355 qemu_put_byte(f, QEMU_VM_EOF);
1360 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1365 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1367 (in_postcopy && se->ops->has_postcopy &&
1368 se->ops->has_postcopy(se->opaque)) ||
1369 !se->ops->save_live_complete_precopy) {
1373 if (se->ops->is_active) {
1374 if (!se->ops->is_active(se->opaque)) {
1378 trace_savevm_section_start(se->idstr, se->section_id);
1380 save_section_header(f, se, QEMU_VM_SECTION_END);
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);
1386 qemu_file_set_error(f, ret);
1394 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1396 bool inactivate_disks)
1398 g_autoptr(JSONWriter) vmdesc = NULL;
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) {
1409 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1412 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1413 trace_savevm_section_skip(se->idstr, se->section_id);
1417 trace_savevm_section_start(se->idstr, se->section_id);
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);
1423 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1424 ret = vmstate_save(f, se, vmdesc);
1426 qemu_file_set_error(f, ret);
1429 trace_savevm_section_end(se->idstr, se->section_id, 0);
1430 save_section_footer(f, se);
1432 json_writer_end_object(vmdesc);
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();
1440 error_report("%s: bdrv_inactivate_all() failed (%d)",
1442 qemu_file_set_error(f, ret);
1447 /* Postcopy stream will still be going */
1448 qemu_put_byte(f, QEMU_VM_EOF);
1451 json_writer_end_array(vmdesc);
1452 json_writer_end_object(vmdesc);
1453 vmdesc_len = strlen(json_writer_get(vmdesc));
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);
1464 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1465 bool inactivate_disks)
1468 Error *local_err = NULL;
1469 bool in_postcopy = migration_in_postcopy();
1471 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1472 error_report_err(local_err);
1475 trace_savevm_state_complete_precopy();
1477 cpu_synchronize_all_states();
1479 if (!in_postcopy || iterable_only) {
1480 ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1486 if (iterable_only) {
1490 ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
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.
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)
1512 *res_precopy_only = 0;
1513 *res_compatible = 0;
1514 *res_postcopy_only = 0;
1517 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1518 if (!se->ops || !se->ops->save_live_pending) {
1521 if (se->ops->is_active) {
1522 if (!se->ops->is_active(se->opaque)) {
1526 se->ops->save_live_pending(f, se->opaque, threshold_size,
1527 res_precopy_only, res_compatible,
1532 void qemu_savevm_state_cleanup(void)
1535 Error *local_err = NULL;
1537 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1538 error_report_err(local_err);
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);
1549 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1552 MigrationState *ms = migrate_get_current();
1553 MigrationStatus status;
1555 if (migration_is_running(ms->state)) {
1556 error_setg(errp, QERR_MIGRATION_ACTIVE);
1560 if (migrate_use_block()) {
1561 error_setg(errp, "Block migration and snapshots are incompatible");
1566 memset(&ram_counters, 0, sizeof(ram_counters));
1567 ms->to_dst_file = f;
1569 qemu_mutex_unlock_iothread();
1570 qemu_savevm_state_header(f);
1571 qemu_savevm_state_setup(f);
1572 qemu_mutex_lock_iothread();
1574 while (qemu_file_get_error(f) == 0) {
1575 if (qemu_savevm_state_iterate(f, false) > 0) {
1580 ret = qemu_file_get_error(f);
1582 qemu_savevm_state_complete_precopy(f, false, false);
1583 ret = qemu_file_get_error(f);
1585 qemu_savevm_state_cleanup();
1587 error_setg_errno(errp, -ret, "Error while writing VM state");
1591 status = MIGRATION_STATUS_FAILED;
1593 status = MIGRATION_STATUS_COMPLETED;
1595 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1597 /* f is outer parameter, it should not stay in global migration state after
1598 * this function finished */
1599 ms->to_dst_file = NULL;
1604 void qemu_savevm_live_state(QEMUFile *f)
1606 /* save QEMU_VM_SECTION_END section */
1607 qemu_savevm_state_complete_precopy(f, true, false);
1608 qemu_put_byte(f, QEMU_VM_EOF);
1611 int qemu_save_device_state(QEMUFile *f)
1615 if (!migration_in_colo_state()) {
1616 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1617 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1619 cpu_synchronize_all_states();
1621 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1627 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1630 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1634 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1636 ret = vmstate_save(f, se, NULL);
1641 save_section_footer(f, se);
1644 qemu_put_byte(f, QEMU_VM_EOF);
1646 return qemu_file_get_error(f);
1649 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
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))
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))
1669 enum LoadVMExitCodes {
1670 /* Allow a command to quit all layers of nested loadvm loops */
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
1679 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
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;
1686 trace_loadvm_postcopy_handle_advise();
1687 if (ps != POSTCOPY_INCOMING_NONE) {
1688 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1694 if (migrate_postcopy_ram()) {
1695 error_report("RAM postcopy is enabled but have 0 byte advise");
1700 if (!migrate_postcopy_ram()) {
1701 error_report("RAM postcopy is disabled but have 16 byte advise");
1706 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1710 if (!postcopy_ram_supported_by_host(mis)) {
1711 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1715 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1716 local_pagesize_summary = ram_pagesize_summary();
1718 if (remote_pagesize_summary != local_pagesize_summary) {
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
1733 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1735 remote_pagesize_summary, local_pagesize_summary);
1739 remote_tps = qemu_get_be64(mis->from_src_file);
1740 if (remote_tps != qemu_target_page_size()) {
1742 * Again, some differences could be dealt with, but for now keep it
1745 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1746 (int)remote_tps, qemu_target_page_size());
1750 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1751 error_report_err(local_err);
1755 if (ram_postcopy_incoming_init(mis)) {
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
1765 * There can be 0..many of these messages, each encoding multiple pages.
1767 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1772 PostcopyState ps = postcopy_state_get();
1774 trace_loadvm_postcopy_ram_handle_discard();
1777 case POSTCOPY_INCOMING_ADVISE:
1779 tmp = postcopy_ram_prepare_discard(mis);
1785 case POSTCOPY_INCOMING_DISCARD:
1786 /* Expected state */
1790 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1794 /* We're expecting a
1796 * a RAM ID string (length byte, name, 0 term)
1797 * then at least 1 16 byte chunk
1799 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1800 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
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);
1810 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1811 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1814 tmp = qemu_get_byte(mis->from_src_file);
1816 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1820 len -= 3 + strlen(ramid);
1822 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1825 trace_loadvm_postcopy_ram_handle_discard_header(ramid, 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);
1832 int ret = ram_discard_range(ramid, start_addr, block_length);
1837 trace_loadvm_postcopy_ram_handle_discard_end();
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)
1849 static void *postcopy_ram_listen_thread(void *opaque)
1851 MigrationIncomingState *mis = migration_incoming_get_current();
1852 QEMUFile *f = mis->from_src_file;
1854 MigrationState *migr = migrate_get_current();
1856 object_ref(OBJECT(migr));
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();
1863 rcu_register_thread();
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.
1868 qemu_file_set_blocking(f, true);
1869 load_res = qemu_loadvm_state_main(f, mis);
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.
1876 f = mis->from_src_file;
1878 /* And non-blocking again so we don't block in any cleanup */
1879 qemu_file_set_blocking(f, false);
1881 trace_postcopy_ram_listen_thread_exit();
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())
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() */
1895 error_report("%s: loadvm failed: %d", __func__, load_res);
1896 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1897 MIGRATION_STATUS_FAILED);
1900 if (load_res >= 0) {
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.
1906 qemu_event_wait(&mis->main_thread_load_event);
1908 postcopy_ram_incoming_cleanup(mis);
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.
1917 rcu_unregister_thread();
1921 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1922 MIGRATION_STATUS_COMPLETED);
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).
1929 migration_incoming_state_destroy();
1930 qemu_loadvm_state_cleanup();
1932 rcu_unregister_thread();
1933 mis->have_listen_thread = false;
1934 postcopy_state_set(POSTCOPY_INCOMING_END);
1936 object_unref(OBJECT(migr));
1941 /* After this message we must be able to immediately receive postcopy data */
1942 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1944 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1945 trace_loadvm_postcopy_handle_listen();
1946 Error *local_err = NULL;
1948 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1949 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1952 if (ps == POSTCOPY_INCOMING_ADVISE) {
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.
1957 if (migrate_postcopy_ram()) {
1958 postcopy_ram_prepare_discard(mis);
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
1967 if (migrate_postcopy_ram()) {
1968 if (postcopy_ram_incoming_setup(mis)) {
1969 postcopy_ram_incoming_cleanup(mis);
1974 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1975 error_report_err(local_err);
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);
1991 static void loadvm_postcopy_handle_run_bh(void *opaque)
1993 Error *local_err = NULL;
1994 MigrationIncomingState *mis = opaque;
1996 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1999 cpu_synchronize_all_post_init();
2001 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
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);
2007 error_report_err(local_err);
2012 trace_loadvm_postcopy_handle_run_cpu_sync();
2014 trace_loadvm_postcopy_handle_run_vmstart();
2016 dirty_bitmap_mig_before_vm_start();
2019 /* Hold onto your hats, starting the CPU */
2022 /* leave it paused and let management decide when to start the CPU */
2023 runstate_set(RUN_STATE_PAUSED);
2026 qemu_bh_delete(mis->bh);
2029 /* After all discards we can start running and asking for pages */
2030 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2032 PostcopyState ps = postcopy_state_get();
2034 trace_loadvm_postcopy_handle_run();
2035 if (ps != POSTCOPY_INCOMING_LISTENING) {
2036 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
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);
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.
2052 /* We must be with page_request_mutex held */
2053 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2056 MigrationIncomingState *mis = data;
2057 void *host_addr = (void *) key;
2058 ram_addr_t rb_offset;
2062 rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
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.
2070 error_report("%s: illegal host addr %p", __func__, host_addr);
2071 /* Try the next entry */
2075 ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2077 /* Please refer to above comment. */
2078 error_report("%s: send rp message failed for addr %p",
2079 __func__, host_addr);
2083 trace_postcopy_page_req_sync(host_addr);
2088 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2090 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2091 g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2095 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
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. */
2104 * Reset the last_rb before we resend any page req to source again, since
2105 * the source should have it reset already.
2107 mis->last_rb = NULL;
2110 * This means source VM is ready to resume the postcopy migration.
2112 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2113 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2115 trace_loadvm_postcopy_handle_resume();
2117 /* Tell source that "we are ready" */
2118 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
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.
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.
2132 migrate_send_rp_req_pages_pending(mis);
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.
2140 qemu_sem_post(&mis->postcopy_pause_sem_fault);
2146 * Immediately following this command is a blob of data containing an embedded
2147 * chunk of migration stream; read it and load it.
2149 * @mis: Incoming state
2150 * @length: Length of packaged data to read
2152 * Returns: Negative values on error
2155 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2159 QIOChannelBuffer *bioc;
2161 length = qemu_get_be32(mis->from_src_file);
2162 trace_loadvm_handle_cmd_packaged(length);
2164 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2165 error_report("Unreasonably large packaged state: %zu", length);
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,
2174 if (ret != length) {
2175 object_unref(OBJECT(bioc));
2176 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2178 return (ret < 0) ? ret : -EAGAIN;
2180 bioc->usage += length;
2181 trace_loadvm_handle_cmd_packaged_received(ret);
2183 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
2185 ret = qemu_loadvm_state_main(packf, mis);
2186 trace_loadvm_handle_cmd_packaged_main(ret);
2188 object_unref(OBJECT(bioc));
2194 * Handle request that source requests for recved_bitmap on
2195 * destination. Payload format:
2197 * len (1 byte) + ramblock_name (<255 bytes)
2199 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2202 QEMUFile *file = mis->from_src_file;
2204 char block_name[256];
2207 cnt = qemu_get_counted_string(file, block_name);
2209 error_report("%s: failed to read block name", __func__);
2213 /* Validate before using the data */
2214 if (qemu_file_get_error(file)) {
2215 return qemu_file_get_error(file);
2218 if (len != cnt + 1) {
2219 error_report("%s: invalid payload length (%d)", __func__, len);
2223 rb = qemu_ram_block_by_name(block_name);
2225 error_report("%s: block '%s' not found", __func__, block_name);
2229 migrate_send_rp_recv_bitmap(mis, block_name);
2231 trace_loadvm_handle_recv_bitmap(block_name);
2236 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2238 int ret = migration_incoming_enable_colo();
2241 ret = colo_init_ram_cache();
2243 migration_incoming_disable_colo();
2250 * Process an incoming 'QEMU_VM_COMMAND'
2251 * 0 just a normal return
2252 * LOADVM_QUIT All good, but exit the loop
2255 static int loadvm_process_command(QEMUFile *f)
2257 MigrationIncomingState *mis = migration_incoming_get_current();
2262 cmd = qemu_get_be16(f);
2263 len = qemu_get_be16(f);
2265 /* Check validity before continue processing of cmds */
2266 if (qemu_file_get_error(f)) {
2267 return qemu_file_get_error(f);
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);
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);
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 */
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");
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",
2305 migrate_send_rp_pong(mis, tmp32);
2308 case MIG_CMD_PACKAGED:
2309 return loadvm_handle_cmd_packaged(mis);
2311 case MIG_CMD_POSTCOPY_ADVISE:
2312 return loadvm_postcopy_handle_advise(mis, len);
2314 case MIG_CMD_POSTCOPY_LISTEN:
2315 return loadvm_postcopy_handle_listen(mis);
2317 case MIG_CMD_POSTCOPY_RUN:
2318 return loadvm_postcopy_handle_run(mis);
2320 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2321 return loadvm_postcopy_ram_handle_discard(mis, len);
2323 case MIG_CMD_POSTCOPY_RESUME:
2324 return loadvm_postcopy_handle_resume(mis);
2326 case MIG_CMD_RECV_BITMAP:
2327 return loadvm_handle_recv_bitmap(mis, len);
2329 case MIG_CMD_ENABLE_COLO:
2330 return loadvm_process_enable_colo(mis);
2337 * Read a footer off the wire and check that it matches the expected section
2339 * Returns: true if the footer was good
2340 * false if there is a problem (and calls error_report to say why)
2342 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2346 uint32_t read_section_id;
2348 if (!migrate_get_current()->send_section_footer) {
2349 /* No footer to check */
2353 read_mark = qemu_get_byte(f);
2355 ret = qemu_file_get_error(f);
2357 error_report("%s: Read section footer failed: %d",
2362 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2363 error_report("Missing section footer for %s", se->idstr);
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);
2380 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2382 uint32_t instance_id, version_id, section_id;
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",
2394 instance_id = qemu_get_be32(f);
2395 version_id = qemu_get_be32(f);
2397 ret = qemu_file_get_error(f);
2399 error_report("%s: Failed to read instance/version ID: %d",
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);
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);
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);
2422 se->load_version_id = version_id;
2423 se->load_section_id = section_id;
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);
2431 ret = vmstate_load(f, se);
2433 error_report("error while loading state for instance 0x%"PRIx32" of"
2434 " device '%s'", instance_id, idstr);
2437 if (!check_section_footer(f, se)) {
2445 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2447 uint32_t section_id;
2451 section_id = qemu_get_be32(f);
2453 ret = qemu_file_get_error(f);
2455 error_report("%s: Failed to read section ID: %d",
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) {
2467 error_report("Unknown savevm section %d", section_id);
2471 ret = vmstate_load(f, se);
2473 error_report("error while loading state section id %d(%s)",
2474 section_id, se->idstr);
2477 if (!check_section_footer(f, se)) {
2484 static int qemu_loadvm_state_header(QEMUFile *f)
2489 v = qemu_get_be32(f);
2490 if (v != QEMU_VM_FILE_MAGIC) {
2491 error_report("Not a migration stream");
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");
2500 if (v != QEMU_VM_FILE_VERSION) {
2501 error_report("Unsupported migration stream version");
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();
2511 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2514 qemu_loadvm_state_cleanup();
2521 static int qemu_loadvm_state_setup(QEMUFile *f)
2526 trace_loadvm_state_setup();
2527 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2528 if (!se->ops || !se->ops->load_setup) {
2531 if (se->ops->is_active) {
2532 if (!se->ops->is_active(se->opaque)) {
2537 ret = se->ops->load_setup(f, se->opaque);
2539 qemu_file_set_error(f, ret);
2540 error_report("Load state of device %s failed", se->idstr);
2547 void qemu_loadvm_state_cleanup(void)
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);
2559 /* Return true if we should continue the migration, or false. */
2560 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2562 trace_postcopy_pause_incoming();
2564 assert(migrate_postcopy_ram());
2566 /* Clear the triggered bit to allow one recovery */
2567 mis->postcopy_recover_triggered = false;
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;
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);
2581 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2582 MIGRATION_STATUS_POSTCOPY_PAUSED);
2584 /* Notify the fault thread for the invalidated file handle */
2585 postcopy_fault_thread_notify(mis);
2587 error_report("Detected IO failure for postcopy. "
2588 "Migration paused.");
2590 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2591 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2594 trace_postcopy_pause_incoming_continued();
2599 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2601 uint8_t section_type;
2606 section_type = qemu_get_byte(f);
2608 if (qemu_file_get_error(f)) {
2609 ret = qemu_file_get_error(f);
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);
2622 case QEMU_VM_SECTION_PART:
2623 case QEMU_VM_SECTION_END:
2624 ret = qemu_loadvm_section_part_end(f, mis);
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)) {
2637 /* This is the end of migration */
2640 error_report("Unknown savevm section type %d", section_type);
2648 qemu_file_set_error(f, ret);
2650 /* Cancel bitmaps incoming regardless of recovery */
2651 dirty_bitmap_mig_cancel_incoming();
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.
2660 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2661 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
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;
2674 int qemu_loadvm_state(QEMUFile *f)
2676 MigrationIncomingState *mis = migration_incoming_get_current();
2677 Error *local_err = NULL;
2680 if (qemu_savevm_state_blocked(&local_err)) {
2681 error_report_err(local_err);
2685 ret = qemu_loadvm_state_header(f);
2690 if (qemu_loadvm_state_setup(f) != 0) {
2694 cpu_synchronize_all_pre_loadvm();
2696 ret = qemu_loadvm_state_main(f, mis);
2697 qemu_event_set(&mis->main_thread_load_event);
2699 trace_qemu_loadvm_state_post_main(ret);
2701 if (mis->have_listen_thread) {
2702 /* Listen thread still going, can't clean up yet */
2707 ret = qemu_file_get_error(f);
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.
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.
2720 if (ret == 0 && should_send_vmdesc()) {
2723 uint8_t section_type = qemu_get_byte(f);
2725 if (section_type != QEMU_VM_VMDESCRIPTION) {
2726 error_report("Expected vmdescription section, but got %d",
2729 * It doesn't seem worth failing at this point since
2730 * we apparently have an otherwise valid VM state
2733 buf = g_malloc(0x1000);
2734 size = qemu_get_be32(f);
2737 uint32_t read_chunk = MIN(size, 0x1000);
2738 qemu_get_buffer(f, buf, read_chunk);
2745 qemu_loadvm_state_cleanup();
2746 cpu_synchronize_all_post_init();
2751 int qemu_load_device_state(QEMUFile *f)
2753 MigrationIncomingState *mis = migration_incoming_get_current();
2756 /* Load QEMU_VM_SECTION_FULL section */
2757 ret = qemu_loadvm_state_main(f, mis);
2759 error_report("Failed to load device state: %d", ret);
2763 cpu_synchronize_all_post_init();
2767 int save_snapshot(const char *name, Error **errp)
2769 BlockDriverState *bs, *bs1;
2770 QEMUSnapshotInfo sn1, *sn = &sn1;
2773 int saved_vm_running;
2774 uint64_t vm_state_size;
2777 AioContext *aio_context;
2779 if (migration_is_blocked(errp)) {
2783 if (!replay_can_snapshot()) {
2784 error_setg(errp, "Record/replay does not allow making snapshot "
2785 "right now. Try once more later.");
2789 if (!bdrv_all_can_snapshot(&bs)) {
2790 error_setg(errp, "Device '%s' is writable but does not support "
2791 "snapshots", bdrv_get_device_or_node_name(bs));
2795 /* Delete old snapshots of the same name */
2797 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2799 error_prepend(errp, "Error while deleting snapshot on device "
2800 "'%s': ", bdrv_get_device_or_node_name(bs1));
2805 bs = bdrv_all_find_vmstate_bs();
2807 error_setg(errp, "No block device can accept snapshots");
2810 aio_context = bdrv_get_aio_context(bs);
2812 saved_vm_running = runstate_is_running();
2814 ret = global_state_store();
2816 error_setg(errp, "Error saving global state");
2819 vm_stop(RUN_STATE_SAVE_VM);
2821 bdrv_drain_all_begin();
2823 aio_context_acquire(aio_context);
2825 memset(sn, 0, sizeof(*sn));
2827 /* fill auxiliary fields */
2828 qemu_gettimeofday(&tv);
2829 sn->date_sec = tv.tv_sec;
2830 sn->date_nsec = tv.tv_usec * 1000;
2831 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2832 if (replay_mode != REPLAY_MODE_NONE) {
2833 sn->icount = replay_get_current_icount();
2839 pstrcpy(sn->name, sizeof(sn->name), name);
2841 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2842 localtime_r((const time_t *)&tv.tv_sec, &tm);
2843 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2846 /* save the VM state */
2847 f = qemu_fopen_bdrv(bs, 1);
2849 error_setg(errp, "Could not open VM state file");
2852 ret = qemu_savevm_state(f, errp);
2853 vm_state_size = qemu_ftell(f);
2854 ret2 = qemu_fclose(f);
2863 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2864 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2865 * it only releases the lock once. Therefore synchronous I/O will deadlock
2866 * unless we release the AioContext before bdrv_all_create_snapshot().
2868 aio_context_release(aio_context);
2871 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2873 error_setg(errp, "Error while creating snapshot on '%s'",
2874 bdrv_get_device_or_node_name(bs));
2875 bdrv_all_delete_snapshot(sn->name, &bs, NULL);
2883 aio_context_release(aio_context);
2886 bdrv_drain_all_end();
2888 if (saved_vm_running) {
2894 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2898 QIOChannelFile *ioc;
2899 int saved_vm_running;
2903 /* live default to true so old version of Xen tool stack can have a
2904 * successful live migration */
2908 saved_vm_running = runstate_is_running();
2909 vm_stop(RUN_STATE_SAVE_VM);
2910 global_state_store_running();
2912 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
2917 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2918 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2919 object_unref(OBJECT(ioc));
2920 ret = qemu_save_device_state(f);
2921 if (ret < 0 || qemu_fclose(f) < 0) {
2922 error_setg(errp, QERR_IO_ERROR);
2924 /* libxl calls the QMP command "stop" before calling
2925 * "xen-save-devices-state" and in case of migration failure, libxl
2926 * would call "cont".
2927 * So call bdrv_inactivate_all (release locks) here to let the other
2928 * side of the migration take control of the images.
2930 if (live && !saved_vm_running) {
2931 ret = bdrv_inactivate_all();
2933 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2940 if (saved_vm_running) {
2945 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2948 QIOChannelFile *ioc;
2951 /* Guest must be paused before loading the device state; the RAM state
2952 * will already have been loaded by xc
2954 if (runstate_is_running()) {
2955 error_setg(errp, "Cannot update device state while vm is running");
2958 vm_stop(RUN_STATE_RESTORE_VM);
2960 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2964 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2965 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2966 object_unref(OBJECT(ioc));
2968 ret = qemu_loadvm_state(f);
2971 error_setg(errp, QERR_IO_ERROR);
2973 migration_incoming_state_destroy();
2976 int load_snapshot(const char *name, Error **errp)
2978 BlockDriverState *bs, *bs_vm_state;
2979 QEMUSnapshotInfo sn;
2982 AioContext *aio_context;
2983 MigrationIncomingState *mis = migration_incoming_get_current();
2985 if (!bdrv_all_can_snapshot(&bs)) {
2987 "Device '%s' is writable but does not support snapshots",
2988 bdrv_get_device_or_node_name(bs));
2991 ret = bdrv_all_find_snapshot(name, &bs);
2994 "Device '%s' does not have the requested snapshot '%s'",
2995 bdrv_get_device_or_node_name(bs), name);
2999 bs_vm_state = bdrv_all_find_vmstate_bs();
3001 error_setg(errp, "No block device supports snapshots");
3004 aio_context = bdrv_get_aio_context(bs_vm_state);
3006 /* Don't even try to load empty VM states */
3007 aio_context_acquire(aio_context);
3008 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3009 aio_context_release(aio_context);
3012 } else if (sn.vm_state_size == 0) {
3013 error_setg(errp, "This is a disk-only snapshot. Revert to it "
3014 " offline using qemu-img");
3019 * Flush the record/replay queue. Now the VM state is going
3020 * to change. Therefore we don't need to preserve its consistency
3022 replay_flush_events();
3024 /* Flush all IO requests so they don't interfere with the new state. */
3025 bdrv_drain_all_begin();
3027 ret = bdrv_all_goto_snapshot(name, &bs, errp);
3029 error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
3030 name, bdrv_get_device_or_node_name(bs));
3034 /* restore the VM state */
3035 f = qemu_fopen_bdrv(bs_vm_state, 0);
3037 error_setg(errp, "Could not open VM state file");
3042 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3043 mis->from_src_file = f;
3045 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3049 aio_context_acquire(aio_context);
3050 ret = qemu_loadvm_state(f);
3051 migration_incoming_state_destroy();
3052 aio_context_release(aio_context);
3054 bdrv_drain_all_end();
3057 error_setg(errp, "Error %d while loading VM state", ret);
3064 bdrv_drain_all_end();
3068 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3070 qemu_ram_set_idstr(mr->ram_block,
3071 memory_region_name(mr), dev);
3072 qemu_ram_set_migratable(mr->ram_block);
3075 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3077 qemu_ram_unset_idstr(mr->ram_block);
3078 qemu_ram_unset_migratable(mr->ram_block);
3081 void vmstate_register_ram_global(MemoryRegion *mr)
3083 vmstate_register_ram(mr, NULL);
3086 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3088 /* check needed if --only-migratable is specified */
3089 if (!only_migratable) {
3093 return !(vmsd && vmsd->unmigratable);