4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
8 * Juan Quintela <quintela@redhat.com>
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 #include "qemu/osdep.h"
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
33 #include "migration.h"
34 #include "migration/snapshot.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
40 #include "qemu-file-channel.h"
41 #include "qemu-file.h"
43 #include "postcopy-ram.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/qapi-commands-misc.h"
47 #include "qapi/qmp/qerror.h"
48 #include "qemu/error-report.h"
49 #include "sysemu/cpus.h"
50 #include "exec/memory.h"
51 #include "exec/target_page.h"
54 #include "qemu/main-loop.h"
55 #include "block/snapshot.h"
56 #include "qemu/cutils.h"
57 #include "io/channel-buffer.h"
58 #include "io/channel-file.h"
59 #include "sysemu/replay.h"
60 #include "sysemu/runstate.h"
61 #include "sysemu/sysemu.h"
63 #include "migration/colo.h"
64 #include "qemu/bitmap.h"
65 #include "net/announce.h"
67 const unsigned int postcopy_ram_discard_version
= 0;
69 /* Subcommands for QEMU_VM_COMMAND */
71 MIG_CMD_INVALID
= 0, /* Must be 0 */
72 MIG_CMD_OPEN_RETURN_PATH
, /* Tell the dest to open the Return path */
73 MIG_CMD_PING
, /* Request a PONG on the RP */
75 MIG_CMD_POSTCOPY_ADVISE
, /* Prior to any page transfers, just
76 warn we might want to do PC */
77 MIG_CMD_POSTCOPY_LISTEN
, /* Start listening for incoming
78 pages as it's running. */
79 MIG_CMD_POSTCOPY_RUN
, /* Start execution */
81 MIG_CMD_POSTCOPY_RAM_DISCARD
, /* A list of pages to discard that
82 were previously sent during
83 precopy but are dirty. */
84 MIG_CMD_PACKAGED
, /* Send a wrapped stream within this stream */
85 MIG_CMD_ENABLE_COLO
, /* Enable COLO */
86 MIG_CMD_POSTCOPY_RESUME
, /* resume postcopy on dest */
87 MIG_CMD_RECV_BITMAP
, /* Request for recved bitmap on dst */
91 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
92 static struct mig_cmd_args
{
93 ssize_t len
; /* -1 = variable */
96 [MIG_CMD_INVALID
] = { .len
= -1, .name
= "INVALID" },
97 [MIG_CMD_OPEN_RETURN_PATH
] = { .len
= 0, .name
= "OPEN_RETURN_PATH" },
98 [MIG_CMD_PING
] = { .len
= sizeof(uint32_t), .name
= "PING" },
99 [MIG_CMD_POSTCOPY_ADVISE
] = { .len
= -1, .name
= "POSTCOPY_ADVISE" },
100 [MIG_CMD_POSTCOPY_LISTEN
] = { .len
= 0, .name
= "POSTCOPY_LISTEN" },
101 [MIG_CMD_POSTCOPY_RUN
] = { .len
= 0, .name
= "POSTCOPY_RUN" },
102 [MIG_CMD_POSTCOPY_RAM_DISCARD
] = {
103 .len
= -1, .name
= "POSTCOPY_RAM_DISCARD" },
104 [MIG_CMD_POSTCOPY_RESUME
] = { .len
= 0, .name
= "POSTCOPY_RESUME" },
105 [MIG_CMD_PACKAGED
] = { .len
= 4, .name
= "PACKAGED" },
106 [MIG_CMD_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
107 [MIG_CMD_MAX
] = { .len
= -1, .name
= "MAX" },
110 /* Note for MIG_CMD_POSTCOPY_ADVISE:
111 * The format of arguments is depending on postcopy mode:
112 * - postcopy RAM only
113 * uint64_t host page size
114 * uint64_t taget page size
116 * - postcopy RAM and postcopy dirty bitmaps
117 * format is the same as for postcopy RAM only
119 * - postcopy dirty bitmaps only
120 * Nothing. Command length field is 0.
122 * Be careful: adding a new postcopy entity with some other parameters should
123 * not break format self-description ability. Good way is to introduce some
124 * generic extendable format with an exception for two old entities.
127 /***********************************************************/
128 /* savevm/loadvm support */
130 static ssize_t
block_writev_buffer(void *opaque
, struct iovec
*iov
, int iovcnt
,
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
,
148 return bdrv_load_vmstate(opaque
, buf
, pos
, size
);
151 static int bdrv_fclose(void *opaque
)
153 return bdrv_flush(opaque
);
156 static const QEMUFileOps bdrv_read_ops
= {
157 .get_buffer
= block_get_buffer
,
161 static const QEMUFileOps bdrv_write_ops
= {
162 .writev_buffer
= block_writev_buffer
,
166 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int is_writable
)
169 return qemu_fopen_ops(bs
, &bdrv_write_ops
);
171 return qemu_fopen_ops(bs
, &bdrv_read_ops
);
175 /* QEMUFile timer support.
176 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
179 void timer_put(QEMUFile
*f
, QEMUTimer
*ts
)
181 uint64_t expire_time
;
183 expire_time
= timer_expire_time_ns(ts
);
184 qemu_put_be64(f
, expire_time
);
187 void timer_get(QEMUFile
*f
, QEMUTimer
*ts
)
189 uint64_t expire_time
;
191 expire_time
= qemu_get_be64(f
);
192 if (expire_time
!= -1) {
193 timer_mod_ns(ts
, expire_time
);
200 /* VMState timer support.
201 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
204 static int get_timer(QEMUFile
*f
, void *pv
, size_t size
,
205 const VMStateField
*field
)
212 static int put_timer(QEMUFile
*f
, void *pv
, size_t size
,
213 const VMStateField
*field
, QJSON
*vmdesc
)
221 const VMStateInfo vmstate_info_timer
= {
228 typedef struct CompatEntry
{
233 typedef struct SaveStateEntry
{
234 QTAILQ_ENTRY(SaveStateEntry
) entry
;
239 /* version id read from the stream */
242 /* section id read from the stream */
244 const SaveVMHandlers
*ops
;
245 const VMStateDescription
*vmsd
;
251 typedef struct SaveState
{
252 QTAILQ_HEAD(, SaveStateEntry
) handlers
;
253 int global_section_id
;
256 uint32_t target_page_bits
;
258 MigrationCapability
*capabilities
;
261 static SaveState savevm_state
= {
262 .handlers
= QTAILQ_HEAD_INITIALIZER(savevm_state
.handlers
),
263 .global_section_id
= 0,
266 static bool should_validate_capability(int capability
)
268 assert(capability
>= 0 && capability
< MIGRATION_CAPABILITY__MAX
);
269 /* Validate only new capabilities to keep compatibility. */
270 switch (capability
) {
271 case MIGRATION_CAPABILITY_X_IGNORE_SHARED
:
278 static uint32_t get_validatable_capabilities_count(void)
280 MigrationState
*s
= migrate_get_current();
283 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
284 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
291 static int configuration_pre_save(void *opaque
)
293 SaveState
*state
= opaque
;
294 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
295 MigrationState
*s
= migrate_get_current();
298 state
->len
= strlen(current_name
);
299 state
->name
= current_name
;
300 state
->target_page_bits
= qemu_target_page_bits();
302 state
->caps_count
= get_validatable_capabilities_count();
303 state
->capabilities
= g_renew(MigrationCapability
, state
->capabilities
,
305 for (i
= j
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
306 if (should_validate_capability(i
) && s
->enabled_capabilities
[i
]) {
307 state
->capabilities
[j
++] = i
;
314 static int configuration_pre_load(void *opaque
)
316 SaveState
*state
= opaque
;
318 /* If there is no target-page-bits subsection it means the source
319 * predates the variable-target-page-bits support and is using the
320 * minimum possible value for this CPU.
322 state
->target_page_bits
= qemu_target_page_bits_min();
326 static bool configuration_validate_capabilities(SaveState
*state
)
329 MigrationState
*s
= migrate_get_current();
330 unsigned long *source_caps_bm
;
333 source_caps_bm
= bitmap_new(MIGRATION_CAPABILITY__MAX
);
334 for (i
= 0; i
< state
->caps_count
; i
++) {
335 MigrationCapability capability
= state
->capabilities
[i
];
336 set_bit(capability
, source_caps_bm
);
339 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
340 bool source_state
, target_state
;
341 if (!should_validate_capability(i
)) {
344 source_state
= test_bit(i
, source_caps_bm
);
345 target_state
= s
->enabled_capabilities
[i
];
346 if (source_state
!= target_state
) {
347 error_report("Capability %s is %s, but received capability is %s",
348 MigrationCapability_str(i
),
349 target_state
? "on" : "off",
350 source_state
? "on" : "off");
352 /* Don't break here to report all failed capabilities */
356 g_free(source_caps_bm
);
360 static int configuration_post_load(void *opaque
, int version_id
)
362 SaveState
*state
= opaque
;
363 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
365 if (strncmp(state
->name
, current_name
, state
->len
) != 0) {
366 error_report("Machine type received is '%.*s' and local is '%s'",
367 (int) state
->len
, state
->name
, current_name
);
371 if (state
->target_page_bits
!= qemu_target_page_bits()) {
372 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
373 state
->target_page_bits
, qemu_target_page_bits());
377 if (!configuration_validate_capabilities(state
)) {
384 static int get_capability(QEMUFile
*f
, void *pv
, size_t size
,
385 const VMStateField
*field
)
387 MigrationCapability
*capability
= pv
;
388 char capability_str
[UINT8_MAX
+ 1];
392 len
= qemu_get_byte(f
);
393 qemu_get_buffer(f
, (uint8_t *)capability_str
, len
);
394 capability_str
[len
] = '\0';
395 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
396 if (!strcmp(MigrationCapability_str(i
), capability_str
)) {
401 error_report("Received unknown capability %s", capability_str
);
405 static int put_capability(QEMUFile
*f
, void *pv
, size_t size
,
406 const VMStateField
*field
, QJSON
*vmdesc
)
408 MigrationCapability
*capability
= pv
;
409 const char *capability_str
= MigrationCapability_str(*capability
);
410 size_t len
= strlen(capability_str
);
411 assert(len
<= UINT8_MAX
);
413 qemu_put_byte(f
, len
);
414 qemu_put_buffer(f
, (uint8_t *)capability_str
, len
);
418 static const VMStateInfo vmstate_info_capability
= {
419 .name
= "capability",
420 .get
= get_capability
,
421 .put
= put_capability
,
424 /* The target-page-bits subsection is present only if the
425 * target page size is not the same as the default (ie the
426 * minimum page size for a variable-page-size guest CPU).
427 * If it is present then it contains the actual target page
428 * bits for the machine, and migration will fail if the
429 * two ends don't agree about it.
431 static bool vmstate_target_page_bits_needed(void *opaque
)
433 return qemu_target_page_bits()
434 > qemu_target_page_bits_min();
437 static const VMStateDescription vmstate_target_page_bits
= {
438 .name
= "configuration/target-page-bits",
440 .minimum_version_id
= 1,
441 .needed
= vmstate_target_page_bits_needed
,
442 .fields
= (VMStateField
[]) {
443 VMSTATE_UINT32(target_page_bits
, SaveState
),
444 VMSTATE_END_OF_LIST()
448 static bool vmstate_capabilites_needed(void *opaque
)
450 return get_validatable_capabilities_count() > 0;
453 static const VMStateDescription vmstate_capabilites
= {
454 .name
= "configuration/capabilities",
456 .minimum_version_id
= 1,
457 .needed
= vmstate_capabilites_needed
,
458 .fields
= (VMStateField
[]) {
459 VMSTATE_UINT32_V(caps_count
, SaveState
, 1),
460 VMSTATE_VARRAY_UINT32_ALLOC(capabilities
, SaveState
, caps_count
, 1,
461 vmstate_info_capability
,
462 MigrationCapability
),
463 VMSTATE_END_OF_LIST()
467 static const VMStateDescription vmstate_configuration
= {
468 .name
= "configuration",
470 .pre_load
= configuration_pre_load
,
471 .post_load
= configuration_post_load
,
472 .pre_save
= configuration_pre_save
,
473 .fields
= (VMStateField
[]) {
474 VMSTATE_UINT32(len
, SaveState
),
475 VMSTATE_VBUFFER_ALLOC_UINT32(name
, SaveState
, 0, NULL
, len
),
476 VMSTATE_END_OF_LIST()
478 .subsections
= (const VMStateDescription
*[]) {
479 &vmstate_target_page_bits
,
480 &vmstate_capabilites
,
485 static void dump_vmstate_vmsd(FILE *out_file
,
486 const VMStateDescription
*vmsd
, int indent
,
489 static void dump_vmstate_vmsf(FILE *out_file
, const VMStateField
*field
,
492 fprintf(out_file
, "%*s{\n", indent
, "");
494 fprintf(out_file
, "%*s\"field\": \"%s\",\n", indent
, "", field
->name
);
495 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
497 fprintf(out_file
, "%*s\"field_exists\": %s,\n", indent
, "",
498 field
->field_exists
? "true" : "false");
499 fprintf(out_file
, "%*s\"size\": %zu", indent
, "", field
->size
);
500 if (field
->vmsd
!= NULL
) {
501 fprintf(out_file
, ",\n");
502 dump_vmstate_vmsd(out_file
, field
->vmsd
, indent
, false);
504 fprintf(out_file
, "\n%*s}", indent
- 2, "");
507 static void dump_vmstate_vmss(FILE *out_file
,
508 const VMStateDescription
**subsection
,
511 if (*subsection
!= NULL
) {
512 dump_vmstate_vmsd(out_file
, *subsection
, indent
, true);
516 static void dump_vmstate_vmsd(FILE *out_file
,
517 const VMStateDescription
*vmsd
, int indent
,
521 fprintf(out_file
, "%*s{\n", indent
, "");
523 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", "Description");
526 fprintf(out_file
, "%*s\"name\": \"%s\",\n", indent
, "", vmsd
->name
);
527 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
529 fprintf(out_file
, "%*s\"minimum_version_id\": %d", indent
, "",
530 vmsd
->minimum_version_id
);
531 if (vmsd
->fields
!= NULL
) {
532 const VMStateField
*field
= vmsd
->fields
;
535 fprintf(out_file
, ",\n%*s\"Fields\": [\n", indent
, "");
537 while (field
->name
!= NULL
) {
538 if (field
->flags
& VMS_MUST_EXIST
) {
539 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
544 fprintf(out_file
, ",\n");
546 dump_vmstate_vmsf(out_file
, field
, indent
+ 2);
550 fprintf(out_file
, "\n%*s]", indent
, "");
552 if (vmsd
->subsections
!= NULL
) {
553 const VMStateDescription
**subsection
= vmsd
->subsections
;
556 fprintf(out_file
, ",\n%*s\"Subsections\": [\n", indent
, "");
558 while (*subsection
!= NULL
) {
560 fprintf(out_file
, ",\n");
562 dump_vmstate_vmss(out_file
, subsection
, indent
+ 2);
566 fprintf(out_file
, "\n%*s]", indent
, "");
568 fprintf(out_file
, "\n%*s}", indent
- 2, "");
571 static void dump_machine_type(FILE *out_file
)
575 mc
= MACHINE_GET_CLASS(current_machine
);
577 fprintf(out_file
, " \"vmschkmachine\": {\n");
578 fprintf(out_file
, " \"Name\": \"%s\"\n", mc
->name
);
579 fprintf(out_file
, " },\n");
582 void dump_vmstate_json_to_file(FILE *out_file
)
587 fprintf(out_file
, "{\n");
588 dump_machine_type(out_file
);
591 list
= object_class_get_list(TYPE_DEVICE
, true);
592 for (elt
= list
; elt
; elt
= elt
->next
) {
593 DeviceClass
*dc
= OBJECT_CLASS_CHECK(DeviceClass
, elt
->data
,
603 fprintf(out_file
, ",\n");
605 name
= object_class_get_name(OBJECT_CLASS(dc
));
606 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", name
);
608 fprintf(out_file
, "%*s\"Name\": \"%s\",\n", indent
, "", name
);
609 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
610 dc
->vmsd
->version_id
);
611 fprintf(out_file
, "%*s\"minimum_version_id\": %d,\n", indent
, "",
612 dc
->vmsd
->minimum_version_id
);
614 dump_vmstate_vmsd(out_file
, dc
->vmsd
, indent
, false);
616 fprintf(out_file
, "\n%*s}", indent
- 2, "");
619 fprintf(out_file
, "\n}\n");
623 static int calculate_new_instance_id(const char *idstr
)
628 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
629 if (strcmp(idstr
, se
->idstr
) == 0
630 && instance_id
<= se
->instance_id
) {
631 instance_id
= se
->instance_id
+ 1;
637 static int calculate_compat_instance_id(const char *idstr
)
642 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
647 if (strcmp(idstr
, se
->compat
->idstr
) == 0
648 && instance_id
<= se
->compat
->instance_id
) {
649 instance_id
= se
->compat
->instance_id
+ 1;
655 static inline MigrationPriority
save_state_priority(SaveStateEntry
*se
)
658 return se
->vmsd
->priority
;
660 return MIG_PRI_DEFAULT
;
663 static void savevm_state_handler_insert(SaveStateEntry
*nse
)
665 MigrationPriority priority
= save_state_priority(nse
);
668 assert(priority
<= MIG_PRI_MAX
);
670 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
671 if (save_state_priority(se
) < priority
) {
677 QTAILQ_INSERT_BEFORE(se
, nse
, entry
);
679 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, nse
, entry
);
683 /* TODO: Individual devices generally have very little idea about the rest
684 of the system, so instance_id should be removed/replaced.
685 Meanwhile pass -1 as instance_id if you do not already have a clearly
686 distinguishing id for all instances of your device class. */
687 int register_savevm_live(DeviceState
*dev
,
691 const SaveVMHandlers
*ops
,
696 se
= g_new0(SaveStateEntry
, 1);
697 se
->version_id
= version_id
;
698 se
->section_id
= savevm_state
.global_section_id
++;
702 /* if this is a live_savem then set is_ram */
703 if (ops
->save_setup
!= NULL
) {
708 char *id
= qdev_get_dev_path(dev
);
710 if (snprintf(se
->idstr
, sizeof(se
->idstr
), "%s/", id
) >=
712 error_report("Path too long for VMState (%s)", id
);
720 se
->compat
= g_new0(CompatEntry
, 1);
721 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), idstr
);
722 se
->compat
->instance_id
= instance_id
== -1 ?
723 calculate_compat_instance_id(idstr
) : instance_id
;
727 pstrcat(se
->idstr
, sizeof(se
->idstr
), idstr
);
729 if (instance_id
== -1) {
730 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
732 se
->instance_id
= instance_id
;
734 assert(!se
->compat
|| se
->instance_id
== 0);
735 savevm_state_handler_insert(se
);
739 void unregister_savevm(DeviceState
*dev
, const char *idstr
, void *opaque
)
741 SaveStateEntry
*se
, *new_se
;
745 char *path
= qdev_get_dev_path(dev
);
747 pstrcpy(id
, sizeof(id
), path
);
748 pstrcat(id
, sizeof(id
), "/");
752 pstrcat(id
, sizeof(id
), idstr
);
754 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
755 if (strcmp(se
->idstr
, id
) == 0 && se
->opaque
== opaque
) {
756 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
763 int vmstate_register_with_alias_id(DeviceState
*dev
, int instance_id
,
764 const VMStateDescription
*vmsd
,
765 void *opaque
, int alias_id
,
766 int required_for_version
,
771 /* If this triggers, alias support can be dropped for the vmsd. */
772 assert(alias_id
== -1 || required_for_version
>= vmsd
->minimum_version_id
);
774 se
= g_new0(SaveStateEntry
, 1);
775 se
->version_id
= vmsd
->version_id
;
776 se
->section_id
= savevm_state
.global_section_id
++;
779 se
->alias_id
= alias_id
;
782 char *id
= qdev_get_dev_path(dev
);
784 if (snprintf(se
->idstr
, sizeof(se
->idstr
), "%s/", id
) >=
786 error_setg(errp
, "Path too long for VMState (%s)", id
);
794 se
->compat
= g_new0(CompatEntry
, 1);
795 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), vmsd
->name
);
796 se
->compat
->instance_id
= instance_id
== -1 ?
797 calculate_compat_instance_id(vmsd
->name
) : instance_id
;
801 pstrcat(se
->idstr
, sizeof(se
->idstr
), vmsd
->name
);
803 if (instance_id
== -1) {
804 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
806 se
->instance_id
= instance_id
;
808 assert(!se
->compat
|| se
->instance_id
== 0);
809 savevm_state_handler_insert(se
);
813 void vmstate_unregister(DeviceState
*dev
, const VMStateDescription
*vmsd
,
816 SaveStateEntry
*se
, *new_se
;
818 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
819 if (se
->vmsd
== vmsd
&& se
->opaque
== opaque
) {
820 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
827 static int vmstate_load(QEMUFile
*f
, SaveStateEntry
*se
)
829 trace_vmstate_load(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
830 if (!se
->vmsd
) { /* Old style */
831 return se
->ops
->load_state(f
, se
->opaque
, se
->load_version_id
);
833 return vmstate_load_state(f
, se
->vmsd
, se
->opaque
, se
->load_version_id
);
836 static void vmstate_save_old_style(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
838 int64_t old_offset
, size
;
840 old_offset
= qemu_ftell_fast(f
);
841 se
->ops
->save_state(f
, se
->opaque
);
842 size
= qemu_ftell_fast(f
) - old_offset
;
845 json_prop_int(vmdesc
, "size", size
);
846 json_start_array(vmdesc
, "fields");
847 json_start_object(vmdesc
, NULL
);
848 json_prop_str(vmdesc
, "name", "data");
849 json_prop_int(vmdesc
, "size", size
);
850 json_prop_str(vmdesc
, "type", "buffer");
851 json_end_object(vmdesc
);
852 json_end_array(vmdesc
);
856 static int vmstate_save(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
858 trace_vmstate_save(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
860 vmstate_save_old_style(f
, se
, vmdesc
);
863 return vmstate_save_state(f
, se
->vmsd
, se
->opaque
, vmdesc
);
867 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
869 static void save_section_header(QEMUFile
*f
, SaveStateEntry
*se
,
870 uint8_t section_type
)
872 qemu_put_byte(f
, section_type
);
873 qemu_put_be32(f
, se
->section_id
);
875 if (section_type
== QEMU_VM_SECTION_FULL
||
876 section_type
== QEMU_VM_SECTION_START
) {
878 size_t len
= strlen(se
->idstr
);
879 qemu_put_byte(f
, len
);
880 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
882 qemu_put_be32(f
, se
->instance_id
);
883 qemu_put_be32(f
, se
->version_id
);
888 * Write a footer onto device sections that catches cases misformatted device
891 static void save_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
893 if (migrate_get_current()->send_section_footer
) {
894 qemu_put_byte(f
, QEMU_VM_SECTION_FOOTER
);
895 qemu_put_be32(f
, se
->section_id
);
900 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
901 * command and associated data.
903 * @f: File to send command on
904 * @command: Command type to send
905 * @len: Length of associated data
906 * @data: Data associated with command.
908 static void qemu_savevm_command_send(QEMUFile
*f
,
909 enum qemu_vm_cmd command
,
913 trace_savevm_command_send(command
, len
);
914 qemu_put_byte(f
, QEMU_VM_COMMAND
);
915 qemu_put_be16(f
, (uint16_t)command
);
916 qemu_put_be16(f
, len
);
917 qemu_put_buffer(f
, data
, len
);
921 void qemu_savevm_send_colo_enable(QEMUFile
*f
)
923 trace_savevm_send_colo_enable();
924 qemu_savevm_command_send(f
, MIG_CMD_ENABLE_COLO
, 0, NULL
);
927 void qemu_savevm_send_ping(QEMUFile
*f
, uint32_t value
)
931 trace_savevm_send_ping(value
);
932 buf
= cpu_to_be32(value
);
933 qemu_savevm_command_send(f
, MIG_CMD_PING
, sizeof(value
), (uint8_t *)&buf
);
936 void qemu_savevm_send_open_return_path(QEMUFile
*f
)
938 trace_savevm_send_open_return_path();
939 qemu_savevm_command_send(f
, MIG_CMD_OPEN_RETURN_PATH
, 0, NULL
);
942 /* We have a buffer of data to send; we don't want that all to be loaded
943 * by the command itself, so the command contains just the length of the
944 * extra buffer that we then send straight after it.
945 * TODO: Must be a better way to organise that
951 int qemu_savevm_send_packaged(QEMUFile
*f
, const uint8_t *buf
, size_t len
)
955 if (len
> MAX_VM_CMD_PACKAGED_SIZE
) {
956 error_report("%s: Unreasonably large packaged state: %zu",
961 tmp
= cpu_to_be32(len
);
963 trace_qemu_savevm_send_packaged();
964 qemu_savevm_command_send(f
, MIG_CMD_PACKAGED
, 4, (uint8_t *)&tmp
);
966 qemu_put_buffer(f
, buf
, len
);
971 /* Send prior to any postcopy transfer */
972 void qemu_savevm_send_postcopy_advise(QEMUFile
*f
)
974 if (migrate_postcopy_ram()) {
976 tmp
[0] = cpu_to_be64(ram_pagesize_summary());
977 tmp
[1] = cpu_to_be64(qemu_target_page_size());
979 trace_qemu_savevm_send_postcopy_advise();
980 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
,
983 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
, 0, NULL
);
987 /* Sent prior to starting the destination running in postcopy, discard pages
988 * that have already been sent but redirtied on the source.
989 * CMD_POSTCOPY_RAM_DISCARD consist of:
991 * byte Length of name field (not including 0)
992 * n x byte RAM block name
993 * byte 0 terminator (just for safety)
994 * n x Byte ranges within the named RAMBlock
995 * be64 Start of the range
998 * name: RAMBlock name that these entries are part of
999 * len: Number of page entries
1000 * start_list: 'len' addresses
1001 * length_list: 'len' addresses
1004 void qemu_savevm_send_postcopy_ram_discard(QEMUFile
*f
, const char *name
,
1006 uint64_t *start_list
,
1007 uint64_t *length_list
)
1012 size_t name_len
= strlen(name
);
1014 trace_qemu_savevm_send_postcopy_ram_discard(name
, len
);
1015 assert(name_len
< 256);
1016 buf
= g_malloc0(1 + 1 + name_len
+ 1 + (8 + 8) * len
);
1017 buf
[0] = postcopy_ram_discard_version
;
1019 memcpy(buf
+ 2, name
, name_len
);
1020 tmplen
= 2 + name_len
;
1021 buf
[tmplen
++] = '\0';
1023 for (t
= 0; t
< len
; t
++) {
1024 stq_be_p(buf
+ tmplen
, start_list
[t
]);
1026 stq_be_p(buf
+ tmplen
, length_list
[t
]);
1029 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RAM_DISCARD
, tmplen
, buf
);
1033 /* Get the destination into a state where it can receive postcopy data. */
1034 void qemu_savevm_send_postcopy_listen(QEMUFile
*f
)
1036 trace_savevm_send_postcopy_listen();
1037 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_LISTEN
, 0, NULL
);
1040 /* Kick the destination into running */
1041 void qemu_savevm_send_postcopy_run(QEMUFile
*f
)
1043 trace_savevm_send_postcopy_run();
1044 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RUN
, 0, NULL
);
1047 void qemu_savevm_send_postcopy_resume(QEMUFile
*f
)
1049 trace_savevm_send_postcopy_resume();
1050 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RESUME
, 0, NULL
);
1053 void qemu_savevm_send_recv_bitmap(QEMUFile
*f
, char *block_name
)
1058 trace_savevm_send_recv_bitmap(block_name
);
1060 buf
[0] = len
= strlen(block_name
);
1061 memcpy(buf
+ 1, block_name
, len
);
1063 qemu_savevm_command_send(f
, MIG_CMD_RECV_BITMAP
, len
+ 1, (uint8_t *)buf
);
1066 bool qemu_savevm_state_blocked(Error
**errp
)
1070 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1071 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
1072 error_setg(errp
, "State blocked by non-migratable device '%s'",
1080 void qemu_savevm_state_header(QEMUFile
*f
)
1082 trace_savevm_state_header();
1083 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1084 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1086 if (migrate_get_current()->send_configuration
) {
1087 qemu_put_byte(f
, QEMU_VM_CONFIGURATION
);
1088 vmstate_save_state(f
, &vmstate_configuration
, &savevm_state
, 0);
1092 void qemu_savevm_state_setup(QEMUFile
*f
)
1095 Error
*local_err
= NULL
;
1098 trace_savevm_state_setup();
1099 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1100 if (!se
->ops
|| !se
->ops
->save_setup
) {
1103 if (se
->ops
&& se
->ops
->is_active
) {
1104 if (!se
->ops
->is_active(se
->opaque
)) {
1108 save_section_header(f
, se
, QEMU_VM_SECTION_START
);
1110 ret
= se
->ops
->save_setup(f
, se
->opaque
);
1111 save_section_footer(f
, se
);
1113 qemu_file_set_error(f
, ret
);
1118 if (precopy_notify(PRECOPY_NOTIFY_SETUP
, &local_err
)) {
1119 error_report_err(local_err
);
1123 int qemu_savevm_state_resume_prepare(MigrationState
*s
)
1128 trace_savevm_state_resume_prepare();
1130 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1131 if (!se
->ops
|| !se
->ops
->resume_prepare
) {
1134 if (se
->ops
&& se
->ops
->is_active
) {
1135 if (!se
->ops
->is_active(se
->opaque
)) {
1139 ret
= se
->ops
->resume_prepare(s
, se
->opaque
);
1149 * this function has three return values:
1150 * negative: there was one error, and we have -errno.
1151 * 0 : We haven't finished, caller have to go again
1152 * 1 : We have finished, we can go to complete phase
1154 int qemu_savevm_state_iterate(QEMUFile
*f
, bool postcopy
)
1159 trace_savevm_state_iterate();
1160 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1161 if (!se
->ops
|| !se
->ops
->save_live_iterate
) {
1164 if (se
->ops
->is_active
&&
1165 !se
->ops
->is_active(se
->opaque
)) {
1168 if (se
->ops
->is_active_iterate
&&
1169 !se
->ops
->is_active_iterate(se
->opaque
)) {
1173 * In the postcopy phase, any device that doesn't know how to
1174 * do postcopy should have saved it's state in the _complete
1175 * call that's already run, it might get confused if we call
1176 * iterate afterwards.
1179 !(se
->ops
->has_postcopy
&& se
->ops
->has_postcopy(se
->opaque
))) {
1182 if (qemu_file_rate_limit(f
)) {
1185 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1187 save_section_header(f
, se
, QEMU_VM_SECTION_PART
);
1189 ret
= se
->ops
->save_live_iterate(f
, se
->opaque
);
1190 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1191 save_section_footer(f
, se
);
1194 qemu_file_set_error(f
, ret
);
1197 /* Do not proceed to the next vmstate before this one reported
1198 completion of the current stage. This serializes the migration
1199 and reduces the probability that a faster changing state is
1200 synchronized over and over again. */
1207 static bool should_send_vmdesc(void)
1209 MachineState
*machine
= MACHINE(qdev_get_machine());
1210 bool in_postcopy
= migration_in_postcopy();
1211 return !machine
->suppress_vmdesc
&& !in_postcopy
;
1215 * Calls the save_live_complete_postcopy methods
1216 * causing the last few pages to be sent immediately and doing any associated
1218 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1219 * all the other devices, but that happens at the point we switch to postcopy.
1221 void qemu_savevm_state_complete_postcopy(QEMUFile
*f
)
1226 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1227 if (!se
->ops
|| !se
->ops
->save_live_complete_postcopy
) {
1230 if (se
->ops
&& se
->ops
->is_active
) {
1231 if (!se
->ops
->is_active(se
->opaque
)) {
1235 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1237 qemu_put_byte(f
, QEMU_VM_SECTION_END
);
1238 qemu_put_be32(f
, se
->section_id
);
1240 ret
= se
->ops
->save_live_complete_postcopy(f
, se
->opaque
);
1241 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1242 save_section_footer(f
, se
);
1244 qemu_file_set_error(f
, ret
);
1249 qemu_put_byte(f
, QEMU_VM_EOF
);
1253 int qemu_savevm_state_complete_precopy(QEMUFile
*f
, bool iterable_only
,
1254 bool inactivate_disks
)
1260 bool in_postcopy
= migration_in_postcopy();
1261 Error
*local_err
= NULL
;
1263 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE
, &local_err
)) {
1264 error_report_err(local_err
);
1267 trace_savevm_state_complete_precopy();
1269 cpu_synchronize_all_states();
1271 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1273 (in_postcopy
&& se
->ops
->has_postcopy
&&
1274 se
->ops
->has_postcopy(se
->opaque
)) ||
1275 (in_postcopy
&& !iterable_only
) ||
1276 !se
->ops
->save_live_complete_precopy
) {
1280 if (se
->ops
&& se
->ops
->is_active
) {
1281 if (!se
->ops
->is_active(se
->opaque
)) {
1285 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1287 save_section_header(f
, se
, QEMU_VM_SECTION_END
);
1289 ret
= se
->ops
->save_live_complete_precopy(f
, se
->opaque
);
1290 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1291 save_section_footer(f
, se
);
1293 qemu_file_set_error(f
, ret
);
1298 if (iterable_only
) {
1302 vmdesc
= qjson_new();
1303 json_prop_int(vmdesc
, "page_size", qemu_target_page_size());
1304 json_start_array(vmdesc
, "devices");
1305 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1307 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1310 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1311 trace_savevm_section_skip(se
->idstr
, se
->section_id
);
1315 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1317 json_start_object(vmdesc
, NULL
);
1318 json_prop_str(vmdesc
, "name", se
->idstr
);
1319 json_prop_int(vmdesc
, "instance_id", se
->instance_id
);
1321 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1322 ret
= vmstate_save(f
, se
, vmdesc
);
1324 qemu_file_set_error(f
, ret
);
1327 trace_savevm_section_end(se
->idstr
, se
->section_id
, 0);
1328 save_section_footer(f
, se
);
1330 json_end_object(vmdesc
);
1333 if (inactivate_disks
) {
1334 /* Inactivate before sending QEMU_VM_EOF so that the
1335 * bdrv_invalidate_cache_all() on the other end won't fail. */
1336 ret
= bdrv_inactivate_all();
1338 error_report("%s: bdrv_inactivate_all() failed (%d)",
1340 qemu_file_set_error(f
, ret
);
1345 /* Postcopy stream will still be going */
1346 qemu_put_byte(f
, QEMU_VM_EOF
);
1349 json_end_array(vmdesc
);
1350 qjson_finish(vmdesc
);
1351 vmdesc_len
= strlen(qjson_get_str(vmdesc
));
1353 if (should_send_vmdesc()) {
1354 qemu_put_byte(f
, QEMU_VM_VMDESCRIPTION
);
1355 qemu_put_be32(f
, vmdesc_len
);
1356 qemu_put_buffer(f
, (uint8_t *)qjson_get_str(vmdesc
), vmdesc_len
);
1358 qjson_destroy(vmdesc
);
1364 /* Give an estimate of the amount left to be transferred,
1365 * the result is split into the amount for units that can and
1366 * for units that can't do postcopy.
1368 void qemu_savevm_state_pending(QEMUFile
*f
, uint64_t threshold_size
,
1369 uint64_t *res_precopy_only
,
1370 uint64_t *res_compatible
,
1371 uint64_t *res_postcopy_only
)
1375 *res_precopy_only
= 0;
1376 *res_compatible
= 0;
1377 *res_postcopy_only
= 0;
1380 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1381 if (!se
->ops
|| !se
->ops
->save_live_pending
) {
1384 if (se
->ops
&& se
->ops
->is_active
) {
1385 if (!se
->ops
->is_active(se
->opaque
)) {
1389 se
->ops
->save_live_pending(f
, se
->opaque
, threshold_size
,
1390 res_precopy_only
, res_compatible
,
1395 void qemu_savevm_state_cleanup(void)
1398 Error
*local_err
= NULL
;
1400 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP
, &local_err
)) {
1401 error_report_err(local_err
);
1404 trace_savevm_state_cleanup();
1405 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1406 if (se
->ops
&& se
->ops
->save_cleanup
) {
1407 se
->ops
->save_cleanup(se
->opaque
);
1412 static int qemu_savevm_state(QEMUFile
*f
, Error
**errp
)
1415 MigrationState
*ms
= migrate_get_current();
1416 MigrationStatus status
;
1418 if (migration_is_setup_or_active(ms
->state
) ||
1419 ms
->state
== MIGRATION_STATUS_CANCELLING
||
1420 ms
->state
== MIGRATION_STATUS_COLO
) {
1421 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1425 if (migrate_use_block()) {
1426 error_setg(errp
, "Block migration and snapshots are incompatible");
1431 ms
->to_dst_file
= f
;
1433 qemu_mutex_unlock_iothread();
1434 qemu_savevm_state_header(f
);
1435 qemu_savevm_state_setup(f
);
1436 qemu_mutex_lock_iothread();
1438 while (qemu_file_get_error(f
) == 0) {
1439 if (qemu_savevm_state_iterate(f
, false) > 0) {
1444 ret
= qemu_file_get_error(f
);
1446 qemu_savevm_state_complete_precopy(f
, false, false);
1447 ret
= qemu_file_get_error(f
);
1449 qemu_savevm_state_cleanup();
1451 error_setg_errno(errp
, -ret
, "Error while writing VM state");
1455 status
= MIGRATION_STATUS_FAILED
;
1457 status
= MIGRATION_STATUS_COMPLETED
;
1459 migrate_set_state(&ms
->state
, MIGRATION_STATUS_SETUP
, status
);
1461 /* f is outer parameter, it should not stay in global migration state after
1462 * this function finished */
1463 ms
->to_dst_file
= NULL
;
1468 void qemu_savevm_live_state(QEMUFile
*f
)
1470 /* save QEMU_VM_SECTION_END section */
1471 qemu_savevm_state_complete_precopy(f
, true, false);
1472 qemu_put_byte(f
, QEMU_VM_EOF
);
1475 int qemu_save_device_state(QEMUFile
*f
)
1479 if (!migration_in_colo_state()) {
1480 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1481 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1483 cpu_synchronize_all_states();
1485 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1491 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1494 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1498 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1500 ret
= vmstate_save(f
, se
, NULL
);
1505 save_section_footer(f
, se
);
1508 qemu_put_byte(f
, QEMU_VM_EOF
);
1510 return qemu_file_get_error(f
);
1513 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
1517 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1518 if (!strcmp(se
->idstr
, idstr
) &&
1519 (instance_id
== se
->instance_id
||
1520 instance_id
== se
->alias_id
))
1522 /* Migrating from an older version? */
1523 if (strstr(se
->idstr
, idstr
) && se
->compat
) {
1524 if (!strcmp(se
->compat
->idstr
, idstr
) &&
1525 (instance_id
== se
->compat
->instance_id
||
1526 instance_id
== se
->alias_id
))
1533 enum LoadVMExitCodes
{
1534 /* Allow a command to quit all layers of nested loadvm loops */
1538 /* ------ incoming postcopy messages ------ */
1539 /* 'advise' arrives before any transfers just to tell us that a postcopy
1540 * *might* happen - it might be skipped if precopy transferred everything
1543 static int loadvm_postcopy_handle_advise(MigrationIncomingState
*mis
,
1546 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1547 uint64_t remote_pagesize_summary
, local_pagesize_summary
, remote_tps
;
1548 Error
*local_err
= NULL
;
1550 trace_loadvm_postcopy_handle_advise();
1551 if (ps
!= POSTCOPY_INCOMING_NONE
) {
1552 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps
);
1558 if (migrate_postcopy_ram()) {
1559 error_report("RAM postcopy is enabled but have 0 byte advise");
1564 if (!migrate_postcopy_ram()) {
1565 error_report("RAM postcopy is disabled but have 16 byte advise");
1570 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len
);
1574 if (!postcopy_ram_supported_by_host(mis
)) {
1575 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
1579 remote_pagesize_summary
= qemu_get_be64(mis
->from_src_file
);
1580 local_pagesize_summary
= ram_pagesize_summary();
1582 if (remote_pagesize_summary
!= local_pagesize_summary
) {
1584 * This detects two potential causes of mismatch:
1585 * a) A mismatch in host page sizes
1586 * Some combinations of mismatch are probably possible but it gets
1587 * a bit more complicated. In particular we need to place whole
1588 * host pages on the dest at once, and we need to ensure that we
1589 * handle dirtying to make sure we never end up sending part of
1590 * a hostpage on it's own.
1591 * b) The use of different huge page sizes on source/destination
1592 * a more fine grain test is performed during RAM block migration
1593 * but this test here causes a nice early clear failure, and
1594 * also fails when passed to an older qemu that doesn't
1597 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1599 remote_pagesize_summary
, local_pagesize_summary
);
1603 remote_tps
= qemu_get_be64(mis
->from_src_file
);
1604 if (remote_tps
!= qemu_target_page_size()) {
1606 * Again, some differences could be dealt with, but for now keep it
1609 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1610 (int)remote_tps
, qemu_target_page_size());
1614 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE
, &local_err
)) {
1615 error_report_err(local_err
);
1619 if (ram_postcopy_incoming_init(mis
)) {
1623 postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1628 /* After postcopy we will be told to throw some pages away since they're
1629 * dirty and will have to be demand fetched. Must happen before CPU is
1631 * There can be 0..many of these messages, each encoding multiple pages.
1633 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState
*mis
,
1638 PostcopyState ps
= postcopy_state_get();
1640 trace_loadvm_postcopy_ram_handle_discard();
1643 case POSTCOPY_INCOMING_ADVISE
:
1645 tmp
= postcopy_ram_prepare_discard(mis
);
1651 case POSTCOPY_INCOMING_DISCARD
:
1652 /* Expected state */
1656 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1660 /* We're expecting a
1662 * a RAM ID string (length byte, name, 0 term)
1663 * then at least 1 16 byte chunk
1665 if (len
< (1 + 1 + 1 + 1 + 2 * 8)) {
1666 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1670 tmp
= qemu_get_byte(mis
->from_src_file
);
1671 if (tmp
!= postcopy_ram_discard_version
) {
1672 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp
);
1676 if (!qemu_get_counted_string(mis
->from_src_file
, ramid
)) {
1677 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1680 tmp
= qemu_get_byte(mis
->from_src_file
);
1682 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp
);
1686 len
-= 3 + strlen(ramid
);
1688 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1691 trace_loadvm_postcopy_ram_handle_discard_header(ramid
, len
);
1693 uint64_t start_addr
, block_length
;
1694 start_addr
= qemu_get_be64(mis
->from_src_file
);
1695 block_length
= qemu_get_be64(mis
->from_src_file
);
1698 int ret
= ram_discard_range(ramid
, start_addr
, block_length
);
1703 trace_loadvm_postcopy_ram_handle_discard_end();
1709 * Triggered by a postcopy_listen command; this thread takes over reading
1710 * the input stream, leaving the main thread free to carry on loading the rest
1711 * of the device state (from RAM).
1712 * (TODO:This could do with being in a postcopy file - but there again it's
1713 * just another input loop, not that postcopy specific)
1715 static void *postcopy_ram_listen_thread(void *opaque
)
1717 MigrationIncomingState
*mis
= migration_incoming_get_current();
1718 QEMUFile
*f
= mis
->from_src_file
;
1721 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
1722 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1723 qemu_sem_post(&mis
->listen_thread_sem
);
1724 trace_postcopy_ram_listen_thread_start();
1726 rcu_register_thread();
1728 * Because we're a thread and not a coroutine we can't yield
1729 * in qemu_file, and thus we must be blocking now.
1731 qemu_file_set_blocking(f
, true);
1732 load_res
= qemu_loadvm_state_main(f
, mis
);
1735 * This is tricky, but, mis->from_src_file can change after it
1736 * returns, when postcopy recovery happened. In the future, we may
1737 * want a wrapper for the QEMUFile handle.
1739 f
= mis
->from_src_file
;
1741 /* And non-blocking again so we don't block in any cleanup */
1742 qemu_file_set_blocking(f
, false);
1744 trace_postcopy_ram_listen_thread_exit();
1746 error_report("%s: loadvm failed: %d", __func__
, load_res
);
1747 qemu_file_set_error(f
, load_res
);
1748 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1749 MIGRATION_STATUS_FAILED
);
1752 * This looks good, but it's possible that the device loading in the
1753 * main thread hasn't finished yet, and so we might not be in 'RUN'
1754 * state yet; wait for the end of the main thread.
1756 qemu_event_wait(&mis
->main_thread_load_event
);
1758 postcopy_ram_incoming_cleanup(mis
);
1762 * If something went wrong then we have a bad state so exit;
1763 * depending how far we got it might be possible at this point
1764 * to leave the guest running and fire MCEs for pages that never
1765 * arrived as a desperate recovery step.
1767 rcu_unregister_thread();
1771 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1772 MIGRATION_STATUS_COMPLETED
);
1774 * If everything has worked fine, then the main thread has waited
1775 * for us to start, and we're the last use of the mis.
1776 * (If something broke then qemu will have to exit anyway since it's
1777 * got a bad migration state).
1779 migration_incoming_state_destroy();
1780 qemu_loadvm_state_cleanup();
1782 rcu_unregister_thread();
1783 mis
->have_listen_thread
= false;
1787 /* After this message we must be able to immediately receive postcopy data */
1788 static int loadvm_postcopy_handle_listen(MigrationIncomingState
*mis
)
1790 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_LISTENING
);
1791 trace_loadvm_postcopy_handle_listen();
1792 Error
*local_err
= NULL
;
1794 if (ps
!= POSTCOPY_INCOMING_ADVISE
&& ps
!= POSTCOPY_INCOMING_DISCARD
) {
1795 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps
);
1798 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
1800 * A rare case, we entered listen without having to do any discards,
1801 * so do the setup that's normally done at the time of the 1st discard.
1803 if (migrate_postcopy_ram()) {
1804 postcopy_ram_prepare_discard(mis
);
1809 * Sensitise RAM - can now generate requests for blocks that don't exist
1810 * However, at this point the CPU shouldn't be running, and the IO
1811 * shouldn't be doing anything yet so don't actually expect requests
1813 if (migrate_postcopy_ram()) {
1814 if (postcopy_ram_enable_notify(mis
)) {
1815 postcopy_ram_incoming_cleanup(mis
);
1820 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN
, &local_err
)) {
1821 error_report_err(local_err
);
1825 if (mis
->have_listen_thread
) {
1826 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1830 mis
->have_listen_thread
= true;
1831 /* Start up the listening thread and wait for it to signal ready */
1832 qemu_sem_init(&mis
->listen_thread_sem
, 0);
1833 qemu_thread_create(&mis
->listen_thread
, "postcopy/listen",
1834 postcopy_ram_listen_thread
, NULL
,
1835 QEMU_THREAD_DETACHED
);
1836 qemu_sem_wait(&mis
->listen_thread_sem
);
1837 qemu_sem_destroy(&mis
->listen_thread_sem
);
1847 static void loadvm_postcopy_handle_run_bh(void *opaque
)
1849 Error
*local_err
= NULL
;
1850 HandleRunBhData
*data
= opaque
;
1851 MigrationIncomingState
*mis
= migration_incoming_get_current();
1853 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1856 cpu_synchronize_all_post_init();
1858 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
1860 /* Make sure all file formats flush their mutable metadata.
1861 * If we get an error here, just don't restart the VM yet. */
1862 bdrv_invalidate_cache_all(&local_err
);
1864 error_report_err(local_err
);
1869 trace_loadvm_postcopy_handle_run_cpu_sync();
1871 trace_loadvm_postcopy_handle_run_vmstart();
1873 dirty_bitmap_mig_before_vm_start();
1876 /* Hold onto your hats, starting the CPU */
1879 /* leave it paused and let management decide when to start the CPU */
1880 runstate_set(RUN_STATE_PAUSED
);
1883 qemu_bh_delete(data
->bh
);
1887 /* After all discards we can start running and asking for pages */
1888 static int loadvm_postcopy_handle_run(MigrationIncomingState
*mis
)
1890 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_RUNNING
);
1891 HandleRunBhData
*data
;
1893 trace_loadvm_postcopy_handle_run();
1894 if (ps
!= POSTCOPY_INCOMING_LISTENING
) {
1895 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps
);
1899 data
= g_new(HandleRunBhData
, 1);
1900 data
->bh
= qemu_bh_new(loadvm_postcopy_handle_run_bh
, data
);
1901 qemu_bh_schedule(data
->bh
);
1903 /* We need to finish reading the stream from the package
1904 * and also stop reading anything more from the stream that loaded the
1905 * package (since it's now being read by the listener thread).
1906 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1911 static int loadvm_postcopy_handle_resume(MigrationIncomingState
*mis
)
1913 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
1914 error_report("%s: illegal resume received", __func__
);
1915 /* Don't fail the load, only for this. */
1920 * This means source VM is ready to resume the postcopy migration.
1921 * It's time to switch state and release the fault thread to
1922 * continue service page faults.
1924 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
1925 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1926 qemu_sem_post(&mis
->postcopy_pause_sem_fault
);
1928 trace_loadvm_postcopy_handle_resume();
1930 /* Tell source that "we are ready" */
1931 migrate_send_rp_resume_ack(mis
, MIGRATION_RESUME_ACK_VALUE
);
1937 * Immediately following this command is a blob of data containing an embedded
1938 * chunk of migration stream; read it and load it.
1940 * @mis: Incoming state
1941 * @length: Length of packaged data to read
1943 * Returns: Negative values on error
1946 static int loadvm_handle_cmd_packaged(MigrationIncomingState
*mis
)
1950 QIOChannelBuffer
*bioc
;
1952 length
= qemu_get_be32(mis
->from_src_file
);
1953 trace_loadvm_handle_cmd_packaged(length
);
1955 if (length
> MAX_VM_CMD_PACKAGED_SIZE
) {
1956 error_report("Unreasonably large packaged state: %zu", length
);
1960 bioc
= qio_channel_buffer_new(length
);
1961 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-loadvm-buffer");
1962 ret
= qemu_get_buffer(mis
->from_src_file
,
1965 if (ret
!= length
) {
1966 object_unref(OBJECT(bioc
));
1967 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1969 return (ret
< 0) ? ret
: -EAGAIN
;
1971 bioc
->usage
+= length
;
1972 trace_loadvm_handle_cmd_packaged_received(ret
);
1974 QEMUFile
*packf
= qemu_fopen_channel_input(QIO_CHANNEL(bioc
));
1976 ret
= qemu_loadvm_state_main(packf
, mis
);
1977 trace_loadvm_handle_cmd_packaged_main(ret
);
1979 object_unref(OBJECT(bioc
));
1985 * Handle request that source requests for recved_bitmap on
1986 * destination. Payload format:
1988 * len (1 byte) + ramblock_name (<255 bytes)
1990 static int loadvm_handle_recv_bitmap(MigrationIncomingState
*mis
,
1993 QEMUFile
*file
= mis
->from_src_file
;
1995 char block_name
[256];
1998 cnt
= qemu_get_counted_string(file
, block_name
);
2000 error_report("%s: failed to read block name", __func__
);
2004 /* Validate before using the data */
2005 if (qemu_file_get_error(file
)) {
2006 return qemu_file_get_error(file
);
2009 if (len
!= cnt
+ 1) {
2010 error_report("%s: invalid payload length (%d)", __func__
, len
);
2014 rb
= qemu_ram_block_by_name(block_name
);
2016 error_report("%s: block '%s' not found", __func__
, block_name
);
2020 migrate_send_rp_recv_bitmap(mis
, block_name
);
2022 trace_loadvm_handle_recv_bitmap(block_name
);
2027 static int loadvm_process_enable_colo(MigrationIncomingState
*mis
)
2029 migration_incoming_enable_colo();
2030 return colo_init_ram_cache();
2034 * Process an incoming 'QEMU_VM_COMMAND'
2035 * 0 just a normal return
2036 * LOADVM_QUIT All good, but exit the loop
2039 static int loadvm_process_command(QEMUFile
*f
)
2041 MigrationIncomingState
*mis
= migration_incoming_get_current();
2046 cmd
= qemu_get_be16(f
);
2047 len
= qemu_get_be16(f
);
2049 /* Check validity before continue processing of cmds */
2050 if (qemu_file_get_error(f
)) {
2051 return qemu_file_get_error(f
);
2054 trace_loadvm_process_command(cmd
, len
);
2055 if (cmd
>= MIG_CMD_MAX
|| cmd
== MIG_CMD_INVALID
) {
2056 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd
, len
);
2060 if (mig_cmd_args
[cmd
].len
!= -1 && mig_cmd_args
[cmd
].len
!= len
) {
2061 error_report("%s received with bad length - expecting %zu, got %d",
2062 mig_cmd_args
[cmd
].name
,
2063 (size_t)mig_cmd_args
[cmd
].len
, len
);
2068 case MIG_CMD_OPEN_RETURN_PATH
:
2069 if (mis
->to_src_file
) {
2070 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2071 /* Not really a problem, so don't give up */
2074 mis
->to_src_file
= qemu_file_get_return_path(f
);
2075 if (!mis
->to_src_file
) {
2076 error_report("CMD_OPEN_RETURN_PATH failed");
2082 tmp32
= qemu_get_be32(f
);
2083 trace_loadvm_process_command_ping(tmp32
);
2084 if (!mis
->to_src_file
) {
2085 error_report("CMD_PING (0x%x) received with no return path",
2089 migrate_send_rp_pong(mis
, tmp32
);
2092 case MIG_CMD_PACKAGED
:
2093 return loadvm_handle_cmd_packaged(mis
);
2095 case MIG_CMD_POSTCOPY_ADVISE
:
2096 return loadvm_postcopy_handle_advise(mis
, len
);
2098 case MIG_CMD_POSTCOPY_LISTEN
:
2099 return loadvm_postcopy_handle_listen(mis
);
2101 case MIG_CMD_POSTCOPY_RUN
:
2102 return loadvm_postcopy_handle_run(mis
);
2104 case MIG_CMD_POSTCOPY_RAM_DISCARD
:
2105 return loadvm_postcopy_ram_handle_discard(mis
, len
);
2107 case MIG_CMD_POSTCOPY_RESUME
:
2108 return loadvm_postcopy_handle_resume(mis
);
2110 case MIG_CMD_RECV_BITMAP
:
2111 return loadvm_handle_recv_bitmap(mis
, len
);
2113 case MIG_CMD_ENABLE_COLO
:
2114 return loadvm_process_enable_colo(mis
);
2121 * Read a footer off the wire and check that it matches the expected section
2123 * Returns: true if the footer was good
2124 * false if there is a problem (and calls error_report to say why)
2126 static bool check_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
2130 uint32_t read_section_id
;
2132 if (!migrate_get_current()->send_section_footer
) {
2133 /* No footer to check */
2137 read_mark
= qemu_get_byte(f
);
2139 ret
= qemu_file_get_error(f
);
2141 error_report("%s: Read section footer failed: %d",
2146 if (read_mark
!= QEMU_VM_SECTION_FOOTER
) {
2147 error_report("Missing section footer for %s", se
->idstr
);
2151 read_section_id
= qemu_get_be32(f
);
2152 if (read_section_id
!= se
->load_section_id
) {
2153 error_report("Mismatched section id in footer for %s -"
2154 " read 0x%x expected 0x%x",
2155 se
->idstr
, read_section_id
, se
->load_section_id
);
2164 qemu_loadvm_section_start_full(QEMUFile
*f
, MigrationIncomingState
*mis
)
2166 uint32_t instance_id
, version_id
, section_id
;
2171 /* Read section start */
2172 section_id
= qemu_get_be32(f
);
2173 if (!qemu_get_counted_string(f
, idstr
)) {
2174 error_report("Unable to read ID string for section %u",
2178 instance_id
= qemu_get_be32(f
);
2179 version_id
= qemu_get_be32(f
);
2181 ret
= qemu_file_get_error(f
);
2183 error_report("%s: Failed to read instance/version ID: %d",
2188 trace_qemu_loadvm_state_section_startfull(section_id
, idstr
,
2189 instance_id
, version_id
);
2190 /* Find savevm section */
2191 se
= find_se(idstr
, instance_id
);
2193 error_report("Unknown savevm section or instance '%s' %d. "
2194 "Make sure that your current VM setup matches your "
2195 "saved VM setup, including any hotplugged devices",
2196 idstr
, instance_id
);
2200 /* Validate version */
2201 if (version_id
> se
->version_id
) {
2202 error_report("savevm: unsupported version %d for '%s' v%d",
2203 version_id
, idstr
, se
->version_id
);
2206 se
->load_version_id
= version_id
;
2207 se
->load_section_id
= section_id
;
2209 /* Validate if it is a device's state */
2210 if (xen_enabled() && se
->is_ram
) {
2211 error_report("loadvm: %s RAM loading not allowed on Xen", idstr
);
2215 ret
= vmstate_load(f
, se
);
2217 error_report("error while loading state for instance 0x%x of"
2218 " device '%s'", instance_id
, idstr
);
2221 if (!check_section_footer(f
, se
)) {
2229 qemu_loadvm_section_part_end(QEMUFile
*f
, MigrationIncomingState
*mis
)
2231 uint32_t section_id
;
2235 section_id
= qemu_get_be32(f
);
2237 ret
= qemu_file_get_error(f
);
2239 error_report("%s: Failed to read section ID: %d",
2244 trace_qemu_loadvm_state_section_partend(section_id
);
2245 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2246 if (se
->load_section_id
== section_id
) {
2251 error_report("Unknown savevm section %d", section_id
);
2255 ret
= vmstate_load(f
, se
);
2257 error_report("error while loading state section id %d(%s)",
2258 section_id
, se
->idstr
);
2261 if (!check_section_footer(f
, se
)) {
2268 static int qemu_loadvm_state_header(QEMUFile
*f
)
2273 v
= qemu_get_be32(f
);
2274 if (v
!= QEMU_VM_FILE_MAGIC
) {
2275 error_report("Not a migration stream");
2279 v
= qemu_get_be32(f
);
2280 if (v
== QEMU_VM_FILE_VERSION_COMPAT
) {
2281 error_report("SaveVM v2 format is obsolete and don't work anymore");
2284 if (v
!= QEMU_VM_FILE_VERSION
) {
2285 error_report("Unsupported migration stream version");
2289 if (migrate_get_current()->send_configuration
) {
2290 if (qemu_get_byte(f
) != QEMU_VM_CONFIGURATION
) {
2291 error_report("Configuration section missing");
2292 qemu_loadvm_state_cleanup();
2295 ret
= vmstate_load_state(f
, &vmstate_configuration
, &savevm_state
, 0);
2298 qemu_loadvm_state_cleanup();
2305 static int qemu_loadvm_state_setup(QEMUFile
*f
)
2310 trace_loadvm_state_setup();
2311 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2312 if (!se
->ops
|| !se
->ops
->load_setup
) {
2315 if (se
->ops
&& se
->ops
->is_active
) {
2316 if (!se
->ops
->is_active(se
->opaque
)) {
2321 ret
= se
->ops
->load_setup(f
, se
->opaque
);
2323 qemu_file_set_error(f
, ret
);
2324 error_report("Load state of device %s failed", se
->idstr
);
2331 void qemu_loadvm_state_cleanup(void)
2335 trace_loadvm_state_cleanup();
2336 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
2337 if (se
->ops
&& se
->ops
->load_cleanup
) {
2338 se
->ops
->load_cleanup(se
->opaque
);
2343 /* Return true if we should continue the migration, or false. */
2344 static bool postcopy_pause_incoming(MigrationIncomingState
*mis
)
2346 trace_postcopy_pause_incoming();
2348 /* Clear the triggered bit to allow one recovery */
2349 mis
->postcopy_recover_triggered
= false;
2351 assert(mis
->from_src_file
);
2352 qemu_file_shutdown(mis
->from_src_file
);
2353 qemu_fclose(mis
->from_src_file
);
2354 mis
->from_src_file
= NULL
;
2356 assert(mis
->to_src_file
);
2357 qemu_file_shutdown(mis
->to_src_file
);
2358 qemu_mutex_lock(&mis
->rp_mutex
);
2359 qemu_fclose(mis
->to_src_file
);
2360 mis
->to_src_file
= NULL
;
2361 qemu_mutex_unlock(&mis
->rp_mutex
);
2363 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2364 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2366 /* Notify the fault thread for the invalidated file handle */
2367 postcopy_fault_thread_notify(mis
);
2369 error_report("Detected IO failure for postcopy. "
2370 "Migration paused.");
2372 while (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2373 qemu_sem_wait(&mis
->postcopy_pause_sem_dst
);
2376 trace_postcopy_pause_incoming_continued();
2381 int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
)
2383 uint8_t section_type
;
2388 section_type
= qemu_get_byte(f
);
2390 if (qemu_file_get_error(f
)) {
2391 ret
= qemu_file_get_error(f
);
2395 trace_qemu_loadvm_state_section(section_type
);
2396 switch (section_type
) {
2397 case QEMU_VM_SECTION_START
:
2398 case QEMU_VM_SECTION_FULL
:
2399 ret
= qemu_loadvm_section_start_full(f
, mis
);
2404 case QEMU_VM_SECTION_PART
:
2405 case QEMU_VM_SECTION_END
:
2406 ret
= qemu_loadvm_section_part_end(f
, mis
);
2411 case QEMU_VM_COMMAND
:
2412 ret
= loadvm_process_command(f
);
2413 trace_qemu_loadvm_state_section_command(ret
);
2414 if ((ret
< 0) || (ret
& LOADVM_QUIT
)) {
2419 /* This is the end of migration */
2422 error_report("Unknown savevm section type %d", section_type
);
2430 qemu_file_set_error(f
, ret
);
2433 * If we are during an active postcopy, then we pause instead
2434 * of bail out to at least keep the VM's dirty data. Note
2435 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2436 * during which we're still receiving device states and we
2437 * still haven't yet started the VM on destination.
2439 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING
&&
2440 postcopy_pause_incoming(mis
)) {
2441 /* Reset f to point to the newly created channel */
2442 f
= mis
->from_src_file
;
2449 int qemu_loadvm_state(QEMUFile
*f
)
2451 MigrationIncomingState
*mis
= migration_incoming_get_current();
2452 Error
*local_err
= NULL
;
2455 if (qemu_savevm_state_blocked(&local_err
)) {
2456 error_report_err(local_err
);
2460 ret
= qemu_loadvm_state_header(f
);
2465 if (qemu_loadvm_state_setup(f
) != 0) {
2469 cpu_synchronize_all_pre_loadvm();
2471 ret
= qemu_loadvm_state_main(f
, mis
);
2472 qemu_event_set(&mis
->main_thread_load_event
);
2474 trace_qemu_loadvm_state_post_main(ret
);
2476 if (mis
->have_listen_thread
) {
2477 /* Listen thread still going, can't clean up yet */
2482 ret
= qemu_file_get_error(f
);
2486 * Try to read in the VMDESC section as well, so that dumping tools that
2487 * intercept our migration stream have the chance to see it.
2490 /* We've got to be careful; if we don't read the data and just shut the fd
2491 * then the sender can error if we close while it's still sending.
2492 * We also mustn't read data that isn't there; some transports (RDMA)
2493 * will stall waiting for that data when the source has already closed.
2495 if (ret
== 0 && should_send_vmdesc()) {
2498 uint8_t section_type
= qemu_get_byte(f
);
2500 if (section_type
!= QEMU_VM_VMDESCRIPTION
) {
2501 error_report("Expected vmdescription section, but got %d",
2504 * It doesn't seem worth failing at this point since
2505 * we apparently have an otherwise valid VM state
2508 buf
= g_malloc(0x1000);
2509 size
= qemu_get_be32(f
);
2512 uint32_t read_chunk
= MIN(size
, 0x1000);
2513 qemu_get_buffer(f
, buf
, read_chunk
);
2520 qemu_loadvm_state_cleanup();
2521 cpu_synchronize_all_post_init();
2526 int qemu_load_device_state(QEMUFile
*f
)
2528 MigrationIncomingState
*mis
= migration_incoming_get_current();
2531 /* Load QEMU_VM_SECTION_FULL section */
2532 ret
= qemu_loadvm_state_main(f
, mis
);
2534 error_report("Failed to load device state: %d", ret
);
2538 cpu_synchronize_all_post_init();
2542 int save_snapshot(const char *name
, Error
**errp
)
2544 BlockDriverState
*bs
, *bs1
;
2545 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
2548 int saved_vm_running
;
2549 uint64_t vm_state_size
;
2552 AioContext
*aio_context
;
2554 if (migration_is_blocked(errp
)) {
2558 if (!replay_can_snapshot()) {
2559 error_setg(errp
, "Record/replay does not allow making snapshot "
2560 "right now. Try once more later.");
2564 if (!bdrv_all_can_snapshot(&bs
)) {
2565 error_setg(errp
, "Device '%s' is writable but does not support "
2566 "snapshots", bdrv_get_device_name(bs
));
2570 /* Delete old snapshots of the same name */
2572 ret
= bdrv_all_delete_snapshot(name
, &bs1
, errp
);
2574 error_prepend(errp
, "Error while deleting snapshot on device "
2575 "'%s': ", bdrv_get_device_name(bs1
));
2580 bs
= bdrv_all_find_vmstate_bs();
2582 error_setg(errp
, "No block device can accept snapshots");
2585 aio_context
= bdrv_get_aio_context(bs
);
2587 saved_vm_running
= runstate_is_running();
2589 ret
= global_state_store();
2591 error_setg(errp
, "Error saving global state");
2594 vm_stop(RUN_STATE_SAVE_VM
);
2596 bdrv_drain_all_begin();
2598 aio_context_acquire(aio_context
);
2600 memset(sn
, 0, sizeof(*sn
));
2602 /* fill auxiliary fields */
2603 qemu_gettimeofday(&tv
);
2604 sn
->date_sec
= tv
.tv_sec
;
2605 sn
->date_nsec
= tv
.tv_usec
* 1000;
2606 sn
->vm_clock_nsec
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
2609 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
2611 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
2612 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
2614 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
2617 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2618 localtime_r((const time_t *)&tv
.tv_sec
, &tm
);
2619 strftime(sn
->name
, sizeof(sn
->name
), "vm-%Y%m%d%H%M%S", &tm
);
2622 /* save the VM state */
2623 f
= qemu_fopen_bdrv(bs
, 1);
2625 error_setg(errp
, "Could not open VM state file");
2628 ret
= qemu_savevm_state(f
, errp
);
2629 vm_state_size
= qemu_ftell(f
);
2635 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2636 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2637 * it only releases the lock once. Therefore synchronous I/O will deadlock
2638 * unless we release the AioContext before bdrv_all_create_snapshot().
2640 aio_context_release(aio_context
);
2643 ret
= bdrv_all_create_snapshot(sn
, bs
, vm_state_size
, &bs
);
2645 error_setg(errp
, "Error while creating snapshot on '%s'",
2646 bdrv_get_device_name(bs
));
2654 aio_context_release(aio_context
);
2657 bdrv_drain_all_end();
2659 if (saved_vm_running
) {
2665 void qmp_xen_save_devices_state(const char *filename
, bool has_live
, bool live
,
2669 QIOChannelFile
*ioc
;
2670 int saved_vm_running
;
2674 /* live default to true so old version of Xen tool stack can have a
2675 * successfull live migration */
2679 saved_vm_running
= runstate_is_running();
2680 vm_stop(RUN_STATE_SAVE_VM
);
2681 global_state_store_running();
2683 ioc
= qio_channel_file_new_path(filename
, O_WRONLY
| O_CREAT
, 0660, errp
);
2687 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-save-state");
2688 f
= qemu_fopen_channel_output(QIO_CHANNEL(ioc
));
2689 object_unref(OBJECT(ioc
));
2690 ret
= qemu_save_device_state(f
);
2691 if (ret
< 0 || qemu_fclose(f
) < 0) {
2692 error_setg(errp
, QERR_IO_ERROR
);
2694 /* libxl calls the QMP command "stop" before calling
2695 * "xen-save-devices-state" and in case of migration failure, libxl
2696 * would call "cont".
2697 * So call bdrv_inactivate_all (release locks) here to let the other
2698 * side of the migration take controle of the images.
2700 if (live
&& !saved_vm_running
) {
2701 ret
= bdrv_inactivate_all();
2703 error_setg(errp
, "%s: bdrv_inactivate_all() failed (%d)",
2710 if (saved_vm_running
) {
2715 void qmp_xen_load_devices_state(const char *filename
, Error
**errp
)
2718 QIOChannelFile
*ioc
;
2721 /* Guest must be paused before loading the device state; the RAM state
2722 * will already have been loaded by xc
2724 if (runstate_is_running()) {
2725 error_setg(errp
, "Cannot update device state while vm is running");
2728 vm_stop(RUN_STATE_RESTORE_VM
);
2730 ioc
= qio_channel_file_new_path(filename
, O_RDONLY
| O_BINARY
, 0, errp
);
2734 qio_channel_set_name(QIO_CHANNEL(ioc
), "migration-xen-load-state");
2735 f
= qemu_fopen_channel_input(QIO_CHANNEL(ioc
));
2736 object_unref(OBJECT(ioc
));
2738 ret
= qemu_loadvm_state(f
);
2741 error_setg(errp
, QERR_IO_ERROR
);
2743 migration_incoming_state_destroy();
2746 int load_snapshot(const char *name
, Error
**errp
)
2748 BlockDriverState
*bs
, *bs_vm_state
;
2749 QEMUSnapshotInfo sn
;
2752 AioContext
*aio_context
;
2753 MigrationIncomingState
*mis
= migration_incoming_get_current();
2755 if (!replay_can_snapshot()) {
2756 error_setg(errp
, "Record/replay does not allow loading snapshot "
2757 "right now. Try once more later.");
2761 if (!bdrv_all_can_snapshot(&bs
)) {
2763 "Device '%s' is writable but does not support snapshots",
2764 bdrv_get_device_name(bs
));
2767 ret
= bdrv_all_find_snapshot(name
, &bs
);
2770 "Device '%s' does not have the requested snapshot '%s'",
2771 bdrv_get_device_name(bs
), name
);
2775 bs_vm_state
= bdrv_all_find_vmstate_bs();
2777 error_setg(errp
, "No block device supports snapshots");
2780 aio_context
= bdrv_get_aio_context(bs_vm_state
);
2782 /* Don't even try to load empty VM states */
2783 aio_context_acquire(aio_context
);
2784 ret
= bdrv_snapshot_find(bs_vm_state
, &sn
, name
);
2785 aio_context_release(aio_context
);
2788 } else if (sn
.vm_state_size
== 0) {
2789 error_setg(errp
, "This is a disk-only snapshot. Revert to it "
2790 " offline using qemu-img");
2794 /* Flush all IO requests so they don't interfere with the new state. */
2795 bdrv_drain_all_begin();
2797 ret
= bdrv_all_goto_snapshot(name
, &bs
, errp
);
2799 error_prepend(errp
, "Could not load snapshot '%s' on '%s': ",
2800 name
, bdrv_get_device_name(bs
));
2804 /* restore the VM state */
2805 f
= qemu_fopen_bdrv(bs_vm_state
, 0);
2807 error_setg(errp
, "Could not open VM state file");
2812 qemu_system_reset(SHUTDOWN_CAUSE_NONE
);
2813 mis
->from_src_file
= f
;
2815 aio_context_acquire(aio_context
);
2816 ret
= qemu_loadvm_state(f
);
2817 migration_incoming_state_destroy();
2818 aio_context_release(aio_context
);
2820 bdrv_drain_all_end();
2823 error_setg(errp
, "Error %d while loading VM state", ret
);
2830 bdrv_drain_all_end();
2834 void vmstate_register_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2836 qemu_ram_set_idstr(mr
->ram_block
,
2837 memory_region_name(mr
), dev
);
2838 qemu_ram_set_migratable(mr
->ram_block
);
2841 void vmstate_unregister_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2843 qemu_ram_unset_idstr(mr
->ram_block
);
2844 qemu_ram_unset_migratable(mr
->ram_block
);
2847 void vmstate_register_ram_global(MemoryRegion
*mr
)
2849 vmstate_register_ram(mr
, NULL
);
2852 bool vmstate_check_only_migratable(const VMStateDescription
*vmsd
)
2854 /* check needed if --only-migratable is specified */
2855 if (!only_migratable
) {
2859 return !(vmsd
&& vmsd
->unmigratable
);