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"
32 #include "migration.h"
33 #include "migration/snapshot.h"
34 #include "migration/vmstate.h"
35 #include "migration/misc.h"
36 #include "migration/register.h"
37 #include "migration/global_state.h"
39 #include "qemu-file-channel.h"
40 #include "qemu-file.h"
42 #include "postcopy-ram.h"
43 #include "qapi/error.h"
44 #include "qapi/qapi-commands-migration.h"
45 #include "qapi/qmp/json-writer.h"
46 #include "qapi/clone-visitor.h"
47 #include "qapi/qapi-builtin-visit.h"
48 #include "qapi/qmp/qerror.h"
49 #include "qemu/error-report.h"
50 #include "sysemu/cpus.h"
51 #include "exec/memory.h"
52 #include "exec/target_page.h"
55 #include "qemu/main-loop.h"
56 #include "block/snapshot.h"
57 #include "qemu/cutils.h"
58 #include "io/channel-buffer.h"
59 #include "io/channel-file.h"
60 #include "sysemu/replay.h"
61 #include "sysemu/runstate.h"
62 #include "sysemu/sysemu.h"
63 #include "sysemu/xen.h"
64 #include "migration/colo.h"
65 #include "qemu/bitmap.h"
66 #include "net/announce.h"
67 #include "qemu/yank.h"
68 #include "yank_functions.h"
70 const unsigned int postcopy_ram_discard_version
;
72 /* Subcommands for QEMU_VM_COMMAND */
74 MIG_CMD_INVALID
= 0, /* Must be 0 */
75 MIG_CMD_OPEN_RETURN_PATH
, /* Tell the dest to open the Return path */
76 MIG_CMD_PING
, /* Request a PONG on the RP */
78 MIG_CMD_POSTCOPY_ADVISE
, /* Prior to any page transfers, just
79 warn we might want to do PC */
80 MIG_CMD_POSTCOPY_LISTEN
, /* Start listening for incoming
81 pages as it's running. */
82 MIG_CMD_POSTCOPY_RUN
, /* Start execution */
84 MIG_CMD_POSTCOPY_RAM_DISCARD
, /* A list of pages to discard that
85 were previously sent during
86 precopy but are dirty. */
87 MIG_CMD_PACKAGED
, /* Send a wrapped stream within this stream */
88 MIG_CMD_ENABLE_COLO
, /* Enable COLO */
89 MIG_CMD_POSTCOPY_RESUME
, /* resume postcopy on dest */
90 MIG_CMD_RECV_BITMAP
, /* Request for recved bitmap on dst */
94 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
95 static struct mig_cmd_args
{
96 ssize_t len
; /* -1 = variable */
99 [MIG_CMD_INVALID
] = { .len
= -1, .name
= "INVALID" },
100 [MIG_CMD_OPEN_RETURN_PATH
] = { .len
= 0, .name
= "OPEN_RETURN_PATH" },
101 [MIG_CMD_PING
] = { .len
= sizeof(uint32_t), .name
= "PING" },
102 [MIG_CMD_POSTCOPY_ADVISE
] = { .len
= -1, .name
= "POSTCOPY_ADVISE" },
103 [MIG_CMD_POSTCOPY_LISTEN
] = { .len
= 0, .name
= "POSTCOPY_LISTEN" },
104 [MIG_CMD_POSTCOPY_RUN
] = { .len
= 0, .name
= "POSTCOPY_RUN" },
105 [MIG_CMD_POSTCOPY_RAM_DISCARD
] = {
106 .len
= -1, .name
= "POSTCOPY_RAM_DISCARD" },
107 [MIG_CMD_POSTCOPY_RESUME
] = { .len
= 0, .name
= "POSTCOPY_RESUME" },
108 [MIG_CMD_PACKAGED
] = { .len
= 4, .name
= "PACKAGED" },
109 [MIG_CMD_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
110 [MIG_CMD_MAX
] = { .len
= -1, .name
= "MAX" },
113 /* Note for MIG_CMD_POSTCOPY_ADVISE:
114 * The format of arguments is depending on postcopy mode:
115 * - postcopy RAM only
116 * uint64_t host page size
117 * uint64_t taget page size
119 * - postcopy RAM and postcopy dirty bitmaps
120 * format is the same as for postcopy RAM only
122 * - postcopy dirty bitmaps only
123 * Nothing. Command length field is 0.
125 * Be careful: adding a new postcopy entity with some other parameters should
126 * not break format self-description ability. Good way is to introduce some
127 * generic extendable format with an exception for two old entities.
130 /***********************************************************/
131 /* savevm/loadvm support */
133 static ssize_t
block_writev_buffer(void *opaque
, struct iovec
*iov
, int iovcnt
,
134 int64_t pos
, Error
**errp
)
139 qemu_iovec_init_external(&qiov
, iov
, iovcnt
);
140 ret
= bdrv_writev_vmstate(opaque
, &qiov
, pos
);
148 static ssize_t
block_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
,
149 size_t size
, Error
**errp
)
151 return bdrv_load_vmstate(opaque
, buf
, pos
, size
);
154 static int bdrv_fclose(void *opaque
, Error
**errp
)
156 return bdrv_flush(opaque
);
159 static const QEMUFileOps bdrv_read_ops
= {
160 .get_buffer
= block_get_buffer
,
164 static const QEMUFileOps bdrv_write_ops
= {
165 .writev_buffer
= block_writev_buffer
,
169 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int is_writable
)
172 return qemu_fopen_ops(bs
, &bdrv_write_ops
, false);
174 return qemu_fopen_ops(bs
, &bdrv_read_ops
, false);
178 /* QEMUFile timer support.
179 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
182 void timer_put(QEMUFile
*f
, QEMUTimer
*ts
)
184 uint64_t expire_time
;
186 expire_time
= timer_expire_time_ns(ts
);
187 qemu_put_be64(f
, expire_time
);
190 void timer_get(QEMUFile
*f
, QEMUTimer
*ts
)
192 uint64_t expire_time
;
194 expire_time
= qemu_get_be64(f
);
195 if (expire_time
!= -1) {
196 timer_mod_ns(ts
, expire_time
);
203 /* VMState timer support.
204 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
207 static int get_timer(QEMUFile
*f
, void *pv
, size_t size
,
208 const VMStateField
*field
)
215 static int put_timer(QEMUFile
*f
, void *pv
, size_t size
,
216 const VMStateField
*field
, JSONWriter
*vmdesc
)
224 const VMStateInfo vmstate_info_timer
= {
231 typedef struct CompatEntry
{
236 typedef struct SaveStateEntry
{
237 QTAILQ_ENTRY(SaveStateEntry
) entry
;
239 uint32_t instance_id
;
242 /* version id read from the stream */
245 /* section id read from the stream */
247 const SaveVMHandlers
*ops
;
248 const VMStateDescription
*vmsd
;
254 typedef struct SaveState
{
255 QTAILQ_HEAD(, SaveStateEntry
) handlers
;
256 SaveStateEntry
*handler_pri_head
[MIG_PRI_MAX
+ 1];
257 int global_section_id
;
260 uint32_t target_page_bits
;
262 MigrationCapability
*capabilities
;
266 static SaveState savevm_state
= {
267 .handlers
= QTAILQ_HEAD_INITIALIZER(savevm_state
.handlers
),
268 .handler_pri_head
= { [MIG_PRI_DEFAULT
... MIG_PRI_MAX
] = NULL
},
269 .global_section_id
= 0,
272 static bool should_validate_capability(int capability
)
274 assert(capability
>= 0 && capability
< MIGRATION_CAPABILITY__MAX
);
275 /* Validate only new capabilities to keep compatibility. */
276 switch (capability
) {
277 case MIGRATION_CAPABILITY_X_IGNORE_SHARED
:
284 static uint32_t get_validatable_capabilities_count(void)
286 MigrationState
*s
= migrate_get_current();
289 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
290 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
297 static int configuration_pre_save(void *opaque
)
299 SaveState
*state
= opaque
;
300 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
301 MigrationState
*s
= migrate_get_current();
304 state
->len
= strlen(current_name
);
305 state
->name
= current_name
;
306 state
->target_page_bits
= qemu_target_page_bits();
308 state
->caps_count
= get_validatable_capabilities_count();
309 state
->capabilities
= g_renew(MigrationCapability
, state
->capabilities
,
311 for (i
= j
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
312 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
313 state
->capabilities
[j
++] = i
;
316 state
->uuid
= qemu_uuid
;
321 static int configuration_post_save(void *opaque
)
323 SaveState
*state
= opaque
;
325 g_free(state
->capabilities
);
326 state
->capabilities
= NULL
;
327 state
->caps_count
= 0;
331 static int configuration_pre_load(void *opaque
)
333 SaveState
*state
= opaque
;
335 /* If there is no target-page-bits subsection it means the source
336 * predates the variable-target-page-bits support and is using the
337 * minimum possible value for this CPU.
339 state
->target_page_bits
= qemu_target_page_bits_min();
343 static bool configuration_validate_capabilities(SaveState
*state
)
346 MigrationState
*s
= migrate_get_current();
347 unsigned long *source_caps_bm
;
350 source_caps_bm
= bitmap_new(MIGRATION_CAPABILITY__MAX
);
351 for (i
= 0; i
< state
->caps_count
; i
++) {
352 MigrationCapability capability
= state
->capabilities
[i
];
353 set_bit(capability
, source_caps_bm
);
356 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
357 bool source_state
, target_state
;
358 if (!should_validate_capability(i
)) {
361 source_state
= test_bit(i
, source_caps_bm
);
362 target_state
= s
->enabled_capabilities
[i
];
363 if (source_state
!= target_state
) {
364 error_report("Capability %s is %s, but received capability is %s",
365 MigrationCapability_str(i
),
366 target_state
? "on" : "off",
367 source_state
? "on" : "off");
369 /* Don't break here to report all failed capabilities */
373 g_free(source_caps_bm
);
377 static int configuration_post_load(void *opaque
, int version_id
)
379 SaveState
*state
= opaque
;
380 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
383 if (strncmp(state
->name
, current_name
, state
->len
) != 0) {
384 error_report("Machine type received is '%.*s' and local is '%s'",
385 (int) state
->len
, state
->name
, current_name
);
390 if (state
->target_page_bits
!= qemu_target_page_bits()) {
391 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
392 state
->target_page_bits
, qemu_target_page_bits());
397 if (!configuration_validate_capabilities(state
)) {
403 g_free((void *)state
->name
);
406 g_free(state
->capabilities
);
407 state
->capabilities
= NULL
;
408 state
->caps_count
= 0;
413 static int get_capability(QEMUFile
*f
, void *pv
, size_t size
,
414 const VMStateField
*field
)
416 MigrationCapability
*capability
= pv
;
417 char capability_str
[UINT8_MAX
+ 1];
421 len
= qemu_get_byte(f
);
422 qemu_get_buffer(f
, (uint8_t *)capability_str
, len
);
423 capability_str
[len
] = '\0';
424 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
425 if (!strcmp(MigrationCapability_str(i
), capability_str
)) {
430 error_report("Received unknown capability %s", capability_str
);
434 static int put_capability(QEMUFile
*f
, void *pv
, size_t size
,
435 const VMStateField
*field
, JSONWriter
*vmdesc
)
437 MigrationCapability
*capability
= pv
;
438 const char *capability_str
= MigrationCapability_str(*capability
);
439 size_t len
= strlen(capability_str
);
440 assert(len
<= UINT8_MAX
);
442 qemu_put_byte(f
, len
);
443 qemu_put_buffer(f
, (uint8_t *)capability_str
, len
);
447 static const VMStateInfo vmstate_info_capability
= {
448 .name
= "capability",
449 .get
= get_capability
,
450 .put
= put_capability
,
453 /* The target-page-bits subsection is present only if the
454 * target page size is not the same as the default (ie the
455 * minimum page size for a variable-page-size guest CPU).
456 * If it is present then it contains the actual target page
457 * bits for the machine, and migration will fail if the
458 * two ends don't agree about it.
460 static bool vmstate_target_page_bits_needed(void *opaque
)
462 return qemu_target_page_bits()
463 > qemu_target_page_bits_min();
466 static const VMStateDescription vmstate_target_page_bits
= {
467 .name
= "configuration/target-page-bits",
469 .minimum_version_id
= 1,
470 .needed
= vmstate_target_page_bits_needed
,
471 .fields
= (VMStateField
[]) {
472 VMSTATE_UINT32(target_page_bits
, SaveState
),
473 VMSTATE_END_OF_LIST()
477 static bool vmstate_capabilites_needed(void *opaque
)
479 return get_validatable_capabilities_count() > 0;
482 static const VMStateDescription vmstate_capabilites
= {
483 .name
= "configuration/capabilities",
485 .minimum_version_id
= 1,
486 .needed
= vmstate_capabilites_needed
,
487 .fields
= (VMStateField
[]) {
488 VMSTATE_UINT32_V(caps_count
, SaveState
, 1),
489 VMSTATE_VARRAY_UINT32_ALLOC(capabilities
, SaveState
, caps_count
, 1,
490 vmstate_info_capability
,
491 MigrationCapability
),
492 VMSTATE_END_OF_LIST()
496 static bool vmstate_uuid_needed(void *opaque
)
498 return qemu_uuid_set
&& migrate_validate_uuid();
501 static int vmstate_uuid_post_load(void *opaque
, int version_id
)
503 SaveState
*state
= opaque
;
504 char uuid_src
[UUID_FMT_LEN
+ 1];
505 char uuid_dst
[UUID_FMT_LEN
+ 1];
507 if (!qemu_uuid_set
) {
509 * It's warning because user might not know UUID in some cases,
510 * e.g. load an old snapshot
512 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
513 warn_report("UUID is received %s, but local uuid isn't set",
517 if (!qemu_uuid_is_equal(&state
->uuid
, &qemu_uuid
)) {
518 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
519 qemu_uuid_unparse(&qemu_uuid
, uuid_dst
);
520 error_report("UUID received is %s and local is %s", uuid_src
, uuid_dst
);
526 static const VMStateDescription vmstate_uuid
= {
527 .name
= "configuration/uuid",
529 .minimum_version_id
= 1,
530 .needed
= vmstate_uuid_needed
,
531 .post_load
= vmstate_uuid_post_load
,
532 .fields
= (VMStateField
[]) {
533 VMSTATE_UINT8_ARRAY_V(uuid
.data
, SaveState
, sizeof(QemuUUID
), 1),
534 VMSTATE_END_OF_LIST()
538 static const VMStateDescription vmstate_configuration
= {
539 .name
= "configuration",
541 .pre_load
= configuration_pre_load
,
542 .post_load
= configuration_post_load
,
543 .pre_save
= configuration_pre_save
,
544 .post_save
= configuration_post_save
,
545 .fields
= (VMStateField
[]) {
546 VMSTATE_UINT32(len
, SaveState
),
547 VMSTATE_VBUFFER_ALLOC_UINT32(name
, SaveState
, 0, NULL
, len
),
548 VMSTATE_END_OF_LIST()
550 .subsections
= (const VMStateDescription
*[]) {
551 &vmstate_target_page_bits
,
552 &vmstate_capabilites
,
558 static void dump_vmstate_vmsd(FILE *out_file
,
559 const VMStateDescription
*vmsd
, int indent
,
562 static void dump_vmstate_vmsf(FILE *out_file
, const VMStateField
*field
,
565 fprintf(out_file
, "%*s{\n", indent
, "");
567 fprintf(out_file
, "%*s\"field\": \"%s\",\n", indent
, "", field
->name
);
568 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
570 fprintf(out_file
, "%*s\"field_exists\": %s,\n", indent
, "",
571 field
->field_exists
? "true" : "false");
572 fprintf(out_file
, "%*s\"size\": %zu", indent
, "", field
->size
);
573 if (field
->vmsd
!= NULL
) {
574 fprintf(out_file
, ",\n");
575 dump_vmstate_vmsd(out_file
, field
->vmsd
, indent
, false);
577 fprintf(out_file
, "\n%*s}", indent
- 2, "");
580 static void dump_vmstate_vmss(FILE *out_file
,
581 const VMStateDescription
**subsection
,
584 if (*subsection
!= NULL
) {
585 dump_vmstate_vmsd(out_file
, *subsection
, indent
, true);
589 static void dump_vmstate_vmsd(FILE *out_file
,
590 const VMStateDescription
*vmsd
, int indent
,
594 fprintf(out_file
, "%*s{\n", indent
, "");
596 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", "Description");
599 fprintf(out_file
, "%*s\"name\": \"%s\",\n", indent
, "", vmsd
->name
);
600 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
602 fprintf(out_file
, "%*s\"minimum_version_id\": %d", indent
, "",
603 vmsd
->minimum_version_id
);
604 if (vmsd
->fields
!= NULL
) {
605 const VMStateField
*field
= vmsd
->fields
;
608 fprintf(out_file
, ",\n%*s\"Fields\": [\n", indent
, "");
610 while (field
->name
!= NULL
) {
611 if (field
->flags
& VMS_MUST_EXIST
) {
612 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
617 fprintf(out_file
, ",\n");
619 dump_vmstate_vmsf(out_file
, field
, indent
+ 2);
623 fprintf(out_file
, "\n%*s]", indent
, "");
625 if (vmsd
->subsections
!= NULL
) {
626 const VMStateDescription
**subsection
= vmsd
->subsections
;
629 fprintf(out_file
, ",\n%*s\"Subsections\": [\n", indent
, "");
631 while (*subsection
!= NULL
) {
633 fprintf(out_file
, ",\n");
635 dump_vmstate_vmss(out_file
, subsection
, indent
+ 2);
639 fprintf(out_file
, "\n%*s]", indent
, "");
641 fprintf(out_file
, "\n%*s}", indent
- 2, "");
644 static void dump_machine_type(FILE *out_file
)
648 mc
= MACHINE_GET_CLASS(current_machine
);
650 fprintf(out_file
, " \"vmschkmachine\": {\n");
651 fprintf(out_file
, " \"Name\": \"%s\"\n", mc
->name
);
652 fprintf(out_file
, " },\n");
655 void dump_vmstate_json_to_file(FILE *out_file
)
660 fprintf(out_file
, "{\n");
661 dump_machine_type(out_file
);
664 list
= object_class_get_list(TYPE_DEVICE
, true);
665 for (elt
= list
; elt
; elt
= elt
->next
) {
666 DeviceClass
*dc
= OBJECT_CLASS_CHECK(DeviceClass
, elt
->data
,
676 fprintf(out_file
, ",\n");
678 name
= object_class_get_name(OBJECT_CLASS(dc
));
679 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", name
);
681 fprintf(out_file
, "%*s\"Name\": \"%s\",\n", indent
, "", name
);
682 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
683 dc
->vmsd
->version_id
);
684 fprintf(out_file
, "%*s\"minimum_version_id\": %d,\n", indent
, "",
685 dc
->vmsd
->minimum_version_id
);
687 dump_vmstate_vmsd(out_file
, dc
->vmsd
, indent
, false);
689 fprintf(out_file
, "\n%*s}", indent
- 2, "");
692 fprintf(out_file
, "\n}\n");
697 static uint32_t calculate_new_instance_id(const char *idstr
)
700 uint32_t instance_id
= 0;
702 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
703 if (strcmp(idstr
, se
->idstr
) == 0
704 && instance_id
<= se
->instance_id
) {
705 instance_id
= se
->instance_id
+ 1;
708 /* Make sure we never loop over without being noticed */
709 assert(instance_id
!= VMSTATE_INSTANCE_ID_ANY
);
713 static int calculate_compat_instance_id(const char *idstr
)
718 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
723 if (strcmp(idstr
, se
->compat
->idstr
) == 0
724 && instance_id
<= se
->compat
->instance_id
) {
725 instance_id
= se
->compat
->instance_id
+ 1;
731 static inline MigrationPriority
save_state_priority(SaveStateEntry
*se
)
734 return se
->vmsd
->priority
;
736 return MIG_PRI_DEFAULT
;
739 static void savevm_state_handler_insert(SaveStateEntry
*nse
)
741 MigrationPriority priority
= save_state_priority(nse
);
745 assert(priority
<= MIG_PRI_MAX
);
747 for (i
= priority
- 1; i
>= 0; i
--) {
748 se
= savevm_state
.handler_pri_head
[i
];
750 assert(save_state_priority(se
) < priority
);
756 QTAILQ_INSERT_BEFORE(se
, nse
, entry
);
758 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, nse
, entry
);
761 if (savevm_state
.handler_pri_head
[priority
] == NULL
) {
762 savevm_state
.handler_pri_head
[priority
] = nse
;
766 static void savevm_state_handler_remove(SaveStateEntry
*se
)
768 SaveStateEntry
*next
;
769 MigrationPriority priority
= save_state_priority(se
);
771 if (se
== savevm_state
.handler_pri_head
[priority
]) {
772 next
= QTAILQ_NEXT(se
, entry
);
773 if (next
!= NULL
&& save_state_priority(next
) == priority
) {
774 savevm_state
.handler_pri_head
[priority
] = next
;
776 savevm_state
.handler_pri_head
[priority
] = NULL
;
779 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
782 /* TODO: Individual devices generally have very little idea about the rest
783 of the system, so instance_id should be removed/replaced.
784 Meanwhile pass -1 as instance_id if you do not already have a clearly
785 distinguishing id for all instances of your device class. */
786 int register_savevm_live(const char *idstr
,
787 uint32_t instance_id
,
789 const SaveVMHandlers
*ops
,
794 se
= g_new0(SaveStateEntry
, 1);
795 se
->version_id
= version_id
;
796 se
->section_id
= savevm_state
.global_section_id
++;
800 /* if this is a live_savem then set is_ram */
801 if (ops
->save_setup
!= NULL
) {
805 pstrcat(se
->idstr
, sizeof(se
->idstr
), idstr
);
807 if (instance_id
== VMSTATE_INSTANCE_ID_ANY
) {
808 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
810 se
->instance_id
= instance_id
;
812 assert(!se
->compat
|| se
->instance_id
== 0);
813 savevm_state_handler_insert(se
);
817 void unregister_savevm(VMStateIf
*obj
, const char *idstr
, void *opaque
)
819 SaveStateEntry
*se
, *new_se
;
823 char *oid
= vmstate_if_get_id(obj
);
825 pstrcpy(id
, sizeof(id
), oid
);
826 pstrcat(id
, sizeof(id
), "/");
830 pstrcat(id
, sizeof(id
), idstr
);
832 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
833 if (strcmp(se
->idstr
, id
) == 0 && se
->opaque
== opaque
) {
834 savevm_state_handler_remove(se
);
841 int vmstate_register_with_alias_id(VMStateIf
*obj
, uint32_t instance_id
,
842 const VMStateDescription
*vmsd
,
843 void *opaque
, int alias_id
,
844 int required_for_version
,
849 /* If this triggers, alias support can be dropped for the vmsd. */
850 assert(alias_id
== -1 || required_for_version
>= vmsd
->minimum_version_id
);
852 se
= g_new0(SaveStateEntry
, 1);
853 se
->version_id
= vmsd
->version_id
;
854 se
->section_id
= savevm_state
.global_section_id
++;
857 se
->alias_id
= alias_id
;
860 char *id
= vmstate_if_get_id(obj
);
862 if (snprintf(se
->idstr
, sizeof(se
->idstr
), "%s/", id
) >=
864 error_setg(errp
, "Path too long for VMState (%s)", id
);
872 se
->compat
= g_new0(CompatEntry
, 1);
873 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), vmsd
->name
);
874 se
->compat
->instance_id
= instance_id
== VMSTATE_INSTANCE_ID_ANY
?
875 calculate_compat_instance_id(vmsd
->name
) : instance_id
;
876 instance_id
= VMSTATE_INSTANCE_ID_ANY
;
879 pstrcat(se
->idstr
, sizeof(se
->idstr
), vmsd
->name
);
881 if (instance_id
== VMSTATE_INSTANCE_ID_ANY
) {
882 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
884 se
->instance_id
= instance_id
;
886 assert(!se
->compat
|| se
->instance_id
== 0);
887 savevm_state_handler_insert(se
);
891 void vmstate_unregister(VMStateIf
*obj
, const VMStateDescription
*vmsd
,
894 SaveStateEntry
*se
, *new_se
;
896 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
897 if (se
->vmsd
== vmsd
&& se
->opaque
== opaque
) {
898 savevm_state_handler_remove(se
);
905 static int vmstate_load(QEMUFile
*f
, SaveStateEntry
*se
)
907 trace_vmstate_load(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
908 if (!se
->vmsd
) { /* Old style */
909 return se
->ops
->load_state(f
, se
->opaque
, se
->load_version_id
);
911 return vmstate_load_state(f
, se
->vmsd
, se
->opaque
, se
->load_version_id
);
914 static void vmstate_save_old_style(QEMUFile
*f
, SaveStateEntry
*se
,
917 int64_t old_offset
, size
;
919 old_offset
= qemu_ftell_fast(f
);
920 se
->ops
->save_state(f
, se
->opaque
);
921 size
= qemu_ftell_fast(f
) - old_offset
;
924 json_writer_int64(vmdesc
, "size", size
);
925 json_writer_start_array(vmdesc
, "fields");
926 json_writer_start_object(vmdesc
, NULL
);
927 json_writer_str(vmdesc
, "name", "data");
928 json_writer_int64(vmdesc
, "size", size
);
929 json_writer_str(vmdesc
, "type", "buffer");
930 json_writer_end_object(vmdesc
);
931 json_writer_end_array(vmdesc
);
935 static int vmstate_save(QEMUFile
*f
, SaveStateEntry
*se
,
938 trace_vmstate_save(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
940 vmstate_save_old_style(f
, se
, vmdesc
);
943 return vmstate_save_state(f
, se
->vmsd
, se
->opaque
, vmdesc
);
947 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
949 static void save_section_header(QEMUFile
*f
, SaveStateEntry
*se
,
950 uint8_t section_type
)
952 qemu_put_byte(f
, section_type
);
953 qemu_put_be32(f
, se
->section_id
);
955 if (section_type
== QEMU_VM_SECTION_FULL
||
956 section_type
== QEMU_VM_SECTION_START
) {
958 size_t len
= strlen(se
->idstr
);
959 qemu_put_byte(f
, len
);
960 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
962 qemu_put_be32(f
, se
->instance_id
);
963 qemu_put_be32(f
, se
->version_id
);
968 * Write a footer onto device sections that catches cases misformatted device
971 static void save_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
973 if (migrate_get_current()->send_section_footer
) {
974 qemu_put_byte(f
, QEMU_VM_SECTION_FOOTER
);
975 qemu_put_be32(f
, se
->section_id
);
980 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
981 * command and associated data.
983 * @f: File to send command on
984 * @command: Command type to send
985 * @len: Length of associated data
986 * @data: Data associated with command.
988 static void qemu_savevm_command_send(QEMUFile
*f
,
989 enum qemu_vm_cmd command
,
993 trace_savevm_command_send(command
, len
);
994 qemu_put_byte(f
, QEMU_VM_COMMAND
);
995 qemu_put_be16(f
, (uint16_t)command
);
996 qemu_put_be16(f
, len
);
997 qemu_put_buffer(f
, data
, len
);
1001 void qemu_savevm_send_colo_enable(QEMUFile
*f
)
1003 trace_savevm_send_colo_enable();
1004 qemu_savevm_command_send(f
, MIG_CMD_ENABLE_COLO
, 0, NULL
);
1007 void qemu_savevm_send_ping(QEMUFile
*f
, uint32_t value
)
1011 trace_savevm_send_ping(value
);
1012 buf
= cpu_to_be32(value
);
1013 qemu_savevm_command_send(f
, MIG_CMD_PING
, sizeof(value
), (uint8_t *)&buf
);
1016 void qemu_savevm_send_open_return_path(QEMUFile
*f
)
1018 trace_savevm_send_open_return_path();
1019 qemu_savevm_command_send(f
, MIG_CMD_OPEN_RETURN_PATH
, 0, NULL
);
1022 /* We have a buffer of data to send; we don't want that all to be loaded
1023 * by the command itself, so the command contains just the length of the
1024 * extra buffer that we then send straight after it.
1025 * TODO: Must be a better way to organise that
1031 int qemu_savevm_send_packaged(QEMUFile
*f
, const uint8_t *buf
, size_t len
)
1035 if (len
> MAX_VM_CMD_PACKAGED_SIZE
) {
1036 error_report("%s: Unreasonably large packaged state: %zu",
1041 tmp
= cpu_to_be32(len
);
1043 trace_qemu_savevm_send_packaged();
1044 qemu_savevm_command_send(f
, MIG_CMD_PACKAGED
, 4, (uint8_t *)&tmp
);
1046 qemu_put_buffer(f
, buf
, len
);
1051 /* Send prior to any postcopy transfer */
1052 void qemu_savevm_send_postcopy_advise(QEMUFile
*f
)
1054 if (migrate_postcopy_ram()) {
1056 tmp
[0] = cpu_to_be64(ram_pagesize_summary());
1057 tmp
[1] = cpu_to_be64(qemu_target_page_size());
1059 trace_qemu_savevm_send_postcopy_advise();
1060 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
,
1061 16, (uint8_t *)tmp
);
1063 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
, 0, NULL
);
1067 /* Sent prior to starting the destination running in postcopy, discard pages
1068 * that have already been sent but redirtied on the source.
1069 * CMD_POSTCOPY_RAM_DISCARD consist of:
1071 * byte Length of name field (not including 0)
1072 * n x byte RAM block name
1073 * byte 0 terminator (just for safety)
1074 * n x Byte ranges within the named RAMBlock
1075 * be64 Start of the range
1078 * name: RAMBlock name that these entries are part of
1079 * len: Number of page entries
1080 * start_list: 'len' addresses
1081 * length_list: 'len' addresses
1084 void qemu_savevm_send_postcopy_ram_discard(QEMUFile
*f
, const char *name
,
1086 uint64_t *start_list
,
1087 uint64_t *length_list
)
1092 size_t name_len
= strlen(name
);
1094 trace_qemu_savevm_send_postcopy_ram_discard(name
, len
);
1095 assert(name_len
< 256);
1096 buf
= g_malloc0(1 + 1 + name_len
+ 1 + (8 + 8) * len
);
1097 buf
[0] = postcopy_ram_discard_version
;
1099 memcpy(buf
+ 2, name
, name_len
);
1100 tmplen
= 2 + name_len
;
1101 buf
[tmplen
++] = '\0';
1103 for (t
= 0; t
< len
; t
++) {
1104 stq_be_p(buf
+ tmplen
, start_list
[t
]);
1106 stq_be_p(buf
+ tmplen
, length_list
[t
]);
1109 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RAM_DISCARD
, tmplen
, buf
);
1113 /* Get the destination into a state where it can receive postcopy data. */
1114 void qemu_savevm_send_postcopy_listen(QEMUFile
*f
)
1116 trace_savevm_send_postcopy_listen();
1117 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_LISTEN
, 0, NULL
);
1120 /* Kick the destination into running */
1121 void qemu_savevm_send_postcopy_run(QEMUFile
*f
)
1123 trace_savevm_send_postcopy_run();
1124 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RUN
, 0, NULL
);
1127 void qemu_savevm_send_postcopy_resume(QEMUFile
*f
)
1129 trace_savevm_send_postcopy_resume();
1130 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RESUME
, 0, NULL
);
1133 void qemu_savevm_send_recv_bitmap(QEMUFile
*f
, char *block_name
)
1138 trace_savevm_send_recv_bitmap(block_name
);
1140 buf
[0] = len
= strlen(block_name
);
1141 memcpy(buf
+ 1, block_name
, len
);
1143 qemu_savevm_command_send(f
, MIG_CMD_RECV_BITMAP
, len
+ 1, (uint8_t *)buf
);
1146 bool qemu_savevm_state_blocked(Error
**errp
)
1150 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1151 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
1152 error_setg(errp
, "State blocked by non-migratable device '%s'",
1160 void qemu_savevm_non_migratable_list(strList
**reasons
)
1164 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1165 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
1166 QAPI_LIST_PREPEND(*reasons
,
1167 g_strdup_printf("non-migratable device: %s",
1173 void qemu_savevm_state_header(QEMUFile
*f
)
1175 trace_savevm_state_header();
1176 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1177 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1179 if (migrate_get_current()->send_configuration
) {
1180 qemu_put_byte(f
, QEMU_VM_CONFIGURATION
);
1181 vmstate_save_state(f
, &vmstate_configuration
, &savevm_state
, 0);
1185 bool qemu_savevm_state_guest_unplug_pending(void)
1189 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1190 if (se
->vmsd
&& se
->vmsd
->dev_unplug_pending
&&
1191 se
->vmsd
->dev_unplug_pending(se
->opaque
)) {
1199 void qemu_savevm_state_setup(QEMUFile
*f
)
1202 Error
*local_err
= NULL
;
1205 trace_savevm_state_setup();
1206 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1207 if (!se
->ops
|| !se
->ops
->save_setup
) {
1210 if (se
->ops
->is_active
) {
1211 if (!se
->ops
->is_active(se
->opaque
)) {
1215 save_section_header(f
, se
, QEMU_VM_SECTION_START
);
1217 ret
= se
->ops
->save_setup(f
, se
->opaque
);
1218 save_section_footer(f
, se
);
1220 qemu_file_set_error(f
, ret
);
1225 if (precopy_notify(PRECOPY_NOTIFY_SETUP
, &local_err
)) {
1226 error_report_err(local_err
);
1230 int qemu_savevm_state_resume_prepare(MigrationState
*s
)
1235 trace_savevm_state_resume_prepare();
1237 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1238 if (!se
->ops
|| !se
->ops
->resume_prepare
) {
1241 if (se
->ops
->is_active
) {
1242 if (!se
->ops
->is_active(se
->opaque
)) {
1246 ret
= se
->ops
->resume_prepare(s
, se
->opaque
);
1256 * this function has three return values:
1257 * negative: there was one error, and we have -errno.
1258 * 0 : We haven't finished, caller have to go again
1259 * 1 : We have finished, we can go to complete phase
1261 int qemu_savevm_state_iterate(QEMUFile
*f
, bool postcopy
)
1266 trace_savevm_state_iterate();
1267 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1268 if (!se
->ops
|| !se
->ops
->save_live_iterate
) {
1271 if (se
->ops
->is_active
&&
1272 !se
->ops
->is_active(se
->opaque
)) {
1275 if (se
->ops
->is_active_iterate
&&
1276 !se
->ops
->is_active_iterate(se
->opaque
)) {
1280 * In the postcopy phase, any device that doesn't know how to
1281 * do postcopy should have saved it's state in the _complete
1282 * call that's already run, it might get confused if we call
1283 * iterate afterwards.
1286 !(se
->ops
->has_postcopy
&& se
->ops
->has_postcopy(se
->opaque
))) {
1289 if (qemu_file_rate_limit(f
)) {
1292 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1294 save_section_header(f
, se
, QEMU_VM_SECTION_PART
);
1296 ret
= se
->ops
->save_live_iterate(f
, se
->opaque
);
1297 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1298 save_section_footer(f
, se
);
1301 error_report("failed to save SaveStateEntry with id(name): "
1303 se
->section_id
, se
->idstr
, ret
);
1304 qemu_file_set_error(f
, ret
);
1307 /* Do not proceed to the next vmstate before this one reported
1308 completion of the current stage. This serializes the migration
1309 and reduces the probability that a faster changing state is
1310 synchronized over and over again. */
1317 static bool should_send_vmdesc(void)
1319 MachineState
*machine
= MACHINE(qdev_get_machine());
1320 bool in_postcopy
= migration_in_postcopy();
1321 return !machine
->suppress_vmdesc
&& !in_postcopy
;
1325 * Calls the save_live_complete_postcopy methods
1326 * causing the last few pages to be sent immediately and doing any associated
1328 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1329 * all the other devices, but that happens at the point we switch to postcopy.
1331 void qemu_savevm_state_complete_postcopy(QEMUFile
*f
)
1336 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1337 if (!se
->ops
|| !se
->ops
->save_live_complete_postcopy
) {
1340 if (se
->ops
->is_active
) {
1341 if (!se
->ops
->is_active(se
->opaque
)) {
1345 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1347 qemu_put_byte(f
, QEMU_VM_SECTION_END
);
1348 qemu_put_be32(f
, se
->section_id
);
1350 ret
= se
->ops
->save_live_complete_postcopy(f
, se
->opaque
);
1351 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1352 save_section_footer(f
, se
);
1354 qemu_file_set_error(f
, ret
);
1359 qemu_put_byte(f
, QEMU_VM_EOF
);
1364 int qemu_savevm_state_complete_precopy_iterable(QEMUFile
*f
, bool in_postcopy
)
1369 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1371 (in_postcopy
&& se
->ops
->has_postcopy
&&
1372 se
->ops
->has_postcopy(se
->opaque
)) ||
1373 !se
->ops
->save_live_complete_precopy
) {
1377 if (se
->ops
->is_active
) {
1378 if (!se
->ops
->is_active(se
->opaque
)) {
1382 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1384 save_section_header(f
, se
, QEMU_VM_SECTION_END
);
1386 ret
= se
->ops
->save_live_complete_precopy(f
, se
->opaque
);
1387 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1388 save_section_footer(f
, se
);
1390 qemu_file_set_error(f
, ret
);
1398 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile
*f
,
1400 bool inactivate_disks
)
1402 g_autoptr(JSONWriter
) vmdesc
= NULL
;
1407 vmdesc
= json_writer_new(false);
1408 json_writer_start_object(vmdesc
, NULL
);
1409 json_writer_int64(vmdesc
, "page_size", qemu_target_page_size());
1410 json_writer_start_array(vmdesc
, "devices");
1411 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1413 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1416 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1417 trace_savevm_section_skip(se
->idstr
, se
->section_id
);
1421 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1423 json_writer_start_object(vmdesc
, NULL
);
1424 json_writer_str(vmdesc
, "name", se
->idstr
);
1425 json_writer_int64(vmdesc
, "instance_id", se
->instance_id
);
1427 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1428 ret
= vmstate_save(f
, se
, vmdesc
);
1430 qemu_file_set_error(f
, ret
);
1433 trace_savevm_section_end(se
->idstr
, se
->section_id
, 0);
1434 save_section_footer(f
, se
);
1436 json_writer_end_object(vmdesc
);
1439 if (inactivate_disks
) {
1440 /* Inactivate before sending QEMU_VM_EOF so that the
1441 * bdrv_invalidate_cache_all() on the other end won't fail. */
1442 ret
= bdrv_inactivate_all();
1444 error_report("%s: bdrv_inactivate_all() failed (%d)",
1446 qemu_file_set_error(f
, ret
);
1451 /* Postcopy stream will still be going */
1452 qemu_put_byte(f
, QEMU_VM_EOF
);
1455 json_writer_end_array(vmdesc
);
1456 json_writer_end_object(vmdesc
);
1457 vmdesc_len
= strlen(json_writer_get(vmdesc
));
1459 if (should_send_vmdesc()) {
1460 qemu_put_byte(f
, QEMU_VM_VMDESCRIPTION
);
1461 qemu_put_be32(f
, vmdesc_len
);
1462 qemu_put_buffer(f
, (uint8_t *)json_writer_get(vmdesc
), vmdesc_len
);
1468 int qemu_savevm_state_complete_precopy(QEMUFile
*f
, bool iterable_only
,
1469 bool inactivate_disks
)
1472 Error
*local_err
= NULL
;
1473 bool in_postcopy
= migration_in_postcopy();
1475 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE
, &local_err
)) {
1476 error_report_err(local_err
);
1479 trace_savevm_state_complete_precopy();
1481 cpu_synchronize_all_states();
1483 if (!in_postcopy
|| iterable_only
) {
1484 ret
= qemu_savevm_state_complete_precopy_iterable(f
, in_postcopy
);
1490 if (iterable_only
) {
1494 ret
= qemu_savevm_state_complete_precopy_non_iterable(f
, in_postcopy
,
1505 /* Give an estimate of the amount left to be transferred,
1506 * the result is split into the amount for units that can and
1507 * for units that can't do postcopy.
1509 void qemu_savevm_state_pending(QEMUFile
*f
, uint64_t threshold_size
,
1510 uint64_t *res_precopy_only
,
1511 uint64_t *res_compatible
,
1512 uint64_t *res_postcopy_only
)
1516 *res_precopy_only
= 0;
1517 *res_compatible
= 0;
1518 *res_postcopy_only
= 0;
1521 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1522 if (!se
->ops
|| !se
->ops
->save_live_pending
) {
1525 if (se
->ops
->is_active
) {
1526 if (!se
->ops
->is_active(se
->opaque
)) {
1530 se
->ops
->save_live_pending(f
, se
->opaque
, threshold_size
,
1531 res_precopy_only
, res_compatible
,
1536 void qemu_savevm_state_cleanup(void)
1539 Error
*local_err
= NULL
;
1541 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP
, &local_err
)) {
1542 error_report_err(local_err
);
1545 trace_savevm_state_cleanup();
1546 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1547 if (se
->ops
&& se
->ops
->save_cleanup
) {
1548 se
->ops
->save_cleanup(se
->opaque
);
1553 static int qemu_savevm_state(QEMUFile
*f
, Error
**errp
)
1556 MigrationState
*ms
= migrate_get_current();
1557 MigrationStatus status
;
1559 if (migration_is_running(ms
->state
)) {
1560 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1564 if (migrate_use_block()) {
1565 error_setg(errp
, "Block migration and snapshots are incompatible");
1570 memset(&ram_counters
, 0, sizeof(ram_counters
));
1571 memset(&compression_counters
, 0, sizeof(compression_counters
));
1572 ms
->to_dst_file
= f
;
1574 qemu_mutex_unlock_iothread();
1575 qemu_savevm_state_header(f
);
1576 qemu_savevm_state_setup(f
);
1577 qemu_mutex_lock_iothread();
1579 while (qemu_file_get_error(f
) == 0) {
1580 if (qemu_savevm_state_iterate(f
, false) > 0) {
1585 ret
= qemu_file_get_error(f
);
1587 qemu_savevm_state_complete_precopy(f
, false, false);
1588 ret
= qemu_file_get_error(f
);
1590 qemu_savevm_state_cleanup();
1592 error_setg_errno(errp
, -ret
, "Error while writing VM state");
1596 status
= MIGRATION_STATUS_FAILED
;
1598 status
= MIGRATION_STATUS_COMPLETED
;
1600 migrate_set_state(&ms
->state
, MIGRATION_STATUS_SETUP
, status
);
1602 /* f is outer parameter, it should not stay in global migration state after
1603 * this function finished */
1604 ms
->to_dst_file
= NULL
;
1609 void qemu_savevm_live_state(QEMUFile
*f
)
1611 /* save QEMU_VM_SECTION_END section */
1612 qemu_savevm_state_complete_precopy(f
, true, false);
1613 qemu_put_byte(f
, QEMU_VM_EOF
);
1616 int qemu_save_device_state(QEMUFile
*f
)
1620 if (!migration_in_colo_state()) {
1621 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1622 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1624 cpu_synchronize_all_states();
1626 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1632 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1635 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1639 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1641 ret
= vmstate_save(f
, se
, NULL
);
1646 save_section_footer(f
, se
);
1649 qemu_put_byte(f
, QEMU_VM_EOF
);
1651 return qemu_file_get_error(f
);
1654 static SaveStateEntry
*find_se(const char *idstr
, uint32_t instance_id
)
1658 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1659 if (!strcmp(se
->idstr
, idstr
) &&
1660 (instance_id
== se
->instance_id
||
1661 instance_id
== se
->alias_id
))
1663 /* Migrating from an older version? */
1664 if (strstr(se
->idstr
, idstr
) && se
->compat
) {
1665 if (!strcmp(se
->compat
->idstr
, idstr
) &&
1666 (instance_id
== se
->compat
->instance_id
||
1667 instance_id
== se
->alias_id
))
1674 enum LoadVMExitCodes
{
1675 /* Allow a command to quit all layers of nested loadvm loops */
1679 /* ------ incoming postcopy messages ------ */
1680 /* 'advise' arrives before any transfers just to tell us that a postcopy
1681 * *might* happen - it might be skipped if precopy transferred everything
1684 static int loadvm_postcopy_handle_advise(MigrationIncomingState
*mis
,
1687 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1688 uint64_t remote_pagesize_summary
, local_pagesize_summary
, remote_tps
;
1689 size_t page_size
= qemu_target_page_size();
1690 Error
*local_err
= NULL
;
1692 trace_loadvm_postcopy_handle_advise();
1693 if (ps
!= POSTCOPY_INCOMING_NONE
) {
1694 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps
);
1700 if (migrate_postcopy_ram()) {
1701 error_report("RAM postcopy is enabled but have 0 byte advise");
1706 if (!migrate_postcopy_ram()) {
1707 error_report("RAM postcopy is disabled but have 16 byte advise");
1712 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len
);
1716 if (!postcopy_ram_supported_by_host(mis
)) {
1717 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
1721 remote_pagesize_summary
= qemu_get_be64(mis
->from_src_file
);
1722 local_pagesize_summary
= ram_pagesize_summary();
1724 if (remote_pagesize_summary
!= local_pagesize_summary
) {
1726 * This detects two potential causes of mismatch:
1727 * a) A mismatch in host page sizes
1728 * Some combinations of mismatch are probably possible but it gets
1729 * a bit more complicated. In particular we need to place whole
1730 * host pages on the dest at once, and we need to ensure that we
1731 * handle dirtying to make sure we never end up sending part of
1732 * a hostpage on it's own.
1733 * b) The use of different huge page sizes on source/destination
1734 * a more fine grain test is performed during RAM block migration
1735 * but this test here causes a nice early clear failure, and
1736 * also fails when passed to an older qemu that doesn't
1739 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1741 remote_pagesize_summary
, local_pagesize_summary
);
1745 remote_tps
= qemu_get_be64(mis
->from_src_file
);
1746 if (remote_tps
!= page_size
) {
1748 * Again, some differences could be dealt with, but for now keep it
1751 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1752 (int)remote_tps
, page_size
);
1756 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE
, &local_err
)) {
1757 error_report_err(local_err
);
1761 if (ram_postcopy_incoming_init(mis
)) {
1768 /* After postcopy we will be told to throw some pages away since they're
1769 * dirty and will have to be demand fetched. Must happen before CPU is
1771 * There can be 0..many of these messages, each encoding multiple pages.
1773 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState
*mis
,
1778 PostcopyState ps
= postcopy_state_get();
1780 trace_loadvm_postcopy_ram_handle_discard();
1783 case POSTCOPY_INCOMING_ADVISE
:
1785 tmp
= postcopy_ram_prepare_discard(mis
);
1791 case POSTCOPY_INCOMING_DISCARD
:
1792 /* Expected state */
1796 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1800 /* We're expecting a
1802 * a RAM ID string (length byte, name, 0 term)
1803 * then at least 1 16 byte chunk
1805 if (len
< (1 + 1 + 1 + 1 + 2 * 8)) {
1806 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1810 tmp
= qemu_get_byte(mis
->from_src_file
);
1811 if (tmp
!= postcopy_ram_discard_version
) {
1812 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp
);
1816 if (!qemu_get_counted_string(mis
->from_src_file
, ramid
)) {
1817 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1820 tmp
= qemu_get_byte(mis
->from_src_file
);
1822 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp
);
1826 len
-= 3 + strlen(ramid
);
1828 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1831 trace_loadvm_postcopy_ram_handle_discard_header(ramid
, len
);
1833 uint64_t start_addr
, block_length
;
1834 start_addr
= qemu_get_be64(mis
->from_src_file
);
1835 block_length
= qemu_get_be64(mis
->from_src_file
);
1838 int ret
= ram_discard_range(ramid
, start_addr
, block_length
);
1843 trace_loadvm_postcopy_ram_handle_discard_end();
1849 * Triggered by a postcopy_listen command; this thread takes over reading
1850 * the input stream, leaving the main thread free to carry on loading the rest
1851 * of the device state (from RAM).
1852 * (TODO:This could do with being in a postcopy file - but there again it's
1853 * just another input loop, not that postcopy specific)
1855 static void *postcopy_ram_listen_thread(void *opaque
)
1857 MigrationIncomingState
*mis
= migration_incoming_get_current();
1858 QEMUFile
*f
= mis
->from_src_file
;
1860 MigrationState
*migr
= migrate_get_current();
1862 object_ref(OBJECT(migr
));
1864 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
1865 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1866 qemu_sem_post(&mis
->listen_thread_sem
);
1867 trace_postcopy_ram_listen_thread_start();
1869 rcu_register_thread();
1871 * Because we're a thread and not a coroutine we can't yield
1872 * in qemu_file, and thus we must be blocking now.
1874 qemu_file_set_blocking(f
, true);
1875 load_res
= qemu_loadvm_state_main(f
, mis
);
1878 * This is tricky, but, mis->from_src_file can change after it
1879 * returns, when postcopy recovery happened. In the future, we may
1880 * want a wrapper for the QEMUFile handle.
1882 f
= mis
->from_src_file
;
1884 /* And non-blocking again so we don't block in any cleanup */
1885 qemu_file_set_blocking(f
, false);
1887 trace_postcopy_ram_listen_thread_exit();
1889 qemu_file_set_error(f
, load_res
);
1890 dirty_bitmap_mig_cancel_incoming();
1891 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
1892 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1894 error_report("%s: loadvm failed during postcopy: %d. All states "
1895 "are migrated except dirty bitmaps. Some dirty "
1896 "bitmaps may be lost, and present migrated dirty "
1897 "bitmaps are correctly migrated and valid.",
1898 __func__
, load_res
);
1899 load_res
= 0; /* prevent further exit() */
1901 error_report("%s: loadvm failed: %d", __func__
, load_res
);
1902 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1903 MIGRATION_STATUS_FAILED
);
1906 if (load_res
>= 0) {
1908 * This looks good, but it's possible that the device loading in the
1909 * main thread hasn't finished yet, and so we might not be in 'RUN'
1910 * state yet; wait for the end of the main thread.
1912 qemu_event_wait(&mis
->main_thread_load_event
);
1914 postcopy_ram_incoming_cleanup(mis
);
1918 * If something went wrong then we have a bad state so exit;
1919 * depending how far we got it might be possible at this point
1920 * to leave the guest running and fire MCEs for pages that never
1921 * arrived as a desperate recovery step.
1923 rcu_unregister_thread();
1927 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1928 MIGRATION_STATUS_COMPLETED
);
1930 * If everything has worked fine, then the main thread has waited
1931 * for us to start, and we're the last use of the mis.
1932 * (If something broke then qemu will have to exit anyway since it's
1933 * got a bad migration state).
1935 migration_incoming_state_destroy();
1936 qemu_loadvm_state_cleanup();
1938 rcu_unregister_thread();
1939 mis
->have_listen_thread
= false;
1940 postcopy_state_set(POSTCOPY_INCOMING_END
);
1942 object_unref(OBJECT(migr
));
1947 /* After this message we must be able to immediately receive postcopy data */
1948 static int loadvm_postcopy_handle_listen(MigrationIncomingState
*mis
)
1950 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_LISTENING
);
1951 trace_loadvm_postcopy_handle_listen();
1952 Error
*local_err
= NULL
;
1954 if (ps
!= POSTCOPY_INCOMING_ADVISE
&& ps
!= POSTCOPY_INCOMING_DISCARD
) {
1955 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps
);
1958 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
1960 * A rare case, we entered listen without having to do any discards,
1961 * so do the setup that's normally done at the time of the 1st discard.
1963 if (migrate_postcopy_ram()) {
1964 postcopy_ram_prepare_discard(mis
);
1969 * Sensitise RAM - can now generate requests for blocks that don't exist
1970 * However, at this point the CPU shouldn't be running, and the IO
1971 * shouldn't be doing anything yet so don't actually expect requests
1973 if (migrate_postcopy_ram()) {
1974 if (postcopy_ram_incoming_setup(mis
)) {
1975 postcopy_ram_incoming_cleanup(mis
);
1980 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN
, &local_err
)) {
1981 error_report_err(local_err
);
1985 mis
->have_listen_thread
= true;
1986 /* Start up the listening thread and wait for it to signal ready */
1987 qemu_sem_init(&mis
->listen_thread_sem
, 0);
1988 qemu_thread_create(&mis
->listen_thread
, "postcopy/listen",
1989 postcopy_ram_listen_thread
, NULL
,
1990 QEMU_THREAD_DETACHED
);
1991 qemu_sem_wait(&mis
->listen_thread_sem
);
1992 qemu_sem_destroy(&mis
->listen_thread_sem
);
1997 static void loadvm_postcopy_handle_run_bh(void *opaque
)
1999 Error
*local_err
= NULL
;
2000 MigrationIncomingState
*mis
= opaque
;
2002 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2005 cpu_synchronize_all_post_init();
2007 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
2009 /* Make sure all file formats flush their mutable metadata.
2010 * If we get an error here, just don't restart the VM yet. */
2011 bdrv_invalidate_cache_all(&local_err
);
2013 error_report_err(local_err
);
2018 trace_loadvm_postcopy_handle_run_cpu_sync();
2020 trace_loadvm_postcopy_handle_run_vmstart();
2022 dirty_bitmap_mig_before_vm_start();
2025 /* Hold onto your hats, starting the CPU */
2028 /* leave it paused and let management decide when to start the CPU */
2029 runstate_set(RUN_STATE_PAUSED
);
2032 qemu_bh_delete(mis
->bh
);
2035 /* After all discards we can start running and asking for pages */
2036 static int loadvm_postcopy_handle_run(MigrationIncomingState
*mis
)
2038 PostcopyState ps
= postcopy_state_get();
2040 trace_loadvm_postcopy_handle_run();
2041 if (ps
!= POSTCOPY_INCOMING_LISTENING
) {
2042 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps
);
2046 postcopy_state_set(POSTCOPY_INCOMING_RUNNING
);
2047 mis
->bh
= qemu_bh_new(loadvm_postcopy_handle_run_bh
, mis
);
2048 qemu_bh_schedule(mis
->bh
);
2050 /* We need to finish reading the stream from the package
2051 * and also stop reading anything more from the stream that loaded the
2052 * package (since it's now being read by the listener thread).
2053 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2058 /* We must be with page_request_mutex held */
2059 static gboolean
postcopy_sync_page_req(gpointer key
, gpointer value
,
2062 MigrationIncomingState
*mis
= data
;
2063 void *host_addr
= (void *) key
;
2064 ram_addr_t rb_offset
;
2068 rb
= qemu_ram_block_from_host(host_addr
, true, &rb_offset
);
2071 * This should _never_ happen. However be nice for a migrating VM to
2072 * not crash/assert. Post an error (note: intended to not use *_once
2073 * because we do want to see all the illegal addresses; and this can
2074 * never be triggered by the guest so we're safe) and move on next.
2076 error_report("%s: illegal host addr %p", __func__
, host_addr
);
2077 /* Try the next entry */
2081 ret
= migrate_send_rp_message_req_pages(mis
, rb
, rb_offset
);
2083 /* Please refer to above comment. */
2084 error_report("%s: send rp message failed for addr %p",
2085 __func__
, host_addr
);
2089 trace_postcopy_page_req_sync(host_addr
);
2094 static void migrate_send_rp_req_pages_pending(MigrationIncomingState
*mis
)
2096 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
2097 g_tree_foreach(mis
->page_requested
, postcopy_sync_page_req
, mis
);
2101 static int loadvm_postcopy_handle_resume(MigrationIncomingState
*mis
)
2103 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2104 error_report("%s: illegal resume received", __func__
);
2105 /* Don't fail the load, only for this. */
2110 * Reset the last_rb before we resend any page req to source again, since
2111 * the source should have it reset already.
2113 mis
->last_rb
= NULL
;
2116 * This means source VM is ready to resume the postcopy migration.
2118 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2119 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2121 trace_loadvm_postcopy_handle_resume();
2123 /* Tell source that "we are ready" */
2124 migrate_send_rp_resume_ack(mis
, MIGRATION_RESUME_ACK_VALUE
);
2127 * After a postcopy recovery, the source should have lost the postcopy
2128 * queue, or potentially the requested pages could have been lost during
2129 * the network down phase. Let's re-sync with the source VM by re-sending
2130 * all the pending pages that we eagerly need, so these threads won't get
2131 * blocked too long due to the recovery.
2133 * Without this procedure, the faulted destination VM threads (waiting for
2134 * page requests right before the postcopy is interrupted) can keep hanging
2135 * until the pages are sent by the source during the background copying of
2136 * pages, or another thread faulted on the same address accidentally.
2138 migrate_send_rp_req_pages_pending(mis
);
2141 * It's time to switch state and release the fault thread to continue
2142 * service page faults. Note that this should be explicitly after the
2143 * above call to migrate_send_rp_req_pages_pending(). In short:
2144 * migrate_send_rp_message_req_pages() is not thread safe, yet.
2146 qemu_sem_post(&mis
->postcopy_pause_sem_fault
);
2152 * Immediately following this command is a blob of data containing an embedded
2153 * chunk of migration stream; read it and load it.
2155 * @mis: Incoming state
2156 * @length: Length of packaged data to read
2158 * Returns: Negative values on error
2161 static int loadvm_handle_cmd_packaged(MigrationIncomingState
*mis
)
2165 QIOChannelBuffer
*bioc
;
2167 length
= qemu_get_be32(mis
->from_src_file
);
2168 trace_loadvm_handle_cmd_packaged(length
);
2170 if (length
> MAX_VM_CMD_PACKAGED_SIZE
) {
2171 error_report("Unreasonably large packaged state: %zu", length
);
2175 bioc
= qio_channel_buffer_new(length
);
2176 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-loadvm-buffer");
2177 ret
= qemu_get_buffer(mis
->from_src_file
,
2180 if (ret
!= length
) {
2181 object_unref(OBJECT(bioc
));
2182 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2184 return (ret
< 0) ? ret
: -EAGAIN
;
2186 bioc
->usage
+= length
;
2187 trace_loadvm_handle_cmd_packaged_received(ret
);
2189 QEMUFile
*packf
= qemu_fopen_channel_input(QIO_CHANNEL(bioc
));
2191 ret
= qemu_loadvm_state_main(packf
, mis
);
2192 trace_loadvm_handle_cmd_packaged_main(ret
);
2194 object_unref(OBJECT(bioc
));
2200 * Handle request that source requests for recved_bitmap on
2201 * destination. Payload format:
2203 * len (1 byte) + ramblock_name (<255 bytes)
2205 static int loadvm_handle_recv_bitmap(MigrationIncomingState
*mis
,
2208 QEMUFile
*file
= mis
->from_src_file
;
2210 char block_name
[256];
2213 cnt
= qemu_get_counted_string(file
, block_name
);
2215 error_report("%s: failed to read block name", __func__
);
2219 /* Validate before using the data */
2220 if (qemu_file_get_error(file
)) {
2221 return qemu_file_get_error(file
);
2224 if (len
!= cnt
+ 1) {
2225 error_report("%s: invalid payload length (%d)", __func__
, len
);
2229 rb
= qemu_ram_block_by_name(block_name
);
2231 error_report("%s: block '%s' not found", __func__
, block_name
);
2235 migrate_send_rp_recv_bitmap(mis
, block_name
);
2237 trace_loadvm_handle_recv_bitmap(block_name
);
2242 static int loadvm_process_enable_colo(MigrationIncomingState
*mis
)
2244 int ret
= migration_incoming_enable_colo();
2247 ret
= colo_init_ram_cache();
2249 migration_incoming_disable_colo();
2256 * Process an incoming 'QEMU_VM_COMMAND'
2257 * 0 just a normal return
2258 * LOADVM_QUIT All good, but exit the loop
2261 static int loadvm_process_command(QEMUFile
*f
)
2263 MigrationIncomingState
*mis
= migration_incoming_get_current();
2268 cmd
= qemu_get_be16(f
);
2269 len
= qemu_get_be16(f
);
2271 /* Check validity before continue processing of cmds */
2272 if (qemu_file_get_error(f
)) {
2273 return qemu_file_get_error(f
);
2276 trace_loadvm_process_command(cmd
, len
);
2277 if (cmd
>= MIG_CMD_MAX
|| cmd
== MIG_CMD_INVALID
) {
2278 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd
, len
);
2282 if (mig_cmd_args
[cmd
].len
!= -1 && mig_cmd_args
[cmd
].len
!= len
) {
2283 error_report("%s received with bad length - expecting %zu, got %d",
2284 mig_cmd_args
[cmd
].name
,
2285 (size_t)mig_cmd_args
[cmd
].len
, len
);
2290 case MIG_CMD_OPEN_RETURN_PATH
:
2291 if (mis
->to_src_file
) {
2292 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2293 /* Not really a problem, so don't give up */
2296 mis
->to_src_file
= qemu_file_get_return_path(f
);
2297 if (!mis
->to_src_file
) {
2298 error_report("CMD_OPEN_RETURN_PATH failed");
2304 tmp32
= qemu_get_be32(f
);
2305 trace_loadvm_process_command_ping(tmp32
);
2306 if (!mis
->to_src_file
) {
2307 error_report("CMD_PING (0x%x) received with no return path",
2311 migrate_send_rp_pong(mis
, tmp32
);
2314 case MIG_CMD_PACKAGED
:
2315 return loadvm_handle_cmd_packaged(mis
);
2317 case MIG_CMD_POSTCOPY_ADVISE
:
2318 return loadvm_postcopy_handle_advise(mis
, len
);
2320 case MIG_CMD_POSTCOPY_LISTEN
:
2321 return loadvm_postcopy_handle_listen(mis
);
2323 case MIG_CMD_POSTCOPY_RUN
:
2324 return loadvm_postcopy_handle_run(mis
);
2326 case MIG_CMD_POSTCOPY_RAM_DISCARD
:
2327 return loadvm_postcopy_ram_handle_discard(mis
, len
);
2329 case MIG_CMD_POSTCOPY_RESUME
:
2330 return loadvm_postcopy_handle_resume(mis
);
2332 case MIG_CMD_RECV_BITMAP
:
2333 return loadvm_handle_recv_bitmap(mis
, len
);
2335 case MIG_CMD_ENABLE_COLO
:
2336 return loadvm_process_enable_colo(mis
);
2343 * Read a footer off the wire and check that it matches the expected section
2345 * Returns: true if the footer was good
2346 * false if there is a problem (and calls error_report to say why)
2348 static bool check_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
2352 uint32_t read_section_id
;
2354 if (!migrate_get_current()->send_section_footer
) {
2355 /* No footer to check */
2359 read_mark
= qemu_get_byte(f
);
2361 ret
= qemu_file_get_error(f
);
2363 error_report("%s: Read section footer failed: %d",
2368 if (read_mark
!= QEMU_VM_SECTION_FOOTER
) {
2369 error_report("Missing section footer for %s", se
->idstr
);
2373 read_section_id
= qemu_get_be32(f
);
2374 if (read_section_id
!= se
->load_section_id
) {
2375 error_report("Mismatched section id in footer for %s -"
2376 " read 0x%x expected 0x%x",
2377 se
->idstr
, read_section_id
, se
->load_section_id
);
2386 qemu_loadvm_section_start_full(QEMUFile
*f
, MigrationIncomingState
*mis
)
2388 uint32_t instance_id
, version_id
, section_id
;
2393 /* Read section start */
2394 section_id
= qemu_get_be32(f
);
2395 if (!qemu_get_counted_string(f
, idstr
)) {
2396 error_report("Unable to read ID string for section %u",
2400 instance_id
= qemu_get_be32(f
);
2401 version_id
= qemu_get_be32(f
);
2403 ret
= qemu_file_get_error(f
);
2405 error_report("%s: Failed to read instance/version ID: %d",
2410 trace_qemu_loadvm_state_section_startfull(section_id
, idstr
,
2411 instance_id
, version_id
);
2412 /* Find savevm section */
2413 se
= find_se(idstr
, instance_id
);
2415 error_report("Unknown savevm section or instance '%s' %"PRIu32
". "
2416 "Make sure that your current VM setup matches your "
2417 "saved VM setup, including any hotplugged devices",
2418 idstr
, instance_id
);
2422 /* Validate version */
2423 if (version_id
> se
->version_id
) {
2424 error_report("savevm: unsupported version %d for '%s' v%d",
2425 version_id
, idstr
, se
->version_id
);
2428 se
->load_version_id
= version_id
;
2429 se
->load_section_id
= section_id
;
2431 /* Validate if it is a device's state */
2432 if (xen_enabled() && se
->is_ram
) {
2433 error_report("loadvm: %s RAM loading not allowed on Xen", idstr
);
2437 ret
= vmstate_load(f
, se
);
2439 error_report("error while loading state for instance 0x%"PRIx32
" of"
2440 " device '%s'", instance_id
, idstr
);
2443 if (!check_section_footer(f
, se
)) {
2451 qemu_loadvm_section_part_end(QEMUFile
*f
, MigrationIncomingState
*mis
)
2453 uint32_t section_id
;
2457 section_id
= qemu_get_be32(f
);
2459 ret
= qemu_file_get_error(f
);
2461 error_report("%s: Failed to read section ID: %d",
2466 trace_qemu_loadvm_state_section_partend(section_id
);
2467 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2468 if (se
->load_section_id
== section_id
) {
2473 error_report("Unknown savevm section %d", section_id
);
2477 ret
= vmstate_load(f
, se
);
2479 error_report("error while loading state section id %d(%s)",
2480 section_id
, se
->idstr
);
2483 if (!check_section_footer(f
, se
)) {
2490 static int qemu_loadvm_state_header(QEMUFile
*f
)
2495 v
= qemu_get_be32(f
);
2496 if (v
!= QEMU_VM_FILE_MAGIC
) {
2497 error_report("Not a migration stream");
2501 v
= qemu_get_be32(f
);
2502 if (v
== QEMU_VM_FILE_VERSION_COMPAT
) {
2503 error_report("SaveVM v2 format is obsolete and don't work anymore");
2506 if (v
!= QEMU_VM_FILE_VERSION
) {
2507 error_report("Unsupported migration stream version");
2511 if (migrate_get_current()->send_configuration
) {
2512 if (qemu_get_byte(f
) != QEMU_VM_CONFIGURATION
) {
2513 error_report("Configuration section missing");
2514 qemu_loadvm_state_cleanup();
2517 ret
= vmstate_load_state(f
, &vmstate_configuration
, &savevm_state
, 0);
2520 qemu_loadvm_state_cleanup();
2527 static int qemu_loadvm_state_setup(QEMUFile
*f
)
2532 trace_loadvm_state_setup();
2533 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2534 if (!se
->ops
|| !se
->ops
->load_setup
) {
2537 if (se
->ops
->is_active
) {
2538 if (!se
->ops
->is_active(se
->opaque
)) {
2543 ret
= se
->ops
->load_setup(f
, se
->opaque
);
2545 qemu_file_set_error(f
, ret
);
2546 error_report("Load state of device %s failed", se
->idstr
);
2553 void qemu_loadvm_state_cleanup(void)
2557 trace_loadvm_state_cleanup();
2558 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2559 if (se
->ops
&& se
->ops
->load_cleanup
) {
2560 se
->ops
->load_cleanup(se
->opaque
);
2565 /* Return true if we should continue the migration, or false. */
2566 static bool postcopy_pause_incoming(MigrationIncomingState
*mis
)
2568 trace_postcopy_pause_incoming();
2570 assert(migrate_postcopy_ram());
2572 /* Clear the triggered bit to allow one recovery */
2573 mis
->postcopy_recover_triggered
= false;
2576 * Unregister yank with either from/to src would work, since ioc behind it
2579 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
2581 assert(mis
->from_src_file
);
2582 qemu_file_shutdown(mis
->from_src_file
);
2583 qemu_fclose(mis
->from_src_file
);
2584 mis
->from_src_file
= NULL
;
2586 assert(mis
->to_src_file
);
2587 qemu_file_shutdown(mis
->to_src_file
);
2588 qemu_mutex_lock(&mis
->rp_mutex
);
2589 qemu_fclose(mis
->to_src_file
);
2590 mis
->to_src_file
= NULL
;
2591 qemu_mutex_unlock(&mis
->rp_mutex
);
2593 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2594 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2596 /* Notify the fault thread for the invalidated file handle */
2597 postcopy_fault_thread_notify(mis
);
2599 error_report("Detected IO failure for postcopy. "
2600 "Migration paused.");
2602 while (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2603 qemu_sem_wait(&mis
->postcopy_pause_sem_dst
);
2606 trace_postcopy_pause_incoming_continued();
2611 int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
)
2613 uint8_t section_type
;
2618 section_type
= qemu_get_byte(f
);
2620 if (qemu_file_get_error(f
)) {
2621 ret
= qemu_file_get_error(f
);
2625 trace_qemu_loadvm_state_section(section_type
);
2626 switch (section_type
) {
2627 case QEMU_VM_SECTION_START
:
2628 case QEMU_VM_SECTION_FULL
:
2629 ret
= qemu_loadvm_section_start_full(f
, mis
);
2634 case QEMU_VM_SECTION_PART
:
2635 case QEMU_VM_SECTION_END
:
2636 ret
= qemu_loadvm_section_part_end(f
, mis
);
2641 case QEMU_VM_COMMAND
:
2642 ret
= loadvm_process_command(f
);
2643 trace_qemu_loadvm_state_section_command(ret
);
2644 if ((ret
< 0) || (ret
== LOADVM_QUIT
)) {
2649 /* This is the end of migration */
2652 error_report("Unknown savevm section type %d", section_type
);
2660 qemu_file_set_error(f
, ret
);
2662 /* Cancel bitmaps incoming regardless of recovery */
2663 dirty_bitmap_mig_cancel_incoming();
2666 * If we are during an active postcopy, then we pause instead
2667 * of bail out to at least keep the VM's dirty data. Note
2668 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2669 * during which we're still receiving device states and we
2670 * still haven't yet started the VM on destination.
2672 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2673 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2676 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
2677 migrate_postcopy_ram() && postcopy_pause_incoming(mis
)) {
2678 /* Reset f to point to the newly created channel */
2679 f
= mis
->from_src_file
;
2686 int qemu_loadvm_state(QEMUFile
*f
)
2688 MigrationIncomingState
*mis
= migration_incoming_get_current();
2689 Error
*local_err
= NULL
;
2692 if (qemu_savevm_state_blocked(&local_err
)) {
2693 error_report_err(local_err
);
2697 ret
= qemu_loadvm_state_header(f
);
2702 if (qemu_loadvm_state_setup(f
) != 0) {
2706 cpu_synchronize_all_pre_loadvm();
2708 ret
= qemu_loadvm_state_main(f
, mis
);
2709 qemu_event_set(&mis
->main_thread_load_event
);
2711 trace_qemu_loadvm_state_post_main(ret
);
2713 if (mis
->have_listen_thread
) {
2714 /* Listen thread still going, can't clean up yet */
2719 ret
= qemu_file_get_error(f
);
2723 * Try to read in the VMDESC section as well, so that dumping tools that
2724 * intercept our migration stream have the chance to see it.
2727 /* We've got to be careful; if we don't read the data and just shut the fd
2728 * then the sender can error if we close while it's still sending.
2729 * We also mustn't read data that isn't there; some transports (RDMA)
2730 * will stall waiting for that data when the source has already closed.
2732 if (ret
== 0 && should_send_vmdesc()) {
2735 uint8_t section_type
= qemu_get_byte(f
);
2737 if (section_type
!= QEMU_VM_VMDESCRIPTION
) {
2738 error_report("Expected vmdescription section, but got %d",
2741 * It doesn't seem worth failing at this point since
2742 * we apparently have an otherwise valid VM state
2745 buf
= g_malloc(0x1000);
2746 size
= qemu_get_be32(f
);
2749 uint32_t read_chunk
= MIN(size
, 0x1000);
2750 qemu_get_buffer(f
, buf
, read_chunk
);
2757 qemu_loadvm_state_cleanup();
2758 cpu_synchronize_all_post_init();
2763 int qemu_load_device_state(QEMUFile
*f
)
2765 MigrationIncomingState
*mis
= migration_incoming_get_current();
2768 /* Load QEMU_VM_SECTION_FULL section */
2769 ret
= qemu_loadvm_state_main(f
, mis
);
2771 error_report("Failed to load device state: %d", ret
);
2775 cpu_synchronize_all_post_init();
2779 bool save_snapshot(const char *name
, bool overwrite
, const char *vmstate
,
2780 bool has_devices
, strList
*devices
, Error
**errp
)
2782 BlockDriverState
*bs
;
2783 QEMUSnapshotInfo sn1
, *sn
= &sn1
;
2786 int saved_vm_running
;
2787 uint64_t vm_state_size
;
2788 g_autoptr(GDateTime
) now
= g_date_time_new_now_local();
2789 AioContext
*aio_context
;
2791 if (migration_is_blocked(errp
)) {
2795 if (!replay_can_snapshot()) {
2796 error_setg(errp
, "Record/replay does not allow making snapshot "
2797 "right now. Try once more later.");
2801 if (!bdrv_all_can_snapshot(has_devices
, devices
, errp
)) {
2805 /* Delete old snapshots of the same name */
2808 if (bdrv_all_delete_snapshot(name
, has_devices
,
2809 devices
, errp
) < 0) {
2813 ret2
= bdrv_all_has_snapshot(name
, has_devices
, devices
, errp
);
2819 "Snapshot '%s' already exists in one or more devices",
2826 bs
= bdrv_all_find_vmstate_bs(vmstate
, has_devices
, devices
, errp
);
2830 aio_context
= bdrv_get_aio_context(bs
);
2832 saved_vm_running
= runstate_is_running();
2834 ret
= global_state_store();
2836 error_setg(errp
, "Error saving global state");
2839 vm_stop(RUN_STATE_SAVE_VM
);
2841 bdrv_drain_all_begin();
2843 aio_context_acquire(aio_context
);
2845 memset(sn
, 0, sizeof(*sn
));
2847 /* fill auxiliary fields */
2848 sn
->date_sec
= g_date_time_to_unix(now
);
2849 sn
->date_nsec
= g_date_time_get_microsecond(now
) * 1000;
2850 sn
->vm_clock_nsec
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
2851 if (replay_mode
!= REPLAY_MODE_NONE
) {
2852 sn
->icount
= replay_get_current_icount();
2858 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
2860 g_autofree
char *autoname
= g_date_time_format(now
, "vm-%Y%m%d%H%M%S");
2861 pstrcpy(sn
->name
, sizeof(sn
->name
), autoname
);
2864 /* save the VM state */
2865 f
= qemu_fopen_bdrv(bs
, 1);
2867 error_setg(errp
, "Could not open VM state file");
2870 ret
= qemu_savevm_state(f
, errp
);
2871 vm_state_size
= qemu_ftell(f
);
2872 ret2
= qemu_fclose(f
);
2881 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2882 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2883 * it only releases the lock once. Therefore synchronous I/O will deadlock
2884 * unless we release the AioContext before bdrv_all_create_snapshot().
2886 aio_context_release(aio_context
);
2889 ret
= bdrv_all_create_snapshot(sn
, bs
, vm_state_size
,
2890 has_devices
, devices
, errp
);
2892 bdrv_all_delete_snapshot(sn
->name
, has_devices
, devices
, NULL
);
2900 aio_context_release(aio_context
);
2903 bdrv_drain_all_end();
2905 if (saved_vm_running
) {
2911 void qmp_xen_save_devices_state(const char *filename
, bool has_live
, bool live
,
2915 QIOChannelFile
*ioc
;
2916 int saved_vm_running
;
2920 /* live default to true so old version of Xen tool stack can have a
2921 * successful live migration */
2925 saved_vm_running
= runstate_is_running();
2926 vm_stop(RUN_STATE_SAVE_VM
);
2927 global_state_store_running();
2929 ioc
= qio_channel_file_new_path(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
,
2934 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-save-state");
2935 f
= qemu_fopen_channel_output(QIO_CHANNEL(ioc
));
2936 object_unref(OBJECT(ioc
));
2937 ret
= qemu_save_device_state(f
);
2938 if (ret
< 0 || qemu_fclose(f
) < 0) {
2939 error_setg(errp
, QERR_IO_ERROR
);
2941 /* libxl calls the QMP command "stop" before calling
2942 * "xen-save-devices-state" and in case of migration failure, libxl
2943 * would call "cont".
2944 * So call bdrv_inactivate_all (release locks) here to let the other
2945 * side of the migration take control of the images.
2947 if (live
&& !saved_vm_running
) {
2948 ret
= bdrv_inactivate_all();
2950 error_setg(errp
, "%s: bdrv_inactivate_all() failed (%d)",
2957 if (saved_vm_running
) {
2962 void qmp_xen_load_devices_state(const char *filename
, Error
**errp
)
2965 QIOChannelFile
*ioc
;
2968 /* Guest must be paused before loading the device state; the RAM state
2969 * will already have been loaded by xc
2971 if (runstate_is_running()) {
2972 error_setg(errp
, "Cannot update device state while vm is running");
2975 vm_stop(RUN_STATE_RESTORE_VM
);
2977 ioc
= qio_channel_file_new_path(filename
, O_RDONLY
| O_BINARY
, 0, errp
);
2981 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-load-state");
2982 f
= qemu_fopen_channel_input(QIO_CHANNEL(ioc
));
2983 object_unref(OBJECT(ioc
));
2985 ret
= qemu_loadvm_state(f
);
2988 error_setg(errp
, QERR_IO_ERROR
);
2990 migration_incoming_state_destroy();
2993 bool load_snapshot(const char *name
, const char *vmstate
,
2994 bool has_devices
, strList
*devices
, Error
**errp
)
2996 BlockDriverState
*bs_vm_state
;
2997 QEMUSnapshotInfo sn
;
3000 AioContext
*aio_context
;
3001 MigrationIncomingState
*mis
= migration_incoming_get_current();
3003 if (!bdrv_all_can_snapshot(has_devices
, devices
, errp
)) {
3006 ret
= bdrv_all_has_snapshot(name
, has_devices
, devices
, errp
);
3011 error_setg(errp
, "Snapshot '%s' does not exist in one or more devices",
3016 bs_vm_state
= bdrv_all_find_vmstate_bs(vmstate
, has_devices
, devices
, errp
);
3020 aio_context
= bdrv_get_aio_context(bs_vm_state
);
3022 /* Don't even try to load empty VM states */
3023 aio_context_acquire(aio_context
);
3024 ret
= bdrv_snapshot_find(bs_vm_state
, &sn
, name
);
3025 aio_context_release(aio_context
);
3028 } else if (sn
.vm_state_size
== 0) {
3029 error_setg(errp
, "This is a disk-only snapshot. Revert to it "
3030 " offline using qemu-img");
3035 * Flush the record/replay queue. Now the VM state is going
3036 * to change. Therefore we don't need to preserve its consistency
3038 replay_flush_events();
3040 /* Flush all IO requests so they don't interfere with the new state. */
3041 bdrv_drain_all_begin();
3043 ret
= bdrv_all_goto_snapshot(name
, has_devices
, devices
, errp
);
3048 /* restore the VM state */
3049 f
= qemu_fopen_bdrv(bs_vm_state
, 0);
3051 error_setg(errp
, "Could not open VM state file");
3055 qemu_system_reset(SHUTDOWN_CAUSE_NONE
);
3056 mis
->from_src_file
= f
;
3058 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
3062 aio_context_acquire(aio_context
);
3063 ret
= qemu_loadvm_state(f
);
3064 migration_incoming_state_destroy();
3065 aio_context_release(aio_context
);
3067 bdrv_drain_all_end();
3070 error_setg(errp
, "Error %d while loading VM state", ret
);
3077 bdrv_drain_all_end();
3081 bool delete_snapshot(const char *name
, bool has_devices
,
3082 strList
*devices
, Error
**errp
)
3084 if (!bdrv_all_can_snapshot(has_devices
, devices
, errp
)) {
3088 if (bdrv_all_delete_snapshot(name
, has_devices
, devices
, errp
) < 0) {
3095 void vmstate_register_ram(MemoryRegion
*mr
, DeviceState
*dev
)
3097 qemu_ram_set_idstr(mr
->ram_block
,
3098 memory_region_name(mr
), dev
);
3099 qemu_ram_set_migratable(mr
->ram_block
);
3102 void vmstate_unregister_ram(MemoryRegion
*mr
, DeviceState
*dev
)
3104 qemu_ram_unset_idstr(mr
->ram_block
);
3105 qemu_ram_unset_migratable(mr
->ram_block
);
3108 void vmstate_register_ram_global(MemoryRegion
*mr
)
3110 vmstate_register_ram(mr
, NULL
);
3113 bool vmstate_check_only_migratable(const VMStateDescription
*vmsd
)
3115 /* check needed if --only-migratable is specified */
3116 if (!only_migratable
) {
3120 return !(vmsd
&& vmsd
->unmigratable
);
3123 typedef struct SnapshotJob
{
3133 static void qmp_snapshot_job_free(SnapshotJob
*s
)
3137 qapi_free_strList(s
->devices
);
3141 static void snapshot_load_job_bh(void *opaque
)
3144 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3145 int orig_vm_running
;
3147 job_progress_set_remaining(&s
->common
, 1);
3149 orig_vm_running
= runstate_is_running();
3150 vm_stop(RUN_STATE_RESTORE_VM
);
3152 s
->ret
= load_snapshot(s
->tag
, s
->vmstate
, true, s
->devices
, s
->errp
);
3153 if (s
->ret
&& orig_vm_running
) {
3157 job_progress_update(&s
->common
, 1);
3159 qmp_snapshot_job_free(s
);
3163 static void snapshot_save_job_bh(void *opaque
)
3166 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3168 job_progress_set_remaining(&s
->common
, 1);
3169 s
->ret
= save_snapshot(s
->tag
, false, s
->vmstate
,
3170 true, s
->devices
, s
->errp
);
3171 job_progress_update(&s
->common
, 1);
3173 qmp_snapshot_job_free(s
);
3177 static void snapshot_delete_job_bh(void *opaque
)
3180 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3182 job_progress_set_remaining(&s
->common
, 1);
3183 s
->ret
= delete_snapshot(s
->tag
, true, s
->devices
, s
->errp
);
3184 job_progress_update(&s
->common
, 1);
3186 qmp_snapshot_job_free(s
);
3190 static int coroutine_fn
snapshot_save_job_run(Job
*job
, Error
**errp
)
3192 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3194 s
->co
= qemu_coroutine_self();
3195 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3196 snapshot_save_job_bh
, job
);
3197 qemu_coroutine_yield();
3198 return s
->ret
? 0 : -1;
3201 static int coroutine_fn
snapshot_load_job_run(Job
*job
, Error
**errp
)
3203 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3205 s
->co
= qemu_coroutine_self();
3206 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3207 snapshot_load_job_bh
, job
);
3208 qemu_coroutine_yield();
3209 return s
->ret
? 0 : -1;
3212 static int coroutine_fn
snapshot_delete_job_run(Job
*job
, Error
**errp
)
3214 SnapshotJob
*s
= container_of(job
, SnapshotJob
, common
);
3216 s
->co
= qemu_coroutine_self();
3217 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3218 snapshot_delete_job_bh
, job
);
3219 qemu_coroutine_yield();
3220 return s
->ret
? 0 : -1;
3224 static const JobDriver snapshot_load_job_driver
= {
3225 .instance_size
= sizeof(SnapshotJob
),
3226 .job_type
= JOB_TYPE_SNAPSHOT_LOAD
,
3227 .run
= snapshot_load_job_run
,
3230 static const JobDriver snapshot_save_job_driver
= {
3231 .instance_size
= sizeof(SnapshotJob
),
3232 .job_type
= JOB_TYPE_SNAPSHOT_SAVE
,
3233 .run
= snapshot_save_job_run
,
3236 static const JobDriver snapshot_delete_job_driver
= {
3237 .instance_size
= sizeof(SnapshotJob
),
3238 .job_type
= JOB_TYPE_SNAPSHOT_DELETE
,
3239 .run
= snapshot_delete_job_run
,
3243 void qmp_snapshot_save(const char *job_id
,
3245 const char *vmstate
,
3251 s
= job_create(job_id
, &snapshot_save_job_driver
, NULL
,
3252 qemu_get_aio_context(), JOB_MANUAL_DISMISS
,
3258 s
->tag
= g_strdup(tag
);
3259 s
->vmstate
= g_strdup(vmstate
);
3260 s
->devices
= QAPI_CLONE(strList
, devices
);
3262 job_start(&s
->common
);
3265 void qmp_snapshot_load(const char *job_id
,
3267 const char *vmstate
,
3273 s
= job_create(job_id
, &snapshot_load_job_driver
, NULL
,
3274 qemu_get_aio_context(), JOB_MANUAL_DISMISS
,
3280 s
->tag
= g_strdup(tag
);
3281 s
->vmstate
= g_strdup(vmstate
);
3282 s
->devices
= QAPI_CLONE(strList
, devices
);
3284 job_start(&s
->common
);
3287 void qmp_snapshot_delete(const char *job_id
,
3294 s
= job_create(job_id
, &snapshot_delete_job_driver
, NULL
,
3295 qemu_get_aio_context(), JOB_MANUAL_DISMISS
,
3301 s
->tag
= g_strdup(tag
);
3302 s
->devices
= QAPI_CLONE(strList
, devices
);
3304 job_start(&s
->common
);