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/qapi-commands-misc.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qemu/error-report.h"
48 #include "sysemu/cpus.h"
49 #include "exec/memory.h"
50 #include "exec/target_page.h"
53 #include "qemu/main-loop.h"
54 #include "block/snapshot.h"
55 #include "qemu/cutils.h"
56 #include "io/channel-buffer.h"
57 #include "io/channel-file.h"
58 #include "sysemu/replay.h"
59 #include "sysemu/runstate.h"
60 #include "sysemu/sysemu.h"
61 #include "sysemu/xen.h"
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
;
236 uint32_t instance_id
;
239 /* version id read from the stream */
242 /* section id read from the stream */
244 const SaveVMHandlers
*ops
;
245 const VMStateDescription
*vmsd
;
251 typedef struct SaveState
{
252 QTAILQ_HEAD(, SaveStateEntry
) handlers
;
253 SaveStateEntry
*handler_pri_head
[MIG_PRI_MAX
+ 1];
254 int global_section_id
;
257 uint32_t target_page_bits
;
259 MigrationCapability
*capabilities
;
263 static SaveState savevm_state
= {
264 .handlers
= QTAILQ_HEAD_INITIALIZER(savevm_state
.handlers
),
265 .handler_pri_head
= { [MIG_PRI_DEFAULT
... MIG_PRI_MAX
] = NULL
},
266 .global_section_id
= 0,
269 static bool should_validate_capability(int capability
)
271 assert(capability
>= 0 && capability
< MIGRATION_CAPABILITY__MAX
);
272 /* Validate only new capabilities to keep compatibility. */
273 switch (capability
) {
274 case MIGRATION_CAPABILITY_X_IGNORE_SHARED
:
281 static uint32_t get_validatable_capabilities_count(void)
283 MigrationState
*s
= migrate_get_current();
286 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
287 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
294 static int configuration_pre_save(void *opaque
)
296 SaveState
*state
= opaque
;
297 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
298 MigrationState
*s
= migrate_get_current();
301 state
->len
= strlen(current_name
);
302 state
->name
= current_name
;
303 state
->target_page_bits
= qemu_target_page_bits();
305 state
->caps_count
= get_validatable_capabilities_count();
306 state
->capabilities
= g_renew(MigrationCapability
, state
->capabilities
,
308 for (i
= j
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
309 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
310 state
->capabilities
[j
++] = i
;
313 state
->uuid
= qemu_uuid
;
318 static int configuration_pre_load(void *opaque
)
320 SaveState
*state
= opaque
;
322 /* If there is no target-page-bits subsection it means the source
323 * predates the variable-target-page-bits support and is using the
324 * minimum possible value for this CPU.
326 state
->target_page_bits
= qemu_target_page_bits_min();
330 static bool configuration_validate_capabilities(SaveState
*state
)
333 MigrationState
*s
= migrate_get_current();
334 unsigned long *source_caps_bm
;
337 source_caps_bm
= bitmap_new(MIGRATION_CAPABILITY__MAX
);
338 for (i
= 0; i
< state
->caps_count
; i
++) {
339 MigrationCapability capability
= state
->capabilities
[i
];
340 set_bit(capability
, source_caps_bm
);
343 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
344 bool source_state
, target_state
;
345 if (!should_validate_capability(i
)) {
348 source_state
= test_bit(i
, source_caps_bm
);
349 target_state
= s
->enabled_capabilities
[i
];
350 if (source_state
!= target_state
) {
351 error_report("Capability %s is %s, but received capability is %s",
352 MigrationCapability_str(i
),
353 target_state
? "on" : "off",
354 source_state
? "on" : "off");
356 /* Don't break here to report all failed capabilities */
360 g_free(source_caps_bm
);
364 static int configuration_post_load(void *opaque
, int version_id
)
366 SaveState
*state
= opaque
;
367 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
369 if (strncmp(state
->name
, current_name
, state
->len
) != 0) {
370 error_report("Machine type received is '%.*s' and local is '%s'",
371 (int) state
->len
, state
->name
, current_name
);
375 if (state
->target_page_bits
!= qemu_target_page_bits()) {
376 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
377 state
->target_page_bits
, qemu_target_page_bits());
381 if (!configuration_validate_capabilities(state
)) {
388 static int get_capability(QEMUFile
*f
, void *pv
, size_t size
,
389 const VMStateField
*field
)
391 MigrationCapability
*capability
= pv
;
392 char capability_str
[UINT8_MAX
+ 1];
396 len
= qemu_get_byte(f
);
397 qemu_get_buffer(f
, (uint8_t *)capability_str
, len
);
398 capability_str
[len
] = '\0';
399 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
400 if (!strcmp(MigrationCapability_str(i
), capability_str
)) {
405 error_report("Received unknown capability %s", capability_str
);
409 static int put_capability(QEMUFile
*f
, void *pv
, size_t size
,
410 const VMStateField
*field
, QJSON
*vmdesc
)
412 MigrationCapability
*capability
= pv
;
413 const char *capability_str
= MigrationCapability_str(*capability
);
414 size_t len
= strlen(capability_str
);
415 assert(len
<= UINT8_MAX
);
417 qemu_put_byte(f
, len
);
418 qemu_put_buffer(f
, (uint8_t *)capability_str
, len
);
422 static const VMStateInfo vmstate_info_capability
= {
423 .name
= "capability",
424 .get
= get_capability
,
425 .put
= put_capability
,
428 /* The target-page-bits subsection is present only if the
429 * target page size is not the same as the default (ie the
430 * minimum page size for a variable-page-size guest CPU).
431 * If it is present then it contains the actual target page
432 * bits for the machine, and migration will fail if the
433 * two ends don't agree about it.
435 static bool vmstate_target_page_bits_needed(void *opaque
)
437 return qemu_target_page_bits()
438 > qemu_target_page_bits_min();
441 static const VMStateDescription vmstate_target_page_bits
= {
442 .name
= "configuration/target-page-bits",
444 .minimum_version_id
= 1,
445 .needed
= vmstate_target_page_bits_needed
,
446 .fields
= (VMStateField
[]) {
447 VMSTATE_UINT32(target_page_bits
, SaveState
),
448 VMSTATE_END_OF_LIST()
452 static bool vmstate_capabilites_needed(void *opaque
)
454 return get_validatable_capabilities_count() > 0;
457 static const VMStateDescription vmstate_capabilites
= {
458 .name
= "configuration/capabilities",
460 .minimum_version_id
= 1,
461 .needed
= vmstate_capabilites_needed
,
462 .fields
= (VMStateField
[]) {
463 VMSTATE_UINT32_V(caps_count
, SaveState
, 1),
464 VMSTATE_VARRAY_UINT32_ALLOC(capabilities
, SaveState
, caps_count
, 1,
465 vmstate_info_capability
,
466 MigrationCapability
),
467 VMSTATE_END_OF_LIST()
471 static bool vmstate_uuid_needed(void *opaque
)
473 return qemu_uuid_set
&& migrate_validate_uuid();
476 static int vmstate_uuid_post_load(void *opaque
, int version_id
)
478 SaveState
*state
= opaque
;
479 char uuid_src
[UUID_FMT_LEN
+ 1];
480 char uuid_dst
[UUID_FMT_LEN
+ 1];
482 if (!qemu_uuid_set
) {
484 * It's warning because user might not know UUID in some cases,
485 * e.g. load an old snapshot
487 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
488 warn_report("UUID is received %s, but local uuid isn't set",
492 if (!qemu_uuid_is_equal(&state
->uuid
, &qemu_uuid
)) {
493 qemu_uuid_unparse(&state
->uuid
, uuid_src
);
494 qemu_uuid_unparse(&qemu_uuid
, uuid_dst
);
495 error_report("UUID received is %s and local is %s", uuid_src
, uuid_dst
);
501 static const VMStateDescription vmstate_uuid
= {
502 .name
= "configuration/uuid",
504 .minimum_version_id
= 1,
505 .needed
= vmstate_uuid_needed
,
506 .post_load
= vmstate_uuid_post_load
,
507 .fields
= (VMStateField
[]) {
508 VMSTATE_UINT8_ARRAY_V(uuid
.data
, SaveState
, sizeof(QemuUUID
), 1),
509 VMSTATE_END_OF_LIST()
513 static const VMStateDescription vmstate_configuration
= {
514 .name
= "configuration",
516 .pre_load
= configuration_pre_load
,
517 .post_load
= configuration_post_load
,
518 .pre_save
= configuration_pre_save
,
519 .fields
= (VMStateField
[]) {
520 VMSTATE_UINT32(len
, SaveState
),
521 VMSTATE_VBUFFER_ALLOC_UINT32(name
, SaveState
, 0, NULL
, len
),
522 VMSTATE_END_OF_LIST()
524 .subsections
= (const VMStateDescription
*[]) {
525 &vmstate_target_page_bits
,
526 &vmstate_capabilites
,
532 static void dump_vmstate_vmsd(FILE *out_file
,
533 const VMStateDescription
*vmsd
, int indent
,
536 static void dump_vmstate_vmsf(FILE *out_file
, const VMStateField
*field
,
539 fprintf(out_file
, "%*s{\n", indent
, "");
541 fprintf(out_file
, "%*s\"field\": \"%s\",\n", indent
, "", field
->name
);
542 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
544 fprintf(out_file
, "%*s\"field_exists\": %s,\n", indent
, "",
545 field
->field_exists
? "true" : "false");
546 fprintf(out_file
, "%*s\"size\": %zu", indent
, "", field
->size
);
547 if (field
->vmsd
!= NULL
) {
548 fprintf(out_file
, ",\n");
549 dump_vmstate_vmsd(out_file
, field
->vmsd
, indent
, false);
551 fprintf(out_file
, "\n%*s}", indent
- 2, "");
554 static void dump_vmstate_vmss(FILE *out_file
,
555 const VMStateDescription
**subsection
,
558 if (*subsection
!= NULL
) {
559 dump_vmstate_vmsd(out_file
, *subsection
, indent
, true);
563 static void dump_vmstate_vmsd(FILE *out_file
,
564 const VMStateDescription
*vmsd
, int indent
,
568 fprintf(out_file
, "%*s{\n", indent
, "");
570 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", "Description");
573 fprintf(out_file
, "%*s\"name\": \"%s\",\n", indent
, "", vmsd
->name
);
574 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
576 fprintf(out_file
, "%*s\"minimum_version_id\": %d", indent
, "",
577 vmsd
->minimum_version_id
);
578 if (vmsd
->fields
!= NULL
) {
579 const VMStateField
*field
= vmsd
->fields
;
582 fprintf(out_file
, ",\n%*s\"Fields\": [\n", indent
, "");
584 while (field
->name
!= NULL
) {
585 if (field
->flags
& VMS_MUST_EXIST
) {
586 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
591 fprintf(out_file
, ",\n");
593 dump_vmstate_vmsf(out_file
, field
, indent
+ 2);
597 fprintf(out_file
, "\n%*s]", indent
, "");
599 if (vmsd
->subsections
!= NULL
) {
600 const VMStateDescription
**subsection
= vmsd
->subsections
;
603 fprintf(out_file
, ",\n%*s\"Subsections\": [\n", indent
, "");
605 while (*subsection
!= NULL
) {
607 fprintf(out_file
, ",\n");
609 dump_vmstate_vmss(out_file
, subsection
, indent
+ 2);
613 fprintf(out_file
, "\n%*s]", indent
, "");
615 fprintf(out_file
, "\n%*s}", indent
- 2, "");
618 static void dump_machine_type(FILE *out_file
)
622 mc
= MACHINE_GET_CLASS(current_machine
);
624 fprintf(out_file
, " \"vmschkmachine\": {\n");
625 fprintf(out_file
, " \"Name\": \"%s\"\n", mc
->name
);
626 fprintf(out_file
, " },\n");
629 void dump_vmstate_json_to_file(FILE *out_file
)
634 fprintf(out_file
, "{\n");
635 dump_machine_type(out_file
);
638 list
= object_class_get_list(TYPE_DEVICE
, true);
639 for (elt
= list
; elt
; elt
= elt
->next
) {
640 DeviceClass
*dc
= OBJECT_CLASS_CHECK(DeviceClass
, elt
->data
,
650 fprintf(out_file
, ",\n");
652 name
= object_class_get_name(OBJECT_CLASS(dc
));
653 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", name
);
655 fprintf(out_file
, "%*s\"Name\": \"%s\",\n", indent
, "", name
);
656 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
657 dc
->vmsd
->version_id
);
658 fprintf(out_file
, "%*s\"minimum_version_id\": %d,\n", indent
, "",
659 dc
->vmsd
->minimum_version_id
);
661 dump_vmstate_vmsd(out_file
, dc
->vmsd
, indent
, false);
663 fprintf(out_file
, "\n%*s}", indent
- 2, "");
666 fprintf(out_file
, "\n}\n");
671 static uint32_t calculate_new_instance_id(const char *idstr
)
674 uint32_t instance_id
= 0;
676 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
677 if (strcmp(idstr
, se
->idstr
) == 0
678 && instance_id
<= se
->instance_id
) {
679 instance_id
= se
->instance_id
+ 1;
682 /* Make sure we never loop over without being noticed */
683 assert(instance_id
!= VMSTATE_INSTANCE_ID_ANY
);
687 static int calculate_compat_instance_id(const char *idstr
)
692 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
697 if (strcmp(idstr
, se
->compat
->idstr
) == 0
698 && instance_id
<= se
->compat
->instance_id
) {
699 instance_id
= se
->compat
->instance_id
+ 1;
705 static inline MigrationPriority
save_state_priority(SaveStateEntry
*se
)
708 return se
->vmsd
->priority
;
710 return MIG_PRI_DEFAULT
;
713 static void savevm_state_handler_insert(SaveStateEntry
*nse
)
715 MigrationPriority priority
= save_state_priority(nse
);
719 assert(priority
<= MIG_PRI_MAX
);
721 for (i
= priority
- 1; i
>= 0; i
--) {
722 se
= savevm_state
.handler_pri_head
[i
];
724 assert(save_state_priority(se
) < priority
);
730 QTAILQ_INSERT_BEFORE(se
, nse
, entry
);
732 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, nse
, entry
);
735 if (savevm_state
.handler_pri_head
[priority
] == NULL
) {
736 savevm_state
.handler_pri_head
[priority
] = nse
;
740 static void savevm_state_handler_remove(SaveStateEntry
*se
)
742 SaveStateEntry
*next
;
743 MigrationPriority priority
= save_state_priority(se
);
745 if (se
== savevm_state
.handler_pri_head
[priority
]) {
746 next
= QTAILQ_NEXT(se
, entry
);
747 if (next
!= NULL
&& save_state_priority(next
) == priority
) {
748 savevm_state
.handler_pri_head
[priority
] = next
;
750 savevm_state
.handler_pri_head
[priority
] = NULL
;
753 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
756 /* TODO: Individual devices generally have very little idea about the rest
757 of the system, so instance_id should be removed/replaced.
758 Meanwhile pass -1 as instance_id if you do not already have a clearly
759 distinguishing id for all instances of your device class. */
760 int register_savevm_live(const char *idstr
,
761 uint32_t instance_id
,
763 const SaveVMHandlers
*ops
,
768 se
= g_new0(SaveStateEntry
, 1);
769 se
->version_id
= version_id
;
770 se
->section_id
= savevm_state
.global_section_id
++;
774 /* if this is a live_savem then set is_ram */
775 if (ops
->save_setup
!= NULL
) {
779 pstrcat(se
->idstr
, sizeof(se
->idstr
), idstr
);
781 if (instance_id
== VMSTATE_INSTANCE_ID_ANY
) {
782 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
784 se
->instance_id
= instance_id
;
786 assert(!se
->compat
|| se
->instance_id
== 0);
787 savevm_state_handler_insert(se
);
791 void unregister_savevm(VMStateIf
*obj
, const char *idstr
, void *opaque
)
793 SaveStateEntry
*se
, *new_se
;
797 char *oid
= vmstate_if_get_id(obj
);
799 pstrcpy(id
, sizeof(id
), oid
);
800 pstrcat(id
, sizeof(id
), "/");
804 pstrcat(id
, sizeof(id
), idstr
);
806 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
807 if (strcmp(se
->idstr
, id
) == 0 && se
->opaque
== opaque
) {
808 savevm_state_handler_remove(se
);
815 int vmstate_register_with_alias_id(VMStateIf
*obj
, uint32_t instance_id
,
816 const VMStateDescription
*vmsd
,
817 void *opaque
, int alias_id
,
818 int required_for_version
,
823 /* If this triggers, alias support can be dropped for the vmsd. */
824 assert(alias_id
== -1 || required_for_version
>= vmsd
->minimum_version_id
);
826 se
= g_new0(SaveStateEntry
, 1);
827 se
->version_id
= vmsd
->version_id
;
828 se
->section_id
= savevm_state
.global_section_id
++;
831 se
->alias_id
= alias_id
;
834 char *id
= vmstate_if_get_id(obj
);
836 if (snprintf(se
->idstr
, sizeof(se
->idstr
), "%s/", id
) >=
838 error_setg(errp
, "Path too long for VMState (%s)", id
);
846 se
->compat
= g_new0(CompatEntry
, 1);
847 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), vmsd
->name
);
848 se
->compat
->instance_id
= instance_id
== VMSTATE_INSTANCE_ID_ANY
?
849 calculate_compat_instance_id(vmsd
->name
) : instance_id
;
850 instance_id
= VMSTATE_INSTANCE_ID_ANY
;
853 pstrcat(se
->idstr
, sizeof(se
->idstr
), vmsd
->name
);
855 if (instance_id
== VMSTATE_INSTANCE_ID_ANY
) {
856 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
858 se
->instance_id
= instance_id
;
860 assert(!se
->compat
|| se
->instance_id
== 0);
861 savevm_state_handler_insert(se
);
865 void vmstate_unregister(VMStateIf
*obj
, const VMStateDescription
*vmsd
,
868 SaveStateEntry
*se
, *new_se
;
870 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
871 if (se
->vmsd
== vmsd
&& se
->opaque
== opaque
) {
872 savevm_state_handler_remove(se
);
879 static int vmstate_load(QEMUFile
*f
, SaveStateEntry
*se
)
881 trace_vmstate_load(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
882 if (!se
->vmsd
) { /* Old style */
883 return se
->ops
->load_state(f
, se
->opaque
, se
->load_version_id
);
885 return vmstate_load_state(f
, se
->vmsd
, se
->opaque
, se
->load_version_id
);
888 static void vmstate_save_old_style(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
890 int64_t old_offset
, size
;
892 old_offset
= qemu_ftell_fast(f
);
893 se
->ops
->save_state(f
, se
->opaque
);
894 size
= qemu_ftell_fast(f
) - old_offset
;
897 json_prop_int(vmdesc
, "size", size
);
898 json_start_array(vmdesc
, "fields");
899 json_start_object(vmdesc
, NULL
);
900 json_prop_str(vmdesc
, "name", "data");
901 json_prop_int(vmdesc
, "size", size
);
902 json_prop_str(vmdesc
, "type", "buffer");
903 json_end_object(vmdesc
);
904 json_end_array(vmdesc
);
908 static int vmstate_save(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
910 trace_vmstate_save(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
912 vmstate_save_old_style(f
, se
, vmdesc
);
915 return vmstate_save_state(f
, se
->vmsd
, se
->opaque
, vmdesc
);
919 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
921 static void save_section_header(QEMUFile
*f
, SaveStateEntry
*se
,
922 uint8_t section_type
)
924 qemu_put_byte(f
, section_type
);
925 qemu_put_be32(f
, se
->section_id
);
927 if (section_type
== QEMU_VM_SECTION_FULL
||
928 section_type
== QEMU_VM_SECTION_START
) {
930 size_t len
= strlen(se
->idstr
);
931 qemu_put_byte(f
, len
);
932 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
934 qemu_put_be32(f
, se
->instance_id
);
935 qemu_put_be32(f
, se
->version_id
);
940 * Write a footer onto device sections that catches cases misformatted device
943 static void save_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
945 if (migrate_get_current()->send_section_footer
) {
946 qemu_put_byte(f
, QEMU_VM_SECTION_FOOTER
);
947 qemu_put_be32(f
, se
->section_id
);
952 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
953 * command and associated data.
955 * @f: File to send command on
956 * @command: Command type to send
957 * @len: Length of associated data
958 * @data: Data associated with command.
960 static void qemu_savevm_command_send(QEMUFile
*f
,
961 enum qemu_vm_cmd command
,
965 trace_savevm_command_send(command
, len
);
966 qemu_put_byte(f
, QEMU_VM_COMMAND
);
967 qemu_put_be16(f
, (uint16_t)command
);
968 qemu_put_be16(f
, len
);
969 qemu_put_buffer(f
, data
, len
);
973 void qemu_savevm_send_colo_enable(QEMUFile
*f
)
975 trace_savevm_send_colo_enable();
976 qemu_savevm_command_send(f
, MIG_CMD_ENABLE_COLO
, 0, NULL
);
979 void qemu_savevm_send_ping(QEMUFile
*f
, uint32_t value
)
983 trace_savevm_send_ping(value
);
984 buf
= cpu_to_be32(value
);
985 qemu_savevm_command_send(f
, MIG_CMD_PING
, sizeof(value
), (uint8_t *)&buf
);
988 void qemu_savevm_send_open_return_path(QEMUFile
*f
)
990 trace_savevm_send_open_return_path();
991 qemu_savevm_command_send(f
, MIG_CMD_OPEN_RETURN_PATH
, 0, NULL
);
994 /* We have a buffer of data to send; we don't want that all to be loaded
995 * by the command itself, so the command contains just the length of the
996 * extra buffer that we then send straight after it.
997 * TODO: Must be a better way to organise that
1003 int qemu_savevm_send_packaged(QEMUFile
*f
, const uint8_t *buf
, size_t len
)
1007 if (len
> MAX_VM_CMD_PACKAGED_SIZE
) {
1008 error_report("%s: Unreasonably large packaged state: %zu",
1013 tmp
= cpu_to_be32(len
);
1015 trace_qemu_savevm_send_packaged();
1016 qemu_savevm_command_send(f
, MIG_CMD_PACKAGED
, 4, (uint8_t *)&tmp
);
1018 qemu_put_buffer(f
, buf
, len
);
1023 /* Send prior to any postcopy transfer */
1024 void qemu_savevm_send_postcopy_advise(QEMUFile
*f
)
1026 if (migrate_postcopy_ram()) {
1028 tmp
[0] = cpu_to_be64(ram_pagesize_summary());
1029 tmp
[1] = cpu_to_be64(qemu_target_page_size());
1031 trace_qemu_savevm_send_postcopy_advise();
1032 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
,
1033 16, (uint8_t *)tmp
);
1035 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
, 0, NULL
);
1039 /* Sent prior to starting the destination running in postcopy, discard pages
1040 * that have already been sent but redirtied on the source.
1041 * CMD_POSTCOPY_RAM_DISCARD consist of:
1043 * byte Length of name field (not including 0)
1044 * n x byte RAM block name
1045 * byte 0 terminator (just for safety)
1046 * n x Byte ranges within the named RAMBlock
1047 * be64 Start of the range
1050 * name: RAMBlock name that these entries are part of
1051 * len: Number of page entries
1052 * start_list: 'len' addresses
1053 * length_list: 'len' addresses
1056 void qemu_savevm_send_postcopy_ram_discard(QEMUFile
*f
, const char *name
,
1058 uint64_t *start_list
,
1059 uint64_t *length_list
)
1064 size_t name_len
= strlen(name
);
1066 trace_qemu_savevm_send_postcopy_ram_discard(name
, len
);
1067 assert(name_len
< 256);
1068 buf
= g_malloc0(1 + 1 + name_len
+ 1 + (8 + 8) * len
);
1069 buf
[0] = postcopy_ram_discard_version
;
1071 memcpy(buf
+ 2, name
, name_len
);
1072 tmplen
= 2 + name_len
;
1073 buf
[tmplen
++] = '\0';
1075 for (t
= 0; t
< len
; t
++) {
1076 stq_be_p(buf
+ tmplen
, start_list
[t
]);
1078 stq_be_p(buf
+ tmplen
, length_list
[t
]);
1081 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RAM_DISCARD
, tmplen
, buf
);
1085 /* Get the destination into a state where it can receive postcopy data. */
1086 void qemu_savevm_send_postcopy_listen(QEMUFile
*f
)
1088 trace_savevm_send_postcopy_listen();
1089 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_LISTEN
, 0, NULL
);
1092 /* Kick the destination into running */
1093 void qemu_savevm_send_postcopy_run(QEMUFile
*f
)
1095 trace_savevm_send_postcopy_run();
1096 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RUN
, 0, NULL
);
1099 void qemu_savevm_send_postcopy_resume(QEMUFile
*f
)
1101 trace_savevm_send_postcopy_resume();
1102 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RESUME
, 0, NULL
);
1105 void qemu_savevm_send_recv_bitmap(QEMUFile
*f
, char *block_name
)
1110 trace_savevm_send_recv_bitmap(block_name
);
1112 buf
[0] = len
= strlen(block_name
);
1113 memcpy(buf
+ 1, block_name
, len
);
1115 qemu_savevm_command_send(f
, MIG_CMD_RECV_BITMAP
, len
+ 1, (uint8_t *)buf
);
1118 bool qemu_savevm_state_blocked(Error
**errp
)
1122 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1123 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
1124 error_setg(errp
, "State blocked by non-migratable device '%s'",
1132 void qemu_savevm_state_header(QEMUFile
*f
)
1134 trace_savevm_state_header();
1135 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1136 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1138 if (migrate_get_current()->send_configuration
) {
1139 qemu_put_byte(f
, QEMU_VM_CONFIGURATION
);
1140 vmstate_save_state(f
, &vmstate_configuration
, &savevm_state
, 0);
1144 bool qemu_savevm_state_guest_unplug_pending(void)
1148 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1149 if (se
->vmsd
&& se
->vmsd
->dev_unplug_pending
&&
1150 se
->vmsd
->dev_unplug_pending(se
->opaque
)) {
1158 void qemu_savevm_state_setup(QEMUFile
*f
)
1161 Error
*local_err
= NULL
;
1164 trace_savevm_state_setup();
1165 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1166 if (!se
->ops
|| !se
->ops
->save_setup
) {
1169 if (se
->ops
->is_active
) {
1170 if (!se
->ops
->is_active(se
->opaque
)) {
1174 save_section_header(f
, se
, QEMU_VM_SECTION_START
);
1176 ret
= se
->ops
->save_setup(f
, se
->opaque
);
1177 save_section_footer(f
, se
);
1179 qemu_file_set_error(f
, ret
);
1184 if (precopy_notify(PRECOPY_NOTIFY_SETUP
, &local_err
)) {
1185 error_report_err(local_err
);
1189 int qemu_savevm_state_resume_prepare(MigrationState
*s
)
1194 trace_savevm_state_resume_prepare();
1196 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1197 if (!se
->ops
|| !se
->ops
->resume_prepare
) {
1200 if (se
->ops
->is_active
) {
1201 if (!se
->ops
->is_active(se
->opaque
)) {
1205 ret
= se
->ops
->resume_prepare(s
, se
->opaque
);
1215 * this function has three return values:
1216 * negative: there was one error, and we have -errno.
1217 * 0 : We haven't finished, caller have to go again
1218 * 1 : We have finished, we can go to complete phase
1220 int qemu_savevm_state_iterate(QEMUFile
*f
, bool postcopy
)
1225 trace_savevm_state_iterate();
1226 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1227 if (!se
->ops
|| !se
->ops
->save_live_iterate
) {
1230 if (se
->ops
->is_active
&&
1231 !se
->ops
->is_active(se
->opaque
)) {
1234 if (se
->ops
->is_active_iterate
&&
1235 !se
->ops
->is_active_iterate(se
->opaque
)) {
1239 * In the postcopy phase, any device that doesn't know how to
1240 * do postcopy should have saved it's state in the _complete
1241 * call that's already run, it might get confused if we call
1242 * iterate afterwards.
1245 !(se
->ops
->has_postcopy
&& se
->ops
->has_postcopy(se
->opaque
))) {
1248 if (qemu_file_rate_limit(f
)) {
1251 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1253 save_section_header(f
, se
, QEMU_VM_SECTION_PART
);
1255 ret
= se
->ops
->save_live_iterate(f
, se
->opaque
);
1256 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1257 save_section_footer(f
, se
);
1260 error_report("failed to save SaveStateEntry with id(name): %d(%s)",
1261 se
->section_id
, se
->idstr
);
1262 qemu_file_set_error(f
, ret
);
1265 /* Do not proceed to the next vmstate before this one reported
1266 completion of the current stage. This serializes the migration
1267 and reduces the probability that a faster changing state is
1268 synchronized over and over again. */
1275 static bool should_send_vmdesc(void)
1277 MachineState
*machine
= MACHINE(qdev_get_machine());
1278 bool in_postcopy
= migration_in_postcopy();
1279 return !machine
->suppress_vmdesc
&& !in_postcopy
;
1283 * Calls the save_live_complete_postcopy methods
1284 * causing the last few pages to be sent immediately and doing any associated
1286 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1287 * all the other devices, but that happens at the point we switch to postcopy.
1289 void qemu_savevm_state_complete_postcopy(QEMUFile
*f
)
1294 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1295 if (!se
->ops
|| !se
->ops
->save_live_complete_postcopy
) {
1298 if (se
->ops
->is_active
) {
1299 if (!se
->ops
->is_active(se
->opaque
)) {
1303 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1305 qemu_put_byte(f
, QEMU_VM_SECTION_END
);
1306 qemu_put_be32(f
, se
->section_id
);
1308 ret
= se
->ops
->save_live_complete_postcopy(f
, se
->opaque
);
1309 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1310 save_section_footer(f
, se
);
1312 qemu_file_set_error(f
, ret
);
1317 qemu_put_byte(f
, QEMU_VM_EOF
);
1322 int qemu_savevm_state_complete_precopy_iterable(QEMUFile
*f
, bool in_postcopy
)
1327 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1329 (in_postcopy
&& se
->ops
->has_postcopy
&&
1330 se
->ops
->has_postcopy(se
->opaque
)) ||
1331 !se
->ops
->save_live_complete_precopy
) {
1335 if (se
->ops
->is_active
) {
1336 if (!se
->ops
->is_active(se
->opaque
)) {
1340 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1342 save_section_header(f
, se
, QEMU_VM_SECTION_END
);
1344 ret
= se
->ops
->save_live_complete_precopy(f
, se
->opaque
);
1345 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1346 save_section_footer(f
, se
);
1348 qemu_file_set_error(f
, ret
);
1357 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile
*f
,
1359 bool inactivate_disks
)
1361 g_autoptr(QJSON
) vmdesc
= NULL
;
1366 vmdesc
= qjson_new();
1367 json_prop_int(vmdesc
, "page_size", qemu_target_page_size());
1368 json_start_array(vmdesc
, "devices");
1369 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1371 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1374 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1375 trace_savevm_section_skip(se
->idstr
, se
->section_id
);
1379 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1381 json_start_object(vmdesc
, NULL
);
1382 json_prop_str(vmdesc
, "name", se
->idstr
);
1383 json_prop_int(vmdesc
, "instance_id", se
->instance_id
);
1385 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1386 ret
= vmstate_save(f
, se
, vmdesc
);
1388 qemu_file_set_error(f
, ret
);
1391 trace_savevm_section_end(se
->idstr
, se
->section_id
, 0);
1392 save_section_footer(f
, se
);
1394 json_end_object(vmdesc
);
1397 if (inactivate_disks
) {
1398 /* Inactivate before sending QEMU_VM_EOF so that the
1399 * bdrv_invalidate_cache_all() on the other end won't fail. */
1400 ret
= bdrv_inactivate_all();
1402 error_report("%s: bdrv_inactivate_all() failed (%d)",
1404 qemu_file_set_error(f
, ret
);
1409 /* Postcopy stream will still be going */
1410 qemu_put_byte(f
, QEMU_VM_EOF
);
1413 json_end_array(vmdesc
);
1414 qjson_finish(vmdesc
);
1415 vmdesc_len
= strlen(qjson_get_str(vmdesc
));
1417 if (should_send_vmdesc()) {
1418 qemu_put_byte(f
, QEMU_VM_VMDESCRIPTION
);
1419 qemu_put_be32(f
, vmdesc_len
);
1420 qemu_put_buffer(f
, (uint8_t *)qjson_get_str(vmdesc
), vmdesc_len
);
1426 int qemu_savevm_state_complete_precopy(QEMUFile
*f
, bool iterable_only
,
1427 bool inactivate_disks
)
1430 Error
*local_err
= NULL
;
1431 bool in_postcopy
= migration_in_postcopy();
1433 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE
, &local_err
)) {
1434 error_report_err(local_err
);
1437 trace_savevm_state_complete_precopy();
1439 cpu_synchronize_all_states();
1441 if (!in_postcopy
|| iterable_only
) {
1442 ret
= qemu_savevm_state_complete_precopy_iterable(f
, in_postcopy
);
1448 if (iterable_only
) {
1452 ret
= qemu_savevm_state_complete_precopy_non_iterable(f
, in_postcopy
,
1463 /* Give an estimate of the amount left to be transferred,
1464 * the result is split into the amount for units that can and
1465 * for units that can't do postcopy.
1467 void qemu_savevm_state_pending(QEMUFile
*f
, uint64_t threshold_size
,
1468 uint64_t *res_precopy_only
,
1469 uint64_t *res_compatible
,
1470 uint64_t *res_postcopy_only
)
1474 *res_precopy_only
= 0;
1475 *res_compatible
= 0;
1476 *res_postcopy_only
= 0;
1479 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1480 if (!se
->ops
|| !se
->ops
->save_live_pending
) {
1483 if (se
->ops
->is_active
) {
1484 if (!se
->ops
->is_active(se
->opaque
)) {
1488 se
->ops
->save_live_pending(f
, se
->opaque
, threshold_size
,
1489 res_precopy_only
, res_compatible
,
1494 void qemu_savevm_state_cleanup(void)
1497 Error
*local_err
= NULL
;
1499 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP
, &local_err
)) {
1500 error_report_err(local_err
);
1503 trace_savevm_state_cleanup();
1504 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1505 if (se
->ops
&& se
->ops
->save_cleanup
) {
1506 se
->ops
->save_cleanup(se
->opaque
);
1511 static int qemu_savevm_state(QEMUFile
*f
, Error
**errp
)
1514 MigrationState
*ms
= migrate_get_current();
1515 MigrationStatus status
;
1517 if (migration_is_running(ms
->state
)) {
1518 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1522 if (migrate_use_block()) {
1523 error_setg(errp
, "Block migration and snapshots are incompatible");
1528 memset(&ram_counters
, 0, sizeof(ram_counters
));
1529 ms
->to_dst_file
= f
;
1531 qemu_mutex_unlock_iothread();
1532 qemu_savevm_state_header(f
);
1533 qemu_savevm_state_setup(f
);
1534 qemu_mutex_lock_iothread();
1536 while (qemu_file_get_error(f
) == 0) {
1537 if (qemu_savevm_state_iterate(f
, false) > 0) {
1542 ret
= qemu_file_get_error(f
);
1544 qemu_savevm_state_complete_precopy(f
, false, false);
1545 ret
= qemu_file_get_error(f
);
1547 qemu_savevm_state_cleanup();
1549 error_setg_errno(errp
, -ret
, "Error while writing VM state");
1553 status
= MIGRATION_STATUS_FAILED
;
1555 status
= MIGRATION_STATUS_COMPLETED
;
1557 migrate_set_state(&ms
->state
, MIGRATION_STATUS_SETUP
, status
);
1559 /* f is outer parameter, it should not stay in global migration state after
1560 * this function finished */
1561 ms
->to_dst_file
= NULL
;
1566 void qemu_savevm_live_state(QEMUFile
*f
)
1568 /* save QEMU_VM_SECTION_END section */
1569 qemu_savevm_state_complete_precopy(f
, true, false);
1570 qemu_put_byte(f
, QEMU_VM_EOF
);
1573 int qemu_save_device_state(QEMUFile
*f
)
1577 if (!migration_in_colo_state()) {
1578 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1579 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1581 cpu_synchronize_all_states();
1583 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1589 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1592 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1596 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1598 ret
= vmstate_save(f
, se
, NULL
);
1603 save_section_footer(f
, se
);
1606 qemu_put_byte(f
, QEMU_VM_EOF
);
1608 return qemu_file_get_error(f
);
1611 static SaveStateEntry
*find_se(const char *idstr
, uint32_t instance_id
)
1615 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1616 if (!strcmp(se
->idstr
, idstr
) &&
1617 (instance_id
== se
->instance_id
||
1618 instance_id
== se
->alias_id
))
1620 /* Migrating from an older version? */
1621 if (strstr(se
->idstr
, idstr
) && se
->compat
) {
1622 if (!strcmp(se
->compat
->idstr
, idstr
) &&
1623 (instance_id
== se
->compat
->instance_id
||
1624 instance_id
== se
->alias_id
))
1631 enum LoadVMExitCodes
{
1632 /* Allow a command to quit all layers of nested loadvm loops */
1636 /* ------ incoming postcopy messages ------ */
1637 /* 'advise' arrives before any transfers just to tell us that a postcopy
1638 * *might* happen - it might be skipped if precopy transferred everything
1641 static int loadvm_postcopy_handle_advise(MigrationIncomingState
*mis
,
1644 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1645 uint64_t remote_pagesize_summary
, local_pagesize_summary
, remote_tps
;
1646 Error
*local_err
= NULL
;
1648 trace_loadvm_postcopy_handle_advise();
1649 if (ps
!= POSTCOPY_INCOMING_NONE
) {
1650 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps
);
1656 if (migrate_postcopy_ram()) {
1657 error_report("RAM postcopy is enabled but have 0 byte advise");
1662 if (!migrate_postcopy_ram()) {
1663 error_report("RAM postcopy is disabled but have 16 byte advise");
1668 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len
);
1672 if (!postcopy_ram_supported_by_host(mis
)) {
1673 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
1677 remote_pagesize_summary
= qemu_get_be64(mis
->from_src_file
);
1678 local_pagesize_summary
= ram_pagesize_summary();
1680 if (remote_pagesize_summary
!= local_pagesize_summary
) {
1682 * This detects two potential causes of mismatch:
1683 * a) A mismatch in host page sizes
1684 * Some combinations of mismatch are probably possible but it gets
1685 * a bit more complicated. In particular we need to place whole
1686 * host pages on the dest at once, and we need to ensure that we
1687 * handle dirtying to make sure we never end up sending part of
1688 * a hostpage on it's own.
1689 * b) The use of different huge page sizes on source/destination
1690 * a more fine grain test is performed during RAM block migration
1691 * but this test here causes a nice early clear failure, and
1692 * also fails when passed to an older qemu that doesn't
1695 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1697 remote_pagesize_summary
, local_pagesize_summary
);
1701 remote_tps
= qemu_get_be64(mis
->from_src_file
);
1702 if (remote_tps
!= qemu_target_page_size()) {
1704 * Again, some differences could be dealt with, but for now keep it
1707 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1708 (int)remote_tps
, qemu_target_page_size());
1712 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE
, &local_err
)) {
1713 error_report_err(local_err
);
1717 if (ram_postcopy_incoming_init(mis
)) {
1724 /* After postcopy we will be told to throw some pages away since they're
1725 * dirty and will have to be demand fetched. Must happen before CPU is
1727 * There can be 0..many of these messages, each encoding multiple pages.
1729 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState
*mis
,
1734 PostcopyState ps
= postcopy_state_get();
1736 trace_loadvm_postcopy_ram_handle_discard();
1739 case POSTCOPY_INCOMING_ADVISE
:
1741 tmp
= postcopy_ram_prepare_discard(mis
);
1747 case POSTCOPY_INCOMING_DISCARD
:
1748 /* Expected state */
1752 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1756 /* We're expecting a
1758 * a RAM ID string (length byte, name, 0 term)
1759 * then at least 1 16 byte chunk
1761 if (len
< (1 + 1 + 1 + 1 + 2 * 8)) {
1762 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1766 tmp
= qemu_get_byte(mis
->from_src_file
);
1767 if (tmp
!= postcopy_ram_discard_version
) {
1768 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp
);
1772 if (!qemu_get_counted_string(mis
->from_src_file
, ramid
)) {
1773 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1776 tmp
= qemu_get_byte(mis
->from_src_file
);
1778 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp
);
1782 len
-= 3 + strlen(ramid
);
1784 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1787 trace_loadvm_postcopy_ram_handle_discard_header(ramid
, len
);
1789 uint64_t start_addr
, block_length
;
1790 start_addr
= qemu_get_be64(mis
->from_src_file
);
1791 block_length
= qemu_get_be64(mis
->from_src_file
);
1794 int ret
= ram_discard_range(ramid
, start_addr
, block_length
);
1799 trace_loadvm_postcopy_ram_handle_discard_end();
1805 * Triggered by a postcopy_listen command; this thread takes over reading
1806 * the input stream, leaving the main thread free to carry on loading the rest
1807 * of the device state (from RAM).
1808 * (TODO:This could do with being in a postcopy file - but there again it's
1809 * just another input loop, not that postcopy specific)
1811 static void *postcopy_ram_listen_thread(void *opaque
)
1813 MigrationIncomingState
*mis
= migration_incoming_get_current();
1814 QEMUFile
*f
= mis
->from_src_file
;
1816 MigrationState
*migr
= migrate_get_current();
1818 object_ref(OBJECT(migr
));
1820 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
1821 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1822 qemu_sem_post(&mis
->listen_thread_sem
);
1823 trace_postcopy_ram_listen_thread_start();
1825 rcu_register_thread();
1827 * Because we're a thread and not a coroutine we can't yield
1828 * in qemu_file, and thus we must be blocking now.
1830 qemu_file_set_blocking(f
, true);
1831 load_res
= qemu_loadvm_state_main(f
, mis
);
1834 * This is tricky, but, mis->from_src_file can change after it
1835 * returns, when postcopy recovery happened. In the future, we may
1836 * want a wrapper for the QEMUFile handle.
1838 f
= mis
->from_src_file
;
1840 /* And non-blocking again so we don't block in any cleanup */
1841 qemu_file_set_blocking(f
, false);
1843 trace_postcopy_ram_listen_thread_exit();
1845 qemu_file_set_error(f
, load_res
);
1846 dirty_bitmap_mig_cancel_incoming();
1847 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
1848 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1850 error_report("%s: loadvm failed during postcopy: %d. All states "
1851 "are migrated except dirty bitmaps. Some dirty "
1852 "bitmaps may be lost, and present migrated dirty "
1853 "bitmaps are correctly migrated and valid.",
1854 __func__
, load_res
);
1855 load_res
= 0; /* prevent further exit() */
1857 error_report("%s: loadvm failed: %d", __func__
, load_res
);
1858 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1859 MIGRATION_STATUS_FAILED
);
1862 if (load_res
>= 0) {
1864 * This looks good, but it's possible that the device loading in the
1865 * main thread hasn't finished yet, and so we might not be in 'RUN'
1866 * state yet; wait for the end of the main thread.
1868 qemu_event_wait(&mis
->main_thread_load_event
);
1870 postcopy_ram_incoming_cleanup(mis
);
1874 * If something went wrong then we have a bad state so exit;
1875 * depending how far we got it might be possible at this point
1876 * to leave the guest running and fire MCEs for pages that never
1877 * arrived as a desperate recovery step.
1879 rcu_unregister_thread();
1883 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1884 MIGRATION_STATUS_COMPLETED
);
1886 * If everything has worked fine, then the main thread has waited
1887 * for us to start, and we're the last use of the mis.
1888 * (If something broke then qemu will have to exit anyway since it's
1889 * got a bad migration state).
1891 migration_incoming_state_destroy();
1892 qemu_loadvm_state_cleanup();
1894 rcu_unregister_thread();
1895 mis
->have_listen_thread
= false;
1896 postcopy_state_set(POSTCOPY_INCOMING_END
);
1898 object_unref(OBJECT(migr
));
1903 /* After this message we must be able to immediately receive postcopy data */
1904 static int loadvm_postcopy_handle_listen(MigrationIncomingState
*mis
)
1906 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_LISTENING
);
1907 trace_loadvm_postcopy_handle_listen();
1908 Error
*local_err
= NULL
;
1910 if (ps
!= POSTCOPY_INCOMING_ADVISE
&& ps
!= POSTCOPY_INCOMING_DISCARD
) {
1911 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps
);
1914 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
1916 * A rare case, we entered listen without having to do any discards,
1917 * so do the setup that's normally done at the time of the 1st discard.
1919 if (migrate_postcopy_ram()) {
1920 postcopy_ram_prepare_discard(mis
);
1925 * Sensitise RAM - can now generate requests for blocks that don't exist
1926 * However, at this point the CPU shouldn't be running, and the IO
1927 * shouldn't be doing anything yet so don't actually expect requests
1929 if (migrate_postcopy_ram()) {
1930 if (postcopy_ram_incoming_setup(mis
)) {
1931 postcopy_ram_incoming_cleanup(mis
);
1936 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN
, &local_err
)) {
1937 error_report_err(local_err
);
1941 mis
->have_listen_thread
= true;
1942 /* Start up the listening thread and wait for it to signal ready */
1943 qemu_sem_init(&mis
->listen_thread_sem
, 0);
1944 qemu_thread_create(&mis
->listen_thread
, "postcopy/listen",
1945 postcopy_ram_listen_thread
, NULL
,
1946 QEMU_THREAD_DETACHED
);
1947 qemu_sem_wait(&mis
->listen_thread_sem
);
1948 qemu_sem_destroy(&mis
->listen_thread_sem
);
1953 static void loadvm_postcopy_handle_run_bh(void *opaque
)
1955 Error
*local_err
= NULL
;
1956 MigrationIncomingState
*mis
= opaque
;
1958 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1961 cpu_synchronize_all_post_init();
1963 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
1965 /* Make sure all file formats flush their mutable metadata.
1966 * If we get an error here, just don't restart the VM yet. */
1967 bdrv_invalidate_cache_all(&local_err
);
1969 error_report_err(local_err
);
1974 trace_loadvm_postcopy_handle_run_cpu_sync();
1976 trace_loadvm_postcopy_handle_run_vmstart();
1978 dirty_bitmap_mig_before_vm_start();
1981 /* Hold onto your hats, starting the CPU */
1984 /* leave it paused and let management decide when to start the CPU */
1985 runstate_set(RUN_STATE_PAUSED
);
1988 qemu_bh_delete(mis
->bh
);
1991 /* After all discards we can start running and asking for pages */
1992 static int loadvm_postcopy_handle_run(MigrationIncomingState
*mis
)
1994 PostcopyState ps
= postcopy_state_get();
1996 trace_loadvm_postcopy_handle_run();
1997 if (ps
!= POSTCOPY_INCOMING_LISTENING
) {
1998 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps
);
2002 postcopy_state_set(POSTCOPY_INCOMING_RUNNING
);
2003 mis
->bh
= qemu_bh_new(loadvm_postcopy_handle_run_bh
, mis
);
2004 qemu_bh_schedule(mis
->bh
);
2006 /* We need to finish reading the stream from the package
2007 * and also stop reading anything more from the stream that loaded the
2008 * package (since it's now being read by the listener thread).
2009 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2014 static int loadvm_postcopy_handle_resume(MigrationIncomingState
*mis
)
2016 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2017 error_report("%s: illegal resume received", __func__
);
2018 /* Don't fail the load, only for this. */
2023 * This means source VM is ready to resume the postcopy migration.
2024 * It's time to switch state and release the fault thread to
2025 * continue service page faults.
2027 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2028 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2029 qemu_sem_post(&mis
->postcopy_pause_sem_fault
);
2031 trace_loadvm_postcopy_handle_resume();
2033 /* Tell source that "we are ready" */
2034 migrate_send_rp_resume_ack(mis
, MIGRATION_RESUME_ACK_VALUE
);
2040 * Immediately following this command is a blob of data containing an embedded
2041 * chunk of migration stream; read it and load it.
2043 * @mis: Incoming state
2044 * @length: Length of packaged data to read
2046 * Returns: Negative values on error
2049 static int loadvm_handle_cmd_packaged(MigrationIncomingState
*mis
)
2053 QIOChannelBuffer
*bioc
;
2055 length
= qemu_get_be32(mis
->from_src_file
);
2056 trace_loadvm_handle_cmd_packaged(length
);
2058 if (length
> MAX_VM_CMD_PACKAGED_SIZE
) {
2059 error_report("Unreasonably large packaged state: %zu", length
);
2063 bioc
= qio_channel_buffer_new(length
);
2064 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-loadvm-buffer");
2065 ret
= qemu_get_buffer(mis
->from_src_file
,
2068 if (ret
!= length
) {
2069 object_unref(OBJECT(bioc
));
2070 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2072 return (ret
< 0) ? ret
: -EAGAIN
;
2074 bioc
->usage
+= length
;
2075 trace_loadvm_handle_cmd_packaged_received(ret
);
2077 QEMUFile
*packf
= qemu_fopen_channel_input(QIO_CHANNEL(bioc
));
2079 ret
= qemu_loadvm_state_main(packf
, mis
);
2080 trace_loadvm_handle_cmd_packaged_main(ret
);
2082 object_unref(OBJECT(bioc
));
2088 * Handle request that source requests for recved_bitmap on
2089 * destination. Payload format:
2091 * len (1 byte) + ramblock_name (<255 bytes)
2093 static int loadvm_handle_recv_bitmap(MigrationIncomingState
*mis
,
2096 QEMUFile
*file
= mis
->from_src_file
;
2098 char block_name
[256];
2101 cnt
= qemu_get_counted_string(file
, block_name
);
2103 error_report("%s: failed to read block name", __func__
);
2107 /* Validate before using the data */
2108 if (qemu_file_get_error(file
)) {
2109 return qemu_file_get_error(file
);
2112 if (len
!= cnt
+ 1) {
2113 error_report("%s: invalid payload length (%d)", __func__
, len
);
2117 rb
= qemu_ram_block_by_name(block_name
);
2119 error_report("%s: block '%s' not found", __func__
, block_name
);
2123 migrate_send_rp_recv_bitmap(mis
, block_name
);
2125 trace_loadvm_handle_recv_bitmap(block_name
);
2130 static int loadvm_process_enable_colo(MigrationIncomingState
*mis
)
2132 int ret
= migration_incoming_enable_colo();
2135 ret
= colo_init_ram_cache();
2137 migration_incoming_disable_colo();
2144 * Process an incoming 'QEMU_VM_COMMAND'
2145 * 0 just a normal return
2146 * LOADVM_QUIT All good, but exit the loop
2149 static int loadvm_process_command(QEMUFile
*f
)
2151 MigrationIncomingState
*mis
= migration_incoming_get_current();
2156 cmd
= qemu_get_be16(f
);
2157 len
= qemu_get_be16(f
);
2159 /* Check validity before continue processing of cmds */
2160 if (qemu_file_get_error(f
)) {
2161 return qemu_file_get_error(f
);
2164 trace_loadvm_process_command(cmd
, len
);
2165 if (cmd
>= MIG_CMD_MAX
|| cmd
== MIG_CMD_INVALID
) {
2166 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd
, len
);
2170 if (mig_cmd_args
[cmd
].len
!= -1 && mig_cmd_args
[cmd
].len
!= len
) {
2171 error_report("%s received with bad length - expecting %zu, got %d",
2172 mig_cmd_args
[cmd
].name
,
2173 (size_t)mig_cmd_args
[cmd
].len
, len
);
2178 case MIG_CMD_OPEN_RETURN_PATH
:
2179 if (mis
->to_src_file
) {
2180 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2181 /* Not really a problem, so don't give up */
2184 mis
->to_src_file
= qemu_file_get_return_path(f
);
2185 if (!mis
->to_src_file
) {
2186 error_report("CMD_OPEN_RETURN_PATH failed");
2192 tmp32
= qemu_get_be32(f
);
2193 trace_loadvm_process_command_ping(tmp32
);
2194 if (!mis
->to_src_file
) {
2195 error_report("CMD_PING (0x%x) received with no return path",
2199 migrate_send_rp_pong(mis
, tmp32
);
2202 case MIG_CMD_PACKAGED
:
2203 return loadvm_handle_cmd_packaged(mis
);
2205 case MIG_CMD_POSTCOPY_ADVISE
:
2206 return loadvm_postcopy_handle_advise(mis
, len
);
2208 case MIG_CMD_POSTCOPY_LISTEN
:
2209 return loadvm_postcopy_handle_listen(mis
);
2211 case MIG_CMD_POSTCOPY_RUN
:
2212 return loadvm_postcopy_handle_run(mis
);
2214 case MIG_CMD_POSTCOPY_RAM_DISCARD
:
2215 return loadvm_postcopy_ram_handle_discard(mis
, len
);
2217 case MIG_CMD_POSTCOPY_RESUME
:
2218 return loadvm_postcopy_handle_resume(mis
);
2220 case MIG_CMD_RECV_BITMAP
:
2221 return loadvm_handle_recv_bitmap(mis
, len
);
2223 case MIG_CMD_ENABLE_COLO
:
2224 return loadvm_process_enable_colo(mis
);
2231 * Read a footer off the wire and check that it matches the expected section
2233 * Returns: true if the footer was good
2234 * false if there is a problem (and calls error_report to say why)
2236 static bool check_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
2240 uint32_t read_section_id
;
2242 if (!migrate_get_current()->send_section_footer
) {
2243 /* No footer to check */
2247 read_mark
= qemu_get_byte(f
);
2249 ret
= qemu_file_get_error(f
);
2251 error_report("%s: Read section footer failed: %d",
2256 if (read_mark
!= QEMU_VM_SECTION_FOOTER
) {
2257 error_report("Missing section footer for %s", se
->idstr
);
2261 read_section_id
= qemu_get_be32(f
);
2262 if (read_section_id
!= se
->load_section_id
) {
2263 error_report("Mismatched section id in footer for %s -"
2264 " read 0x%x expected 0x%x",
2265 se
->idstr
, read_section_id
, se
->load_section_id
);
2274 qemu_loadvm_section_start_full(QEMUFile
*f
, MigrationIncomingState
*mis
)
2276 uint32_t instance_id
, version_id
, section_id
;
2281 /* Read section start */
2282 section_id
= qemu_get_be32(f
);
2283 if (!qemu_get_counted_string(f
, idstr
)) {
2284 error_report("Unable to read ID string for section %u",
2288 instance_id
= qemu_get_be32(f
);
2289 version_id
= qemu_get_be32(f
);
2291 ret
= qemu_file_get_error(f
);
2293 error_report("%s: Failed to read instance/version ID: %d",
2298 trace_qemu_loadvm_state_section_startfull(section_id
, idstr
,
2299 instance_id
, version_id
);
2300 /* Find savevm section */
2301 se
= find_se(idstr
, instance_id
);
2303 error_report("Unknown savevm section or instance '%s' %"PRIu32
". "
2304 "Make sure that your current VM setup matches your "
2305 "saved VM setup, including any hotplugged devices",
2306 idstr
, instance_id
);
2310 /* Validate version */
2311 if (version_id
> se
->version_id
) {
2312 error_report("savevm: unsupported version %d for '%s' v%d",
2313 version_id
, idstr
, se
->version_id
);
2316 se
->load_version_id
= version_id
;
2317 se
->load_section_id
= section_id
;
2319 /* Validate if it is a device's state */
2320 if (xen_enabled() && se
->is_ram
) {
2321 error_report("loadvm: %s RAM loading not allowed on Xen", idstr
);
2325 ret
= vmstate_load(f
, se
);
2327 error_report("error while loading state for instance 0x%"PRIx32
" of"
2328 " device '%s'", instance_id
, idstr
);
2331 if (!check_section_footer(f
, se
)) {
2339 qemu_loadvm_section_part_end(QEMUFile
*f
, MigrationIncomingState
*mis
)
2341 uint32_t section_id
;
2345 section_id
= qemu_get_be32(f
);
2347 ret
= qemu_file_get_error(f
);
2349 error_report("%s: Failed to read section ID: %d",
2354 trace_qemu_loadvm_state_section_partend(section_id
);
2355 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2356 if (se
->load_section_id
== section_id
) {
2361 error_report("Unknown savevm section %d", section_id
);
2365 ret
= vmstate_load(f
, se
);
2367 error_report("error while loading state section id %d(%s)",
2368 section_id
, se
->idstr
);
2371 if (!check_section_footer(f
, se
)) {
2378 static int qemu_loadvm_state_header(QEMUFile
*f
)
2383 v
= qemu_get_be32(f
);
2384 if (v
!= QEMU_VM_FILE_MAGIC
) {
2385 error_report("Not a migration stream");
2389 v
= qemu_get_be32(f
);
2390 if (v
== QEMU_VM_FILE_VERSION_COMPAT
) {
2391 error_report("SaveVM v2 format is obsolete and don't work anymore");
2394 if (v
!= QEMU_VM_FILE_VERSION
) {
2395 error_report("Unsupported migration stream version");
2399 if (migrate_get_current()->send_configuration
) {
2400 if (qemu_get_byte(f
) != QEMU_VM_CONFIGURATION
) {
2401 error_report("Configuration section missing");
2402 qemu_loadvm_state_cleanup();
2405 ret
= vmstate_load_state(f
, &vmstate_configuration
, &savevm_state
, 0);
2408 qemu_loadvm_state_cleanup();
2415 static int qemu_loadvm_state_setup(QEMUFile
*f
)
2420 trace_loadvm_state_setup();
2421 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2422 if (!se
->ops
|| !se
->ops
->load_setup
) {
2425 if (se
->ops
->is_active
) {
2426 if (!se
->ops
->is_active(se
->opaque
)) {
2431 ret
= se
->ops
->load_setup(f
, se
->opaque
);
2433 qemu_file_set_error(f
, ret
);
2434 error_report("Load state of device %s failed", se
->idstr
);
2441 void qemu_loadvm_state_cleanup(void)
2445 trace_loadvm_state_cleanup();
2446 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2447 if (se
->ops
&& se
->ops
->load_cleanup
) {
2448 se
->ops
->load_cleanup(se
->opaque
);
2453 /* Return true if we should continue the migration, or false. */
2454 static bool postcopy_pause_incoming(MigrationIncomingState
*mis
)
2456 trace_postcopy_pause_incoming();
2458 assert(migrate_postcopy_ram());
2460 /* Clear the triggered bit to allow one recovery */
2461 mis
->postcopy_recover_triggered
= false;
2463 assert(mis
->from_src_file
);
2464 qemu_file_shutdown(mis
->from_src_file
);
2465 qemu_fclose(mis
->from_src_file
);
2466 mis
->from_src_file
= NULL
;
2468 assert(mis
->to_src_file
);
2469 qemu_file_shutdown(mis
->to_src_file
);
2470 qemu_mutex_lock(&mis
->rp_mutex
);
2471 qemu_fclose(mis
->to_src_file
);
2472 mis
->to_src_file
= NULL
;
2473 qemu_mutex_unlock(&mis
->rp_mutex
);
2475 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2476 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2478 /* Notify the fault thread for the invalidated file handle */
2479 postcopy_fault_thread_notify(mis
);
2481 error_report("Detected IO failure for postcopy. "
2482 "Migration paused.");
2484 while (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2485 qemu_sem_wait(&mis
->postcopy_pause_sem_dst
);
2488 trace_postcopy_pause_incoming_continued();
2493 int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
)
2495 uint8_t section_type
;
2500 section_type
= qemu_get_byte(f
);
2502 if (qemu_file_get_error(f
)) {
2503 ret
= qemu_file_get_error(f
);
2507 trace_qemu_loadvm_state_section(section_type
);
2508 switch (section_type
) {
2509 case QEMU_VM_SECTION_START
:
2510 case QEMU_VM_SECTION_FULL
:
2511 ret
= qemu_loadvm_section_start_full(f
, mis
);
2516 case QEMU_VM_SECTION_PART
:
2517 case QEMU_VM_SECTION_END
:
2518 ret
= qemu_loadvm_section_part_end(f
, mis
);
2523 case QEMU_VM_COMMAND
:
2524 ret
= loadvm_process_command(f
);
2525 trace_qemu_loadvm_state_section_command(ret
);
2526 if ((ret
< 0) || (ret
== LOADVM_QUIT
)) {
2531 /* This is the end of migration */
2534 error_report("Unknown savevm section type %d", section_type
);
2542 qemu_file_set_error(f
, ret
);
2544 /* Cancel bitmaps incoming regardless of recovery */
2545 dirty_bitmap_mig_cancel_incoming();
2548 * If we are during an active postcopy, then we pause instead
2549 * of bail out to at least keep the VM's dirty data. Note
2550 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2551 * during which we're still receiving device states and we
2552 * still haven't yet started the VM on destination.
2554 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2555 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2558 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
2559 migrate_postcopy_ram() && postcopy_pause_incoming(mis
)) {
2560 /* Reset f to point to the newly created channel */
2561 f
= mis
->from_src_file
;
2568 int qemu_loadvm_state(QEMUFile
*f
)
2570 MigrationIncomingState
*mis
= migration_incoming_get_current();
2571 Error
*local_err
= NULL
;
2574 if (qemu_savevm_state_blocked(&local_err
)) {
2575 error_report_err(local_err
);
2579 ret
= qemu_loadvm_state_header(f
);
2584 if (qemu_loadvm_state_setup(f
) != 0) {
2588 cpu_synchronize_all_pre_loadvm();
2590 ret
= qemu_loadvm_state_main(f
, mis
);
2591 qemu_event_set(&mis
->main_thread_load_event
);
2593 trace_qemu_loadvm_state_post_main(ret
);
2595 if (mis
->have_listen_thread
) {
2596 /* Listen thread still going, can't clean up yet */
2601 ret
= qemu_file_get_error(f
);
2605 * Try to read in the VMDESC section as well, so that dumping tools that
2606 * intercept our migration stream have the chance to see it.
2609 /* We've got to be careful; if we don't read the data and just shut the fd
2610 * then the sender can error if we close while it's still sending.
2611 * We also mustn't read data that isn't there; some transports (RDMA)
2612 * will stall waiting for that data when the source has already closed.
2614 if (ret
== 0 && should_send_vmdesc()) {
2617 uint8_t section_type
= qemu_get_byte(f
);
2619 if (section_type
!= QEMU_VM_VMDESCRIPTION
) {
2620 error_report("Expected vmdescription section, but got %d",
2623 * It doesn't seem worth failing at this point since
2624 * we apparently have an otherwise valid VM state
2627 buf
= g_malloc(0x1000);
2628 size
= qemu_get_be32(f
);
2631 uint32_t read_chunk
= MIN(size
, 0x1000);
2632 qemu_get_buffer(f
, buf
, read_chunk
);
2639 qemu_loadvm_state_cleanup();
2640 cpu_synchronize_all_post_init();
2645 int qemu_load_device_state(QEMUFile
*f
)
2647 MigrationIncomingState
*mis
= migration_incoming_get_current();
2650 /* Load QEMU_VM_SECTION_FULL section */
2651 ret
= qemu_loadvm_state_main(f
, mis
);
2653 error_report("Failed to load device state: %d", ret
);
2657 cpu_synchronize_all_post_init();
2661 int save_snapshot(const char *name
, Error
**errp
)
2663 BlockDriverState
*bs
, *bs1
;
2664 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
2667 int saved_vm_running
;
2668 uint64_t vm_state_size
;
2671 AioContext
*aio_context
;
2673 if (migration_is_blocked(errp
)) {
2677 if (!replay_can_snapshot()) {
2678 error_setg(errp
, "Record/replay does not allow making snapshot "
2679 "right now. Try once more later.");
2683 if (!bdrv_all_can_snapshot(&bs
)) {
2684 error_setg(errp
, "Device '%s' is writable but does not support "
2685 "snapshots", bdrv_get_device_name(bs
));
2689 /* Delete old snapshots of the same name */
2691 ret
= bdrv_all_delete_snapshot(name
, &bs1
, errp
);
2693 error_prepend(errp
, "Error while deleting snapshot on device "
2694 "'%s': ", bdrv_get_device_name(bs1
));
2699 bs
= bdrv_all_find_vmstate_bs();
2701 error_setg(errp
, "No block device can accept snapshots");
2704 aio_context
= bdrv_get_aio_context(bs
);
2706 saved_vm_running
= runstate_is_running();
2708 ret
= global_state_store();
2710 error_setg(errp
, "Error saving global state");
2713 vm_stop(RUN_STATE_SAVE_VM
);
2715 bdrv_drain_all_begin();
2717 aio_context_acquire(aio_context
);
2719 memset(sn
, 0, sizeof(*sn
));
2721 /* fill auxiliary fields */
2722 qemu_gettimeofday(&tv
);
2723 sn
->date_sec
= tv
.tv_sec
;
2724 sn
->date_nsec
= tv
.tv_usec
* 1000;
2725 sn
->vm_clock_nsec
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
2728 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
2730 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
2731 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
2733 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
2736 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2737 localtime_r((const time_t *)&tv
.tv_sec
, &tm
);
2738 strftime(sn
->name
, sizeof(sn
->name
), "vm-%Y%m%d%H%M%S", &tm
);
2741 /* save the VM state */
2742 f
= qemu_fopen_bdrv(bs
, 1);
2744 error_setg(errp
, "Could not open VM state file");
2747 ret
= qemu_savevm_state(f
, errp
);
2748 vm_state_size
= qemu_ftell(f
);
2749 ret2
= qemu_fclose(f
);
2758 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2759 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2760 * it only releases the lock once. Therefore synchronous I/O will deadlock
2761 * unless we release the AioContext before bdrv_all_create_snapshot().
2763 aio_context_release(aio_context
);
2766 ret
= bdrv_all_create_snapshot(sn
, bs
, vm_state_size
, &bs
);
2768 error_setg(errp
, "Error while creating snapshot on '%s'",
2769 bdrv_get_device_name(bs
));
2777 aio_context_release(aio_context
);
2780 bdrv_drain_all_end();
2782 if (saved_vm_running
) {
2788 void qmp_xen_save_devices_state(const char *filename
, bool has_live
, bool live
,
2792 QIOChannelFile
*ioc
;
2793 int saved_vm_running
;
2797 /* live default to true so old version of Xen tool stack can have a
2798 * successfull live migration */
2802 saved_vm_running
= runstate_is_running();
2803 vm_stop(RUN_STATE_SAVE_VM
);
2804 global_state_store_running();
2806 ioc
= qio_channel_file_new_path(filename
, O_WRONLY
| O_CREAT
, 0660, errp
);
2810 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-save-state");
2811 f
= qemu_fopen_channel_output(QIO_CHANNEL(ioc
));
2812 object_unref(OBJECT(ioc
));
2813 ret
= qemu_save_device_state(f
);
2814 if (ret
< 0 || qemu_fclose(f
) < 0) {
2815 error_setg(errp
, QERR_IO_ERROR
);
2817 /* libxl calls the QMP command "stop" before calling
2818 * "xen-save-devices-state" and in case of migration failure, libxl
2819 * would call "cont".
2820 * So call bdrv_inactivate_all (release locks) here to let the other
2821 * side of the migration take controle of the images.
2823 if (live
&& !saved_vm_running
) {
2824 ret
= bdrv_inactivate_all();
2826 error_setg(errp
, "%s: bdrv_inactivate_all() failed (%d)",
2833 if (saved_vm_running
) {
2838 void qmp_xen_load_devices_state(const char *filename
, Error
**errp
)
2841 QIOChannelFile
*ioc
;
2844 /* Guest must be paused before loading the device state; the RAM state
2845 * will already have been loaded by xc
2847 if (runstate_is_running()) {
2848 error_setg(errp
, "Cannot update device state while vm is running");
2851 vm_stop(RUN_STATE_RESTORE_VM
);
2853 ioc
= qio_channel_file_new_path(filename
, O_RDONLY
| O_BINARY
, 0, errp
);
2857 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-load-state");
2858 f
= qemu_fopen_channel_input(QIO_CHANNEL(ioc
));
2859 object_unref(OBJECT(ioc
));
2861 ret
= qemu_loadvm_state(f
);
2864 error_setg(errp
, QERR_IO_ERROR
);
2866 migration_incoming_state_destroy();
2869 int load_snapshot(const char *name
, Error
**errp
)
2871 BlockDriverState
*bs
, *bs_vm_state
;
2872 QEMUSnapshotInfo sn
;
2875 AioContext
*aio_context
;
2876 MigrationIncomingState
*mis
= migration_incoming_get_current();
2878 if (!replay_can_snapshot()) {
2879 error_setg(errp
, "Record/replay does not allow loading snapshot "
2880 "right now. Try once more later.");
2884 if (!bdrv_all_can_snapshot(&bs
)) {
2886 "Device '%s' is writable but does not support snapshots",
2887 bdrv_get_device_name(bs
));
2890 ret
= bdrv_all_find_snapshot(name
, &bs
);
2893 "Device '%s' does not have the requested snapshot '%s'",
2894 bdrv_get_device_name(bs
), name
);
2898 bs_vm_state
= bdrv_all_find_vmstate_bs();
2900 error_setg(errp
, "No block device supports snapshots");
2903 aio_context
= bdrv_get_aio_context(bs_vm_state
);
2905 /* Don't even try to load empty VM states */
2906 aio_context_acquire(aio_context
);
2907 ret
= bdrv_snapshot_find(bs_vm_state
, &sn
, name
);
2908 aio_context_release(aio_context
);
2911 } else if (sn
.vm_state_size
== 0) {
2912 error_setg(errp
, "This is a disk-only snapshot. Revert to it "
2913 " offline using qemu-img");
2917 /* Flush all IO requests so they don't interfere with the new state. */
2918 bdrv_drain_all_begin();
2920 ret
= bdrv_all_goto_snapshot(name
, &bs
, errp
);
2922 error_prepend(errp
, "Could not load snapshot '%s' on '%s': ",
2923 name
, bdrv_get_device_name(bs
));
2927 /* restore the VM state */
2928 f
= qemu_fopen_bdrv(bs_vm_state
, 0);
2930 error_setg(errp
, "Could not open VM state file");
2935 qemu_system_reset(SHUTDOWN_CAUSE_NONE
);
2936 mis
->from_src_file
= f
;
2938 aio_context_acquire(aio_context
);
2939 ret
= qemu_loadvm_state(f
);
2940 migration_incoming_state_destroy();
2941 aio_context_release(aio_context
);
2943 bdrv_drain_all_end();
2946 error_setg(errp
, "Error %d while loading VM state", ret
);
2953 bdrv_drain_all_end();
2957 void vmstate_register_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2959 qemu_ram_set_idstr(mr
->ram_block
,
2960 memory_region_name(mr
), dev
);
2961 qemu_ram_set_migratable(mr
->ram_block
);
2964 void vmstate_unregister_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2966 qemu_ram_unset_idstr(mr
->ram_block
);
2967 qemu_ram_unset_migratable(mr
->ram_block
);
2970 void vmstate_register_ram_global(MemoryRegion
*mr
)
2972 vmstate_register_ram(mr
, NULL
);
2975 bool vmstate_check_only_migratable(const VMStateDescription
*vmsd
)
2977 /* check needed if --only-migratable is specified */
2978 if (!only_migratable
) {
2982 return !(vmsd
&& vmsd
->unmigratable
);