4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
8 * Juan Quintela <quintela@redhat.com>
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"
60 #include "sysemu/runstate.h"
61 #include "sysemu/sysemu.h"
63 #include "migration/colo.h"
64 #include "qemu/bitmap.h"
65 #include "net/announce.h"
67 const unsigned int postcopy_ram_discard_version
= 0;
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
, QJSON
*vmdesc
)
221 const VMStateInfo vmstate_info_timer
= {
228 typedef struct CompatEntry
{
233 typedef struct SaveStateEntry
{
234 QTAILQ_ENTRY(SaveStateEntry
) entry
;
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 int global_section_id
;
256 uint32_t target_page_bits
;
258 MigrationCapability
*capabilities
;
262 static SaveState savevm_state
= {
263 .handlers
= QTAILQ_HEAD_INITIALIZER(savevm_state
.handlers
),
264 .global_section_id
= 0,
267 static bool should_validate_capability(int capability
)
269 assert(capability
>= 0 && capability
< MIGRATION_CAPABILITY__MAX
);
270 /* Validate only new capabilities to keep compatibility. */
271 switch (capability
) {
272 case MIGRATION_CAPABILITY_X_IGNORE_SHARED
:
279 static uint32_t get_validatable_capabilities_count(void)
281 MigrationState
*s
= migrate_get_current();
284 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
285 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
292 static int configuration_pre_save(void *opaque
)
294 SaveState
*state
= opaque
;
295 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
296 MigrationState
*s
= migrate_get_current();
299 state
->len
= strlen(current_name
);
300 state
->name
= current_name
;
301 state
->target_page_bits
= qemu_target_page_bits();
303 state
->caps_count
= get_validatable_capabilities_count();
304 state
->capabilities
= g_renew(MigrationCapability
, state
->capabilities
,
306 for (i
= j
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
307 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
308 state
->capabilities
[j
++] = i
;
311 state
->uuid
= qemu_uuid
;
316 static int configuration_pre_load(void *opaque
)
318 SaveState
*state
= opaque
;
320 /* If there is no target-page-bits subsection it means the source
321 * predates the variable-target-page-bits support and is using the
322 * minimum possible value for this CPU.
324 state
->target_page_bits
= qemu_target_page_bits_min();
328 static bool configuration_validate_capabilities(SaveState
*state
)
331 MigrationState
*s
= migrate_get_current();
332 unsigned long *source_caps_bm
;
335 source_caps_bm
= bitmap_new(MIGRATION_CAPABILITY__MAX
);
336 for (i
= 0; i
< state
->caps_count
; i
++) {
337 MigrationCapability capability
= state
->capabilities
[i
];
338 set_bit(capability
, source_caps_bm
);
341 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
342 bool source_state
, target_state
;
343 if (!should_validate_capability(i
)) {
346 source_state
= test_bit(i
, source_caps_bm
);
347 target_state
= s
->enabled_capabilities
[i
];
348 if (source_state
!= target_state
) {
349 error_report("Capability %s is %s, but received capability is %s",
350 MigrationCapability_str(i
),
351 target_state
? "on" : "off",
352 source_state
? "on" : "off");
354 /* Don't break here to report all failed capabilities */
358 g_free(source_caps_bm
);
362 static int configuration_post_load(void *opaque
, int version_id
)
364 SaveState
*state
= opaque
;
365 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
367 if (strncmp(state
->name
, current_name
, state
->len
) != 0) {
368 error_report("Machine type received is '%.*s' and local is '%s'",
369 (int) state
->len
, state
->name
, current_name
);
373 if (state
->target_page_bits
!= qemu_target_page_bits()) {
374 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
375 state
->target_page_bits
, qemu_target_page_bits());
379 if (!configuration_validate_capabilities(state
)) {
386 static int get_capability(QEMUFile
*f
, void *pv
, size_t size
,
387 const VMStateField
*field
)
389 MigrationCapability
*capability
= pv
;
390 char capability_str
[UINT8_MAX
+ 1];
394 len
= qemu_get_byte(f
);
395 qemu_get_buffer(f
, (uint8_t *)capability_str
, len
);
396 capability_str
[len
] = '\0';
397 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
398 if (!strcmp(MigrationCapability_str(i
), capability_str
)) {
403 error_report("Received unknown capability %s", capability_str
);
407 static int put_capability(QEMUFile
*f
, void *pv
, size_t size
,
408 const VMStateField
*field
, QJSON
*vmdesc
)
410 MigrationCapability
*capability
= pv
;
411 const char *capability_str
= MigrationCapability_str(*capability
);
412 size_t len
= strlen(capability_str
);
413 assert(len
<= UINT8_MAX
);
415 qemu_put_byte(f
, len
);
416 qemu_put_buffer(f
, (uint8_t *)capability_str
, len
);
420 static const VMStateInfo vmstate_info_capability
= {
421 .name
= "capability",
422 .get
= get_capability
,
423 .put
= put_capability
,
426 /* The target-page-bits subsection is present only if the
427 * target page size is not the same as the default (ie the
428 * minimum page size for a variable-page-size guest CPU).
429 * If it is present then it contains the actual target page
430 * bits for the machine, and migration will fail if the
431 * two ends don't agree about it.
433 static bool vmstate_target_page_bits_needed(void *opaque
)
435 return qemu_target_page_bits()
436 > qemu_target_page_bits_min();
439 static const VMStateDescription vmstate_target_page_bits
= {
440 .name
= "configuration/target-page-bits",
442 .minimum_version_id
= 1,
443 .needed
= vmstate_target_page_bits_needed
,
444 .fields
= (VMStateField
[]) {
445 VMSTATE_UINT32(target_page_bits
, SaveState
),
446 VMSTATE_END_OF_LIST()
450 static bool vmstate_capabilites_needed(void *opaque
)
452 return get_validatable_capabilities_count() > 0;
455 static const VMStateDescription vmstate_capabilites
= {
456 .name
= "configuration/capabilities",
458 .minimum_version_id
= 1,
459 .needed
= vmstate_capabilites_needed
,
460 .fields
= (VMStateField
[]) {
461 VMSTATE_UINT32_V(caps_count
, SaveState
, 1),
462 VMSTATE_VARRAY_UINT32_ALLOC(capabilities
, SaveState
, caps_count
, 1,
463 vmstate_info_capability
,
464 MigrationCapability
),
465 VMSTATE_END_OF_LIST()
469 static bool vmstate_uuid_needed(void *opaque
)
471 return qemu_uuid_set
&& migrate_validate_uuid();
474 static int vmstate_uuid_post_load(void *opaque
, int version_id
)
476 SaveState
*state
= opaque
;
477 char uuid_src
[UUID_FMT_LEN
+ 1];
478 char uuid_dst
[UUID_FMT_LEN
+ 1];
480 if (!qemu_uuid_set
) {
482 * It's warning because user might not know UUID in some cases,
483 * e.g. load an old snapshot
485 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
486 warn_report("UUID is received %s, but local uuid isn't set",
490 if (!qemu_uuid_is_equal(&state
->uuid
, &qemu_uuid
)) {
491 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
492 qemu_uuid_unparse(&qemu_uuid
, uuid_dst
);
493 error_report("UUID received is %s and local is %s", uuid_src
, uuid_dst
);
499 static const VMStateDescription vmstate_uuid
= {
500 .name
= "configuration/uuid",
502 .minimum_version_id
= 1,
503 .needed
= vmstate_uuid_needed
,
504 .post_load
= vmstate_uuid_post_load
,
505 .fields
= (VMStateField
[]) {
506 VMSTATE_UINT8_ARRAY_V(uuid
.data
, SaveState
, sizeof(QemuUUID
), 1),
507 VMSTATE_END_OF_LIST()
511 static const VMStateDescription vmstate_configuration
= {
512 .name
= "configuration",
514 .pre_load
= configuration_pre_load
,
515 .post_load
= configuration_post_load
,
516 .pre_save
= configuration_pre_save
,
517 .fields
= (VMStateField
[]) {
518 VMSTATE_UINT32(len
, SaveState
),
519 VMSTATE_VBUFFER_ALLOC_UINT32(name
, SaveState
, 0, NULL
, len
),
520 VMSTATE_END_OF_LIST()
522 .subsections
= (const VMStateDescription
*[]) {
523 &vmstate_target_page_bits
,
524 &vmstate_capabilites
,
530 static void dump_vmstate_vmsd(FILE *out_file
,
531 const VMStateDescription
*vmsd
, int indent
,
534 static void dump_vmstate_vmsf(FILE *out_file
, const VMStateField
*field
,
537 fprintf(out_file
, "%*s{\n", indent
, "");
539 fprintf(out_file
, "%*s\"field\": \"%s\",\n", indent
, "", field
->name
);
540 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
542 fprintf(out_file
, "%*s\"field_exists\": %s,\n", indent
, "",
543 field
->field_exists
? "true" : "false");
544 fprintf(out_file
, "%*s\"size\": %zu", indent
, "", field
->size
);
545 if (field
->vmsd
!= NULL
) {
546 fprintf(out_file
, ",\n");
547 dump_vmstate_vmsd(out_file
, field
->vmsd
, indent
, false);
549 fprintf(out_file
, "\n%*s}", indent
- 2, "");
552 static void dump_vmstate_vmss(FILE *out_file
,
553 const VMStateDescription
**subsection
,
556 if (*subsection
!= NULL
) {
557 dump_vmstate_vmsd(out_file
, *subsection
, indent
, true);
561 static void dump_vmstate_vmsd(FILE *out_file
,
562 const VMStateDescription
*vmsd
, int indent
,
566 fprintf(out_file
, "%*s{\n", indent
, "");
568 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", "Description");
571 fprintf(out_file
, "%*s\"name\": \"%s\",\n", indent
, "", vmsd
->name
);
572 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
574 fprintf(out_file
, "%*s\"minimum_version_id\": %d", indent
, "",
575 vmsd
->minimum_version_id
);
576 if (vmsd
->fields
!= NULL
) {
577 const VMStateField
*field
= vmsd
->fields
;
580 fprintf(out_file
, ",\n%*s\"Fields\": [\n", indent
, "");
582 while (field
->name
!= NULL
) {
583 if (field
->flags
& VMS_MUST_EXIST
) {
584 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
589 fprintf(out_file
, ",\n");
591 dump_vmstate_vmsf(out_file
, field
, indent
+ 2);
595 fprintf(out_file
, "\n%*s]", indent
, "");
597 if (vmsd
->subsections
!= NULL
) {
598 const VMStateDescription
**subsection
= vmsd
->subsections
;
601 fprintf(out_file
, ",\n%*s\"Subsections\": [\n", indent
, "");
603 while (*subsection
!= NULL
) {
605 fprintf(out_file
, ",\n");
607 dump_vmstate_vmss(out_file
, subsection
, indent
+ 2);
611 fprintf(out_file
, "\n%*s]", indent
, "");
613 fprintf(out_file
, "\n%*s}", indent
- 2, "");
616 static void dump_machine_type(FILE *out_file
)
620 mc
= MACHINE_GET_CLASS(current_machine
);
622 fprintf(out_file
, " \"vmschkmachine\": {\n");
623 fprintf(out_file
, " \"Name\": \"%s\"\n", mc
->name
);
624 fprintf(out_file
, " },\n");
627 void dump_vmstate_json_to_file(FILE *out_file
)
632 fprintf(out_file
, "{\n");
633 dump_machine_type(out_file
);
636 list
= object_class_get_list(TYPE_DEVICE
, true);
637 for (elt
= list
; elt
; elt
= elt
->next
) {
638 DeviceClass
*dc
= OBJECT_CLASS_CHECK(DeviceClass
, elt
->data
,
648 fprintf(out_file
, ",\n");
650 name
= object_class_get_name(OBJECT_CLASS(dc
));
651 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", name
);
653 fprintf(out_file
, "%*s\"Name\": \"%s\",\n", indent
, "", name
);
654 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
655 dc
->vmsd
->version_id
);
656 fprintf(out_file
, "%*s\"minimum_version_id\": %d,\n", indent
, "",
657 dc
->vmsd
->minimum_version_id
);
659 dump_vmstate_vmsd(out_file
, dc
->vmsd
, indent
, false);
661 fprintf(out_file
, "\n%*s}", indent
- 2, "");
664 fprintf(out_file
, "\n}\n");
668 static int calculate_new_instance_id(const char *idstr
)
673 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
674 if (strcmp(idstr
, se
->idstr
) == 0
675 && instance_id
<= se
->instance_id
) {
676 instance_id
= se
->instance_id
+ 1;
682 static int calculate_compat_instance_id(const char *idstr
)
687 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
692 if (strcmp(idstr
, se
->compat
->idstr
) == 0
693 && instance_id
<= se
->compat
->instance_id
) {
694 instance_id
= se
->compat
->instance_id
+ 1;
700 static inline MigrationPriority
save_state_priority(SaveStateEntry
*se
)
703 return se
->vmsd
->priority
;
705 return MIG_PRI_DEFAULT
;
708 static void savevm_state_handler_insert(SaveStateEntry
*nse
)
710 MigrationPriority priority
= save_state_priority(nse
);
713 assert(priority
<= MIG_PRI_MAX
);
715 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
716 if (save_state_priority(se
) < priority
) {
722 QTAILQ_INSERT_BEFORE(se
, nse
, entry
);
724 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, nse
, entry
);
728 /* TODO: Individual devices generally have very little idea about the rest
729 of the system, so instance_id should be removed/replaced.
730 Meanwhile pass -1 as instance_id if you do not already have a clearly
731 distinguishing id for all instances of your device class. */
732 int register_savevm_live(const char *idstr
,
735 const SaveVMHandlers
*ops
,
740 se
= g_new0(SaveStateEntry
, 1);
741 se
->version_id
= version_id
;
742 se
->section_id
= savevm_state
.global_section_id
++;
746 /* if this is a live_savem then set is_ram */
747 if (ops
->save_setup
!= NULL
) {
751 pstrcat(se
->idstr
, sizeof(se
->idstr
), idstr
);
753 if (instance_id
== -1) {
754 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
756 se
->instance_id
= instance_id
;
758 assert(!se
->compat
|| se
->instance_id
== 0);
759 savevm_state_handler_insert(se
);
763 void unregister_savevm(DeviceState
*dev
, const char *idstr
, void *opaque
)
765 SaveStateEntry
*se
, *new_se
;
769 char *path
= qdev_get_dev_path(dev
);
771 pstrcpy(id
, sizeof(id
), path
);
772 pstrcat(id
, sizeof(id
), "/");
776 pstrcat(id
, sizeof(id
), idstr
);
778 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
779 if (strcmp(se
->idstr
, id
) == 0 && se
->opaque
== opaque
) {
780 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
787 int vmstate_register_with_alias_id(DeviceState
*dev
, int instance_id
,
788 const VMStateDescription
*vmsd
,
789 void *opaque
, int alias_id
,
790 int required_for_version
,
795 /* If this triggers, alias support can be dropped for the vmsd. */
796 assert(alias_id
== -1 || required_for_version
>= vmsd
->minimum_version_id
);
798 se
= g_new0(SaveStateEntry
, 1);
799 se
->version_id
= vmsd
->version_id
;
800 se
->section_id
= savevm_state
.global_section_id
++;
803 se
->alias_id
= alias_id
;
806 char *id
= qdev_get_dev_path(dev
);
808 if (snprintf(se
->idstr
, sizeof(se
->idstr
), "%s/", id
) >=
810 error_setg(errp
, "Path too long for VMState (%s)", id
);
818 se
->compat
= g_new0(CompatEntry
, 1);
819 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), vmsd
->name
);
820 se
->compat
->instance_id
= instance_id
== -1 ?
821 calculate_compat_instance_id(vmsd
->name
) : instance_id
;
825 pstrcat(se
->idstr
, sizeof(se
->idstr
), vmsd
->name
);
827 if (instance_id
== -1) {
828 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
830 se
->instance_id
= instance_id
;
832 assert(!se
->compat
|| se
->instance_id
== 0);
833 savevm_state_handler_insert(se
);
837 void vmstate_unregister(DeviceState
*dev
, const VMStateDescription
*vmsd
,
840 SaveStateEntry
*se
, *new_se
;
842 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
843 if (se
->vmsd
== vmsd
&& se
->opaque
== opaque
) {
844 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
851 static int vmstate_load(QEMUFile
*f
, SaveStateEntry
*se
)
853 trace_vmstate_load(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
854 if (!se
->vmsd
) { /* Old style */
855 return se
->ops
->load_state(f
, se
->opaque
, se
->load_version_id
);
857 return vmstate_load_state(f
, se
->vmsd
, se
->opaque
, se
->load_version_id
);
860 static void vmstate_save_old_style(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
862 int64_t old_offset
, size
;
864 old_offset
= qemu_ftell_fast(f
);
865 se
->ops
->save_state(f
, se
->opaque
);
866 size
= qemu_ftell_fast(f
) - old_offset
;
869 json_prop_int(vmdesc
, "size", size
);
870 json_start_array(vmdesc
, "fields");
871 json_start_object(vmdesc
, NULL
);
872 json_prop_str(vmdesc
, "name", "data");
873 json_prop_int(vmdesc
, "size", size
);
874 json_prop_str(vmdesc
, "type", "buffer");
875 json_end_object(vmdesc
);
876 json_end_array(vmdesc
);
880 static int vmstate_save(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
882 trace_vmstate_save(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
884 vmstate_save_old_style(f
, se
, vmdesc
);
887 return vmstate_save_state(f
, se
->vmsd
, se
->opaque
, vmdesc
);
891 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
893 static void save_section_header(QEMUFile
*f
, SaveStateEntry
*se
,
894 uint8_t section_type
)
896 qemu_put_byte(f
, section_type
);
897 qemu_put_be32(f
, se
->section_id
);
899 if (section_type
== QEMU_VM_SECTION_FULL
||
900 section_type
== QEMU_VM_SECTION_START
) {
902 size_t len
= strlen(se
->idstr
);
903 qemu_put_byte(f
, len
);
904 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
906 qemu_put_be32(f
, se
->instance_id
);
907 qemu_put_be32(f
, se
->version_id
);
912 * Write a footer onto device sections that catches cases misformatted device
915 static void save_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
917 if (migrate_get_current()->send_section_footer
) {
918 qemu_put_byte(f
, QEMU_VM_SECTION_FOOTER
);
919 qemu_put_be32(f
, se
->section_id
);
924 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
925 * command and associated data.
927 * @f: File to send command on
928 * @command: Command type to send
929 * @len: Length of associated data
930 * @data: Data associated with command.
932 static void qemu_savevm_command_send(QEMUFile
*f
,
933 enum qemu_vm_cmd command
,
937 trace_savevm_command_send(command
, len
);
938 qemu_put_byte(f
, QEMU_VM_COMMAND
);
939 qemu_put_be16(f
, (uint16_t)command
);
940 qemu_put_be16(f
, len
);
941 qemu_put_buffer(f
, data
, len
);
945 void qemu_savevm_send_colo_enable(QEMUFile
*f
)
947 trace_savevm_send_colo_enable();
948 qemu_savevm_command_send(f
, MIG_CMD_ENABLE_COLO
, 0, NULL
);
951 void qemu_savevm_send_ping(QEMUFile
*f
, uint32_t value
)
955 trace_savevm_send_ping(value
);
956 buf
= cpu_to_be32(value
);
957 qemu_savevm_command_send(f
, MIG_CMD_PING
, sizeof(value
), (uint8_t *)&buf
);
960 void qemu_savevm_send_open_return_path(QEMUFile
*f
)
962 trace_savevm_send_open_return_path();
963 qemu_savevm_command_send(f
, MIG_CMD_OPEN_RETURN_PATH
, 0, NULL
);
966 /* We have a buffer of data to send; we don't want that all to be loaded
967 * by the command itself, so the command contains just the length of the
968 * extra buffer that we then send straight after it.
969 * TODO: Must be a better way to organise that
975 int qemu_savevm_send_packaged(QEMUFile
*f
, const uint8_t *buf
, size_t len
)
979 if (len
> MAX_VM_CMD_PACKAGED_SIZE
) {
980 error_report("%s: Unreasonably large packaged state: %zu",
985 tmp
= cpu_to_be32(len
);
987 trace_qemu_savevm_send_packaged();
988 qemu_savevm_command_send(f
, MIG_CMD_PACKAGED
, 4, (uint8_t *)&tmp
);
990 qemu_put_buffer(f
, buf
, len
);
995 /* Send prior to any postcopy transfer */
996 void qemu_savevm_send_postcopy_advise(QEMUFile
*f
)
998 if (migrate_postcopy_ram()) {
1000 tmp
[0] = cpu_to_be64(ram_pagesize_summary());
1001 tmp
[1] = cpu_to_be64(qemu_target_page_size());
1003 trace_qemu_savevm_send_postcopy_advise();
1004 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
,
1005 16, (uint8_t *)tmp
);
1007 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
, 0, NULL
);
1011 /* Sent prior to starting the destination running in postcopy, discard pages
1012 * that have already been sent but redirtied on the source.
1013 * CMD_POSTCOPY_RAM_DISCARD consist of:
1015 * byte Length of name field (not including 0)
1016 * n x byte RAM block name
1017 * byte 0 terminator (just for safety)
1018 * n x Byte ranges within the named RAMBlock
1019 * be64 Start of the range
1022 * name: RAMBlock name that these entries are part of
1023 * len: Number of page entries
1024 * start_list: 'len' addresses
1025 * length_list: 'len' addresses
1028 void qemu_savevm_send_postcopy_ram_discard(QEMUFile
*f
, const char *name
,
1030 uint64_t *start_list
,
1031 uint64_t *length_list
)
1036 size_t name_len
= strlen(name
);
1038 trace_qemu_savevm_send_postcopy_ram_discard(name
, len
);
1039 assert(name_len
< 256);
1040 buf
= g_malloc0(1 + 1 + name_len
+ 1 + (8 + 8) * len
);
1041 buf
[0] = postcopy_ram_discard_version
;
1043 memcpy(buf
+ 2, name
, name_len
);
1044 tmplen
= 2 + name_len
;
1045 buf
[tmplen
++] = '\0';
1047 for (t
= 0; t
< len
; t
++) {
1048 stq_be_p(buf
+ tmplen
, start_list
[t
]);
1050 stq_be_p(buf
+ tmplen
, length_list
[t
]);
1053 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RAM_DISCARD
, tmplen
, buf
);
1057 /* Get the destination into a state where it can receive postcopy data. */
1058 void qemu_savevm_send_postcopy_listen(QEMUFile
*f
)
1060 trace_savevm_send_postcopy_listen();
1061 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_LISTEN
, 0, NULL
);
1064 /* Kick the destination into running */
1065 void qemu_savevm_send_postcopy_run(QEMUFile
*f
)
1067 trace_savevm_send_postcopy_run();
1068 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RUN
, 0, NULL
);
1071 void qemu_savevm_send_postcopy_resume(QEMUFile
*f
)
1073 trace_savevm_send_postcopy_resume();
1074 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RESUME
, 0, NULL
);
1077 void qemu_savevm_send_recv_bitmap(QEMUFile
*f
, char *block_name
)
1082 trace_savevm_send_recv_bitmap(block_name
);
1084 buf
[0] = len
= strlen(block_name
);
1085 memcpy(buf
+ 1, block_name
, len
);
1087 qemu_savevm_command_send(f
, MIG_CMD_RECV_BITMAP
, len
+ 1, (uint8_t *)buf
);
1090 bool qemu_savevm_state_blocked(Error
**errp
)
1094 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1095 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
1096 error_setg(errp
, "State blocked by non-migratable device '%s'",
1104 void qemu_savevm_state_header(QEMUFile
*f
)
1106 trace_savevm_state_header();
1107 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1108 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1110 if (migrate_get_current()->send_configuration
) {
1111 qemu_put_byte(f
, QEMU_VM_CONFIGURATION
);
1112 vmstate_save_state(f
, &vmstate_configuration
, &savevm_state
, 0);
1116 int qemu_savevm_nr_failover_devices(void)
1121 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1122 if (se
->vmsd
&& se
->vmsd
->dev_unplug_pending
&&
1123 se
->vmsd
->dev_unplug_pending(se
->opaque
)) {
1131 bool qemu_savevm_state_guest_unplug_pending(void)
1136 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1137 if (!se
->vmsd
|| !se
->vmsd
->dev_unplug_pending
) {
1140 if (se
->vmsd
->dev_unplug_pending(se
->opaque
)) {
1148 void qemu_savevm_state_setup(QEMUFile
*f
)
1151 Error
*local_err
= NULL
;
1154 trace_savevm_state_setup();
1155 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1156 if (!se
->ops
|| !se
->ops
->save_setup
) {
1159 if (se
->ops
->is_active
) {
1160 if (!se
->ops
->is_active(se
->opaque
)) {
1164 save_section_header(f
, se
, QEMU_VM_SECTION_START
);
1166 ret
= se
->ops
->save_setup(f
, se
->opaque
);
1167 save_section_footer(f
, se
);
1169 qemu_file_set_error(f
, ret
);
1174 if (precopy_notify(PRECOPY_NOTIFY_SETUP
, &local_err
)) {
1175 error_report_err(local_err
);
1179 int qemu_savevm_state_resume_prepare(MigrationState
*s
)
1184 trace_savevm_state_resume_prepare();
1186 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1187 if (!se
->ops
|| !se
->ops
->resume_prepare
) {
1190 if (se
->ops
->is_active
) {
1191 if (!se
->ops
->is_active(se
->opaque
)) {
1195 ret
= se
->ops
->resume_prepare(s
, se
->opaque
);
1205 * this function has three return values:
1206 * negative: there was one error, and we have -errno.
1207 * 0 : We haven't finished, caller have to go again
1208 * 1 : We have finished, we can go to complete phase
1210 int qemu_savevm_state_iterate(QEMUFile
*f
, bool postcopy
)
1215 trace_savevm_state_iterate();
1216 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1217 if (!se
->ops
|| !se
->ops
->save_live_iterate
) {
1220 if (se
->ops
->is_active
&&
1221 !se
->ops
->is_active(se
->opaque
)) {
1224 if (se
->ops
->is_active_iterate
&&
1225 !se
->ops
->is_active_iterate(se
->opaque
)) {
1229 * In the postcopy phase, any device that doesn't know how to
1230 * do postcopy should have saved it's state in the _complete
1231 * call that's already run, it might get confused if we call
1232 * iterate afterwards.
1235 !(se
->ops
->has_postcopy
&& se
->ops
->has_postcopy(se
->opaque
))) {
1238 if (qemu_file_rate_limit(f
)) {
1241 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1243 save_section_header(f
, se
, QEMU_VM_SECTION_PART
);
1245 ret
= se
->ops
->save_live_iterate(f
, se
->opaque
);
1246 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1247 save_section_footer(f
, se
);
1250 error_report("failed to save SaveStateEntry with id(name): %d(%s)",
1251 se
->section_id
, se
->idstr
);
1252 qemu_file_set_error(f
, ret
);
1255 /* Do not proceed to the next vmstate before this one reported
1256 completion of the current stage. This serializes the migration
1257 and reduces the probability that a faster changing state is
1258 synchronized over and over again. */
1265 static bool should_send_vmdesc(void)
1267 MachineState
*machine
= MACHINE(qdev_get_machine());
1268 bool in_postcopy
= migration_in_postcopy();
1269 return !machine
->suppress_vmdesc
&& !in_postcopy
;
1273 * Calls the save_live_complete_postcopy methods
1274 * causing the last few pages to be sent immediately and doing any associated
1276 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1277 * all the other devices, but that happens at the point we switch to postcopy.
1279 void qemu_savevm_state_complete_postcopy(QEMUFile
*f
)
1284 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1285 if (!se
->ops
|| !se
->ops
->save_live_complete_postcopy
) {
1288 if (se
->ops
->is_active
) {
1289 if (!se
->ops
->is_active(se
->opaque
)) {
1293 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1295 qemu_put_byte(f
, QEMU_VM_SECTION_END
);
1296 qemu_put_be32(f
, se
->section_id
);
1298 ret
= se
->ops
->save_live_complete_postcopy(f
, se
->opaque
);
1299 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1300 save_section_footer(f
, se
);
1302 qemu_file_set_error(f
, ret
);
1307 qemu_put_byte(f
, QEMU_VM_EOF
);
1312 int qemu_savevm_state_complete_precopy_iterable(QEMUFile
*f
, bool in_postcopy
)
1317 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1319 (in_postcopy
&& se
->ops
->has_postcopy
&&
1320 se
->ops
->has_postcopy(se
->opaque
)) ||
1321 !se
->ops
->save_live_complete_precopy
) {
1325 if (se
->ops
->is_active
) {
1326 if (!se
->ops
->is_active(se
->opaque
)) {
1330 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1332 save_section_header(f
, se
, QEMU_VM_SECTION_END
);
1334 ret
= se
->ops
->save_live_complete_precopy(f
, se
->opaque
);
1335 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1336 save_section_footer(f
, se
);
1338 qemu_file_set_error(f
, ret
);
1347 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile
*f
,
1349 bool inactivate_disks
)
1351 g_autoptr(QJSON
) vmdesc
= NULL
;
1356 vmdesc
= qjson_new();
1357 json_prop_int(vmdesc
, "page_size", qemu_target_page_size());
1358 json_start_array(vmdesc
, "devices");
1359 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1361 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1364 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1365 trace_savevm_section_skip(se
->idstr
, se
->section_id
);
1369 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1371 json_start_object(vmdesc
, NULL
);
1372 json_prop_str(vmdesc
, "name", se
->idstr
);
1373 json_prop_int(vmdesc
, "instance_id", se
->instance_id
);
1375 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1376 ret
= vmstate_save(f
, se
, vmdesc
);
1378 qemu_file_set_error(f
, ret
);
1381 trace_savevm_section_end(se
->idstr
, se
->section_id
, 0);
1382 save_section_footer(f
, se
);
1384 json_end_object(vmdesc
);
1387 if (inactivate_disks
) {
1388 /* Inactivate before sending QEMU_VM_EOF so that the
1389 * bdrv_invalidate_cache_all() on the other end won't fail. */
1390 ret
= bdrv_inactivate_all();
1392 error_report("%s: bdrv_inactivate_all() failed (%d)",
1394 qemu_file_set_error(f
, ret
);
1399 /* Postcopy stream will still be going */
1400 qemu_put_byte(f
, QEMU_VM_EOF
);
1403 json_end_array(vmdesc
);
1404 qjson_finish(vmdesc
);
1405 vmdesc_len
= strlen(qjson_get_str(vmdesc
));
1407 if (should_send_vmdesc()) {
1408 qemu_put_byte(f
, QEMU_VM_VMDESCRIPTION
);
1409 qemu_put_be32(f
, vmdesc_len
);
1410 qemu_put_buffer(f
, (uint8_t *)qjson_get_str(vmdesc
), vmdesc_len
);
1416 int qemu_savevm_state_complete_precopy(QEMUFile
*f
, bool iterable_only
,
1417 bool inactivate_disks
)
1420 Error
*local_err
= NULL
;
1421 bool in_postcopy
= migration_in_postcopy();
1423 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE
, &local_err
)) {
1424 error_report_err(local_err
);
1427 trace_savevm_state_complete_precopy();
1429 cpu_synchronize_all_states();
1431 if (!in_postcopy
|| iterable_only
) {
1432 ret
= qemu_savevm_state_complete_precopy_iterable(f
, in_postcopy
);
1438 if (iterable_only
) {
1442 ret
= qemu_savevm_state_complete_precopy_non_iterable(f
, in_postcopy
,
1453 /* Give an estimate of the amount left to be transferred,
1454 * the result is split into the amount for units that can and
1455 * for units that can't do postcopy.
1457 void qemu_savevm_state_pending(QEMUFile
*f
, uint64_t threshold_size
,
1458 uint64_t *res_precopy_only
,
1459 uint64_t *res_compatible
,
1460 uint64_t *res_postcopy_only
)
1464 *res_precopy_only
= 0;
1465 *res_compatible
= 0;
1466 *res_postcopy_only
= 0;
1469 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1470 if (!se
->ops
|| !se
->ops
->save_live_pending
) {
1473 if (se
->ops
->is_active
) {
1474 if (!se
->ops
->is_active(se
->opaque
)) {
1478 se
->ops
->save_live_pending(f
, se
->opaque
, threshold_size
,
1479 res_precopy_only
, res_compatible
,
1484 void qemu_savevm_state_cleanup(void)
1487 Error
*local_err
= NULL
;
1489 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP
, &local_err
)) {
1490 error_report_err(local_err
);
1493 trace_savevm_state_cleanup();
1494 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1495 if (se
->ops
&& se
->ops
->save_cleanup
) {
1496 se
->ops
->save_cleanup(se
->opaque
);
1501 static int qemu_savevm_state(QEMUFile
*f
, Error
**errp
)
1504 MigrationState
*ms
= migrate_get_current();
1505 MigrationStatus status
;
1507 if (migration_is_setup_or_active(ms
->state
) ||
1508 ms
->state
== MIGRATION_STATUS_CANCELLING
||
1509 ms
->state
== MIGRATION_STATUS_COLO
) {
1510 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1514 if (migrate_use_block()) {
1515 error_setg(errp
, "Block migration and snapshots are incompatible");
1520 memset(&ram_counters
, 0, sizeof(ram_counters
));
1521 ms
->to_dst_file
= f
;
1523 qemu_mutex_unlock_iothread();
1524 qemu_savevm_state_header(f
);
1525 qemu_savevm_state_setup(f
);
1526 qemu_mutex_lock_iothread();
1528 while (qemu_file_get_error(f
) == 0) {
1529 if (qemu_savevm_state_iterate(f
, false) > 0) {
1534 ret
= qemu_file_get_error(f
);
1536 qemu_savevm_state_complete_precopy(f
, false, false);
1537 ret
= qemu_file_get_error(f
);
1539 qemu_savevm_state_cleanup();
1541 error_setg_errno(errp
, -ret
, "Error while writing VM state");
1545 status
= MIGRATION_STATUS_FAILED
;
1547 status
= MIGRATION_STATUS_COMPLETED
;
1549 migrate_set_state(&ms
->state
, MIGRATION_STATUS_SETUP
, status
);
1551 /* f is outer parameter, it should not stay in global migration state after
1552 * this function finished */
1553 ms
->to_dst_file
= NULL
;
1558 void qemu_savevm_live_state(QEMUFile
*f
)
1560 /* save QEMU_VM_SECTION_END section */
1561 qemu_savevm_state_complete_precopy(f
, true, false);
1562 qemu_put_byte(f
, QEMU_VM_EOF
);
1565 int qemu_save_device_state(QEMUFile
*f
)
1569 if (!migration_in_colo_state()) {
1570 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1571 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1573 cpu_synchronize_all_states();
1575 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1581 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1584 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1588 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1590 ret
= vmstate_save(f
, se
, NULL
);
1595 save_section_footer(f
, se
);
1598 qemu_put_byte(f
, QEMU_VM_EOF
);
1600 return qemu_file_get_error(f
);
1603 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
1607 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1608 if (!strcmp(se
->idstr
, idstr
) &&
1609 (instance_id
== se
->instance_id
||
1610 instance_id
== se
->alias_id
))
1612 /* Migrating from an older version? */
1613 if (strstr(se
->idstr
, idstr
) && se
->compat
) {
1614 if (!strcmp(se
->compat
->idstr
, idstr
) &&
1615 (instance_id
== se
->compat
->instance_id
||
1616 instance_id
== se
->alias_id
))
1623 enum LoadVMExitCodes
{
1624 /* Allow a command to quit all layers of nested loadvm loops */
1628 /* ------ incoming postcopy messages ------ */
1629 /* 'advise' arrives before any transfers just to tell us that a postcopy
1630 * *might* happen - it might be skipped if precopy transferred everything
1633 static int loadvm_postcopy_handle_advise(MigrationIncomingState
*mis
,
1636 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1637 uint64_t remote_pagesize_summary
, local_pagesize_summary
, remote_tps
;
1638 Error
*local_err
= NULL
;
1640 trace_loadvm_postcopy_handle_advise();
1641 if (ps
!= POSTCOPY_INCOMING_NONE
) {
1642 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps
);
1648 if (migrate_postcopy_ram()) {
1649 error_report("RAM postcopy is enabled but have 0 byte advise");
1654 if (!migrate_postcopy_ram()) {
1655 error_report("RAM postcopy is disabled but have 16 byte advise");
1660 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len
);
1664 if (!postcopy_ram_supported_by_host(mis
)) {
1665 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
1669 remote_pagesize_summary
= qemu_get_be64(mis
->from_src_file
);
1670 local_pagesize_summary
= ram_pagesize_summary();
1672 if (remote_pagesize_summary
!= local_pagesize_summary
) {
1674 * This detects two potential causes of mismatch:
1675 * a) A mismatch in host page sizes
1676 * Some combinations of mismatch are probably possible but it gets
1677 * a bit more complicated. In particular we need to place whole
1678 * host pages on the dest at once, and we need to ensure that we
1679 * handle dirtying to make sure we never end up sending part of
1680 * a hostpage on it's own.
1681 * b) The use of different huge page sizes on source/destination
1682 * a more fine grain test is performed during RAM block migration
1683 * but this test here causes a nice early clear failure, and
1684 * also fails when passed to an older qemu that doesn't
1687 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1689 remote_pagesize_summary
, local_pagesize_summary
);
1693 remote_tps
= qemu_get_be64(mis
->from_src_file
);
1694 if (remote_tps
!= qemu_target_page_size()) {
1696 * Again, some differences could be dealt with, but for now keep it
1699 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1700 (int)remote_tps
, qemu_target_page_size());
1704 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE
, &local_err
)) {
1705 error_report_err(local_err
);
1709 if (ram_postcopy_incoming_init(mis
)) {
1716 /* After postcopy we will be told to throw some pages away since they're
1717 * dirty and will have to be demand fetched. Must happen before CPU is
1719 * There can be 0..many of these messages, each encoding multiple pages.
1721 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState
*mis
,
1726 PostcopyState ps
= postcopy_state_get();
1728 trace_loadvm_postcopy_ram_handle_discard();
1731 case POSTCOPY_INCOMING_ADVISE
:
1733 tmp
= postcopy_ram_prepare_discard(mis
);
1739 case POSTCOPY_INCOMING_DISCARD
:
1740 /* Expected state */
1744 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1748 /* We're expecting a
1750 * a RAM ID string (length byte, name, 0 term)
1751 * then at least 1 16 byte chunk
1753 if (len
< (1 + 1 + 1 + 1 + 2 * 8)) {
1754 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1758 tmp
= qemu_get_byte(mis
->from_src_file
);
1759 if (tmp
!= postcopy_ram_discard_version
) {
1760 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp
);
1764 if (!qemu_get_counted_string(mis
->from_src_file
, ramid
)) {
1765 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1768 tmp
= qemu_get_byte(mis
->from_src_file
);
1770 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp
);
1774 len
-= 3 + strlen(ramid
);
1776 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1779 trace_loadvm_postcopy_ram_handle_discard_header(ramid
, len
);
1781 uint64_t start_addr
, block_length
;
1782 start_addr
= qemu_get_be64(mis
->from_src_file
);
1783 block_length
= qemu_get_be64(mis
->from_src_file
);
1786 int ret
= ram_discard_range(ramid
, start_addr
, block_length
);
1791 trace_loadvm_postcopy_ram_handle_discard_end();
1797 * Triggered by a postcopy_listen command; this thread takes over reading
1798 * the input stream, leaving the main thread free to carry on loading the rest
1799 * of the device state (from RAM).
1800 * (TODO:This could do with being in a postcopy file - but there again it's
1801 * just another input loop, not that postcopy specific)
1803 static void *postcopy_ram_listen_thread(void *opaque
)
1805 MigrationIncomingState
*mis
= migration_incoming_get_current();
1806 QEMUFile
*f
= mis
->from_src_file
;
1809 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
1810 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1811 qemu_sem_post(&mis
->listen_thread_sem
);
1812 trace_postcopy_ram_listen_thread_start();
1814 rcu_register_thread();
1816 * Because we're a thread and not a coroutine we can't yield
1817 * in qemu_file, and thus we must be blocking now.
1819 qemu_file_set_blocking(f
, true);
1820 load_res
= qemu_loadvm_state_main(f
, mis
);
1823 * This is tricky, but, mis->from_src_file can change after it
1824 * returns, when postcopy recovery happened. In the future, we may
1825 * want a wrapper for the QEMUFile handle.
1827 f
= mis
->from_src_file
;
1829 /* And non-blocking again so we don't block in any cleanup */
1830 qemu_file_set_blocking(f
, false);
1832 trace_postcopy_ram_listen_thread_exit();
1834 error_report("%s: loadvm failed: %d", __func__
, load_res
);
1835 qemu_file_set_error(f
, load_res
);
1836 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1837 MIGRATION_STATUS_FAILED
);
1840 * This looks good, but it's possible that the device loading in the
1841 * main thread hasn't finished yet, and so we might not be in 'RUN'
1842 * state yet; wait for the end of the main thread.
1844 qemu_event_wait(&mis
->main_thread_load_event
);
1846 postcopy_ram_incoming_cleanup(mis
);
1850 * If something went wrong then we have a bad state so exit;
1851 * depending how far we got it might be possible at this point
1852 * to leave the guest running and fire MCEs for pages that never
1853 * arrived as a desperate recovery step.
1855 rcu_unregister_thread();
1859 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1860 MIGRATION_STATUS_COMPLETED
);
1862 * If everything has worked fine, then the main thread has waited
1863 * for us to start, and we're the last use of the mis.
1864 * (If something broke then qemu will have to exit anyway since it's
1865 * got a bad migration state).
1867 migration_incoming_state_destroy();
1868 qemu_loadvm_state_cleanup();
1870 rcu_unregister_thread();
1871 mis
->have_listen_thread
= false;
1872 postcopy_state_set(POSTCOPY_INCOMING_END
);
1877 /* After this message we must be able to immediately receive postcopy data */
1878 static int loadvm_postcopy_handle_listen(MigrationIncomingState
*mis
)
1880 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_LISTENING
);
1881 trace_loadvm_postcopy_handle_listen();
1882 Error
*local_err
= NULL
;
1884 if (ps
!= POSTCOPY_INCOMING_ADVISE
&& ps
!= POSTCOPY_INCOMING_DISCARD
) {
1885 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps
);
1888 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
1890 * A rare case, we entered listen without having to do any discards,
1891 * so do the setup that's normally done at the time of the 1st discard.
1893 if (migrate_postcopy_ram()) {
1894 postcopy_ram_prepare_discard(mis
);
1899 * Sensitise RAM - can now generate requests for blocks that don't exist
1900 * However, at this point the CPU shouldn't be running, and the IO
1901 * shouldn't be doing anything yet so don't actually expect requests
1903 if (migrate_postcopy_ram()) {
1904 if (postcopy_ram_incoming_setup(mis
)) {
1905 postcopy_ram_incoming_cleanup(mis
);
1910 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN
, &local_err
)) {
1911 error_report_err(local_err
);
1915 mis
->have_listen_thread
= true;
1916 /* Start up the listening thread and wait for it to signal ready */
1917 qemu_sem_init(&mis
->listen_thread_sem
, 0);
1918 qemu_thread_create(&mis
->listen_thread
, "postcopy/listen",
1919 postcopy_ram_listen_thread
, NULL
,
1920 QEMU_THREAD_DETACHED
);
1921 qemu_sem_wait(&mis
->listen_thread_sem
);
1922 qemu_sem_destroy(&mis
->listen_thread_sem
);
1927 static void loadvm_postcopy_handle_run_bh(void *opaque
)
1929 Error
*local_err
= NULL
;
1930 MigrationIncomingState
*mis
= opaque
;
1932 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1935 cpu_synchronize_all_post_init();
1937 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
1939 /* Make sure all file formats flush their mutable metadata.
1940 * If we get an error here, just don't restart the VM yet. */
1941 bdrv_invalidate_cache_all(&local_err
);
1943 error_report_err(local_err
);
1948 trace_loadvm_postcopy_handle_run_cpu_sync();
1950 trace_loadvm_postcopy_handle_run_vmstart();
1952 dirty_bitmap_mig_before_vm_start();
1955 /* Hold onto your hats, starting the CPU */
1958 /* leave it paused and let management decide when to start the CPU */
1959 runstate_set(RUN_STATE_PAUSED
);
1962 qemu_bh_delete(mis
->bh
);
1965 /* After all discards we can start running and asking for pages */
1966 static int loadvm_postcopy_handle_run(MigrationIncomingState
*mis
)
1968 PostcopyState ps
= postcopy_state_get();
1970 trace_loadvm_postcopy_handle_run();
1971 if (ps
!= POSTCOPY_INCOMING_LISTENING
) {
1972 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps
);
1976 postcopy_state_set(POSTCOPY_INCOMING_RUNNING
);
1977 mis
->bh
= qemu_bh_new(loadvm_postcopy_handle_run_bh
, mis
);
1978 qemu_bh_schedule(mis
->bh
);
1980 /* We need to finish reading the stream from the package
1981 * and also stop reading anything more from the stream that loaded the
1982 * package (since it's now being read by the listener thread).
1983 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1988 static int loadvm_postcopy_handle_resume(MigrationIncomingState
*mis
)
1990 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
1991 error_report("%s: illegal resume received", __func__
);
1992 /* Don't fail the load, only for this. */
1997 * This means source VM is ready to resume the postcopy migration.
1998 * It's time to switch state and release the fault thread to
1999 * continue service page faults.
2001 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2002 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2003 qemu_sem_post(&mis
->postcopy_pause_sem_fault
);
2005 trace_loadvm_postcopy_handle_resume();
2007 /* Tell source that "we are ready" */
2008 migrate_send_rp_resume_ack(mis
, MIGRATION_RESUME_ACK_VALUE
);
2014 * Immediately following this command is a blob of data containing an embedded
2015 * chunk of migration stream; read it and load it.
2017 * @mis: Incoming state
2018 * @length: Length of packaged data to read
2020 * Returns: Negative values on error
2023 static int loadvm_handle_cmd_packaged(MigrationIncomingState
*mis
)
2027 QIOChannelBuffer
*bioc
;
2029 length
= qemu_get_be32(mis
->from_src_file
);
2030 trace_loadvm_handle_cmd_packaged(length
);
2032 if (length
> MAX_VM_CMD_PACKAGED_SIZE
) {
2033 error_report("Unreasonably large packaged state: %zu", length
);
2037 bioc
= qio_channel_buffer_new(length
);
2038 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-loadvm-buffer");
2039 ret
= qemu_get_buffer(mis
->from_src_file
,
2042 if (ret
!= length
) {
2043 object_unref(OBJECT(bioc
));
2044 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2046 return (ret
< 0) ? ret
: -EAGAIN
;
2048 bioc
->usage
+= length
;
2049 trace_loadvm_handle_cmd_packaged_received(ret
);
2051 QEMUFile
*packf
= qemu_fopen_channel_input(QIO_CHANNEL(bioc
));
2053 ret
= qemu_loadvm_state_main(packf
, mis
);
2054 trace_loadvm_handle_cmd_packaged_main(ret
);
2056 object_unref(OBJECT(bioc
));
2062 * Handle request that source requests for recved_bitmap on
2063 * destination. Payload format:
2065 * len (1 byte) + ramblock_name (<255 bytes)
2067 static int loadvm_handle_recv_bitmap(MigrationIncomingState
*mis
,
2070 QEMUFile
*file
= mis
->from_src_file
;
2072 char block_name
[256];
2075 cnt
= qemu_get_counted_string(file
, block_name
);
2077 error_report("%s: failed to read block name", __func__
);
2081 /* Validate before using the data */
2082 if (qemu_file_get_error(file
)) {
2083 return qemu_file_get_error(file
);
2086 if (len
!= cnt
+ 1) {
2087 error_report("%s: invalid payload length (%d)", __func__
, len
);
2091 rb
= qemu_ram_block_by_name(block_name
);
2093 error_report("%s: block '%s' not found", __func__
, block_name
);
2097 migrate_send_rp_recv_bitmap(mis
, block_name
);
2099 trace_loadvm_handle_recv_bitmap(block_name
);
2104 static int loadvm_process_enable_colo(MigrationIncomingState
*mis
)
2106 migration_incoming_enable_colo();
2107 return colo_init_ram_cache();
2111 * Process an incoming 'QEMU_VM_COMMAND'
2112 * 0 just a normal return
2113 * LOADVM_QUIT All good, but exit the loop
2116 static int loadvm_process_command(QEMUFile
*f
)
2118 MigrationIncomingState
*mis
= migration_incoming_get_current();
2123 cmd
= qemu_get_be16(f
);
2124 len
= qemu_get_be16(f
);
2126 /* Check validity before continue processing of cmds */
2127 if (qemu_file_get_error(f
)) {
2128 return qemu_file_get_error(f
);
2131 trace_loadvm_process_command(cmd
, len
);
2132 if (cmd
>= MIG_CMD_MAX
|| cmd
== MIG_CMD_INVALID
) {
2133 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd
, len
);
2137 if (mig_cmd_args
[cmd
].len
!= -1 && mig_cmd_args
[cmd
].len
!= len
) {
2138 error_report("%s received with bad length - expecting %zu, got %d",
2139 mig_cmd_args
[cmd
].name
,
2140 (size_t)mig_cmd_args
[cmd
].len
, len
);
2145 case MIG_CMD_OPEN_RETURN_PATH
:
2146 if (mis
->to_src_file
) {
2147 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2148 /* Not really a problem, so don't give up */
2151 mis
->to_src_file
= qemu_file_get_return_path(f
);
2152 if (!mis
->to_src_file
) {
2153 error_report("CMD_OPEN_RETURN_PATH failed");
2159 tmp32
= qemu_get_be32(f
);
2160 trace_loadvm_process_command_ping(tmp32
);
2161 if (!mis
->to_src_file
) {
2162 error_report("CMD_PING (0x%x) received with no return path",
2166 migrate_send_rp_pong(mis
, tmp32
);
2169 case MIG_CMD_PACKAGED
:
2170 return loadvm_handle_cmd_packaged(mis
);
2172 case MIG_CMD_POSTCOPY_ADVISE
:
2173 return loadvm_postcopy_handle_advise(mis
, len
);
2175 case MIG_CMD_POSTCOPY_LISTEN
:
2176 return loadvm_postcopy_handle_listen(mis
);
2178 case MIG_CMD_POSTCOPY_RUN
:
2179 return loadvm_postcopy_handle_run(mis
);
2181 case MIG_CMD_POSTCOPY_RAM_DISCARD
:
2182 return loadvm_postcopy_ram_handle_discard(mis
, len
);
2184 case MIG_CMD_POSTCOPY_RESUME
:
2185 return loadvm_postcopy_handle_resume(mis
);
2187 case MIG_CMD_RECV_BITMAP
:
2188 return loadvm_handle_recv_bitmap(mis
, len
);
2190 case MIG_CMD_ENABLE_COLO
:
2191 return loadvm_process_enable_colo(mis
);
2198 * Read a footer off the wire and check that it matches the expected section
2200 * Returns: true if the footer was good
2201 * false if there is a problem (and calls error_report to say why)
2203 static bool check_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
2207 uint32_t read_section_id
;
2209 if (!migrate_get_current()->send_section_footer
) {
2210 /* No footer to check */
2214 read_mark
= qemu_get_byte(f
);
2216 ret
= qemu_file_get_error(f
);
2218 error_report("%s: Read section footer failed: %d",
2223 if (read_mark
!= QEMU_VM_SECTION_FOOTER
) {
2224 error_report("Missing section footer for %s", se
->idstr
);
2228 read_section_id
= qemu_get_be32(f
);
2229 if (read_section_id
!= se
->load_section_id
) {
2230 error_report("Mismatched section id in footer for %s -"
2231 " read 0x%x expected 0x%x",
2232 se
->idstr
, read_section_id
, se
->load_section_id
);
2241 qemu_loadvm_section_start_full(QEMUFile
*f
, MigrationIncomingState
*mis
)
2243 uint32_t instance_id
, version_id
, section_id
;
2248 /* Read section start */
2249 section_id
= qemu_get_be32(f
);
2250 if (!qemu_get_counted_string(f
, idstr
)) {
2251 error_report("Unable to read ID string for section %u",
2255 instance_id
= qemu_get_be32(f
);
2256 version_id
= qemu_get_be32(f
);
2258 ret
= qemu_file_get_error(f
);
2260 error_report("%s: Failed to read instance/version ID: %d",
2265 trace_qemu_loadvm_state_section_startfull(section_id
, idstr
,
2266 instance_id
, version_id
);
2267 /* Find savevm section */
2268 se
= find_se(idstr
, instance_id
);
2270 error_report("Unknown savevm section or instance '%s' %d. "
2271 "Make sure that your current VM setup matches your "
2272 "saved VM setup, including any hotplugged devices",
2273 idstr
, instance_id
);
2277 /* Validate version */
2278 if (version_id
> se
->version_id
) {
2279 error_report("savevm: unsupported version %d for '%s' v%d",
2280 version_id
, idstr
, se
->version_id
);
2283 se
->load_version_id
= version_id
;
2284 se
->load_section_id
= section_id
;
2286 /* Validate if it is a device's state */
2287 if (xen_enabled() && se
->is_ram
) {
2288 error_report("loadvm: %s RAM loading not allowed on Xen", idstr
);
2292 ret
= vmstate_load(f
, se
);
2294 error_report("error while loading state for instance 0x%x of"
2295 " device '%s'", instance_id
, idstr
);
2298 if (!check_section_footer(f
, se
)) {
2306 qemu_loadvm_section_part_end(QEMUFile
*f
, MigrationIncomingState
*mis
)
2308 uint32_t section_id
;
2312 section_id
= qemu_get_be32(f
);
2314 ret
= qemu_file_get_error(f
);
2316 error_report("%s: Failed to read section ID: %d",
2321 trace_qemu_loadvm_state_section_partend(section_id
);
2322 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2323 if (se
->load_section_id
== section_id
) {
2328 error_report("Unknown savevm section %d", section_id
);
2332 ret
= vmstate_load(f
, se
);
2334 error_report("error while loading state section id %d(%s)",
2335 section_id
, se
->idstr
);
2338 if (!check_section_footer(f
, se
)) {
2345 static int qemu_loadvm_state_header(QEMUFile
*f
)
2350 v
= qemu_get_be32(f
);
2351 if (v
!= QEMU_VM_FILE_MAGIC
) {
2352 error_report("Not a migration stream");
2356 v
= qemu_get_be32(f
);
2357 if (v
== QEMU_VM_FILE_VERSION_COMPAT
) {
2358 error_report("SaveVM v2 format is obsolete and don't work anymore");
2361 if (v
!= QEMU_VM_FILE_VERSION
) {
2362 error_report("Unsupported migration stream version");
2366 if (migrate_get_current()->send_configuration
) {
2367 if (qemu_get_byte(f
) != QEMU_VM_CONFIGURATION
) {
2368 error_report("Configuration section missing");
2369 qemu_loadvm_state_cleanup();
2372 ret
= vmstate_load_state(f
, &vmstate_configuration
, &savevm_state
, 0);
2375 qemu_loadvm_state_cleanup();
2382 static int qemu_loadvm_state_setup(QEMUFile
*f
)
2387 trace_loadvm_state_setup();
2388 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2389 if (!se
->ops
|| !se
->ops
->load_setup
) {
2392 if (se
->ops
->is_active
) {
2393 if (!se
->ops
->is_active(se
->opaque
)) {
2398 ret
= se
->ops
->load_setup(f
, se
->opaque
);
2400 qemu_file_set_error(f
, ret
);
2401 error_report("Load state of device %s failed", se
->idstr
);
2408 void qemu_loadvm_state_cleanup(void)
2412 trace_loadvm_state_cleanup();
2413 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2414 if (se
->ops
&& se
->ops
->load_cleanup
) {
2415 se
->ops
->load_cleanup(se
->opaque
);
2420 /* Return true if we should continue the migration, or false. */
2421 static bool postcopy_pause_incoming(MigrationIncomingState
*mis
)
2423 trace_postcopy_pause_incoming();
2425 /* Clear the triggered bit to allow one recovery */
2426 mis
->postcopy_recover_triggered
= false;
2428 assert(mis
->from_src_file
);
2429 qemu_file_shutdown(mis
->from_src_file
);
2430 qemu_fclose(mis
->from_src_file
);
2431 mis
->from_src_file
= NULL
;
2433 assert(mis
->to_src_file
);
2434 qemu_file_shutdown(mis
->to_src_file
);
2435 qemu_mutex_lock(&mis
->rp_mutex
);
2436 qemu_fclose(mis
->to_src_file
);
2437 mis
->to_src_file
= NULL
;
2438 qemu_mutex_unlock(&mis
->rp_mutex
);
2440 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2441 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2443 /* Notify the fault thread for the invalidated file handle */
2444 postcopy_fault_thread_notify(mis
);
2446 error_report("Detected IO failure for postcopy. "
2447 "Migration paused.");
2449 while (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2450 qemu_sem_wait(&mis
->postcopy_pause_sem_dst
);
2453 trace_postcopy_pause_incoming_continued();
2458 int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
)
2460 uint8_t section_type
;
2465 section_type
= qemu_get_byte(f
);
2467 if (qemu_file_get_error(f
)) {
2468 ret
= qemu_file_get_error(f
);
2472 trace_qemu_loadvm_state_section(section_type
);
2473 switch (section_type
) {
2474 case QEMU_VM_SECTION_START
:
2475 case QEMU_VM_SECTION_FULL
:
2476 ret
= qemu_loadvm_section_start_full(f
, mis
);
2481 case QEMU_VM_SECTION_PART
:
2482 case QEMU_VM_SECTION_END
:
2483 ret
= qemu_loadvm_section_part_end(f
, mis
);
2488 case QEMU_VM_COMMAND
:
2489 ret
= loadvm_process_command(f
);
2490 trace_qemu_loadvm_state_section_command(ret
);
2491 if ((ret
< 0) || (ret
== LOADVM_QUIT
)) {
2496 /* This is the end of migration */
2499 error_report("Unknown savevm section type %d", section_type
);
2507 qemu_file_set_error(f
, ret
);
2510 * If we are during an active postcopy, then we pause instead
2511 * of bail out to at least keep the VM's dirty data. Note
2512 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2513 * during which we're still receiving device states and we
2514 * still haven't yet started the VM on destination.
2516 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
2517 postcopy_pause_incoming(mis
)) {
2518 /* Reset f to point to the newly created channel */
2519 f
= mis
->from_src_file
;
2526 int qemu_loadvm_state(QEMUFile
*f
)
2528 MigrationIncomingState
*mis
= migration_incoming_get_current();
2529 Error
*local_err
= NULL
;
2532 if (qemu_savevm_state_blocked(&local_err
)) {
2533 error_report_err(local_err
);
2537 ret
= qemu_loadvm_state_header(f
);
2542 if (qemu_loadvm_state_setup(f
) != 0) {
2546 cpu_synchronize_all_pre_loadvm();
2548 ret
= qemu_loadvm_state_main(f
, mis
);
2549 qemu_event_set(&mis
->main_thread_load_event
);
2551 trace_qemu_loadvm_state_post_main(ret
);
2553 if (mis
->have_listen_thread
) {
2554 /* Listen thread still going, can't clean up yet */
2559 ret
= qemu_file_get_error(f
);
2563 * Try to read in the VMDESC section as well, so that dumping tools that
2564 * intercept our migration stream have the chance to see it.
2567 /* We've got to be careful; if we don't read the data and just shut the fd
2568 * then the sender can error if we close while it's still sending.
2569 * We also mustn't read data that isn't there; some transports (RDMA)
2570 * will stall waiting for that data when the source has already closed.
2572 if (ret
== 0 && should_send_vmdesc()) {
2575 uint8_t section_type
= qemu_get_byte(f
);
2577 if (section_type
!= QEMU_VM_VMDESCRIPTION
) {
2578 error_report("Expected vmdescription section, but got %d",
2581 * It doesn't seem worth failing at this point since
2582 * we apparently have an otherwise valid VM state
2585 buf
= g_malloc(0x1000);
2586 size
= qemu_get_be32(f
);
2589 uint32_t read_chunk
= MIN(size
, 0x1000);
2590 qemu_get_buffer(f
, buf
, read_chunk
);
2597 qemu_loadvm_state_cleanup();
2598 cpu_synchronize_all_post_init();
2603 int qemu_load_device_state(QEMUFile
*f
)
2605 MigrationIncomingState
*mis
= migration_incoming_get_current();
2608 /* Load QEMU_VM_SECTION_FULL section */
2609 ret
= qemu_loadvm_state_main(f
, mis
);
2611 error_report("Failed to load device state: %d", ret
);
2615 cpu_synchronize_all_post_init();
2619 int save_snapshot(const char *name
, Error
**errp
)
2621 BlockDriverState
*bs
, *bs1
;
2622 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
2625 int saved_vm_running
;
2626 uint64_t vm_state_size
;
2629 AioContext
*aio_context
;
2631 if (migration_is_blocked(errp
)) {
2635 if (!replay_can_snapshot()) {
2636 error_setg(errp
, "Record/replay does not allow making snapshot "
2637 "right now. Try once more later.");
2641 if (!bdrv_all_can_snapshot(&bs
)) {
2642 error_setg(errp
, "Device '%s' is writable but does not support "
2643 "snapshots", bdrv_get_device_name(bs
));
2647 /* Delete old snapshots of the same name */
2649 ret
= bdrv_all_delete_snapshot(name
, &bs1
, errp
);
2651 error_prepend(errp
, "Error while deleting snapshot on device "
2652 "'%s': ", bdrv_get_device_name(bs1
));
2657 bs
= bdrv_all_find_vmstate_bs();
2659 error_setg(errp
, "No block device can accept snapshots");
2662 aio_context
= bdrv_get_aio_context(bs
);
2664 saved_vm_running
= runstate_is_running();
2666 ret
= global_state_store();
2668 error_setg(errp
, "Error saving global state");
2671 vm_stop(RUN_STATE_SAVE_VM
);
2673 bdrv_drain_all_begin();
2675 aio_context_acquire(aio_context
);
2677 memset(sn
, 0, sizeof(*sn
));
2679 /* fill auxiliary fields */
2680 qemu_gettimeofday(&tv
);
2681 sn
->date_sec
= tv
.tv_sec
;
2682 sn
->date_nsec
= tv
.tv_usec
* 1000;
2683 sn
->vm_clock_nsec
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
2686 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
2688 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
2689 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
2691 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
2694 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2695 localtime_r((const time_t *)&tv
.tv_sec
, &tm
);
2696 strftime(sn
->name
, sizeof(sn
->name
), "vm-%Y%m%d%H%M%S", &tm
);
2699 /* save the VM state */
2700 f
= qemu_fopen_bdrv(bs
, 1);
2702 error_setg(errp
, "Could not open VM state file");
2705 ret
= qemu_savevm_state(f
, errp
);
2706 vm_state_size
= qemu_ftell(f
);
2712 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2713 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2714 * it only releases the lock once. Therefore synchronous I/O will deadlock
2715 * unless we release the AioContext before bdrv_all_create_snapshot().
2717 aio_context_release(aio_context
);
2720 ret
= bdrv_all_create_snapshot(sn
, bs
, vm_state_size
, &bs
);
2722 error_setg(errp
, "Error while creating snapshot on '%s'",
2723 bdrv_get_device_name(bs
));
2731 aio_context_release(aio_context
);
2734 bdrv_drain_all_end();
2736 if (saved_vm_running
) {
2742 void qmp_xen_save_devices_state(const char *filename
, bool has_live
, bool live
,
2746 QIOChannelFile
*ioc
;
2747 int saved_vm_running
;
2751 /* live default to true so old version of Xen tool stack can have a
2752 * successfull live migration */
2756 saved_vm_running
= runstate_is_running();
2757 vm_stop(RUN_STATE_SAVE_VM
);
2758 global_state_store_running();
2760 ioc
= qio_channel_file_new_path(filename
, O_WRONLY
| O_CREAT
, 0660, errp
);
2764 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-save-state");
2765 f
= qemu_fopen_channel_output(QIO_CHANNEL(ioc
));
2766 object_unref(OBJECT(ioc
));
2767 ret
= qemu_save_device_state(f
);
2768 if (ret
< 0 || qemu_fclose(f
) < 0) {
2769 error_setg(errp
, QERR_IO_ERROR
);
2771 /* libxl calls the QMP command "stop" before calling
2772 * "xen-save-devices-state" and in case of migration failure, libxl
2773 * would call "cont".
2774 * So call bdrv_inactivate_all (release locks) here to let the other
2775 * side of the migration take controle of the images.
2777 if (live
&& !saved_vm_running
) {
2778 ret
= bdrv_inactivate_all();
2780 error_setg(errp
, "%s: bdrv_inactivate_all() failed (%d)",
2787 if (saved_vm_running
) {
2792 void qmp_xen_load_devices_state(const char *filename
, Error
**errp
)
2795 QIOChannelFile
*ioc
;
2798 /* Guest must be paused before loading the device state; the RAM state
2799 * will already have been loaded by xc
2801 if (runstate_is_running()) {
2802 error_setg(errp
, "Cannot update device state while vm is running");
2805 vm_stop(RUN_STATE_RESTORE_VM
);
2807 ioc
= qio_channel_file_new_path(filename
, O_RDONLY
| O_BINARY
, 0, errp
);
2811 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-load-state");
2812 f
= qemu_fopen_channel_input(QIO_CHANNEL(ioc
));
2813 object_unref(OBJECT(ioc
));
2815 ret
= qemu_loadvm_state(f
);
2818 error_setg(errp
, QERR_IO_ERROR
);
2820 migration_incoming_state_destroy();
2823 int load_snapshot(const char *name
, Error
**errp
)
2825 BlockDriverState
*bs
, *bs_vm_state
;
2826 QEMUSnapshotInfo sn
;
2829 AioContext
*aio_context
;
2830 MigrationIncomingState
*mis
= migration_incoming_get_current();
2832 if (!replay_can_snapshot()) {
2833 error_setg(errp
, "Record/replay does not allow loading snapshot "
2834 "right now. Try once more later.");
2838 if (!bdrv_all_can_snapshot(&bs
)) {
2840 "Device '%s' is writable but does not support snapshots",
2841 bdrv_get_device_name(bs
));
2844 ret
= bdrv_all_find_snapshot(name
, &bs
);
2847 "Device '%s' does not have the requested snapshot '%s'",
2848 bdrv_get_device_name(bs
), name
);
2852 bs_vm_state
= bdrv_all_find_vmstate_bs();
2854 error_setg(errp
, "No block device supports snapshots");
2857 aio_context
= bdrv_get_aio_context(bs_vm_state
);
2859 /* Don't even try to load empty VM states */
2860 aio_context_acquire(aio_context
);
2861 ret
= bdrv_snapshot_find(bs_vm_state
, &sn
, name
);
2862 aio_context_release(aio_context
);
2865 } else if (sn
.vm_state_size
== 0) {
2866 error_setg(errp
, "This is a disk-only snapshot. Revert to it "
2867 " offline using qemu-img");
2871 /* Flush all IO requests so they don't interfere with the new state. */
2872 bdrv_drain_all_begin();
2874 ret
= bdrv_all_goto_snapshot(name
, &bs
, errp
);
2876 error_prepend(errp
, "Could not load snapshot '%s' on '%s': ",
2877 name
, bdrv_get_device_name(bs
));
2881 /* restore the VM state */
2882 f
= qemu_fopen_bdrv(bs_vm_state
, 0);
2884 error_setg(errp
, "Could not open VM state file");
2889 qemu_system_reset(SHUTDOWN_CAUSE_NONE
);
2890 mis
->from_src_file
= f
;
2892 aio_context_acquire(aio_context
);
2893 ret
= qemu_loadvm_state(f
);
2894 migration_incoming_state_destroy();
2895 aio_context_release(aio_context
);
2897 bdrv_drain_all_end();
2900 error_setg(errp
, "Error %d while loading VM state", ret
);
2907 bdrv_drain_all_end();
2911 void vmstate_register_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2913 qemu_ram_set_idstr(mr
->ram_block
,
2914 memory_region_name(mr
), dev
);
2915 qemu_ram_set_migratable(mr
->ram_block
);
2918 void vmstate_unregister_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2920 qemu_ram_unset_idstr(mr
->ram_block
);
2921 qemu_ram_unset_migratable(mr
->ram_block
);
2924 void vmstate_register_ram_global(MemoryRegion
*mr
)
2926 vmstate_register_ram(mr
, NULL
);
2929 bool vmstate_check_only_migratable(const VMStateDescription
*vmsd
)
2931 /* check needed if --only-migratable is specified */
2932 if (!only_migratable
) {
2936 return !(vmsd
&& vmsd
->unmigratable
);