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"
31 #include "hw/xen/xen.h"
33 #include "migration.h"
34 #include "migration/snapshot.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
40 #include "qemu-file-channel.h"
41 #include "qemu-file.h"
43 #include "postcopy-ram.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/qapi-commands-misc.h"
47 #include "qapi/qmp/qerror.h"
48 #include "qemu/error-report.h"
49 #include "sysemu/cpus.h"
50 #include "exec/memory.h"
51 #include "exec/target_page.h"
54 #include "qemu/main-loop.h"
55 #include "block/snapshot.h"
56 #include "qemu/cutils.h"
57 #include "io/channel-buffer.h"
58 #include "io/channel-file.h"
59 #include "sysemu/replay.h"
61 #include "migration/colo.h"
62 #include "qemu/bitmap.h"
63 #include "net/announce.h"
65 const unsigned int postcopy_ram_discard_version = 0;
67 /* Subcommands for QEMU_VM_COMMAND */
69 MIG_CMD_INVALID = 0, /* Must be 0 */
70 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
71 MIG_CMD_PING, /* Request a PONG on the RP */
73 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
74 warn we might want to do PC */
75 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
76 pages as it's running. */
77 MIG_CMD_POSTCOPY_RUN, /* Start execution */
79 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
80 were previously sent during
81 precopy but are dirty. */
82 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
83 MIG_CMD_ENABLE_COLO, /* Enable COLO */
84 MIG_CMD_POSTCOPY_RESUME, /* resume postcopy on dest */
85 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
89 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
90 static struct mig_cmd_args {
91 ssize_t len; /* -1 = variable */
94 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
95 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
96 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
97 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
98 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
99 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
100 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
101 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
102 [MIG_CMD_POSTCOPY_RESUME] = { .len = 0, .name = "POSTCOPY_RESUME" },
103 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
104 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
105 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
108 /* Note for MIG_CMD_POSTCOPY_ADVISE:
109 * The format of arguments is depending on postcopy mode:
110 * - postcopy RAM only
111 * uint64_t host page size
112 * uint64_t taget page size
114 * - postcopy RAM and postcopy dirty bitmaps
115 * format is the same as for postcopy RAM only
117 * - postcopy dirty bitmaps only
118 * Nothing. Command length field is 0.
120 * Be careful: adding a new postcopy entity with some other parameters should
121 * not break format self-description ability. Good way is to introduce some
122 * generic extendable format with an exception for two old entities.
125 /***********************************************************/
126 /* savevm/loadvm support */
128 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
134 qemu_iovec_init_external(&qiov, iov, iovcnt);
135 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
143 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
146 return bdrv_load_vmstate(opaque, buf, pos, size);
149 static int bdrv_fclose(void *opaque)
151 return bdrv_flush(opaque);
154 static const QEMUFileOps bdrv_read_ops = {
155 .get_buffer = block_get_buffer,
159 static const QEMUFileOps bdrv_write_ops = {
160 .writev_buffer = block_writev_buffer,
164 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
167 return qemu_fopen_ops(bs, &bdrv_write_ops);
169 return qemu_fopen_ops(bs, &bdrv_read_ops);
173 /* QEMUFile timer support.
174 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
177 void timer_put(QEMUFile *f, QEMUTimer *ts)
179 uint64_t expire_time;
181 expire_time = timer_expire_time_ns(ts);
182 qemu_put_be64(f, expire_time);
185 void timer_get(QEMUFile *f, QEMUTimer *ts)
187 uint64_t expire_time;
189 expire_time = qemu_get_be64(f);
190 if (expire_time != -1) {
191 timer_mod_ns(ts, expire_time);
198 /* VMState timer support.
199 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
202 static int get_timer(QEMUFile *f, void *pv, size_t size,
203 const VMStateField *field)
210 static int put_timer(QEMUFile *f, void *pv, size_t size,
211 const VMStateField *field, QJSON *vmdesc)
219 const VMStateInfo vmstate_info_timer = {
226 typedef struct CompatEntry {
231 typedef struct SaveStateEntry {
232 QTAILQ_ENTRY(SaveStateEntry) entry;
237 /* version id read from the stream */
240 /* section id read from the stream */
242 const SaveVMHandlers *ops;
243 const VMStateDescription *vmsd;
249 typedef struct SaveState {
250 QTAILQ_HEAD(, SaveStateEntry) handlers;
251 int global_section_id;
254 uint32_t target_page_bits;
256 MigrationCapability *capabilities;
259 static SaveState savevm_state = {
260 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
261 .global_section_id = 0,
264 static bool should_validate_capability(int capability)
266 assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
267 /* Validate only new capabilities to keep compatibility. */
268 switch (capability) {
269 case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
276 static uint32_t get_validatable_capabilities_count(void)
278 MigrationState *s = migrate_get_current();
281 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
282 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
289 static int configuration_pre_save(void *opaque)
291 SaveState *state = opaque;
292 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
293 MigrationState *s = migrate_get_current();
296 state->len = strlen(current_name);
297 state->name = current_name;
298 state->target_page_bits = qemu_target_page_bits();
300 state->caps_count = get_validatable_capabilities_count();
301 state->capabilities = g_renew(MigrationCapability, state->capabilities,
303 for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
304 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
305 state->capabilities[j++] = i;
312 static int configuration_pre_load(void *opaque)
314 SaveState *state = opaque;
316 /* If there is no target-page-bits subsection it means the source
317 * predates the variable-target-page-bits support and is using the
318 * minimum possible value for this CPU.
320 state->target_page_bits = qemu_target_page_bits_min();
324 static bool configuration_validate_capabilities(SaveState *state)
327 MigrationState *s = migrate_get_current();
328 unsigned long *source_caps_bm;
331 source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
332 for (i = 0; i < state->caps_count; i++) {
333 MigrationCapability capability = state->capabilities[i];
334 set_bit(capability, source_caps_bm);
337 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
338 bool source_state, target_state;
339 if (!should_validate_capability(i)) {
342 source_state = test_bit(i, source_caps_bm);
343 target_state = s->enabled_capabilities[i];
344 if (source_state != target_state) {
345 error_report("Capability %s is %s, but received capability is %s",
346 MigrationCapability_str(i),
347 target_state ? "on" : "off",
348 source_state ? "on" : "off");
350 /* Don't break here to report all failed capabilities */
354 g_free(source_caps_bm);
358 static int configuration_post_load(void *opaque, int version_id)
360 SaveState *state = opaque;
361 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
363 if (strncmp(state->name, current_name, state->len) != 0) {
364 error_report("Machine type received is '%.*s' and local is '%s'",
365 (int) state->len, state->name, current_name);
369 if (state->target_page_bits != qemu_target_page_bits()) {
370 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
371 state->target_page_bits, qemu_target_page_bits());
375 if (!configuration_validate_capabilities(state)) {
382 static int get_capability(QEMUFile *f, void *pv, size_t size,
383 const VMStateField *field)
385 MigrationCapability *capability = pv;
386 char capability_str[UINT8_MAX + 1];
390 len = qemu_get_byte(f);
391 qemu_get_buffer(f, (uint8_t *)capability_str, len);
392 capability_str[len] = '\0';
393 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
394 if (!strcmp(MigrationCapability_str(i), capability_str)) {
399 error_report("Received unknown capability %s", capability_str);
403 static int put_capability(QEMUFile *f, void *pv, size_t size,
404 const VMStateField *field, QJSON *vmdesc)
406 MigrationCapability *capability = pv;
407 const char *capability_str = MigrationCapability_str(*capability);
408 size_t len = strlen(capability_str);
409 assert(len <= UINT8_MAX);
411 qemu_put_byte(f, len);
412 qemu_put_buffer(f, (uint8_t *)capability_str, len);
416 static const VMStateInfo vmstate_info_capability = {
417 .name = "capability",
418 .get = get_capability,
419 .put = put_capability,
422 /* The target-page-bits subsection is present only if the
423 * target page size is not the same as the default (ie the
424 * minimum page size for a variable-page-size guest CPU).
425 * If it is present then it contains the actual target page
426 * bits for the machine, and migration will fail if the
427 * two ends don't agree about it.
429 static bool vmstate_target_page_bits_needed(void *opaque)
431 return qemu_target_page_bits()
432 > qemu_target_page_bits_min();
435 static const VMStateDescription vmstate_target_page_bits = {
436 .name = "configuration/target-page-bits",
438 .minimum_version_id = 1,
439 .needed = vmstate_target_page_bits_needed,
440 .fields = (VMStateField[]) {
441 VMSTATE_UINT32(target_page_bits, SaveState),
442 VMSTATE_END_OF_LIST()
446 static bool vmstate_capabilites_needed(void *opaque)
448 return get_validatable_capabilities_count() > 0;
451 static const VMStateDescription vmstate_capabilites = {
452 .name = "configuration/capabilities",
454 .minimum_version_id = 1,
455 .needed = vmstate_capabilites_needed,
456 .fields = (VMStateField[]) {
457 VMSTATE_UINT32_V(caps_count, SaveState, 1),
458 VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
459 vmstate_info_capability,
460 MigrationCapability),
461 VMSTATE_END_OF_LIST()
465 static const VMStateDescription vmstate_configuration = {
466 .name = "configuration",
468 .pre_load = configuration_pre_load,
469 .post_load = configuration_post_load,
470 .pre_save = configuration_pre_save,
471 .fields = (VMStateField[]) {
472 VMSTATE_UINT32(len, SaveState),
473 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
474 VMSTATE_END_OF_LIST()
476 .subsections = (const VMStateDescription*[]) {
477 &vmstate_target_page_bits,
478 &vmstate_capabilites,
483 static void dump_vmstate_vmsd(FILE *out_file,
484 const VMStateDescription *vmsd, int indent,
487 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
490 fprintf(out_file, "%*s{\n", indent, "");
492 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
493 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
495 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
496 field->field_exists ? "true" : "false");
497 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
498 if (field->vmsd != NULL) {
499 fprintf(out_file, ",\n");
500 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
502 fprintf(out_file, "\n%*s}", indent - 2, "");
505 static void dump_vmstate_vmss(FILE *out_file,
506 const VMStateDescription **subsection,
509 if (*subsection != NULL) {
510 dump_vmstate_vmsd(out_file, *subsection, indent, true);
514 static void dump_vmstate_vmsd(FILE *out_file,
515 const VMStateDescription *vmsd, int indent,
519 fprintf(out_file, "%*s{\n", indent, "");
521 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
524 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
525 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
527 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
528 vmsd->minimum_version_id);
529 if (vmsd->fields != NULL) {
530 const VMStateField *field = vmsd->fields;
533 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
535 while (field->name != NULL) {
536 if (field->flags & VMS_MUST_EXIST) {
537 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
542 fprintf(out_file, ",\n");
544 dump_vmstate_vmsf(out_file, field, indent + 2);
548 fprintf(out_file, "\n%*s]", indent, "");
550 if (vmsd->subsections != NULL) {
551 const VMStateDescription **subsection = vmsd->subsections;
554 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
556 while (*subsection != NULL) {
558 fprintf(out_file, ",\n");
560 dump_vmstate_vmss(out_file, subsection, indent + 2);
564 fprintf(out_file, "\n%*s]", indent, "");
566 fprintf(out_file, "\n%*s}", indent - 2, "");
569 static void dump_machine_type(FILE *out_file)
573 mc = MACHINE_GET_CLASS(current_machine);
575 fprintf(out_file, " \"vmschkmachine\": {\n");
576 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
577 fprintf(out_file, " },\n");
580 void dump_vmstate_json_to_file(FILE *out_file)
585 fprintf(out_file, "{\n");
586 dump_machine_type(out_file);
589 list = object_class_get_list(TYPE_DEVICE, true);
590 for (elt = list; elt; elt = elt->next) {
591 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
601 fprintf(out_file, ",\n");
603 name = object_class_get_name(OBJECT_CLASS(dc));
604 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
606 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
607 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
608 dc->vmsd->version_id);
609 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
610 dc->vmsd->minimum_version_id);
612 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
614 fprintf(out_file, "\n%*s}", indent - 2, "");
617 fprintf(out_file, "\n}\n");
621 static int calculate_new_instance_id(const char *idstr)
626 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
627 if (strcmp(idstr, se->idstr) == 0
628 && instance_id <= se->instance_id) {
629 instance_id = se->instance_id + 1;
635 static int calculate_compat_instance_id(const char *idstr)
640 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
645 if (strcmp(idstr, se->compat->idstr) == 0
646 && instance_id <= se->compat->instance_id) {
647 instance_id = se->compat->instance_id + 1;
653 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
656 return se->vmsd->priority;
658 return MIG_PRI_DEFAULT;
661 static void savevm_state_handler_insert(SaveStateEntry *nse)
663 MigrationPriority priority = save_state_priority(nse);
666 assert(priority <= MIG_PRI_MAX);
668 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
669 if (save_state_priority(se) < priority) {
675 QTAILQ_INSERT_BEFORE(se, nse, entry);
677 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
681 /* TODO: Individual devices generally have very little idea about the rest
682 of the system, so instance_id should be removed/replaced.
683 Meanwhile pass -1 as instance_id if you do not already have a clearly
684 distinguishing id for all instances of your device class. */
685 int register_savevm_live(DeviceState *dev,
689 const SaveVMHandlers *ops,
694 se = g_new0(SaveStateEntry, 1);
695 se->version_id = version_id;
696 se->section_id = savevm_state.global_section_id++;
700 /* if this is a live_savem then set is_ram */
701 if (ops->save_setup != NULL) {
706 char *id = qdev_get_dev_path(dev);
708 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
710 error_report("Path too long for VMState (%s)", id);
718 se->compat = g_new0(CompatEntry, 1);
719 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
720 se->compat->instance_id = instance_id == -1 ?
721 calculate_compat_instance_id(idstr) : instance_id;
725 pstrcat(se->idstr, sizeof(se->idstr), idstr);
727 if (instance_id == -1) {
728 se->instance_id = calculate_new_instance_id(se->idstr);
730 se->instance_id = instance_id;
732 assert(!se->compat || se->instance_id == 0);
733 savevm_state_handler_insert(se);
737 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
739 SaveStateEntry *se, *new_se;
743 char *path = qdev_get_dev_path(dev);
745 pstrcpy(id, sizeof(id), path);
746 pstrcat(id, sizeof(id), "/");
750 pstrcat(id, sizeof(id), idstr);
752 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
753 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
754 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
761 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
762 const VMStateDescription *vmsd,
763 void *opaque, int alias_id,
764 int required_for_version,
769 /* If this triggers, alias support can be dropped for the vmsd. */
770 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
772 se = g_new0(SaveStateEntry, 1);
773 se->version_id = vmsd->version_id;
774 se->section_id = savevm_state.global_section_id++;
777 se->alias_id = alias_id;
780 char *id = qdev_get_dev_path(dev);
782 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
784 error_setg(errp, "Path too long for VMState (%s)", id);
792 se->compat = g_new0(CompatEntry, 1);
793 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
794 se->compat->instance_id = instance_id == -1 ?
795 calculate_compat_instance_id(vmsd->name) : instance_id;
799 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
801 if (instance_id == -1) {
802 se->instance_id = calculate_new_instance_id(se->idstr);
804 se->instance_id = instance_id;
806 assert(!se->compat || se->instance_id == 0);
807 savevm_state_handler_insert(se);
811 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
814 SaveStateEntry *se, *new_se;
816 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
817 if (se->vmsd == vmsd && se->opaque == opaque) {
818 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
825 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
827 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
828 if (!se->vmsd) { /* Old style */
829 return se->ops->load_state(f, se->opaque, se->load_version_id);
831 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
834 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
836 int64_t old_offset, size;
838 old_offset = qemu_ftell_fast(f);
839 se->ops->save_state(f, se->opaque);
840 size = qemu_ftell_fast(f) - old_offset;
843 json_prop_int(vmdesc, "size", size);
844 json_start_array(vmdesc, "fields");
845 json_start_object(vmdesc, NULL);
846 json_prop_str(vmdesc, "name", "data");
847 json_prop_int(vmdesc, "size", size);
848 json_prop_str(vmdesc, "type", "buffer");
849 json_end_object(vmdesc);
850 json_end_array(vmdesc);
854 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
856 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
858 vmstate_save_old_style(f, se, vmdesc);
861 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
865 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
867 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
868 uint8_t section_type)
870 qemu_put_byte(f, section_type);
871 qemu_put_be32(f, se->section_id);
873 if (section_type == QEMU_VM_SECTION_FULL ||
874 section_type == QEMU_VM_SECTION_START) {
876 size_t len = strlen(se->idstr);
877 qemu_put_byte(f, len);
878 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
880 qemu_put_be32(f, se->instance_id);
881 qemu_put_be32(f, se->version_id);
886 * Write a footer onto device sections that catches cases misformatted device
889 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
891 if (migrate_get_current()->send_section_footer) {
892 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
893 qemu_put_be32(f, se->section_id);
898 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
899 * command and associated data.
901 * @f: File to send command on
902 * @command: Command type to send
903 * @len: Length of associated data
904 * @data: Data associated with command.
906 static void qemu_savevm_command_send(QEMUFile *f,
907 enum qemu_vm_cmd command,
911 trace_savevm_command_send(command, len);
912 qemu_put_byte(f, QEMU_VM_COMMAND);
913 qemu_put_be16(f, (uint16_t)command);
914 qemu_put_be16(f, len);
915 qemu_put_buffer(f, data, len);
919 void qemu_savevm_send_colo_enable(QEMUFile *f)
921 trace_savevm_send_colo_enable();
922 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
925 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
929 trace_savevm_send_ping(value);
930 buf = cpu_to_be32(value);
931 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
934 void qemu_savevm_send_open_return_path(QEMUFile *f)
936 trace_savevm_send_open_return_path();
937 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
940 /* We have a buffer of data to send; we don't want that all to be loaded
941 * by the command itself, so the command contains just the length of the
942 * extra buffer that we then send straight after it.
943 * TODO: Must be a better way to organise that
949 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
953 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
954 error_report("%s: Unreasonably large packaged state: %zu",
959 tmp = cpu_to_be32(len);
961 trace_qemu_savevm_send_packaged();
962 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
964 qemu_put_buffer(f, buf, len);
969 /* Send prior to any postcopy transfer */
970 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
972 if (migrate_postcopy_ram()) {
974 tmp[0] = cpu_to_be64(ram_pagesize_summary());
975 tmp[1] = cpu_to_be64(qemu_target_page_size());
977 trace_qemu_savevm_send_postcopy_advise();
978 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
981 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
985 /* Sent prior to starting the destination running in postcopy, discard pages
986 * that have already been sent but redirtied on the source.
987 * CMD_POSTCOPY_RAM_DISCARD consist of:
989 * byte Length of name field (not including 0)
990 * n x byte RAM block name
991 * byte 0 terminator (just for safety)
992 * n x Byte ranges within the named RAMBlock
993 * be64 Start of the range
996 * name: RAMBlock name that these entries are part of
997 * len: Number of page entries
998 * start_list: 'len' addresses
999 * length_list: 'len' addresses
1002 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1004 uint64_t *start_list,
1005 uint64_t *length_list)
1010 size_t name_len = strlen(name);
1012 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1013 assert(name_len < 256);
1014 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1015 buf[0] = postcopy_ram_discard_version;
1017 memcpy(buf + 2, name, name_len);
1018 tmplen = 2 + name_len;
1019 buf[tmplen++] = '\0';
1021 for (t = 0; t < len; t++) {
1022 stq_be_p(buf + tmplen, start_list[t]);
1024 stq_be_p(buf + tmplen, length_list[t]);
1027 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1031 /* Get the destination into a state where it can receive postcopy data. */
1032 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1034 trace_savevm_send_postcopy_listen();
1035 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1038 /* Kick the destination into running */
1039 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1041 trace_savevm_send_postcopy_run();
1042 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1045 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1047 trace_savevm_send_postcopy_resume();
1048 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1051 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1056 trace_savevm_send_recv_bitmap(block_name);
1058 buf[0] = len = strlen(block_name);
1059 memcpy(buf + 1, block_name, len);
1061 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1064 bool qemu_savevm_state_blocked(Error **errp)
1068 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1069 if (se->vmsd && se->vmsd->unmigratable) {
1070 error_setg(errp, "State blocked by non-migratable device '%s'",
1078 void qemu_savevm_state_header(QEMUFile *f)
1080 trace_savevm_state_header();
1081 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1082 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1084 if (migrate_get_current()->send_configuration) {
1085 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1086 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1090 void qemu_savevm_state_setup(QEMUFile *f)
1093 Error *local_err = NULL;
1096 trace_savevm_state_setup();
1097 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1098 if (!se->ops || !se->ops->save_setup) {
1101 if (se->ops && se->ops->is_active) {
1102 if (!se->ops->is_active(se->opaque)) {
1106 save_section_header(f, se, QEMU_VM_SECTION_START);
1108 ret = se->ops->save_setup(f, se->opaque);
1109 save_section_footer(f, se);
1111 qemu_file_set_error(f, ret);
1116 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1117 error_report_err(local_err);
1121 int qemu_savevm_state_resume_prepare(MigrationState *s)
1126 trace_savevm_state_resume_prepare();
1128 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1129 if (!se->ops || !se->ops->resume_prepare) {
1132 if (se->ops && se->ops->is_active) {
1133 if (!se->ops->is_active(se->opaque)) {
1137 ret = se->ops->resume_prepare(s, se->opaque);
1147 * this function has three return values:
1148 * negative: there was one error, and we have -errno.
1149 * 0 : We haven't finished, caller have to go again
1150 * 1 : We have finished, we can go to complete phase
1152 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1157 trace_savevm_state_iterate();
1158 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1159 if (!se->ops || !se->ops->save_live_iterate) {
1162 if (se->ops->is_active &&
1163 !se->ops->is_active(se->opaque)) {
1166 if (se->ops->is_active_iterate &&
1167 !se->ops->is_active_iterate(se->opaque)) {
1171 * In the postcopy phase, any device that doesn't know how to
1172 * do postcopy should have saved it's state in the _complete
1173 * call that's already run, it might get confused if we call
1174 * iterate afterwards.
1177 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1180 if (qemu_file_rate_limit(f)) {
1183 trace_savevm_section_start(se->idstr, se->section_id);
1185 save_section_header(f, se, QEMU_VM_SECTION_PART);
1187 ret = se->ops->save_live_iterate(f, se->opaque);
1188 trace_savevm_section_end(se->idstr, se->section_id, ret);
1189 save_section_footer(f, se);
1192 qemu_file_set_error(f, ret);
1195 /* Do not proceed to the next vmstate before this one reported
1196 completion of the current stage. This serializes the migration
1197 and reduces the probability that a faster changing state is
1198 synchronized over and over again. */
1205 static bool should_send_vmdesc(void)
1207 MachineState *machine = MACHINE(qdev_get_machine());
1208 bool in_postcopy = migration_in_postcopy();
1209 return !machine->suppress_vmdesc && !in_postcopy;
1213 * Calls the save_live_complete_postcopy methods
1214 * causing the last few pages to be sent immediately and doing any associated
1216 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1217 * all the other devices, but that happens at the point we switch to postcopy.
1219 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1224 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1225 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1228 if (se->ops && se->ops->is_active) {
1229 if (!se->ops->is_active(se->opaque)) {
1233 trace_savevm_section_start(se->idstr, se->section_id);
1235 qemu_put_byte(f, QEMU_VM_SECTION_END);
1236 qemu_put_be32(f, se->section_id);
1238 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1239 trace_savevm_section_end(se->idstr, se->section_id, ret);
1240 save_section_footer(f, se);
1242 qemu_file_set_error(f, ret);
1247 qemu_put_byte(f, QEMU_VM_EOF);
1251 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1252 bool inactivate_disks)
1258 bool in_postcopy = migration_in_postcopy();
1259 Error *local_err = NULL;
1261 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1262 error_report_err(local_err);
1265 trace_savevm_state_complete_precopy();
1267 cpu_synchronize_all_states();
1269 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1271 (in_postcopy && se->ops->has_postcopy &&
1272 se->ops->has_postcopy(se->opaque)) ||
1273 (in_postcopy && !iterable_only) ||
1274 !se->ops->save_live_complete_precopy) {
1278 if (se->ops && se->ops->is_active) {
1279 if (!se->ops->is_active(se->opaque)) {
1283 trace_savevm_section_start(se->idstr, se->section_id);
1285 save_section_header(f, se, QEMU_VM_SECTION_END);
1287 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1288 trace_savevm_section_end(se->idstr, se->section_id, ret);
1289 save_section_footer(f, se);
1291 qemu_file_set_error(f, ret);
1296 if (iterable_only) {
1300 vmdesc = qjson_new();
1301 json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1302 json_start_array(vmdesc, "devices");
1303 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1305 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1308 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1309 trace_savevm_section_skip(se->idstr, se->section_id);
1313 trace_savevm_section_start(se->idstr, se->section_id);
1315 json_start_object(vmdesc, NULL);
1316 json_prop_str(vmdesc, "name", se->idstr);
1317 json_prop_int(vmdesc, "instance_id", se->instance_id);
1319 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1320 ret = vmstate_save(f, se, vmdesc);
1322 qemu_file_set_error(f, ret);
1325 trace_savevm_section_end(se->idstr, se->section_id, 0);
1326 save_section_footer(f, se);
1328 json_end_object(vmdesc);
1331 if (inactivate_disks) {
1332 /* Inactivate before sending QEMU_VM_EOF so that the
1333 * bdrv_invalidate_cache_all() on the other end won't fail. */
1334 ret = bdrv_inactivate_all();
1336 error_report("%s: bdrv_inactivate_all() failed (%d)",
1338 qemu_file_set_error(f, ret);
1343 /* Postcopy stream will still be going */
1344 qemu_put_byte(f, QEMU_VM_EOF);
1347 json_end_array(vmdesc);
1348 qjson_finish(vmdesc);
1349 vmdesc_len = strlen(qjson_get_str(vmdesc));
1351 if (should_send_vmdesc()) {
1352 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1353 qemu_put_be32(f, vmdesc_len);
1354 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1356 qjson_destroy(vmdesc);
1362 /* Give an estimate of the amount left to be transferred,
1363 * the result is split into the amount for units that can and
1364 * for units that can't do postcopy.
1366 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1367 uint64_t *res_precopy_only,
1368 uint64_t *res_compatible,
1369 uint64_t *res_postcopy_only)
1373 *res_precopy_only = 0;
1374 *res_compatible = 0;
1375 *res_postcopy_only = 0;
1378 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1379 if (!se->ops || !se->ops->save_live_pending) {
1382 if (se->ops && se->ops->is_active) {
1383 if (!se->ops->is_active(se->opaque)) {
1387 se->ops->save_live_pending(f, se->opaque, threshold_size,
1388 res_precopy_only, res_compatible,
1393 void qemu_savevm_state_cleanup(void)
1396 Error *local_err = NULL;
1398 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1399 error_report_err(local_err);
1402 trace_savevm_state_cleanup();
1403 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1404 if (se->ops && se->ops->save_cleanup) {
1405 se->ops->save_cleanup(se->opaque);
1410 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1413 MigrationState *ms = migrate_get_current();
1414 MigrationStatus status;
1416 if (migration_is_setup_or_active(ms->state) ||
1417 ms->state == MIGRATION_STATUS_CANCELLING ||
1418 ms->state == MIGRATION_STATUS_COLO) {
1419 error_setg(errp, QERR_MIGRATION_ACTIVE);
1423 if (migrate_use_block()) {
1424 error_setg(errp, "Block migration and snapshots are incompatible");
1429 ms->to_dst_file = f;
1431 qemu_mutex_unlock_iothread();
1432 qemu_savevm_state_header(f);
1433 qemu_savevm_state_setup(f);
1434 qemu_mutex_lock_iothread();
1436 while (qemu_file_get_error(f) == 0) {
1437 if (qemu_savevm_state_iterate(f, false) > 0) {
1442 ret = qemu_file_get_error(f);
1444 qemu_savevm_state_complete_precopy(f, false, false);
1445 ret = qemu_file_get_error(f);
1447 qemu_savevm_state_cleanup();
1449 error_setg_errno(errp, -ret, "Error while writing VM state");
1453 status = MIGRATION_STATUS_FAILED;
1455 status = MIGRATION_STATUS_COMPLETED;
1457 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1459 /* f is outer parameter, it should not stay in global migration state after
1460 * this function finished */
1461 ms->to_dst_file = NULL;
1466 void qemu_savevm_live_state(QEMUFile *f)
1468 /* save QEMU_VM_SECTION_END section */
1469 qemu_savevm_state_complete_precopy(f, true, false);
1470 qemu_put_byte(f, QEMU_VM_EOF);
1473 int qemu_save_device_state(QEMUFile *f)
1477 if (!migration_in_colo_state()) {
1478 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1479 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1481 cpu_synchronize_all_states();
1483 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1489 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1492 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1496 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1498 ret = vmstate_save(f, se, NULL);
1503 save_section_footer(f, se);
1506 qemu_put_byte(f, QEMU_VM_EOF);
1508 return qemu_file_get_error(f);
1511 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1515 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1516 if (!strcmp(se->idstr, idstr) &&
1517 (instance_id == se->instance_id ||
1518 instance_id == se->alias_id))
1520 /* Migrating from an older version? */
1521 if (strstr(se->idstr, idstr) && se->compat) {
1522 if (!strcmp(se->compat->idstr, idstr) &&
1523 (instance_id == se->compat->instance_id ||
1524 instance_id == se->alias_id))
1531 enum LoadVMExitCodes {
1532 /* Allow a command to quit all layers of nested loadvm loops */
1536 /* ------ incoming postcopy messages ------ */
1537 /* 'advise' arrives before any transfers just to tell us that a postcopy
1538 * *might* happen - it might be skipped if precopy transferred everything
1541 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1544 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1545 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1546 Error *local_err = NULL;
1548 trace_loadvm_postcopy_handle_advise();
1549 if (ps != POSTCOPY_INCOMING_NONE) {
1550 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1556 if (migrate_postcopy_ram()) {
1557 error_report("RAM postcopy is enabled but have 0 byte advise");
1562 if (!migrate_postcopy_ram()) {
1563 error_report("RAM postcopy is disabled but have 16 byte advise");
1568 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1572 if (!postcopy_ram_supported_by_host(mis)) {
1573 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1577 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1578 local_pagesize_summary = ram_pagesize_summary();
1580 if (remote_pagesize_summary != local_pagesize_summary) {
1582 * This detects two potential causes of mismatch:
1583 * a) A mismatch in host page sizes
1584 * Some combinations of mismatch are probably possible but it gets
1585 * a bit more complicated. In particular we need to place whole
1586 * host pages on the dest at once, and we need to ensure that we
1587 * handle dirtying to make sure we never end up sending part of
1588 * a hostpage on it's own.
1589 * b) The use of different huge page sizes on source/destination
1590 * a more fine grain test is performed during RAM block migration
1591 * but this test here causes a nice early clear failure, and
1592 * also fails when passed to an older qemu that doesn't
1595 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1597 remote_pagesize_summary, local_pagesize_summary);
1601 remote_tps = qemu_get_be64(mis->from_src_file);
1602 if (remote_tps != qemu_target_page_size()) {
1604 * Again, some differences could be dealt with, but for now keep it
1607 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1608 (int)remote_tps, qemu_target_page_size());
1612 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1613 error_report_err(local_err);
1617 if (ram_postcopy_incoming_init(mis)) {
1621 postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1626 /* After postcopy we will be told to throw some pages away since they're
1627 * dirty and will have to be demand fetched. Must happen before CPU is
1629 * There can be 0..many of these messages, each encoding multiple pages.
1631 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1636 PostcopyState ps = postcopy_state_get();
1638 trace_loadvm_postcopy_ram_handle_discard();
1641 case POSTCOPY_INCOMING_ADVISE:
1643 tmp = postcopy_ram_prepare_discard(mis);
1649 case POSTCOPY_INCOMING_DISCARD:
1650 /* Expected state */
1654 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1658 /* We're expecting a
1660 * a RAM ID string (length byte, name, 0 term)
1661 * then at least 1 16 byte chunk
1663 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1664 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1668 tmp = qemu_get_byte(mis->from_src_file);
1669 if (tmp != postcopy_ram_discard_version) {
1670 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1674 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1675 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1678 tmp = qemu_get_byte(mis->from_src_file);
1680 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1684 len -= 3 + strlen(ramid);
1686 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1689 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1691 uint64_t start_addr, block_length;
1692 start_addr = qemu_get_be64(mis->from_src_file);
1693 block_length = qemu_get_be64(mis->from_src_file);
1696 int ret = ram_discard_range(ramid, start_addr, block_length);
1701 trace_loadvm_postcopy_ram_handle_discard_end();
1707 * Triggered by a postcopy_listen command; this thread takes over reading
1708 * the input stream, leaving the main thread free to carry on loading the rest
1709 * of the device state (from RAM).
1710 * (TODO:This could do with being in a postcopy file - but there again it's
1711 * just another input loop, not that postcopy specific)
1713 static void *postcopy_ram_listen_thread(void *opaque)
1715 MigrationIncomingState *mis = migration_incoming_get_current();
1716 QEMUFile *f = mis->from_src_file;
1719 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1720 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1721 qemu_sem_post(&mis->listen_thread_sem);
1722 trace_postcopy_ram_listen_thread_start();
1724 rcu_register_thread();
1726 * Because we're a thread and not a coroutine we can't yield
1727 * in qemu_file, and thus we must be blocking now.
1729 qemu_file_set_blocking(f, true);
1730 load_res = qemu_loadvm_state_main(f, mis);
1733 * This is tricky, but, mis->from_src_file can change after it
1734 * returns, when postcopy recovery happened. In the future, we may
1735 * want a wrapper for the QEMUFile handle.
1737 f = mis->from_src_file;
1739 /* And non-blocking again so we don't block in any cleanup */
1740 qemu_file_set_blocking(f, false);
1742 trace_postcopy_ram_listen_thread_exit();
1744 error_report("%s: loadvm failed: %d", __func__, load_res);
1745 qemu_file_set_error(f, load_res);
1746 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1747 MIGRATION_STATUS_FAILED);
1750 * This looks good, but it's possible that the device loading in the
1751 * main thread hasn't finished yet, and so we might not be in 'RUN'
1752 * state yet; wait for the end of the main thread.
1754 qemu_event_wait(&mis->main_thread_load_event);
1756 postcopy_ram_incoming_cleanup(mis);
1760 * If something went wrong then we have a bad state so exit;
1761 * depending how far we got it might be possible at this point
1762 * to leave the guest running and fire MCEs for pages that never
1763 * arrived as a desperate recovery step.
1765 rcu_unregister_thread();
1769 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1770 MIGRATION_STATUS_COMPLETED);
1772 * If everything has worked fine, then the main thread has waited
1773 * for us to start, and we're the last use of the mis.
1774 * (If something broke then qemu will have to exit anyway since it's
1775 * got a bad migration state).
1777 migration_incoming_state_destroy();
1778 qemu_loadvm_state_cleanup();
1780 rcu_unregister_thread();
1781 mis->have_listen_thread = false;
1785 /* After this message we must be able to immediately receive postcopy data */
1786 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1788 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1789 trace_loadvm_postcopy_handle_listen();
1790 Error *local_err = NULL;
1792 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1793 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1796 if (ps == POSTCOPY_INCOMING_ADVISE) {
1798 * A rare case, we entered listen without having to do any discards,
1799 * so do the setup that's normally done at the time of the 1st discard.
1801 if (migrate_postcopy_ram()) {
1802 postcopy_ram_prepare_discard(mis);
1807 * Sensitise RAM - can now generate requests for blocks that don't exist
1808 * However, at this point the CPU shouldn't be running, and the IO
1809 * shouldn't be doing anything yet so don't actually expect requests
1811 if (migrate_postcopy_ram()) {
1812 if (postcopy_ram_enable_notify(mis)) {
1813 postcopy_ram_incoming_cleanup(mis);
1818 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1819 error_report_err(local_err);
1823 if (mis->have_listen_thread) {
1824 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1828 mis->have_listen_thread = true;
1829 /* Start up the listening thread and wait for it to signal ready */
1830 qemu_sem_init(&mis->listen_thread_sem, 0);
1831 qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1832 postcopy_ram_listen_thread, NULL,
1833 QEMU_THREAD_DETACHED);
1834 qemu_sem_wait(&mis->listen_thread_sem);
1835 qemu_sem_destroy(&mis->listen_thread_sem);
1845 static void loadvm_postcopy_handle_run_bh(void *opaque)
1847 Error *local_err = NULL;
1848 HandleRunBhData *data = opaque;
1849 MigrationIncomingState *mis = migration_incoming_get_current();
1851 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1854 cpu_synchronize_all_post_init();
1856 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
1858 /* Make sure all file formats flush their mutable metadata.
1859 * If we get an error here, just don't restart the VM yet. */
1860 bdrv_invalidate_cache_all(&local_err);
1862 error_report_err(local_err);
1867 trace_loadvm_postcopy_handle_run_cpu_sync();
1869 trace_loadvm_postcopy_handle_run_vmstart();
1871 dirty_bitmap_mig_before_vm_start();
1874 /* Hold onto your hats, starting the CPU */
1877 /* leave it paused and let management decide when to start the CPU */
1878 runstate_set(RUN_STATE_PAUSED);
1881 qemu_bh_delete(data->bh);
1885 /* After all discards we can start running and asking for pages */
1886 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1888 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1889 HandleRunBhData *data;
1891 trace_loadvm_postcopy_handle_run();
1892 if (ps != POSTCOPY_INCOMING_LISTENING) {
1893 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1897 data = g_new(HandleRunBhData, 1);
1898 data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1899 qemu_bh_schedule(data->bh);
1901 /* We need to finish reading the stream from the package
1902 * and also stop reading anything more from the stream that loaded the
1903 * package (since it's now being read by the listener thread).
1904 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1909 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
1911 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
1912 error_report("%s: illegal resume received", __func__);
1913 /* Don't fail the load, only for this. */
1918 * This means source VM is ready to resume the postcopy migration.
1919 * It's time to switch state and release the fault thread to
1920 * continue service page faults.
1922 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1923 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1924 qemu_sem_post(&mis->postcopy_pause_sem_fault);
1926 trace_loadvm_postcopy_handle_resume();
1928 /* Tell source that "we are ready" */
1929 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
1935 * Immediately following this command is a blob of data containing an embedded
1936 * chunk of migration stream; read it and load it.
1938 * @mis: Incoming state
1939 * @length: Length of packaged data to read
1941 * Returns: Negative values on error
1944 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1948 QIOChannelBuffer *bioc;
1950 length = qemu_get_be32(mis->from_src_file);
1951 trace_loadvm_handle_cmd_packaged(length);
1953 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1954 error_report("Unreasonably large packaged state: %zu", length);
1958 bioc = qio_channel_buffer_new(length);
1959 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1960 ret = qemu_get_buffer(mis->from_src_file,
1963 if (ret != length) {
1964 object_unref(OBJECT(bioc));
1965 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1967 return (ret < 0) ? ret : -EAGAIN;
1969 bioc->usage += length;
1970 trace_loadvm_handle_cmd_packaged_received(ret);
1972 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1974 ret = qemu_loadvm_state_main(packf, mis);
1975 trace_loadvm_handle_cmd_packaged_main(ret);
1977 object_unref(OBJECT(bioc));
1983 * Handle request that source requests for recved_bitmap on
1984 * destination. Payload format:
1986 * len (1 byte) + ramblock_name (<255 bytes)
1988 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
1991 QEMUFile *file = mis->from_src_file;
1993 char block_name[256];
1996 cnt = qemu_get_counted_string(file, block_name);
1998 error_report("%s: failed to read block name", __func__);
2002 /* Validate before using the data */
2003 if (qemu_file_get_error(file)) {
2004 return qemu_file_get_error(file);
2007 if (len != cnt + 1) {
2008 error_report("%s: invalid payload length (%d)", __func__, len);
2012 rb = qemu_ram_block_by_name(block_name);
2014 error_report("%s: block '%s' not found", __func__, block_name);
2018 migrate_send_rp_recv_bitmap(mis, block_name);
2020 trace_loadvm_handle_recv_bitmap(block_name);
2025 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2027 migration_incoming_enable_colo();
2028 return colo_init_ram_cache();
2032 * Process an incoming 'QEMU_VM_COMMAND'
2033 * 0 just a normal return
2034 * LOADVM_QUIT All good, but exit the loop
2037 static int loadvm_process_command(QEMUFile *f)
2039 MigrationIncomingState *mis = migration_incoming_get_current();
2044 cmd = qemu_get_be16(f);
2045 len = qemu_get_be16(f);
2047 /* Check validity before continue processing of cmds */
2048 if (qemu_file_get_error(f)) {
2049 return qemu_file_get_error(f);
2052 trace_loadvm_process_command(cmd, len);
2053 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2054 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2058 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2059 error_report("%s received with bad length - expecting %zu, got %d",
2060 mig_cmd_args[cmd].name,
2061 (size_t)mig_cmd_args[cmd].len, len);
2066 case MIG_CMD_OPEN_RETURN_PATH:
2067 if (mis->to_src_file) {
2068 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2069 /* Not really a problem, so don't give up */
2072 mis->to_src_file = qemu_file_get_return_path(f);
2073 if (!mis->to_src_file) {
2074 error_report("CMD_OPEN_RETURN_PATH failed");
2080 tmp32 = qemu_get_be32(f);
2081 trace_loadvm_process_command_ping(tmp32);
2082 if (!mis->to_src_file) {
2083 error_report("CMD_PING (0x%x) received with no return path",
2087 migrate_send_rp_pong(mis, tmp32);
2090 case MIG_CMD_PACKAGED:
2091 return loadvm_handle_cmd_packaged(mis);
2093 case MIG_CMD_POSTCOPY_ADVISE:
2094 return loadvm_postcopy_handle_advise(mis, len);
2096 case MIG_CMD_POSTCOPY_LISTEN:
2097 return loadvm_postcopy_handle_listen(mis);
2099 case MIG_CMD_POSTCOPY_RUN:
2100 return loadvm_postcopy_handle_run(mis);
2102 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2103 return loadvm_postcopy_ram_handle_discard(mis, len);
2105 case MIG_CMD_POSTCOPY_RESUME:
2106 return loadvm_postcopy_handle_resume(mis);
2108 case MIG_CMD_RECV_BITMAP:
2109 return loadvm_handle_recv_bitmap(mis, len);
2111 case MIG_CMD_ENABLE_COLO:
2112 return loadvm_process_enable_colo(mis);
2119 * Read a footer off the wire and check that it matches the expected section
2121 * Returns: true if the footer was good
2122 * false if there is a problem (and calls error_report to say why)
2124 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2128 uint32_t read_section_id;
2130 if (!migrate_get_current()->send_section_footer) {
2131 /* No footer to check */
2135 read_mark = qemu_get_byte(f);
2137 ret = qemu_file_get_error(f);
2139 error_report("%s: Read section footer failed: %d",
2144 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2145 error_report("Missing section footer for %s", se->idstr);
2149 read_section_id = qemu_get_be32(f);
2150 if (read_section_id != se->load_section_id) {
2151 error_report("Mismatched section id in footer for %s -"
2152 " read 0x%x expected 0x%x",
2153 se->idstr, read_section_id, se->load_section_id);
2162 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2164 uint32_t instance_id, version_id, section_id;
2169 /* Read section start */
2170 section_id = qemu_get_be32(f);
2171 if (!qemu_get_counted_string(f, idstr)) {
2172 error_report("Unable to read ID string for section %u",
2176 instance_id = qemu_get_be32(f);
2177 version_id = qemu_get_be32(f);
2179 ret = qemu_file_get_error(f);
2181 error_report("%s: Failed to read instance/version ID: %d",
2186 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2187 instance_id, version_id);
2188 /* Find savevm section */
2189 se = find_se(idstr, instance_id);
2191 error_report("Unknown savevm section or instance '%s' %d. "
2192 "Make sure that your current VM setup matches your "
2193 "saved VM setup, including any hotplugged devices",
2194 idstr, instance_id);
2198 /* Validate version */
2199 if (version_id > se->version_id) {
2200 error_report("savevm: unsupported version %d for '%s' v%d",
2201 version_id, idstr, se->version_id);
2204 se->load_version_id = version_id;
2205 se->load_section_id = section_id;
2207 /* Validate if it is a device's state */
2208 if (xen_enabled() && se->is_ram) {
2209 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2213 ret = vmstate_load(f, se);
2215 error_report("error while loading state for instance 0x%x of"
2216 " device '%s'", instance_id, idstr);
2219 if (!check_section_footer(f, se)) {
2227 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2229 uint32_t section_id;
2233 section_id = qemu_get_be32(f);
2235 ret = qemu_file_get_error(f);
2237 error_report("%s: Failed to read section ID: %d",
2242 trace_qemu_loadvm_state_section_partend(section_id);
2243 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2244 if (se->load_section_id == section_id) {
2249 error_report("Unknown savevm section %d", section_id);
2253 ret = vmstate_load(f, se);
2255 error_report("error while loading state section id %d(%s)",
2256 section_id, se->idstr);
2259 if (!check_section_footer(f, se)) {
2266 static int qemu_loadvm_state_header(QEMUFile *f)
2271 v = qemu_get_be32(f);
2272 if (v != QEMU_VM_FILE_MAGIC) {
2273 error_report("Not a migration stream");
2277 v = qemu_get_be32(f);
2278 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2279 error_report("SaveVM v2 format is obsolete and don't work anymore");
2282 if (v != QEMU_VM_FILE_VERSION) {
2283 error_report("Unsupported migration stream version");
2287 if (migrate_get_current()->send_configuration) {
2288 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2289 error_report("Configuration section missing");
2290 qemu_loadvm_state_cleanup();
2293 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2296 qemu_loadvm_state_cleanup();
2303 static int qemu_loadvm_state_setup(QEMUFile *f)
2308 trace_loadvm_state_setup();
2309 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2310 if (!se->ops || !se->ops->load_setup) {
2313 if (se->ops && se->ops->is_active) {
2314 if (!se->ops->is_active(se->opaque)) {
2319 ret = se->ops->load_setup(f, se->opaque);
2321 qemu_file_set_error(f, ret);
2322 error_report("Load state of device %s failed", se->idstr);
2329 void qemu_loadvm_state_cleanup(void)
2333 trace_loadvm_state_cleanup();
2334 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2335 if (se->ops && se->ops->load_cleanup) {
2336 se->ops->load_cleanup(se->opaque);
2341 /* Return true if we should continue the migration, or false. */
2342 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2344 trace_postcopy_pause_incoming();
2346 /* Clear the triggered bit to allow one recovery */
2347 mis->postcopy_recover_triggered = false;
2349 assert(mis->from_src_file);
2350 qemu_file_shutdown(mis->from_src_file);
2351 qemu_fclose(mis->from_src_file);
2352 mis->from_src_file = NULL;
2354 assert(mis->to_src_file);
2355 qemu_file_shutdown(mis->to_src_file);
2356 qemu_mutex_lock(&mis->rp_mutex);
2357 qemu_fclose(mis->to_src_file);
2358 mis->to_src_file = NULL;
2359 qemu_mutex_unlock(&mis->rp_mutex);
2361 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2362 MIGRATION_STATUS_POSTCOPY_PAUSED);
2364 /* Notify the fault thread for the invalidated file handle */
2365 postcopy_fault_thread_notify(mis);
2367 error_report("Detected IO failure for postcopy. "
2368 "Migration paused.");
2370 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2371 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2374 trace_postcopy_pause_incoming_continued();
2379 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2381 uint8_t section_type;
2386 section_type = qemu_get_byte(f);
2388 if (qemu_file_get_error(f)) {
2389 ret = qemu_file_get_error(f);
2393 trace_qemu_loadvm_state_section(section_type);
2394 switch (section_type) {
2395 case QEMU_VM_SECTION_START:
2396 case QEMU_VM_SECTION_FULL:
2397 ret = qemu_loadvm_section_start_full(f, mis);
2402 case QEMU_VM_SECTION_PART:
2403 case QEMU_VM_SECTION_END:
2404 ret = qemu_loadvm_section_part_end(f, mis);
2409 case QEMU_VM_COMMAND:
2410 ret = loadvm_process_command(f);
2411 trace_qemu_loadvm_state_section_command(ret);
2412 if ((ret < 0) || (ret & LOADVM_QUIT)) {
2417 /* This is the end of migration */
2420 error_report("Unknown savevm section type %d", section_type);
2428 qemu_file_set_error(f, ret);
2431 * If we are during an active postcopy, then we pause instead
2432 * of bail out to at least keep the VM's dirty data. Note
2433 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2434 * during which we're still receiving device states and we
2435 * still haven't yet started the VM on destination.
2437 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2438 postcopy_pause_incoming(mis)) {
2439 /* Reset f to point to the newly created channel */
2440 f = mis->from_src_file;
2447 int qemu_loadvm_state(QEMUFile *f)
2449 MigrationIncomingState *mis = migration_incoming_get_current();
2450 Error *local_err = NULL;
2453 if (qemu_savevm_state_blocked(&local_err)) {
2454 error_report_err(local_err);
2458 ret = qemu_loadvm_state_header(f);
2463 if (qemu_loadvm_state_setup(f) != 0) {
2467 cpu_synchronize_all_pre_loadvm();
2469 ret = qemu_loadvm_state_main(f, mis);
2470 qemu_event_set(&mis->main_thread_load_event);
2472 trace_qemu_loadvm_state_post_main(ret);
2474 if (mis->have_listen_thread) {
2475 /* Listen thread still going, can't clean up yet */
2480 ret = qemu_file_get_error(f);
2484 * Try to read in the VMDESC section as well, so that dumping tools that
2485 * intercept our migration stream have the chance to see it.
2488 /* We've got to be careful; if we don't read the data and just shut the fd
2489 * then the sender can error if we close while it's still sending.
2490 * We also mustn't read data that isn't there; some transports (RDMA)
2491 * will stall waiting for that data when the source has already closed.
2493 if (ret == 0 && should_send_vmdesc()) {
2496 uint8_t section_type = qemu_get_byte(f);
2498 if (section_type != QEMU_VM_VMDESCRIPTION) {
2499 error_report("Expected vmdescription section, but got %d",
2502 * It doesn't seem worth failing at this point since
2503 * we apparently have an otherwise valid VM state
2506 buf = g_malloc(0x1000);
2507 size = qemu_get_be32(f);
2510 uint32_t read_chunk = MIN(size, 0x1000);
2511 qemu_get_buffer(f, buf, read_chunk);
2518 qemu_loadvm_state_cleanup();
2519 cpu_synchronize_all_post_init();
2524 int qemu_load_device_state(QEMUFile *f)
2526 MigrationIncomingState *mis = migration_incoming_get_current();
2529 /* Load QEMU_VM_SECTION_FULL section */
2530 ret = qemu_loadvm_state_main(f, mis);
2532 error_report("Failed to load device state: %d", ret);
2536 cpu_synchronize_all_post_init();
2540 int save_snapshot(const char *name, Error **errp)
2542 BlockDriverState *bs, *bs1;
2543 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2546 int saved_vm_running;
2547 uint64_t vm_state_size;
2550 AioContext *aio_context;
2552 if (migration_is_blocked(errp)) {
2556 if (!replay_can_snapshot()) {
2557 error_setg(errp, "Record/replay does not allow making snapshot "
2558 "right now. Try once more later.");
2562 if (!bdrv_all_can_snapshot(&bs)) {
2563 error_setg(errp, "Device '%s' is writable but does not support "
2564 "snapshots", bdrv_get_device_name(bs));
2568 /* Delete old snapshots of the same name */
2570 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2572 error_prepend(errp, "Error while deleting snapshot on device "
2573 "'%s': ", bdrv_get_device_name(bs1));
2578 bs = bdrv_all_find_vmstate_bs();
2580 error_setg(errp, "No block device can accept snapshots");
2583 aio_context = bdrv_get_aio_context(bs);
2585 saved_vm_running = runstate_is_running();
2587 ret = global_state_store();
2589 error_setg(errp, "Error saving global state");
2592 vm_stop(RUN_STATE_SAVE_VM);
2594 bdrv_drain_all_begin();
2596 aio_context_acquire(aio_context);
2598 memset(sn, 0, sizeof(*sn));
2600 /* fill auxiliary fields */
2601 qemu_gettimeofday(&tv);
2602 sn->date_sec = tv.tv_sec;
2603 sn->date_nsec = tv.tv_usec * 1000;
2604 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2607 ret = bdrv_snapshot_find(bs, old_sn, name);
2609 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2610 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2612 pstrcpy(sn->name, sizeof(sn->name), name);
2615 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2616 localtime_r((const time_t *)&tv.tv_sec, &tm);
2617 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2620 /* save the VM state */
2621 f = qemu_fopen_bdrv(bs, 1);
2623 error_setg(errp, "Could not open VM state file");
2626 ret = qemu_savevm_state(f, errp);
2627 vm_state_size = qemu_ftell(f);
2633 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2634 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2635 * it only releases the lock once. Therefore synchronous I/O will deadlock
2636 * unless we release the AioContext before bdrv_all_create_snapshot().
2638 aio_context_release(aio_context);
2641 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2643 error_setg(errp, "Error while creating snapshot on '%s'",
2644 bdrv_get_device_name(bs));
2652 aio_context_release(aio_context);
2655 bdrv_drain_all_end();
2657 if (saved_vm_running) {
2663 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2667 QIOChannelFile *ioc;
2668 int saved_vm_running;
2672 /* live default to true so old version of Xen tool stack can have a
2673 * successfull live migration */
2677 saved_vm_running = runstate_is_running();
2678 vm_stop(RUN_STATE_SAVE_VM);
2679 global_state_store_running();
2681 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2685 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2686 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2687 object_unref(OBJECT(ioc));
2688 ret = qemu_save_device_state(f);
2689 if (ret < 0 || qemu_fclose(f) < 0) {
2690 error_setg(errp, QERR_IO_ERROR);
2692 /* libxl calls the QMP command "stop" before calling
2693 * "xen-save-devices-state" and in case of migration failure, libxl
2694 * would call "cont".
2695 * So call bdrv_inactivate_all (release locks) here to let the other
2696 * side of the migration take controle of the images.
2698 if (live && !saved_vm_running) {
2699 ret = bdrv_inactivate_all();
2701 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2708 if (saved_vm_running) {
2713 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2716 QIOChannelFile *ioc;
2719 /* Guest must be paused before loading the device state; the RAM state
2720 * will already have been loaded by xc
2722 if (runstate_is_running()) {
2723 error_setg(errp, "Cannot update device state while vm is running");
2726 vm_stop(RUN_STATE_RESTORE_VM);
2728 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2732 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2733 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2734 object_unref(OBJECT(ioc));
2736 ret = qemu_loadvm_state(f);
2739 error_setg(errp, QERR_IO_ERROR);
2741 migration_incoming_state_destroy();
2744 int load_snapshot(const char *name, Error **errp)
2746 BlockDriverState *bs, *bs_vm_state;
2747 QEMUSnapshotInfo sn;
2750 AioContext *aio_context;
2751 MigrationIncomingState *mis = migration_incoming_get_current();
2753 if (!replay_can_snapshot()) {
2754 error_setg(errp, "Record/replay does not allow loading snapshot "
2755 "right now. Try once more later.");
2759 if (!bdrv_all_can_snapshot(&bs)) {
2761 "Device '%s' is writable but does not support snapshots",
2762 bdrv_get_device_name(bs));
2765 ret = bdrv_all_find_snapshot(name, &bs);
2768 "Device '%s' does not have the requested snapshot '%s'",
2769 bdrv_get_device_name(bs), name);
2773 bs_vm_state = bdrv_all_find_vmstate_bs();
2775 error_setg(errp, "No block device supports snapshots");
2778 aio_context = bdrv_get_aio_context(bs_vm_state);
2780 /* Don't even try to load empty VM states */
2781 aio_context_acquire(aio_context);
2782 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2783 aio_context_release(aio_context);
2786 } else if (sn.vm_state_size == 0) {
2787 error_setg(errp, "This is a disk-only snapshot. Revert to it "
2788 " offline using qemu-img");
2792 /* Flush all IO requests so they don't interfere with the new state. */
2793 bdrv_drain_all_begin();
2795 ret = bdrv_all_goto_snapshot(name, &bs, errp);
2797 error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
2798 name, bdrv_get_device_name(bs));
2802 /* restore the VM state */
2803 f = qemu_fopen_bdrv(bs_vm_state, 0);
2805 error_setg(errp, "Could not open VM state file");
2810 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2811 mis->from_src_file = f;
2813 aio_context_acquire(aio_context);
2814 ret = qemu_loadvm_state(f);
2815 migration_incoming_state_destroy();
2816 aio_context_release(aio_context);
2818 bdrv_drain_all_end();
2821 error_setg(errp, "Error %d while loading VM state", ret);
2828 bdrv_drain_all_end();
2832 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2834 qemu_ram_set_idstr(mr->ram_block,
2835 memory_region_name(mr), dev);
2836 qemu_ram_set_migratable(mr->ram_block);
2839 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2841 qemu_ram_unset_idstr(mr->ram_block);
2842 qemu_ram_unset_migratable(mr->ram_block);
2845 void vmstate_register_ram_global(MemoryRegion *mr)
2847 vmstate_register_ram(mr, NULL);
2850 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2852 /* check needed if --only-migratable is specified */
2853 if (!only_migratable) {
2857 return !(vmsd && vmsd->unmigratable);