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 "config-host.h"
30 #include "qemu-common.h"
31 #include "hw/boards.h"
35 #include "monitor/monitor.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/timer.h"
38 #include "audio/audio.h"
39 #include "migration/migration.h"
40 #include "qapi/qmp/qerror.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "qemu/queue.h"
44 #include "sysemu/cpus.h"
45 #include "exec/memory.h"
46 #include "qmp-commands.h"
48 #include "qemu/bitops.h"
50 #include "block/snapshot.h"
51 #include "block/qapi.h"
55 #define ETH_P_RARP 0x8035
57 #define ARP_HTYPE_ETH 0x0001
58 #define ARP_PTYPE_IP 0x0800
59 #define ARP_OP_REQUEST_REV 0x3
61 const unsigned int postcopy_ram_discard_version
= 0;
63 static bool skip_section_footers
;
65 static struct mig_cmd_args
{
66 ssize_t len
; /* -1 = variable */
69 [MIG_CMD_INVALID
] = { .len
= -1, .name
= "INVALID" },
70 [MIG_CMD_OPEN_RETURN_PATH
] = { .len
= 0, .name
= "OPEN_RETURN_PATH" },
71 [MIG_CMD_PING
] = { .len
= sizeof(uint32_t), .name
= "PING" },
72 [MIG_CMD_POSTCOPY_ADVISE
] = { .len
= 16, .name
= "POSTCOPY_ADVISE" },
73 [MIG_CMD_POSTCOPY_LISTEN
] = { .len
= 0, .name
= "POSTCOPY_LISTEN" },
74 [MIG_CMD_POSTCOPY_RUN
] = { .len
= 0, .name
= "POSTCOPY_RUN" },
75 [MIG_CMD_POSTCOPY_RAM_DISCARD
] = {
76 .len
= -1, .name
= "POSTCOPY_RAM_DISCARD" },
77 [MIG_CMD_PACKAGED
] = { .len
= 4, .name
= "PACKAGED" },
78 [MIG_CMD_MAX
] = { .len
= -1, .name
= "MAX" },
81 static int announce_self_create(uint8_t *buf
,
84 /* Ethernet header. */
85 memset(buf
, 0xff, 6); /* destination MAC addr */
86 memcpy(buf
+ 6, mac_addr
, 6); /* source MAC addr */
87 *(uint16_t *)(buf
+ 12) = htons(ETH_P_RARP
); /* ethertype */
90 *(uint16_t *)(buf
+ 14) = htons(ARP_HTYPE_ETH
); /* hardware addr space */
91 *(uint16_t *)(buf
+ 16) = htons(ARP_PTYPE_IP
); /* protocol addr space */
92 *(buf
+ 18) = 6; /* hardware addr length (ethernet) */
93 *(buf
+ 19) = 4; /* protocol addr length (IPv4) */
94 *(uint16_t *)(buf
+ 20) = htons(ARP_OP_REQUEST_REV
); /* opcode */
95 memcpy(buf
+ 22, mac_addr
, 6); /* source hw addr */
96 memset(buf
+ 28, 0x00, 4); /* source protocol addr */
97 memcpy(buf
+ 32, mac_addr
, 6); /* target hw addr */
98 memset(buf
+ 38, 0x00, 4); /* target protocol addr */
100 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
101 memset(buf
+ 42, 0x00, 18);
103 return 60; /* len (FCS will be added by hardware) */
106 static void qemu_announce_self_iter(NICState
*nic
, void *opaque
)
111 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic
->conf
->macaddr
));
112 len
= announce_self_create(buf
, nic
->conf
->macaddr
.a
);
114 qemu_send_packet_raw(qemu_get_queue(nic
), buf
, len
);
118 static void qemu_announce_self_once(void *opaque
)
120 static int count
= SELF_ANNOUNCE_ROUNDS
;
121 QEMUTimer
*timer
= *(QEMUTimer
**)opaque
;
123 qemu_foreach_nic(qemu_announce_self_iter
, NULL
);
126 /* delay 50ms, 150ms, 250ms, ... */
127 timer_mod(timer
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) +
128 self_announce_delay(count
));
135 void qemu_announce_self(void)
137 static QEMUTimer
*timer
;
138 timer
= timer_new_ms(QEMU_CLOCK_REALTIME
, qemu_announce_self_once
, &timer
);
139 qemu_announce_self_once(&timer
);
142 /***********************************************************/
143 /* savevm/loadvm support */
145 static ssize_t
block_writev_buffer(void *opaque
, struct iovec
*iov
, int iovcnt
,
151 qemu_iovec_init_external(&qiov
, iov
, iovcnt
);
152 ret
= bdrv_writev_vmstate(opaque
, &qiov
, pos
);
160 static ssize_t
block_put_buffer(void *opaque
, const uint8_t *buf
,
161 int64_t pos
, size_t size
)
163 bdrv_save_vmstate(opaque
, buf
, pos
, size
);
167 static ssize_t
block_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
,
170 return bdrv_load_vmstate(opaque
, buf
, pos
, size
);
173 static int bdrv_fclose(void *opaque
)
175 return bdrv_flush(opaque
);
178 static const QEMUFileOps bdrv_read_ops
= {
179 .get_buffer
= block_get_buffer
,
183 static const QEMUFileOps bdrv_write_ops
= {
184 .put_buffer
= block_put_buffer
,
185 .writev_buffer
= block_writev_buffer
,
189 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int is_writable
)
192 return qemu_fopen_ops(bs
, &bdrv_write_ops
);
194 return qemu_fopen_ops(bs
, &bdrv_read_ops
);
198 /* QEMUFile timer support.
199 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
202 void timer_put(QEMUFile
*f
, QEMUTimer
*ts
)
204 uint64_t expire_time
;
206 expire_time
= timer_expire_time_ns(ts
);
207 qemu_put_be64(f
, expire_time
);
210 void timer_get(QEMUFile
*f
, QEMUTimer
*ts
)
212 uint64_t expire_time
;
214 expire_time
= qemu_get_be64(f
);
215 if (expire_time
!= -1) {
216 timer_mod_ns(ts
, expire_time
);
223 /* VMState timer support.
224 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
227 static int get_timer(QEMUFile
*f
, void *pv
, size_t size
)
234 static void put_timer(QEMUFile
*f
, void *pv
, size_t size
)
240 const VMStateInfo vmstate_info_timer
= {
247 typedef struct CompatEntry
{
252 typedef struct SaveStateEntry
{
253 QTAILQ_ENTRY(SaveStateEntry
) entry
;
260 const VMStateDescription
*vmsd
;
266 typedef struct SaveState
{
267 QTAILQ_HEAD(, SaveStateEntry
) handlers
;
268 int global_section_id
;
269 bool skip_configuration
;
274 static SaveState savevm_state
= {
275 .handlers
= QTAILQ_HEAD_INITIALIZER(savevm_state
.handlers
),
276 .global_section_id
= 0,
277 .skip_configuration
= false,
280 void savevm_skip_configuration(void)
282 savevm_state
.skip_configuration
= true;
286 static void configuration_pre_save(void *opaque
)
288 SaveState
*state
= opaque
;
289 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
291 state
->len
= strlen(current_name
);
292 state
->name
= current_name
;
295 static int configuration_post_load(void *opaque
, int version_id
)
297 SaveState
*state
= opaque
;
298 const char *current_name
= MACHINE_GET_CLASS(current_machine
)->name
;
300 if (strncmp(state
->name
, current_name
, state
->len
) != 0) {
301 error_report("Machine type received is '%s' and local is '%s'",
302 state
->name
, current_name
);
308 static const VMStateDescription vmstate_configuration
= {
309 .name
= "configuration",
311 .post_load
= configuration_post_load
,
312 .pre_save
= configuration_pre_save
,
313 .fields
= (VMStateField
[]) {
314 VMSTATE_UINT32(len
, SaveState
),
315 VMSTATE_VBUFFER_ALLOC_UINT32(name
, SaveState
, 0, NULL
, 0, len
),
316 VMSTATE_END_OF_LIST()
320 static void dump_vmstate_vmsd(FILE *out_file
,
321 const VMStateDescription
*vmsd
, int indent
,
324 static void dump_vmstate_vmsf(FILE *out_file
, const VMStateField
*field
,
327 fprintf(out_file
, "%*s{\n", indent
, "");
329 fprintf(out_file
, "%*s\"field\": \"%s\",\n", indent
, "", field
->name
);
330 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
332 fprintf(out_file
, "%*s\"field_exists\": %s,\n", indent
, "",
333 field
->field_exists
? "true" : "false");
334 fprintf(out_file
, "%*s\"size\": %zu", indent
, "", field
->size
);
335 if (field
->vmsd
!= NULL
) {
336 fprintf(out_file
, ",\n");
337 dump_vmstate_vmsd(out_file
, field
->vmsd
, indent
, false);
339 fprintf(out_file
, "\n%*s}", indent
- 2, "");
342 static void dump_vmstate_vmss(FILE *out_file
,
343 const VMStateDescription
**subsection
,
346 if (*subsection
!= NULL
) {
347 dump_vmstate_vmsd(out_file
, *subsection
, indent
, true);
351 static void dump_vmstate_vmsd(FILE *out_file
,
352 const VMStateDescription
*vmsd
, int indent
,
356 fprintf(out_file
, "%*s{\n", indent
, "");
358 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", "Description");
361 fprintf(out_file
, "%*s\"name\": \"%s\",\n", indent
, "", vmsd
->name
);
362 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
364 fprintf(out_file
, "%*s\"minimum_version_id\": %d", indent
, "",
365 vmsd
->minimum_version_id
);
366 if (vmsd
->fields
!= NULL
) {
367 const VMStateField
*field
= vmsd
->fields
;
370 fprintf(out_file
, ",\n%*s\"Fields\": [\n", indent
, "");
372 while (field
->name
!= NULL
) {
373 if (field
->flags
& VMS_MUST_EXIST
) {
374 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
379 fprintf(out_file
, ",\n");
381 dump_vmstate_vmsf(out_file
, field
, indent
+ 2);
385 fprintf(out_file
, "\n%*s]", indent
, "");
387 if (vmsd
->subsections
!= NULL
) {
388 const VMStateDescription
**subsection
= vmsd
->subsections
;
391 fprintf(out_file
, ",\n%*s\"Subsections\": [\n", indent
, "");
393 while (*subsection
!= NULL
) {
395 fprintf(out_file
, ",\n");
397 dump_vmstate_vmss(out_file
, subsection
, indent
+ 2);
401 fprintf(out_file
, "\n%*s]", indent
, "");
403 fprintf(out_file
, "\n%*s}", indent
- 2, "");
406 static void dump_machine_type(FILE *out_file
)
410 mc
= MACHINE_GET_CLASS(current_machine
);
412 fprintf(out_file
, " \"vmschkmachine\": {\n");
413 fprintf(out_file
, " \"Name\": \"%s\"\n", mc
->name
);
414 fprintf(out_file
, " },\n");
417 void dump_vmstate_json_to_file(FILE *out_file
)
422 fprintf(out_file
, "{\n");
423 dump_machine_type(out_file
);
426 list
= object_class_get_list(TYPE_DEVICE
, true);
427 for (elt
= list
; elt
; elt
= elt
->next
) {
428 DeviceClass
*dc
= OBJECT_CLASS_CHECK(DeviceClass
, elt
->data
,
438 fprintf(out_file
, ",\n");
440 name
= object_class_get_name(OBJECT_CLASS(dc
));
441 fprintf(out_file
, "%*s\"%s\": {\n", indent
, "", name
);
443 fprintf(out_file
, "%*s\"Name\": \"%s\",\n", indent
, "", name
);
444 fprintf(out_file
, "%*s\"version_id\": %d,\n", indent
, "",
445 dc
->vmsd
->version_id
);
446 fprintf(out_file
, "%*s\"minimum_version_id\": %d,\n", indent
, "",
447 dc
->vmsd
->minimum_version_id
);
449 dump_vmstate_vmsd(out_file
, dc
->vmsd
, indent
, false);
451 fprintf(out_file
, "\n%*s}", indent
- 2, "");
454 fprintf(out_file
, "\n}\n");
458 static int calculate_new_instance_id(const char *idstr
)
463 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
464 if (strcmp(idstr
, se
->idstr
) == 0
465 && instance_id
<= se
->instance_id
) {
466 instance_id
= se
->instance_id
+ 1;
472 static int calculate_compat_instance_id(const char *idstr
)
477 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
482 if (strcmp(idstr
, se
->compat
->idstr
) == 0
483 && instance_id
<= se
->compat
->instance_id
) {
484 instance_id
= se
->compat
->instance_id
+ 1;
490 /* TODO: Individual devices generally have very little idea about the rest
491 of the system, so instance_id should be removed/replaced.
492 Meanwhile pass -1 as instance_id if you do not already have a clearly
493 distinguishing id for all instances of your device class. */
494 int register_savevm_live(DeviceState
*dev
,
503 se
= g_new0(SaveStateEntry
, 1);
504 se
->version_id
= version_id
;
505 se
->section_id
= savevm_state
.global_section_id
++;
509 /* if this is a live_savem then set is_ram */
510 if (ops
->save_live_setup
!= NULL
) {
515 char *id
= qdev_get_dev_path(dev
);
517 pstrcpy(se
->idstr
, sizeof(se
->idstr
), id
);
518 pstrcat(se
->idstr
, sizeof(se
->idstr
), "/");
521 se
->compat
= g_new0(CompatEntry
, 1);
522 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), idstr
);
523 se
->compat
->instance_id
= instance_id
== -1 ?
524 calculate_compat_instance_id(idstr
) : instance_id
;
528 pstrcat(se
->idstr
, sizeof(se
->idstr
), idstr
);
530 if (instance_id
== -1) {
531 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
533 se
->instance_id
= instance_id
;
535 assert(!se
->compat
|| se
->instance_id
== 0);
536 /* add at the end of list */
537 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, se
, entry
);
541 int register_savevm(DeviceState
*dev
,
545 SaveStateHandler
*save_state
,
546 LoadStateHandler
*load_state
,
549 SaveVMHandlers
*ops
= g_new0(SaveVMHandlers
, 1);
550 ops
->save_state
= save_state
;
551 ops
->load_state
= load_state
;
552 return register_savevm_live(dev
, idstr
, instance_id
, version_id
,
556 void unregister_savevm(DeviceState
*dev
, const char *idstr
, void *opaque
)
558 SaveStateEntry
*se
, *new_se
;
562 char *path
= qdev_get_dev_path(dev
);
564 pstrcpy(id
, sizeof(id
), path
);
565 pstrcat(id
, sizeof(id
), "/");
569 pstrcat(id
, sizeof(id
), idstr
);
571 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
572 if (strcmp(se
->idstr
, id
) == 0 && se
->opaque
== opaque
) {
573 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
581 int vmstate_register_with_alias_id(DeviceState
*dev
, int instance_id
,
582 const VMStateDescription
*vmsd
,
583 void *opaque
, int alias_id
,
584 int required_for_version
)
588 /* If this triggers, alias support can be dropped for the vmsd. */
589 assert(alias_id
== -1 || required_for_version
>= vmsd
->minimum_version_id
);
591 se
= g_new0(SaveStateEntry
, 1);
592 se
->version_id
= vmsd
->version_id
;
593 se
->section_id
= savevm_state
.global_section_id
++;
596 se
->alias_id
= alias_id
;
599 char *id
= qdev_get_dev_path(dev
);
601 pstrcpy(se
->idstr
, sizeof(se
->idstr
), id
);
602 pstrcat(se
->idstr
, sizeof(se
->idstr
), "/");
605 se
->compat
= g_new0(CompatEntry
, 1);
606 pstrcpy(se
->compat
->idstr
, sizeof(se
->compat
->idstr
), vmsd
->name
);
607 se
->compat
->instance_id
= instance_id
== -1 ?
608 calculate_compat_instance_id(vmsd
->name
) : instance_id
;
612 pstrcat(se
->idstr
, sizeof(se
->idstr
), vmsd
->name
);
614 if (instance_id
== -1) {
615 se
->instance_id
= calculate_new_instance_id(se
->idstr
);
617 se
->instance_id
= instance_id
;
619 assert(!se
->compat
|| se
->instance_id
== 0);
620 /* add at the end of list */
621 QTAILQ_INSERT_TAIL(&savevm_state
.handlers
, se
, entry
);
625 void vmstate_unregister(DeviceState
*dev
, const VMStateDescription
*vmsd
,
628 SaveStateEntry
*se
, *new_se
;
630 QTAILQ_FOREACH_SAFE(se
, &savevm_state
.handlers
, entry
, new_se
) {
631 if (se
->vmsd
== vmsd
&& se
->opaque
== opaque
) {
632 QTAILQ_REMOVE(&savevm_state
.handlers
, se
, entry
);
639 static int vmstate_load(QEMUFile
*f
, SaveStateEntry
*se
, int version_id
)
641 trace_vmstate_load(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
642 if (!se
->vmsd
) { /* Old style */
643 return se
->ops
->load_state(f
, se
->opaque
, version_id
);
645 return vmstate_load_state(f
, se
->vmsd
, se
->opaque
, version_id
);
648 static void vmstate_save_old_style(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
650 int64_t old_offset
, size
;
652 old_offset
= qemu_ftell_fast(f
);
653 se
->ops
->save_state(f
, se
->opaque
);
654 size
= qemu_ftell_fast(f
) - old_offset
;
657 json_prop_int(vmdesc
, "size", size
);
658 json_start_array(vmdesc
, "fields");
659 json_start_object(vmdesc
, NULL
);
660 json_prop_str(vmdesc
, "name", "data");
661 json_prop_int(vmdesc
, "size", size
);
662 json_prop_str(vmdesc
, "type", "buffer");
663 json_end_object(vmdesc
);
664 json_end_array(vmdesc
);
668 static void vmstate_save(QEMUFile
*f
, SaveStateEntry
*se
, QJSON
*vmdesc
)
670 trace_vmstate_save(se
->idstr
, se
->vmsd
? se
->vmsd
->name
: "(old)");
672 vmstate_save_old_style(f
, se
, vmdesc
);
675 vmstate_save_state(f
, se
->vmsd
, se
->opaque
, vmdesc
);
678 void savevm_skip_section_footers(void)
680 skip_section_footers
= true;
684 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
686 static void save_section_header(QEMUFile
*f
, SaveStateEntry
*se
,
687 uint8_t section_type
)
689 qemu_put_byte(f
, section_type
);
690 qemu_put_be32(f
, se
->section_id
);
692 if (section_type
== QEMU_VM_SECTION_FULL
||
693 section_type
== QEMU_VM_SECTION_START
) {
695 size_t len
= strlen(se
->idstr
);
696 qemu_put_byte(f
, len
);
697 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
699 qemu_put_be32(f
, se
->instance_id
);
700 qemu_put_be32(f
, se
->version_id
);
705 * Write a footer onto device sections that catches cases misformatted device
708 static void save_section_footer(QEMUFile
*f
, SaveStateEntry
*se
)
710 if (!skip_section_footers
) {
711 qemu_put_byte(f
, QEMU_VM_SECTION_FOOTER
);
712 qemu_put_be32(f
, se
->section_id
);
717 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
718 * command and associated data.
720 * @f: File to send command on
721 * @command: Command type to send
722 * @len: Length of associated data
723 * @data: Data associated with command.
725 void qemu_savevm_command_send(QEMUFile
*f
,
726 enum qemu_vm_cmd command
,
730 trace_savevm_command_send(command
, len
);
731 qemu_put_byte(f
, QEMU_VM_COMMAND
);
732 qemu_put_be16(f
, (uint16_t)command
);
733 qemu_put_be16(f
, len
);
734 qemu_put_buffer(f
, data
, len
);
738 void qemu_savevm_send_ping(QEMUFile
*f
, uint32_t value
)
742 trace_savevm_send_ping(value
);
743 buf
= cpu_to_be32(value
);
744 qemu_savevm_command_send(f
, MIG_CMD_PING
, sizeof(value
), (uint8_t *)&buf
);
747 void qemu_savevm_send_open_return_path(QEMUFile
*f
)
749 trace_savevm_send_open_return_path();
750 qemu_savevm_command_send(f
, MIG_CMD_OPEN_RETURN_PATH
, 0, NULL
);
753 /* We have a buffer of data to send; we don't want that all to be loaded
754 * by the command itself, so the command contains just the length of the
755 * extra buffer that we then send straight after it.
756 * TODO: Must be a better way to organise that
762 int qemu_savevm_send_packaged(QEMUFile
*f
, const QEMUSizedBuffer
*qsb
)
765 size_t len
= qsb_get_length(qsb
);
768 if (len
> MAX_VM_CMD_PACKAGED_SIZE
) {
769 error_report("%s: Unreasonably large packaged state: %zu",
774 tmp
= cpu_to_be32(len
);
776 trace_qemu_savevm_send_packaged();
777 qemu_savevm_command_send(f
, MIG_CMD_PACKAGED
, 4, (uint8_t *)&tmp
);
779 /* all the data follows (concatinating the iov's) */
780 for (cur_iov
= 0; cur_iov
< qsb
->n_iov
; cur_iov
++) {
781 /* The iov entries are partially filled */
782 size_t towrite
= MIN(qsb
->iov
[cur_iov
].iov_len
, len
);
789 qemu_put_buffer(f
, qsb
->iov
[cur_iov
].iov_base
, towrite
);
795 /* Send prior to any postcopy transfer */
796 void qemu_savevm_send_postcopy_advise(QEMUFile
*f
)
799 tmp
[0] = cpu_to_be64(getpagesize());
800 tmp
[1] = cpu_to_be64(1ul << qemu_target_page_bits());
802 trace_qemu_savevm_send_postcopy_advise();
803 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_ADVISE
, 16, (uint8_t *)tmp
);
806 /* Sent prior to starting the destination running in postcopy, discard pages
807 * that have already been sent but redirtied on the source.
808 * CMD_POSTCOPY_RAM_DISCARD consist of:
810 * byte Length of name field (not including 0)
811 * n x byte RAM block name
812 * byte 0 terminator (just for safety)
813 * n x Byte ranges within the named RAMBlock
814 * be64 Start of the range
817 * name: RAMBlock name that these entries are part of
818 * len: Number of page entries
819 * start_list: 'len' addresses
820 * length_list: 'len' addresses
823 void qemu_savevm_send_postcopy_ram_discard(QEMUFile
*f
, const char *name
,
825 uint64_t *start_list
,
826 uint64_t *length_list
)
831 size_t name_len
= strlen(name
);
833 trace_qemu_savevm_send_postcopy_ram_discard(name
, len
);
834 assert(name_len
< 256);
835 buf
= g_malloc0(1 + 1 + name_len
+ 1 + (8 + 8) * len
);
836 buf
[0] = postcopy_ram_discard_version
;
838 memcpy(buf
+ 2, name
, name_len
);
839 tmplen
= 2 + name_len
;
840 buf
[tmplen
++] = '\0';
842 for (t
= 0; t
< len
; t
++) {
843 cpu_to_be64w((uint64_t *)(buf
+ tmplen
), start_list
[t
]);
845 cpu_to_be64w((uint64_t *)(buf
+ tmplen
), length_list
[t
]);
848 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RAM_DISCARD
, tmplen
, buf
);
852 /* Get the destination into a state where it can receive postcopy data. */
853 void qemu_savevm_send_postcopy_listen(QEMUFile
*f
)
855 trace_savevm_send_postcopy_listen();
856 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_LISTEN
, 0, NULL
);
859 /* Kick the destination into running */
860 void qemu_savevm_send_postcopy_run(QEMUFile
*f
)
862 trace_savevm_send_postcopy_run();
863 qemu_savevm_command_send(f
, MIG_CMD_POSTCOPY_RUN
, 0, NULL
);
866 bool qemu_savevm_state_blocked(Error
**errp
)
870 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
871 if (se
->vmsd
&& se
->vmsd
->unmigratable
) {
872 error_setg(errp
, "State blocked by non-migratable device '%s'",
880 void qemu_savevm_state_header(QEMUFile
*f
)
882 trace_savevm_state_header();
883 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
884 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
886 if (!savevm_state
.skip_configuration
) {
887 qemu_put_byte(f
, QEMU_VM_CONFIGURATION
);
888 vmstate_save_state(f
, &vmstate_configuration
, &savevm_state
, 0);
893 void qemu_savevm_state_begin(QEMUFile
*f
,
894 const MigrationParams
*params
)
899 trace_savevm_state_begin();
900 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
901 if (!se
->ops
|| !se
->ops
->set_params
) {
904 se
->ops
->set_params(params
, se
->opaque
);
907 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
908 if (!se
->ops
|| !se
->ops
->save_live_setup
) {
911 if (se
->ops
&& se
->ops
->is_active
) {
912 if (!se
->ops
->is_active(se
->opaque
)) {
916 save_section_header(f
, se
, QEMU_VM_SECTION_START
);
918 ret
= se
->ops
->save_live_setup(f
, se
->opaque
);
919 save_section_footer(f
, se
);
921 qemu_file_set_error(f
, ret
);
928 * this function has three return values:
929 * negative: there was one error, and we have -errno.
930 * 0 : We haven't finished, caller have to go again
931 * 1 : We have finished, we can go to complete phase
933 int qemu_savevm_state_iterate(QEMUFile
*f
)
938 trace_savevm_state_iterate();
939 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
940 if (!se
->ops
|| !se
->ops
->save_live_iterate
) {
943 if (se
->ops
&& se
->ops
->is_active
) {
944 if (!se
->ops
->is_active(se
->opaque
)) {
948 if (qemu_file_rate_limit(f
)) {
951 trace_savevm_section_start(se
->idstr
, se
->section_id
);
953 save_section_header(f
, se
, QEMU_VM_SECTION_PART
);
955 ret
= se
->ops
->save_live_iterate(f
, se
->opaque
);
956 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
957 save_section_footer(f
, se
);
960 qemu_file_set_error(f
, ret
);
963 /* Do not proceed to the next vmstate before this one reported
964 completion of the current stage. This serializes the migration
965 and reduces the probability that a faster changing state is
966 synchronized over and over again. */
973 static bool should_send_vmdesc(void)
975 MachineState
*machine
= MACHINE(qdev_get_machine());
976 return !machine
->suppress_vmdesc
;
979 void qemu_savevm_state_complete_precopy(QEMUFile
*f
)
986 trace_savevm_state_complete_precopy();
988 cpu_synchronize_all_states();
990 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
991 if (!se
->ops
|| !se
->ops
->save_live_complete_precopy
) {
994 if (se
->ops
&& se
->ops
->is_active
) {
995 if (!se
->ops
->is_active(se
->opaque
)) {
999 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1001 save_section_header(f
, se
, QEMU_VM_SECTION_END
);
1003 ret
= se
->ops
->save_live_complete_precopy(f
, se
->opaque
);
1004 trace_savevm_section_end(se
->idstr
, se
->section_id
, ret
);
1005 save_section_footer(f
, se
);
1007 qemu_file_set_error(f
, ret
);
1012 vmdesc
= qjson_new();
1013 json_prop_int(vmdesc
, "page_size", TARGET_PAGE_SIZE
);
1014 json_start_array(vmdesc
, "devices");
1015 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1017 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1020 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1021 trace_savevm_section_skip(se
->idstr
, se
->section_id
);
1025 trace_savevm_section_start(se
->idstr
, se
->section_id
);
1027 json_start_object(vmdesc
, NULL
);
1028 json_prop_str(vmdesc
, "name", se
->idstr
);
1029 json_prop_int(vmdesc
, "instance_id", se
->instance_id
);
1031 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1033 vmstate_save(f
, se
, vmdesc
);
1035 json_end_object(vmdesc
);
1036 trace_savevm_section_end(se
->idstr
, se
->section_id
, 0);
1037 save_section_footer(f
, se
);
1040 qemu_put_byte(f
, QEMU_VM_EOF
);
1042 json_end_array(vmdesc
);
1043 qjson_finish(vmdesc
);
1044 vmdesc_len
= strlen(qjson_get_str(vmdesc
));
1046 if (should_send_vmdesc()) {
1047 qemu_put_byte(f
, QEMU_VM_VMDESCRIPTION
);
1048 qemu_put_be32(f
, vmdesc_len
);
1049 qemu_put_buffer(f
, (uint8_t *)qjson_get_str(vmdesc
), vmdesc_len
);
1051 object_unref(OBJECT(vmdesc
));
1056 uint64_t qemu_savevm_state_pending(QEMUFile
*f
, uint64_t max_size
)
1061 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1062 if (!se
->ops
|| !se
->ops
->save_live_pending
) {
1065 if (se
->ops
&& se
->ops
->is_active
) {
1066 if (!se
->ops
->is_active(se
->opaque
)) {
1070 ret
+= se
->ops
->save_live_pending(f
, se
->opaque
, max_size
);
1075 void qemu_savevm_state_cleanup(void)
1079 trace_savevm_state_cleanup();
1080 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1081 if (se
->ops
&& se
->ops
->cleanup
) {
1082 se
->ops
->cleanup(se
->opaque
);
1087 static int qemu_savevm_state(QEMUFile
*f
, Error
**errp
)
1090 MigrationParams params
= {
1094 MigrationState
*ms
= migrate_init(¶ms
);
1097 if (qemu_savevm_state_blocked(errp
)) {
1101 qemu_mutex_unlock_iothread();
1102 qemu_savevm_state_header(f
);
1103 qemu_savevm_state_begin(f
, ¶ms
);
1104 qemu_mutex_lock_iothread();
1106 while (qemu_file_get_error(f
) == 0) {
1107 if (qemu_savevm_state_iterate(f
) > 0) {
1112 ret
= qemu_file_get_error(f
);
1114 qemu_savevm_state_complete_precopy(f
);
1115 ret
= qemu_file_get_error(f
);
1118 qemu_savevm_state_cleanup();
1119 error_setg_errno(errp
, -ret
, "Error while writing VM state");
1124 static int qemu_save_device_state(QEMUFile
*f
)
1128 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
1129 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
1131 cpu_synchronize_all_states();
1133 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1137 if ((!se
->ops
|| !se
->ops
->save_state
) && !se
->vmsd
) {
1140 if (se
->vmsd
&& !vmstate_save_needed(se
->vmsd
, se
->opaque
)) {
1144 save_section_header(f
, se
, QEMU_VM_SECTION_FULL
);
1146 vmstate_save(f
, se
, NULL
);
1148 save_section_footer(f
, se
);
1151 qemu_put_byte(f
, QEMU_VM_EOF
);
1153 return qemu_file_get_error(f
);
1156 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
1160 QTAILQ_FOREACH(se
, &savevm_state
.handlers
, entry
) {
1161 if (!strcmp(se
->idstr
, idstr
) &&
1162 (instance_id
== se
->instance_id
||
1163 instance_id
== se
->alias_id
))
1165 /* Migrating from an older version? */
1166 if (strstr(se
->idstr
, idstr
) && se
->compat
) {
1167 if (!strcmp(se
->compat
->idstr
, idstr
) &&
1168 (instance_id
== se
->compat
->instance_id
||
1169 instance_id
== se
->alias_id
))
1176 enum LoadVMExitCodes
{
1177 /* Allow a command to quit all layers of nested loadvm loops */
1181 static int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
);
1183 /* ------ incoming postcopy messages ------ */
1184 /* 'advise' arrives before any transfers just to tell us that a postcopy
1185 * *might* happen - it might be skipped if precopy transferred everything
1188 static int loadvm_postcopy_handle_advise(MigrationIncomingState
*mis
)
1190 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_ADVISE
);
1191 uint64_t remote_hps
, remote_tps
;
1193 trace_loadvm_postcopy_handle_advise();
1194 if (ps
!= POSTCOPY_INCOMING_NONE
) {
1195 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps
);
1199 remote_hps
= qemu_get_be64(mis
->from_src_file
);
1200 if (remote_hps
!= getpagesize()) {
1202 * Some combinations of mismatch are probably possible but it gets
1203 * a bit more complicated. In particular we need to place whole
1204 * host pages on the dest at once, and we need to ensure that we
1205 * handle dirtying to make sure we never end up sending part of
1206 * a hostpage on it's own.
1208 error_report("Postcopy needs matching host page sizes (s=%d d=%d)",
1209 (int)remote_hps
, getpagesize());
1213 remote_tps
= qemu_get_be64(mis
->from_src_file
);
1214 if (remote_tps
!= (1ul << qemu_target_page_bits())) {
1216 * Again, some differences could be dealt with, but for now keep it
1219 error_report("Postcopy needs matching target page sizes (s=%d d=%d)",
1220 (int)remote_tps
, 1 << qemu_target_page_bits());
1227 /* After postcopy we will be told to throw some pages away since they're
1228 * dirty and will have to be demand fetched. Must happen before CPU is
1230 * There can be 0..many of these messages, each encoding multiple pages.
1232 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState
*mis
,
1237 PostcopyState ps
= postcopy_state_get();
1239 trace_loadvm_postcopy_ram_handle_discard();
1242 case POSTCOPY_INCOMING_ADVISE
:
1244 tmp
= 0; /* TODO: later patch postcopy_ram_prepare_discard(mis); */
1250 case POSTCOPY_INCOMING_DISCARD
:
1251 /* Expected state */
1255 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1259 /* We're expecting a
1261 * a RAM ID string (length byte, name, 0 term)
1262 * then at least 1 16 byte chunk
1264 if (len
< (1 + 1 + 1 + 1 + 2 * 8)) {
1265 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1269 tmp
= qemu_get_byte(mis
->from_src_file
);
1270 if (tmp
!= postcopy_ram_discard_version
) {
1271 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp
);
1275 if (!qemu_get_counted_string(mis
->from_src_file
, ramid
)) {
1276 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1279 tmp
= qemu_get_byte(mis
->from_src_file
);
1281 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp
);
1285 len
-= 3 + strlen(ramid
);
1287 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len
);
1290 trace_loadvm_postcopy_ram_handle_discard_header(ramid
, len
);
1292 /* TODO - ram_discard_range gets added in a later patch
1293 uint64_t start_addr, block_length;
1294 start_addr = qemu_get_be64(mis->from_src_file);
1295 block_length = qemu_get_be64(mis->from_src_file);
1298 int ret = ram_discard_range(mis, ramid, start_addr,
1305 trace_loadvm_postcopy_ram_handle_discard_end();
1310 /* After this message we must be able to immediately receive postcopy data */
1311 static int loadvm_postcopy_handle_listen(MigrationIncomingState
*mis
)
1313 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_LISTENING
);
1314 trace_loadvm_postcopy_handle_listen();
1315 if (ps
!= POSTCOPY_INCOMING_ADVISE
&& ps
!= POSTCOPY_INCOMING_DISCARD
) {
1316 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps
);
1320 /* TODO start up the postcopy listening thread */
1324 /* After all discards we can start running and asking for pages */
1325 static int loadvm_postcopy_handle_run(MigrationIncomingState
*mis
)
1327 PostcopyState ps
= postcopy_state_set(POSTCOPY_INCOMING_RUNNING
);
1328 trace_loadvm_postcopy_handle_run();
1329 if (ps
!= POSTCOPY_INCOMING_LISTENING
) {
1330 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps
);
1335 /* Hold onto your hats, starting the CPU */
1338 /* leave it paused and let management decide when to start the CPU */
1339 runstate_set(RUN_STATE_PAUSED
);
1346 * Immediately following this command is a blob of data containing an embedded
1347 * chunk of migration stream; read it and load it.
1349 * @mis: Incoming state
1350 * @length: Length of packaged data to read
1352 * Returns: Negative values on error
1355 static int loadvm_handle_cmd_packaged(MigrationIncomingState
*mis
)
1360 QEMUSizedBuffer
*qsb
;
1362 length
= qemu_get_be32(mis
->from_src_file
);
1363 trace_loadvm_handle_cmd_packaged(length
);
1365 if (length
> MAX_VM_CMD_PACKAGED_SIZE
) {
1366 error_report("Unreasonably large packaged state: %u", length
);
1369 buffer
= g_malloc0(length
);
1370 ret
= qemu_get_buffer(mis
->from_src_file
, buffer
, (int)length
);
1371 if (ret
!= length
) {
1373 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%d\n",
1375 return (ret
< 0) ? ret
: -EAGAIN
;
1377 trace_loadvm_handle_cmd_packaged_received(ret
);
1379 /* Setup a dummy QEMUFile that actually reads from the buffer */
1380 qsb
= qsb_create(buffer
, length
);
1381 g_free(buffer
); /* Because qsb_create copies */
1383 error_report("Unable to create qsb");
1385 QEMUFile
*packf
= qemu_bufopen("r", qsb
);
1387 ret
= qemu_loadvm_state_main(packf
, mis
);
1388 trace_loadvm_handle_cmd_packaged_main(ret
);
1396 * Process an incoming 'QEMU_VM_COMMAND'
1397 * 0 just a normal return
1398 * LOADVM_QUIT All good, but exit the loop
1401 static int loadvm_process_command(QEMUFile
*f
)
1403 MigrationIncomingState
*mis
= migration_incoming_get_current();
1408 cmd
= qemu_get_be16(f
);
1409 len
= qemu_get_be16(f
);
1411 trace_loadvm_process_command(cmd
, len
);
1412 if (cmd
>= MIG_CMD_MAX
|| cmd
== MIG_CMD_INVALID
) {
1413 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd
, len
);
1417 if (mig_cmd_args
[cmd
].len
!= -1 && mig_cmd_args
[cmd
].len
!= len
) {
1418 error_report("%s received with bad length - expecting %zu, got %d",
1419 mig_cmd_args
[cmd
].name
,
1420 (size_t)mig_cmd_args
[cmd
].len
, len
);
1425 case MIG_CMD_OPEN_RETURN_PATH
:
1426 if (mis
->to_src_file
) {
1427 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1428 /* Not really a problem, so don't give up */
1431 mis
->to_src_file
= qemu_file_get_return_path(f
);
1432 if (!mis
->to_src_file
) {
1433 error_report("CMD_OPEN_RETURN_PATH failed");
1439 tmp32
= qemu_get_be32(f
);
1440 trace_loadvm_process_command_ping(tmp32
);
1441 if (!mis
->to_src_file
) {
1442 error_report("CMD_PING (0x%x) received with no return path",
1446 migrate_send_rp_pong(mis
, tmp32
);
1449 case MIG_CMD_PACKAGED
:
1450 return loadvm_handle_cmd_packaged(mis
);
1452 case MIG_CMD_POSTCOPY_ADVISE
:
1453 return loadvm_postcopy_handle_advise(mis
);
1455 case MIG_CMD_POSTCOPY_LISTEN
:
1456 return loadvm_postcopy_handle_listen(mis
);
1458 case MIG_CMD_POSTCOPY_RUN
:
1459 return loadvm_postcopy_handle_run(mis
);
1461 case MIG_CMD_POSTCOPY_RAM_DISCARD
:
1462 return loadvm_postcopy_ram_handle_discard(mis
, len
);
1468 struct LoadStateEntry
{
1469 QLIST_ENTRY(LoadStateEntry
) entry
;
1476 * Read a footer off the wire and check that it matches the expected section
1478 * Returns: true if the footer was good
1479 * false if there is a problem (and calls error_report to say why)
1481 static bool check_section_footer(QEMUFile
*f
, LoadStateEntry
*le
)
1484 uint32_t read_section_id
;
1486 if (skip_section_footers
) {
1487 /* No footer to check */
1491 read_mark
= qemu_get_byte(f
);
1493 if (read_mark
!= QEMU_VM_SECTION_FOOTER
) {
1494 error_report("Missing section footer for %s", le
->se
->idstr
);
1498 read_section_id
= qemu_get_be32(f
);
1499 if (read_section_id
!= le
->section_id
) {
1500 error_report("Mismatched section id in footer for %s -"
1501 " read 0x%x expected 0x%x",
1502 le
->se
->idstr
, read_section_id
, le
->section_id
);
1510 void loadvm_free_handlers(MigrationIncomingState
*mis
)
1512 LoadStateEntry
*le
, *new_le
;
1514 QLIST_FOREACH_SAFE(le
, &mis
->loadvm_handlers
, entry
, new_le
) {
1515 QLIST_REMOVE(le
, entry
);
1520 static int qemu_loadvm_state_main(QEMUFile
*f
, MigrationIncomingState
*mis
)
1522 uint8_t section_type
;
1525 while ((section_type
= qemu_get_byte(f
)) != QEMU_VM_EOF
) {
1526 uint32_t instance_id
, version_id
, section_id
;
1531 trace_qemu_loadvm_state_section(section_type
);
1532 switch (section_type
) {
1533 case QEMU_VM_SECTION_START
:
1534 case QEMU_VM_SECTION_FULL
:
1535 /* Read section start */
1536 section_id
= qemu_get_be32(f
);
1537 if (!qemu_get_counted_string(f
, idstr
)) {
1538 error_report("Unable to read ID string for section %u",
1542 instance_id
= qemu_get_be32(f
);
1543 version_id
= qemu_get_be32(f
);
1545 trace_qemu_loadvm_state_section_startfull(section_id
, idstr
,
1546 instance_id
, version_id
);
1547 /* Find savevm section */
1548 se
= find_se(idstr
, instance_id
);
1550 error_report("Unknown savevm section or instance '%s' %d",
1551 idstr
, instance_id
);
1555 /* Validate version */
1556 if (version_id
> se
->version_id
) {
1557 error_report("savevm: unsupported version %d for '%s' v%d",
1558 version_id
, idstr
, se
->version_id
);
1563 le
= g_malloc0(sizeof(*le
));
1566 le
->section_id
= section_id
;
1567 le
->version_id
= version_id
;
1568 QLIST_INSERT_HEAD(&mis
->loadvm_handlers
, le
, entry
);
1570 ret
= vmstate_load(f
, le
->se
, le
->version_id
);
1572 error_report("error while loading state for instance 0x%x of"
1573 " device '%s'", instance_id
, idstr
);
1576 if (!check_section_footer(f
, le
)) {
1580 case QEMU_VM_SECTION_PART
:
1581 case QEMU_VM_SECTION_END
:
1582 section_id
= qemu_get_be32(f
);
1584 trace_qemu_loadvm_state_section_partend(section_id
);
1585 QLIST_FOREACH(le
, &mis
->loadvm_handlers
, entry
) {
1586 if (le
->section_id
== section_id
) {
1591 error_report("Unknown savevm section %d", section_id
);
1595 ret
= vmstate_load(f
, le
->se
, le
->version_id
);
1597 error_report("error while loading state section id %d(%s)",
1598 section_id
, le
->se
->idstr
);
1601 if (!check_section_footer(f
, le
)) {
1605 case QEMU_VM_COMMAND
:
1606 ret
= loadvm_process_command(f
);
1607 trace_qemu_loadvm_state_section_command(ret
);
1608 if ((ret
< 0) || (ret
& LOADVM_QUIT
)) {
1613 error_report("Unknown savevm section type %d", section_type
);
1621 int qemu_loadvm_state(QEMUFile
*f
)
1623 MigrationIncomingState
*mis
= migration_incoming_get_current();
1624 Error
*local_err
= NULL
;
1628 if (qemu_savevm_state_blocked(&local_err
)) {
1629 error_report_err(local_err
);
1633 v
= qemu_get_be32(f
);
1634 if (v
!= QEMU_VM_FILE_MAGIC
) {
1635 error_report("Not a migration stream");
1639 v
= qemu_get_be32(f
);
1640 if (v
== QEMU_VM_FILE_VERSION_COMPAT
) {
1641 error_report("SaveVM v2 format is obsolete and don't work anymore");
1644 if (v
!= QEMU_VM_FILE_VERSION
) {
1645 error_report("Unsupported migration stream version");
1649 if (!savevm_state
.skip_configuration
) {
1650 if (qemu_get_byte(f
) != QEMU_VM_CONFIGURATION
) {
1651 error_report("Configuration section missing");
1654 ret
= vmstate_load_state(f
, &vmstate_configuration
, &savevm_state
, 0);
1661 ret
= qemu_loadvm_state_main(f
, mis
);
1662 qemu_event_set(&mis
->main_thread_load_event
);
1664 trace_qemu_loadvm_state_post_main(ret
);
1667 ret
= qemu_file_get_error(f
);
1671 * Try to read in the VMDESC section as well, so that dumping tools that
1672 * intercept our migration stream have the chance to see it.
1675 /* We've got to be careful; if we don't read the data and just shut the fd
1676 * then the sender can error if we close while it's still sending.
1677 * We also mustn't read data that isn't there; some transports (RDMA)
1678 * will stall waiting for that data when the source has already closed.
1680 if (ret
== 0 && should_send_vmdesc()) {
1683 uint8_t section_type
= qemu_get_byte(f
);
1685 if (section_type
!= QEMU_VM_VMDESCRIPTION
) {
1686 error_report("Expected vmdescription section, but got %d",
1689 * It doesn't seem worth failing at this point since
1690 * we apparently have an otherwise valid VM state
1693 buf
= g_malloc(0x1000);
1694 size
= qemu_get_be32(f
);
1697 uint32_t read_chunk
= MIN(size
, 0x1000);
1698 qemu_get_buffer(f
, buf
, read_chunk
);
1705 cpu_synchronize_all_post_init();
1710 static BlockDriverState
*find_vmstate_bs(void)
1712 BlockDriverState
*bs
= NULL
;
1713 while ((bs
= bdrv_next(bs
))) {
1714 if (bdrv_can_snapshot(bs
)) {
1722 * Deletes snapshots of a given name in all opened images.
1724 static int del_existing_snapshots(Monitor
*mon
, const char *name
)
1726 BlockDriverState
*bs
;
1727 QEMUSnapshotInfo sn1
, *snapshot
= &sn1
;
1731 while ((bs
= bdrv_next(bs
))) {
1732 if (bdrv_can_snapshot(bs
) &&
1733 bdrv_snapshot_find(bs
, snapshot
, name
) >= 0) {
1734 bdrv_snapshot_delete_by_id_or_name(bs
, name
, &err
);
1737 "Error while deleting snapshot on device '%s':"
1739 bdrv_get_device_name(bs
),
1740 error_get_pretty(err
));
1750 void hmp_savevm(Monitor
*mon
, const QDict
*qdict
)
1752 BlockDriverState
*bs
, *bs1
;
1753 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
1756 int saved_vm_running
;
1757 uint64_t vm_state_size
;
1760 const char *name
= qdict_get_try_str(qdict
, "name");
1761 Error
*local_err
= NULL
;
1763 /* Verify if there is a device that doesn't support snapshots and is writable */
1765 while ((bs
= bdrv_next(bs
))) {
1767 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
)) {
1771 if (!bdrv_can_snapshot(bs
)) {
1772 monitor_printf(mon
, "Device '%s' is writable but does not support snapshots.\n",
1773 bdrv_get_device_name(bs
));
1778 bs
= find_vmstate_bs();
1780 monitor_printf(mon
, "No block device can accept snapshots\n");
1784 saved_vm_running
= runstate_is_running();
1786 ret
= global_state_store();
1788 monitor_printf(mon
, "Error saving global state\n");
1791 vm_stop(RUN_STATE_SAVE_VM
);
1793 memset(sn
, 0, sizeof(*sn
));
1795 /* fill auxiliary fields */
1796 qemu_gettimeofday(&tv
);
1797 sn
->date_sec
= tv
.tv_sec
;
1798 sn
->date_nsec
= tv
.tv_usec
* 1000;
1799 sn
->vm_clock_nsec
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
1802 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
1804 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
1805 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
1807 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
1810 /* cast below needed for OpenBSD where tv_sec is still 'long' */
1811 localtime_r((const time_t *)&tv
.tv_sec
, &tm
);
1812 strftime(sn
->name
, sizeof(sn
->name
), "vm-%Y%m%d%H%M%S", &tm
);
1815 /* Delete old snapshots of the same name */
1816 if (name
&& del_existing_snapshots(mon
, name
) < 0) {
1820 /* save the VM state */
1821 f
= qemu_fopen_bdrv(bs
, 1);
1823 monitor_printf(mon
, "Could not open VM state file\n");
1826 ret
= qemu_savevm_state(f
, &local_err
);
1827 vm_state_size
= qemu_ftell(f
);
1830 monitor_printf(mon
, "%s\n", error_get_pretty(local_err
));
1831 error_free(local_err
);
1835 /* create the snapshots */
1838 while ((bs1
= bdrv_next(bs1
))) {
1839 if (bdrv_can_snapshot(bs1
)) {
1840 /* Write VM state size only to the image that contains the state */
1841 sn
->vm_state_size
= (bs
== bs1
? vm_state_size
: 0);
1842 ret
= bdrv_snapshot_create(bs1
, sn
);
1844 monitor_printf(mon
, "Error while creating snapshot on '%s'\n",
1845 bdrv_get_device_name(bs1
));
1851 if (saved_vm_running
) {
1856 void qmp_xen_save_devices_state(const char *filename
, Error
**errp
)
1859 int saved_vm_running
;
1862 saved_vm_running
= runstate_is_running();
1863 vm_stop(RUN_STATE_SAVE_VM
);
1864 global_state_store_running();
1866 f
= qemu_fopen(filename
, "wb");
1868 error_setg_file_open(errp
, errno
, filename
);
1871 ret
= qemu_save_device_state(f
);
1874 error_setg(errp
, QERR_IO_ERROR
);
1878 if (saved_vm_running
) {
1883 int load_vmstate(const char *name
)
1885 BlockDriverState
*bs
, *bs_vm_state
;
1886 QEMUSnapshotInfo sn
;
1890 bs_vm_state
= find_vmstate_bs();
1892 error_report("No block device supports snapshots");
1896 /* Don't even try to load empty VM states */
1897 ret
= bdrv_snapshot_find(bs_vm_state
, &sn
, name
);
1900 } else if (sn
.vm_state_size
== 0) {
1901 error_report("This is a disk-only snapshot. Revert to it offline "
1906 /* Verify if there is any device that doesn't support snapshots and is
1907 writable and check if the requested snapshot is available too. */
1909 while ((bs
= bdrv_next(bs
))) {
1911 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
)) {
1915 if (!bdrv_can_snapshot(bs
)) {
1916 error_report("Device '%s' is writable but does not support snapshots.",
1917 bdrv_get_device_name(bs
));
1921 ret
= bdrv_snapshot_find(bs
, &sn
, name
);
1923 error_report("Device '%s' does not have the requested snapshot '%s'",
1924 bdrv_get_device_name(bs
), name
);
1929 /* Flush all IO requests so they don't interfere with the new state. */
1933 while ((bs
= bdrv_next(bs
))) {
1934 if (bdrv_can_snapshot(bs
)) {
1935 ret
= bdrv_snapshot_goto(bs
, name
);
1937 error_report("Error %d while activating snapshot '%s' on '%s'",
1938 ret
, name
, bdrv_get_device_name(bs
));
1944 /* restore the VM state */
1945 f
= qemu_fopen_bdrv(bs_vm_state
, 0);
1947 error_report("Could not open VM state file");
1951 qemu_system_reset(VMRESET_SILENT
);
1952 migration_incoming_state_new(f
);
1953 ret
= qemu_loadvm_state(f
);
1956 migration_incoming_state_destroy();
1958 error_report("Error %d while loading VM state", ret
);
1965 void hmp_delvm(Monitor
*mon
, const QDict
*qdict
)
1967 BlockDriverState
*bs
;
1969 const char *name
= qdict_get_str(qdict
, "name");
1971 if (!find_vmstate_bs()) {
1972 monitor_printf(mon
, "No block device supports snapshots\n");
1977 while ((bs
= bdrv_next(bs
))) {
1978 if (bdrv_can_snapshot(bs
)) {
1980 bdrv_snapshot_delete_by_id_or_name(bs
, name
, &err
);
1983 "Error while deleting snapshot on device '%s':"
1985 bdrv_get_device_name(bs
),
1986 error_get_pretty(err
));
1993 void hmp_info_snapshots(Monitor
*mon
, const QDict
*qdict
)
1995 BlockDriverState
*bs
, *bs1
;
1996 QEMUSnapshotInfo
*sn_tab
, *sn
, s
, *sn_info
= &s
;
1997 int nb_sns
, i
, ret
, available
;
1999 int *available_snapshots
;
2001 bs
= find_vmstate_bs();
2003 monitor_printf(mon
, "No available block device supports snapshots\n");
2007 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2009 monitor_printf(mon
, "bdrv_snapshot_list: error %d\n", nb_sns
);
2014 monitor_printf(mon
, "There is no snapshot available.\n");
2018 available_snapshots
= g_new0(int, nb_sns
);
2020 for (i
= 0; i
< nb_sns
; i
++) {
2025 while ((bs1
= bdrv_next(bs1
))) {
2026 if (bdrv_can_snapshot(bs1
) && bs1
!= bs
) {
2027 ret
= bdrv_snapshot_find(bs1
, sn_info
, sn
->id_str
);
2036 available_snapshots
[total
] = i
;
2042 bdrv_snapshot_dump((fprintf_function
)monitor_printf
, mon
, NULL
);
2043 monitor_printf(mon
, "\n");
2044 for (i
= 0; i
< total
; i
++) {
2045 sn
= &sn_tab
[available_snapshots
[i
]];
2046 bdrv_snapshot_dump((fprintf_function
)monitor_printf
, mon
, sn
);
2047 monitor_printf(mon
, "\n");
2050 monitor_printf(mon
, "There is no suitable snapshot available\n");
2054 g_free(available_snapshots
);
2058 void vmstate_register_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2060 qemu_ram_set_idstr(memory_region_get_ram_addr(mr
) & TARGET_PAGE_MASK
,
2061 memory_region_name(mr
), dev
);
2064 void vmstate_unregister_ram(MemoryRegion
*mr
, DeviceState
*dev
)
2066 qemu_ram_unset_idstr(memory_region_get_ram_addr(mr
) & TARGET_PAGE_MASK
);
2069 void vmstate_register_ram_global(MemoryRegion
*mr
)
2071 vmstate_register_ram(mr
, NULL
);