qed: Use a coroutine for need_check_timer
[qemu/kevin.git] / migration / savevm.c
blobc7a49c93c59f282d2d3b69450274fed5c76ef4ec
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
7 * Authors:
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
26 * THE SOFTWARE.
29 #include "qemu/osdep.h"
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
32 #include "net/net.h"
33 #include "migration.h"
34 #include "migration/snapshot.h"
35 #include "migration/misc.h"
36 #include "migration/register.h"
37 #include "migration/global_state.h"
38 #include "ram.h"
39 #include "qemu-file-channel.h"
40 #include "qemu-file.h"
41 #include "savevm.h"
42 #include "postcopy-ram.h"
43 #include "qapi/qmp/qerror.h"
44 #include "qemu/error-report.h"
45 #include "sysemu/cpus.h"
46 #include "exec/memory.h"
47 #include "exec/target_page.h"
48 #include "qmp-commands.h"
49 #include "trace.h"
50 #include "qemu/iov.h"
51 #include "block/snapshot.h"
52 #include "qemu/cutils.h"
53 #include "io/channel-buffer.h"
54 #include "io/channel-file.h"
56 #ifndef ETH_P_RARP
57 #define ETH_P_RARP 0x8035
58 #endif
59 #define ARP_HTYPE_ETH 0x0001
60 #define ARP_PTYPE_IP 0x0800
61 #define ARP_OP_REQUEST_REV 0x3
63 const unsigned int postcopy_ram_discard_version = 0;
65 static bool skip_section_footers;
67 /* Subcommands for QEMU_VM_COMMAND */
68 enum qemu_vm_cmd {
69 MIG_CMD_INVALID = 0, /* Must be 0 */
70 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
71 MIG_CMD_PING, /* Request a PONG on the RP */
73 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
74 warn we might want to do PC */
75 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
76 pages as it's running. */
77 MIG_CMD_POSTCOPY_RUN, /* Start execution */
79 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
80 were previously sent during
81 precopy but are dirty. */
82 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
83 MIG_CMD_MAX
86 #define MAX_VM_CMD_PACKAGED_SIZE (1ul << 24)
87 static struct mig_cmd_args {
88 ssize_t len; /* -1 = variable */
89 const char *name;
90 } mig_cmd_args[] = {
91 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
92 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
93 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
94 [MIG_CMD_POSTCOPY_ADVISE] = { .len = 16, .name = "POSTCOPY_ADVISE" },
95 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
96 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
97 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
98 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
99 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
100 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
103 static int announce_self_create(uint8_t *buf,
104 uint8_t *mac_addr)
106 /* Ethernet header. */
107 memset(buf, 0xff, 6); /* destination MAC addr */
108 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
109 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
111 /* RARP header. */
112 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
113 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
114 *(buf + 18) = 6; /* hardware addr length (ethernet) */
115 *(buf + 19) = 4; /* protocol addr length (IPv4) */
116 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
117 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
118 memset(buf + 28, 0x00, 4); /* source protocol addr */
119 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
120 memset(buf + 38, 0x00, 4); /* target protocol addr */
122 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
123 memset(buf + 42, 0x00, 18);
125 return 60; /* len (FCS will be added by hardware) */
128 static void qemu_announce_self_iter(NICState *nic, void *opaque)
130 uint8_t buf[60];
131 int len;
133 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic->conf->macaddr));
134 len = announce_self_create(buf, nic->conf->macaddr.a);
136 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
140 static void qemu_announce_self_once(void *opaque)
142 static int count = SELF_ANNOUNCE_ROUNDS;
143 QEMUTimer *timer = *(QEMUTimer **)opaque;
145 qemu_foreach_nic(qemu_announce_self_iter, NULL);
147 if (--count) {
148 /* delay 50ms, 150ms, 250ms, ... */
149 timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
150 self_announce_delay(count));
151 } else {
152 timer_del(timer);
153 timer_free(timer);
157 void qemu_announce_self(void)
159 static QEMUTimer *timer;
160 timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
161 qemu_announce_self_once(&timer);
164 /***********************************************************/
165 /* savevm/loadvm support */
167 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
168 int64_t pos)
170 int ret;
171 QEMUIOVector qiov;
173 qemu_iovec_init_external(&qiov, iov, iovcnt);
174 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
175 if (ret < 0) {
176 return ret;
179 return qiov.size;
182 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
183 size_t size)
185 return bdrv_load_vmstate(opaque, buf, pos, size);
188 static int bdrv_fclose(void *opaque)
190 return bdrv_flush(opaque);
193 static const QEMUFileOps bdrv_read_ops = {
194 .get_buffer = block_get_buffer,
195 .close = bdrv_fclose
198 static const QEMUFileOps bdrv_write_ops = {
199 .writev_buffer = block_writev_buffer,
200 .close = bdrv_fclose
203 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
205 if (is_writable) {
206 return qemu_fopen_ops(bs, &bdrv_write_ops);
208 return qemu_fopen_ops(bs, &bdrv_read_ops);
212 /* QEMUFile timer support.
213 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
216 void timer_put(QEMUFile *f, QEMUTimer *ts)
218 uint64_t expire_time;
220 expire_time = timer_expire_time_ns(ts);
221 qemu_put_be64(f, expire_time);
224 void timer_get(QEMUFile *f, QEMUTimer *ts)
226 uint64_t expire_time;
228 expire_time = qemu_get_be64(f);
229 if (expire_time != -1) {
230 timer_mod_ns(ts, expire_time);
231 } else {
232 timer_del(ts);
237 /* VMState timer support.
238 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
241 static int get_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field)
243 QEMUTimer *v = pv;
244 timer_get(f, v);
245 return 0;
248 static int put_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field,
249 QJSON *vmdesc)
251 QEMUTimer *v = pv;
252 timer_put(f, v);
254 return 0;
257 const VMStateInfo vmstate_info_timer = {
258 .name = "timer",
259 .get = get_timer,
260 .put = put_timer,
264 typedef struct CompatEntry {
265 char idstr[256];
266 int instance_id;
267 } CompatEntry;
269 typedef struct SaveStateEntry {
270 QTAILQ_ENTRY(SaveStateEntry) entry;
271 char idstr[256];
272 int instance_id;
273 int alias_id;
274 int version_id;
275 /* version id read from the stream */
276 int load_version_id;
277 int section_id;
278 /* section id read from the stream */
279 int load_section_id;
280 SaveVMHandlers *ops;
281 const VMStateDescription *vmsd;
282 void *opaque;
283 CompatEntry *compat;
284 int is_ram;
285 } SaveStateEntry;
287 typedef struct SaveState {
288 QTAILQ_HEAD(, SaveStateEntry) handlers;
289 int global_section_id;
290 bool skip_configuration;
291 uint32_t len;
292 const char *name;
293 uint32_t target_page_bits;
294 } SaveState;
296 static SaveState savevm_state = {
297 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
298 .global_section_id = 0,
299 .skip_configuration = false,
302 void savevm_skip_configuration(void)
304 savevm_state.skip_configuration = true;
308 static void configuration_pre_save(void *opaque)
310 SaveState *state = opaque;
311 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
313 state->len = strlen(current_name);
314 state->name = current_name;
315 state->target_page_bits = qemu_target_page_bits();
318 static int configuration_pre_load(void *opaque)
320 SaveState *state = opaque;
322 /* If there is no target-page-bits subsection it means the source
323 * predates the variable-target-page-bits support and is using the
324 * minimum possible value for this CPU.
326 state->target_page_bits = qemu_target_page_bits_min();
327 return 0;
330 static int configuration_post_load(void *opaque, int version_id)
332 SaveState *state = opaque;
333 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
335 if (strncmp(state->name, current_name, state->len) != 0) {
336 error_report("Machine type received is '%.*s' and local is '%s'",
337 (int) state->len, state->name, current_name);
338 return -EINVAL;
341 if (state->target_page_bits != qemu_target_page_bits()) {
342 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
343 state->target_page_bits, qemu_target_page_bits());
344 return -EINVAL;
347 return 0;
350 /* The target-page-bits subsection is present only if the
351 * target page size is not the same as the default (ie the
352 * minimum page size for a variable-page-size guest CPU).
353 * If it is present then it contains the actual target page
354 * bits for the machine, and migration will fail if the
355 * two ends don't agree about it.
357 static bool vmstate_target_page_bits_needed(void *opaque)
359 return qemu_target_page_bits()
360 > qemu_target_page_bits_min();
363 static const VMStateDescription vmstate_target_page_bits = {
364 .name = "configuration/target-page-bits",
365 .version_id = 1,
366 .minimum_version_id = 1,
367 .needed = vmstate_target_page_bits_needed,
368 .fields = (VMStateField[]) {
369 VMSTATE_UINT32(target_page_bits, SaveState),
370 VMSTATE_END_OF_LIST()
374 static const VMStateDescription vmstate_configuration = {
375 .name = "configuration",
376 .version_id = 1,
377 .pre_load = configuration_pre_load,
378 .post_load = configuration_post_load,
379 .pre_save = configuration_pre_save,
380 .fields = (VMStateField[]) {
381 VMSTATE_UINT32(len, SaveState),
382 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
383 VMSTATE_END_OF_LIST()
385 .subsections = (const VMStateDescription*[]) {
386 &vmstate_target_page_bits,
387 NULL
391 static void dump_vmstate_vmsd(FILE *out_file,
392 const VMStateDescription *vmsd, int indent,
393 bool is_subsection);
395 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
396 int indent)
398 fprintf(out_file, "%*s{\n", indent, "");
399 indent += 2;
400 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
401 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
402 field->version_id);
403 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
404 field->field_exists ? "true" : "false");
405 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
406 if (field->vmsd != NULL) {
407 fprintf(out_file, ",\n");
408 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
410 fprintf(out_file, "\n%*s}", indent - 2, "");
413 static void dump_vmstate_vmss(FILE *out_file,
414 const VMStateDescription **subsection,
415 int indent)
417 if (*subsection != NULL) {
418 dump_vmstate_vmsd(out_file, *subsection, indent, true);
422 static void dump_vmstate_vmsd(FILE *out_file,
423 const VMStateDescription *vmsd, int indent,
424 bool is_subsection)
426 if (is_subsection) {
427 fprintf(out_file, "%*s{\n", indent, "");
428 } else {
429 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
431 indent += 2;
432 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
433 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
434 vmsd->version_id);
435 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
436 vmsd->minimum_version_id);
437 if (vmsd->fields != NULL) {
438 const VMStateField *field = vmsd->fields;
439 bool first;
441 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
442 first = true;
443 while (field->name != NULL) {
444 if (field->flags & VMS_MUST_EXIST) {
445 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
446 field++;
447 continue;
449 if (!first) {
450 fprintf(out_file, ",\n");
452 dump_vmstate_vmsf(out_file, field, indent + 2);
453 field++;
454 first = false;
456 fprintf(out_file, "\n%*s]", indent, "");
458 if (vmsd->subsections != NULL) {
459 const VMStateDescription **subsection = vmsd->subsections;
460 bool first;
462 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
463 first = true;
464 while (*subsection != NULL) {
465 if (!first) {
466 fprintf(out_file, ",\n");
468 dump_vmstate_vmss(out_file, subsection, indent + 2);
469 subsection++;
470 first = false;
472 fprintf(out_file, "\n%*s]", indent, "");
474 fprintf(out_file, "\n%*s}", indent - 2, "");
477 static void dump_machine_type(FILE *out_file)
479 MachineClass *mc;
481 mc = MACHINE_GET_CLASS(current_machine);
483 fprintf(out_file, " \"vmschkmachine\": {\n");
484 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
485 fprintf(out_file, " },\n");
488 void dump_vmstate_json_to_file(FILE *out_file)
490 GSList *list, *elt;
491 bool first;
493 fprintf(out_file, "{\n");
494 dump_machine_type(out_file);
496 first = true;
497 list = object_class_get_list(TYPE_DEVICE, true);
498 for (elt = list; elt; elt = elt->next) {
499 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
500 TYPE_DEVICE);
501 const char *name;
502 int indent = 2;
504 if (!dc->vmsd) {
505 continue;
508 if (!first) {
509 fprintf(out_file, ",\n");
511 name = object_class_get_name(OBJECT_CLASS(dc));
512 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
513 indent += 2;
514 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
515 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
516 dc->vmsd->version_id);
517 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
518 dc->vmsd->minimum_version_id);
520 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
522 fprintf(out_file, "\n%*s}", indent - 2, "");
523 first = false;
525 fprintf(out_file, "\n}\n");
526 fclose(out_file);
529 static int calculate_new_instance_id(const char *idstr)
531 SaveStateEntry *se;
532 int instance_id = 0;
534 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
535 if (strcmp(idstr, se->idstr) == 0
536 && instance_id <= se->instance_id) {
537 instance_id = se->instance_id + 1;
540 return instance_id;
543 static int calculate_compat_instance_id(const char *idstr)
545 SaveStateEntry *se;
546 int instance_id = 0;
548 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
549 if (!se->compat) {
550 continue;
553 if (strcmp(idstr, se->compat->idstr) == 0
554 && instance_id <= se->compat->instance_id) {
555 instance_id = se->compat->instance_id + 1;
558 return instance_id;
561 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
563 if (se->vmsd) {
564 return se->vmsd->priority;
566 return MIG_PRI_DEFAULT;
569 static void savevm_state_handler_insert(SaveStateEntry *nse)
571 MigrationPriority priority = save_state_priority(nse);
572 SaveStateEntry *se;
574 assert(priority <= MIG_PRI_MAX);
576 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
577 if (save_state_priority(se) < priority) {
578 break;
582 if (se) {
583 QTAILQ_INSERT_BEFORE(se, nse, entry);
584 } else {
585 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
589 /* TODO: Individual devices generally have very little idea about the rest
590 of the system, so instance_id should be removed/replaced.
591 Meanwhile pass -1 as instance_id if you do not already have a clearly
592 distinguishing id for all instances of your device class. */
593 int register_savevm_live(DeviceState *dev,
594 const char *idstr,
595 int instance_id,
596 int version_id,
597 SaveVMHandlers *ops,
598 void *opaque)
600 SaveStateEntry *se;
602 se = g_new0(SaveStateEntry, 1);
603 se->version_id = version_id;
604 se->section_id = savevm_state.global_section_id++;
605 se->ops = ops;
606 se->opaque = opaque;
607 se->vmsd = NULL;
608 /* if this is a live_savem then set is_ram */
609 if (ops->save_live_setup != NULL) {
610 se->is_ram = 1;
613 if (dev) {
614 char *id = qdev_get_dev_path(dev);
615 if (id) {
616 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
617 sizeof(se->idstr)) {
618 error_report("Path too long for VMState (%s)", id);
619 g_free(id);
620 g_free(se);
622 return -1;
624 g_free(id);
626 se->compat = g_new0(CompatEntry, 1);
627 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
628 se->compat->instance_id = instance_id == -1 ?
629 calculate_compat_instance_id(idstr) : instance_id;
630 instance_id = -1;
633 pstrcat(se->idstr, sizeof(se->idstr), idstr);
635 if (instance_id == -1) {
636 se->instance_id = calculate_new_instance_id(se->idstr);
637 } else {
638 se->instance_id = instance_id;
640 assert(!se->compat || se->instance_id == 0);
641 savevm_state_handler_insert(se);
642 return 0;
645 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
647 SaveStateEntry *se, *new_se;
648 char id[256] = "";
650 if (dev) {
651 char *path = qdev_get_dev_path(dev);
652 if (path) {
653 pstrcpy(id, sizeof(id), path);
654 pstrcat(id, sizeof(id), "/");
655 g_free(path);
658 pstrcat(id, sizeof(id), idstr);
660 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
661 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
662 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
663 g_free(se->compat);
664 g_free(se);
669 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
670 const VMStateDescription *vmsd,
671 void *opaque, int alias_id,
672 int required_for_version,
673 Error **errp)
675 SaveStateEntry *se;
677 /* If this triggers, alias support can be dropped for the vmsd. */
678 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
680 se = g_new0(SaveStateEntry, 1);
681 se->version_id = vmsd->version_id;
682 se->section_id = savevm_state.global_section_id++;
683 se->opaque = opaque;
684 se->vmsd = vmsd;
685 se->alias_id = alias_id;
687 if (dev) {
688 char *id = qdev_get_dev_path(dev);
689 if (id) {
690 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
691 sizeof(se->idstr)) {
692 error_setg(errp, "Path too long for VMState (%s)", id);
693 g_free(id);
694 g_free(se);
696 return -1;
698 g_free(id);
700 se->compat = g_new0(CompatEntry, 1);
701 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
702 se->compat->instance_id = instance_id == -1 ?
703 calculate_compat_instance_id(vmsd->name) : instance_id;
704 instance_id = -1;
707 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
709 if (instance_id == -1) {
710 se->instance_id = calculate_new_instance_id(se->idstr);
711 } else {
712 se->instance_id = instance_id;
714 assert(!se->compat || se->instance_id == 0);
715 savevm_state_handler_insert(se);
716 return 0;
719 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
720 void *opaque)
722 SaveStateEntry *se, *new_se;
724 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
725 if (se->vmsd == vmsd && se->opaque == opaque) {
726 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
727 g_free(se->compat);
728 g_free(se);
733 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
735 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
736 if (!se->vmsd) { /* Old style */
737 return se->ops->load_state(f, se->opaque, se->load_version_id);
739 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
742 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
744 int64_t old_offset, size;
746 old_offset = qemu_ftell_fast(f);
747 se->ops->save_state(f, se->opaque);
748 size = qemu_ftell_fast(f) - old_offset;
750 if (vmdesc) {
751 json_prop_int(vmdesc, "size", size);
752 json_start_array(vmdesc, "fields");
753 json_start_object(vmdesc, NULL);
754 json_prop_str(vmdesc, "name", "data");
755 json_prop_int(vmdesc, "size", size);
756 json_prop_str(vmdesc, "type", "buffer");
757 json_end_object(vmdesc);
758 json_end_array(vmdesc);
762 static void vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
764 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
765 if (!se->vmsd) {
766 vmstate_save_old_style(f, se, vmdesc);
767 return;
769 vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
772 void savevm_skip_section_footers(void)
774 skip_section_footers = true;
778 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
780 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
781 uint8_t section_type)
783 qemu_put_byte(f, section_type);
784 qemu_put_be32(f, se->section_id);
786 if (section_type == QEMU_VM_SECTION_FULL ||
787 section_type == QEMU_VM_SECTION_START) {
788 /* ID string */
789 size_t len = strlen(se->idstr);
790 qemu_put_byte(f, len);
791 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
793 qemu_put_be32(f, se->instance_id);
794 qemu_put_be32(f, se->version_id);
799 * Write a footer onto device sections that catches cases misformatted device
800 * sections.
802 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
804 if (!skip_section_footers) {
805 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
806 qemu_put_be32(f, se->section_id);
811 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
812 * command and associated data.
814 * @f: File to send command on
815 * @command: Command type to send
816 * @len: Length of associated data
817 * @data: Data associated with command.
819 static void qemu_savevm_command_send(QEMUFile *f,
820 enum qemu_vm_cmd command,
821 uint16_t len,
822 uint8_t *data)
824 trace_savevm_command_send(command, len);
825 qemu_put_byte(f, QEMU_VM_COMMAND);
826 qemu_put_be16(f, (uint16_t)command);
827 qemu_put_be16(f, len);
828 qemu_put_buffer(f, data, len);
829 qemu_fflush(f);
832 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
834 uint32_t buf;
836 trace_savevm_send_ping(value);
837 buf = cpu_to_be32(value);
838 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
841 void qemu_savevm_send_open_return_path(QEMUFile *f)
843 trace_savevm_send_open_return_path();
844 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
847 /* We have a buffer of data to send; we don't want that all to be loaded
848 * by the command itself, so the command contains just the length of the
849 * extra buffer that we then send straight after it.
850 * TODO: Must be a better way to organise that
852 * Returns:
853 * 0 on success
854 * -ve on error
856 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
858 uint32_t tmp;
860 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
861 error_report("%s: Unreasonably large packaged state: %zu",
862 __func__, len);
863 return -1;
866 tmp = cpu_to_be32(len);
868 trace_qemu_savevm_send_packaged();
869 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
871 qemu_put_buffer(f, buf, len);
873 return 0;
876 /* Send prior to any postcopy transfer */
877 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
879 uint64_t tmp[2];
880 tmp[0] = cpu_to_be64(ram_pagesize_summary());
881 tmp[1] = cpu_to_be64(qemu_target_page_size());
883 trace_qemu_savevm_send_postcopy_advise();
884 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 16, (uint8_t *)tmp);
887 /* Sent prior to starting the destination running in postcopy, discard pages
888 * that have already been sent but redirtied on the source.
889 * CMD_POSTCOPY_RAM_DISCARD consist of:
890 * byte version (0)
891 * byte Length of name field (not including 0)
892 * n x byte RAM block name
893 * byte 0 terminator (just for safety)
894 * n x Byte ranges within the named RAMBlock
895 * be64 Start of the range
896 * be64 Length
898 * name: RAMBlock name that these entries are part of
899 * len: Number of page entries
900 * start_list: 'len' addresses
901 * length_list: 'len' addresses
904 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
905 uint16_t len,
906 uint64_t *start_list,
907 uint64_t *length_list)
909 uint8_t *buf;
910 uint16_t tmplen;
911 uint16_t t;
912 size_t name_len = strlen(name);
914 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
915 assert(name_len < 256);
916 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
917 buf[0] = postcopy_ram_discard_version;
918 buf[1] = name_len;
919 memcpy(buf + 2, name, name_len);
920 tmplen = 2 + name_len;
921 buf[tmplen++] = '\0';
923 for (t = 0; t < len; t++) {
924 stq_be_p(buf + tmplen, start_list[t]);
925 tmplen += 8;
926 stq_be_p(buf + tmplen, length_list[t]);
927 tmplen += 8;
929 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
930 g_free(buf);
933 /* Get the destination into a state where it can receive postcopy data. */
934 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
936 trace_savevm_send_postcopy_listen();
937 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
940 /* Kick the destination into running */
941 void qemu_savevm_send_postcopy_run(QEMUFile *f)
943 trace_savevm_send_postcopy_run();
944 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
947 bool qemu_savevm_state_blocked(Error **errp)
949 SaveStateEntry *se;
951 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
952 if (se->vmsd && se->vmsd->unmigratable) {
953 error_setg(errp, "State blocked by non-migratable device '%s'",
954 se->idstr);
955 return true;
958 return false;
961 static bool enforce_config_section(void)
963 MachineState *machine = MACHINE(qdev_get_machine());
964 return machine->enforce_config_section;
967 void qemu_savevm_state_header(QEMUFile *f)
969 trace_savevm_state_header();
970 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
971 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
973 if (!savevm_state.skip_configuration || enforce_config_section()) {
974 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
975 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
980 void qemu_savevm_state_begin(QEMUFile *f)
982 SaveStateEntry *se;
983 int ret;
985 trace_savevm_state_begin();
986 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
987 if (!se->ops || !se->ops->save_live_setup) {
988 continue;
990 if (se->ops && se->ops->is_active) {
991 if (!se->ops->is_active(se->opaque)) {
992 continue;
995 save_section_header(f, se, QEMU_VM_SECTION_START);
997 ret = se->ops->save_live_setup(f, se->opaque);
998 save_section_footer(f, se);
999 if (ret < 0) {
1000 qemu_file_set_error(f, ret);
1001 break;
1007 * this function has three return values:
1008 * negative: there was one error, and we have -errno.
1009 * 0 : We haven't finished, caller have to go again
1010 * 1 : We have finished, we can go to complete phase
1012 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1014 SaveStateEntry *se;
1015 int ret = 1;
1017 trace_savevm_state_iterate();
1018 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1019 if (!se->ops || !se->ops->save_live_iterate) {
1020 continue;
1022 if (se->ops && se->ops->is_active) {
1023 if (!se->ops->is_active(se->opaque)) {
1024 continue;
1028 * In the postcopy phase, any device that doesn't know how to
1029 * do postcopy should have saved it's state in the _complete
1030 * call that's already run, it might get confused if we call
1031 * iterate afterwards.
1033 if (postcopy && !se->ops->save_live_complete_postcopy) {
1034 continue;
1036 if (qemu_file_rate_limit(f)) {
1037 return 0;
1039 trace_savevm_section_start(se->idstr, se->section_id);
1041 save_section_header(f, se, QEMU_VM_SECTION_PART);
1043 ret = se->ops->save_live_iterate(f, se->opaque);
1044 trace_savevm_section_end(se->idstr, se->section_id, ret);
1045 save_section_footer(f, se);
1047 if (ret < 0) {
1048 qemu_file_set_error(f, ret);
1050 if (ret <= 0) {
1051 /* Do not proceed to the next vmstate before this one reported
1052 completion of the current stage. This serializes the migration
1053 and reduces the probability that a faster changing state is
1054 synchronized over and over again. */
1055 break;
1058 return ret;
1061 static bool should_send_vmdesc(void)
1063 MachineState *machine = MACHINE(qdev_get_machine());
1064 bool in_postcopy = migration_in_postcopy();
1065 return !machine->suppress_vmdesc && !in_postcopy;
1069 * Calls the save_live_complete_postcopy methods
1070 * causing the last few pages to be sent immediately and doing any associated
1071 * cleanup.
1072 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1073 * all the other devices, but that happens at the point we switch to postcopy.
1075 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1077 SaveStateEntry *se;
1078 int ret;
1080 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1081 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1082 continue;
1084 if (se->ops && se->ops->is_active) {
1085 if (!se->ops->is_active(se->opaque)) {
1086 continue;
1089 trace_savevm_section_start(se->idstr, se->section_id);
1090 /* Section type */
1091 qemu_put_byte(f, QEMU_VM_SECTION_END);
1092 qemu_put_be32(f, se->section_id);
1094 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1095 trace_savevm_section_end(se->idstr, se->section_id, ret);
1096 save_section_footer(f, se);
1097 if (ret < 0) {
1098 qemu_file_set_error(f, ret);
1099 return;
1103 qemu_put_byte(f, QEMU_VM_EOF);
1104 qemu_fflush(f);
1107 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1108 bool inactivate_disks)
1110 QJSON *vmdesc;
1111 int vmdesc_len;
1112 SaveStateEntry *se;
1113 int ret;
1114 bool in_postcopy = migration_in_postcopy();
1116 trace_savevm_state_complete_precopy();
1118 cpu_synchronize_all_states();
1120 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1121 if (!se->ops ||
1122 (in_postcopy && se->ops->save_live_complete_postcopy) ||
1123 (in_postcopy && !iterable_only) ||
1124 !se->ops->save_live_complete_precopy) {
1125 continue;
1128 if (se->ops && se->ops->is_active) {
1129 if (!se->ops->is_active(se->opaque)) {
1130 continue;
1133 trace_savevm_section_start(se->idstr, se->section_id);
1135 save_section_header(f, se, QEMU_VM_SECTION_END);
1137 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1138 trace_savevm_section_end(se->idstr, se->section_id, ret);
1139 save_section_footer(f, se);
1140 if (ret < 0) {
1141 qemu_file_set_error(f, ret);
1142 return -1;
1146 if (iterable_only) {
1147 return 0;
1150 vmdesc = qjson_new();
1151 json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1152 json_start_array(vmdesc, "devices");
1153 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1155 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1156 continue;
1158 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1159 trace_savevm_section_skip(se->idstr, se->section_id);
1160 continue;
1163 trace_savevm_section_start(se->idstr, se->section_id);
1165 json_start_object(vmdesc, NULL);
1166 json_prop_str(vmdesc, "name", se->idstr);
1167 json_prop_int(vmdesc, "instance_id", se->instance_id);
1169 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1170 vmstate_save(f, se, vmdesc);
1171 trace_savevm_section_end(se->idstr, se->section_id, 0);
1172 save_section_footer(f, se);
1174 json_end_object(vmdesc);
1177 if (inactivate_disks) {
1178 /* Inactivate before sending QEMU_VM_EOF so that the
1179 * bdrv_invalidate_cache_all() on the other end won't fail. */
1180 ret = bdrv_inactivate_all();
1181 if (ret) {
1182 qemu_file_set_error(f, ret);
1183 return ret;
1186 if (!in_postcopy) {
1187 /* Postcopy stream will still be going */
1188 qemu_put_byte(f, QEMU_VM_EOF);
1191 json_end_array(vmdesc);
1192 qjson_finish(vmdesc);
1193 vmdesc_len = strlen(qjson_get_str(vmdesc));
1195 if (should_send_vmdesc()) {
1196 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1197 qemu_put_be32(f, vmdesc_len);
1198 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1200 qjson_destroy(vmdesc);
1202 qemu_fflush(f);
1203 return 0;
1206 /* Give an estimate of the amount left to be transferred,
1207 * the result is split into the amount for units that can and
1208 * for units that can't do postcopy.
1210 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1211 uint64_t *res_non_postcopiable,
1212 uint64_t *res_postcopiable)
1214 SaveStateEntry *se;
1216 *res_non_postcopiable = 0;
1217 *res_postcopiable = 0;
1220 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1221 if (!se->ops || !se->ops->save_live_pending) {
1222 continue;
1224 if (se->ops && se->ops->is_active) {
1225 if (!se->ops->is_active(se->opaque)) {
1226 continue;
1229 se->ops->save_live_pending(f, se->opaque, threshold_size,
1230 res_non_postcopiable, res_postcopiable);
1234 void qemu_savevm_state_cleanup(void)
1236 SaveStateEntry *se;
1238 trace_savevm_state_cleanup();
1239 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1240 if (se->ops && se->ops->cleanup) {
1241 se->ops->cleanup(se->opaque);
1246 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1248 int ret;
1249 MigrationState *ms = migrate_init();
1250 MigrationStatus status;
1251 ms->to_dst_file = f;
1253 if (migration_is_blocked(errp)) {
1254 ret = -EINVAL;
1255 goto done;
1258 if (migrate_use_block()) {
1259 error_setg(errp, "Block migration and snapshots are incompatible");
1260 ret = -EINVAL;
1261 goto done;
1264 qemu_mutex_unlock_iothread();
1265 qemu_savevm_state_header(f);
1266 qemu_savevm_state_begin(f);
1267 qemu_mutex_lock_iothread();
1269 while (qemu_file_get_error(f) == 0) {
1270 if (qemu_savevm_state_iterate(f, false) > 0) {
1271 break;
1275 ret = qemu_file_get_error(f);
1276 if (ret == 0) {
1277 qemu_savevm_state_complete_precopy(f, false, false);
1278 ret = qemu_file_get_error(f);
1280 qemu_savevm_state_cleanup();
1281 if (ret != 0) {
1282 error_setg_errno(errp, -ret, "Error while writing VM state");
1285 done:
1286 if (ret != 0) {
1287 status = MIGRATION_STATUS_FAILED;
1288 } else {
1289 status = MIGRATION_STATUS_COMPLETED;
1291 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1293 /* f is outer parameter, it should not stay in global migration state after
1294 * this function finished */
1295 ms->to_dst_file = NULL;
1297 return ret;
1300 static int qemu_save_device_state(QEMUFile *f)
1302 SaveStateEntry *se;
1304 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1305 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1307 cpu_synchronize_all_states();
1309 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1310 if (se->is_ram) {
1311 continue;
1313 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1314 continue;
1316 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1317 continue;
1320 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1322 vmstate_save(f, se, NULL);
1324 save_section_footer(f, se);
1327 qemu_put_byte(f, QEMU_VM_EOF);
1329 return qemu_file_get_error(f);
1332 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1334 SaveStateEntry *se;
1336 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1337 if (!strcmp(se->idstr, idstr) &&
1338 (instance_id == se->instance_id ||
1339 instance_id == se->alias_id))
1340 return se;
1341 /* Migrating from an older version? */
1342 if (strstr(se->idstr, idstr) && se->compat) {
1343 if (!strcmp(se->compat->idstr, idstr) &&
1344 (instance_id == se->compat->instance_id ||
1345 instance_id == se->alias_id))
1346 return se;
1349 return NULL;
1352 enum LoadVMExitCodes {
1353 /* Allow a command to quit all layers of nested loadvm loops */
1354 LOADVM_QUIT = 1,
1357 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
1359 /* ------ incoming postcopy messages ------ */
1360 /* 'advise' arrives before any transfers just to tell us that a postcopy
1361 * *might* happen - it might be skipped if precopy transferred everything
1362 * quickly.
1364 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)
1366 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1367 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1369 trace_loadvm_postcopy_handle_advise();
1370 if (ps != POSTCOPY_INCOMING_NONE) {
1371 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1372 return -1;
1375 if (!postcopy_ram_supported_by_host()) {
1376 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1377 return -1;
1380 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1381 local_pagesize_summary = ram_pagesize_summary();
1383 if (remote_pagesize_summary != local_pagesize_summary) {
1385 * This detects two potential causes of mismatch:
1386 * a) A mismatch in host page sizes
1387 * Some combinations of mismatch are probably possible but it gets
1388 * a bit more complicated. In particular we need to place whole
1389 * host pages on the dest at once, and we need to ensure that we
1390 * handle dirtying to make sure we never end up sending part of
1391 * a hostpage on it's own.
1392 * b) The use of different huge page sizes on source/destination
1393 * a more fine grain test is performed during RAM block migration
1394 * but this test here causes a nice early clear failure, and
1395 * also fails when passed to an older qemu that doesn't
1396 * do huge pages.
1398 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1399 " d=%" PRIx64 ")",
1400 remote_pagesize_summary, local_pagesize_summary);
1401 return -1;
1404 remote_tps = qemu_get_be64(mis->from_src_file);
1405 if (remote_tps != qemu_target_page_size()) {
1407 * Again, some differences could be dealt with, but for now keep it
1408 * simple.
1410 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1411 (int)remote_tps, qemu_target_page_size());
1412 return -1;
1415 if (ram_postcopy_incoming_init(mis)) {
1416 return -1;
1419 postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1421 return 0;
1424 /* After postcopy we will be told to throw some pages away since they're
1425 * dirty and will have to be demand fetched. Must happen before CPU is
1426 * started.
1427 * There can be 0..many of these messages, each encoding multiple pages.
1429 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1430 uint16_t len)
1432 int tmp;
1433 char ramid[256];
1434 PostcopyState ps = postcopy_state_get();
1436 trace_loadvm_postcopy_ram_handle_discard();
1438 switch (ps) {
1439 case POSTCOPY_INCOMING_ADVISE:
1440 /* 1st discard */
1441 tmp = postcopy_ram_prepare_discard(mis);
1442 if (tmp) {
1443 return tmp;
1445 break;
1447 case POSTCOPY_INCOMING_DISCARD:
1448 /* Expected state */
1449 break;
1451 default:
1452 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1453 ps);
1454 return -1;
1456 /* We're expecting a
1457 * Version (0)
1458 * a RAM ID string (length byte, name, 0 term)
1459 * then at least 1 16 byte chunk
1461 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1462 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1463 return -1;
1466 tmp = qemu_get_byte(mis->from_src_file);
1467 if (tmp != postcopy_ram_discard_version) {
1468 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1469 return -1;
1472 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1473 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1474 return -1;
1476 tmp = qemu_get_byte(mis->from_src_file);
1477 if (tmp != 0) {
1478 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1479 return -1;
1482 len -= 3 + strlen(ramid);
1483 if (len % 16) {
1484 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1485 return -1;
1487 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1488 while (len) {
1489 uint64_t start_addr, block_length;
1490 start_addr = qemu_get_be64(mis->from_src_file);
1491 block_length = qemu_get_be64(mis->from_src_file);
1493 len -= 16;
1494 int ret = ram_discard_range(ramid, start_addr, block_length);
1495 if (ret) {
1496 return ret;
1499 trace_loadvm_postcopy_ram_handle_discard_end();
1501 return 0;
1505 * Triggered by a postcopy_listen command; this thread takes over reading
1506 * the input stream, leaving the main thread free to carry on loading the rest
1507 * of the device state (from RAM).
1508 * (TODO:This could do with being in a postcopy file - but there again it's
1509 * just another input loop, not that postcopy specific)
1511 static void *postcopy_ram_listen_thread(void *opaque)
1513 QEMUFile *f = opaque;
1514 MigrationIncomingState *mis = migration_incoming_get_current();
1515 int load_res;
1517 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1518 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1519 qemu_sem_post(&mis->listen_thread_sem);
1520 trace_postcopy_ram_listen_thread_start();
1523 * Because we're a thread and not a coroutine we can't yield
1524 * in qemu_file, and thus we must be blocking now.
1526 qemu_file_set_blocking(f, true);
1527 load_res = qemu_loadvm_state_main(f, mis);
1528 /* And non-blocking again so we don't block in any cleanup */
1529 qemu_file_set_blocking(f, false);
1531 trace_postcopy_ram_listen_thread_exit();
1532 if (load_res < 0) {
1533 error_report("%s: loadvm failed: %d", __func__, load_res);
1534 qemu_file_set_error(f, load_res);
1535 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1536 MIGRATION_STATUS_FAILED);
1537 } else {
1539 * This looks good, but it's possible that the device loading in the
1540 * main thread hasn't finished yet, and so we might not be in 'RUN'
1541 * state yet; wait for the end of the main thread.
1543 qemu_event_wait(&mis->main_thread_load_event);
1545 postcopy_ram_incoming_cleanup(mis);
1547 if (load_res < 0) {
1549 * If something went wrong then we have a bad state so exit;
1550 * depending how far we got it might be possible at this point
1551 * to leave the guest running and fire MCEs for pages that never
1552 * arrived as a desperate recovery step.
1554 exit(EXIT_FAILURE);
1557 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1558 MIGRATION_STATUS_COMPLETED);
1560 * If everything has worked fine, then the main thread has waited
1561 * for us to start, and we're the last use of the mis.
1562 * (If something broke then qemu will have to exit anyway since it's
1563 * got a bad migration state).
1565 migration_incoming_state_destroy();
1568 return NULL;
1571 /* After this message we must be able to immediately receive postcopy data */
1572 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1574 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1575 trace_loadvm_postcopy_handle_listen();
1576 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1577 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1578 return -1;
1580 if (ps == POSTCOPY_INCOMING_ADVISE) {
1582 * A rare case, we entered listen without having to do any discards,
1583 * so do the setup that's normally done at the time of the 1st discard.
1585 postcopy_ram_prepare_discard(mis);
1589 * Sensitise RAM - can now generate requests for blocks that don't exist
1590 * However, at this point the CPU shouldn't be running, and the IO
1591 * shouldn't be doing anything yet so don't actually expect requests
1593 if (postcopy_ram_enable_notify(mis)) {
1594 return -1;
1597 if (mis->have_listen_thread) {
1598 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1599 return -1;
1602 mis->have_listen_thread = true;
1603 /* Start up the listening thread and wait for it to signal ready */
1604 qemu_sem_init(&mis->listen_thread_sem, 0);
1605 qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1606 postcopy_ram_listen_thread, mis->from_src_file,
1607 QEMU_THREAD_DETACHED);
1608 qemu_sem_wait(&mis->listen_thread_sem);
1609 qemu_sem_destroy(&mis->listen_thread_sem);
1611 return 0;
1615 typedef struct {
1616 QEMUBH *bh;
1617 } HandleRunBhData;
1619 static void loadvm_postcopy_handle_run_bh(void *opaque)
1621 Error *local_err = NULL;
1622 HandleRunBhData *data = opaque;
1624 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1625 * in migration.c
1627 cpu_synchronize_all_post_init();
1629 qemu_announce_self();
1631 /* Make sure all file formats flush their mutable metadata.
1632 * If we get an error here, just don't restart the VM yet. */
1633 bdrv_invalidate_cache_all(&local_err);
1634 if (local_err) {
1635 error_report_err(local_err);
1636 local_err = NULL;
1637 autostart = false;
1640 trace_loadvm_postcopy_handle_run_cpu_sync();
1641 cpu_synchronize_all_post_init();
1643 trace_loadvm_postcopy_handle_run_vmstart();
1645 if (autostart) {
1646 /* Hold onto your hats, starting the CPU */
1647 vm_start();
1648 } else {
1649 /* leave it paused and let management decide when to start the CPU */
1650 runstate_set(RUN_STATE_PAUSED);
1653 qemu_bh_delete(data->bh);
1654 g_free(data);
1657 /* After all discards we can start running and asking for pages */
1658 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1660 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1661 HandleRunBhData *data;
1663 trace_loadvm_postcopy_handle_run();
1664 if (ps != POSTCOPY_INCOMING_LISTENING) {
1665 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1666 return -1;
1669 data = g_new(HandleRunBhData, 1);
1670 data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1671 qemu_bh_schedule(data->bh);
1673 /* We need to finish reading the stream from the package
1674 * and also stop reading anything more from the stream that loaded the
1675 * package (since it's now being read by the listener thread).
1676 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1678 return LOADVM_QUIT;
1682 * Immediately following this command is a blob of data containing an embedded
1683 * chunk of migration stream; read it and load it.
1685 * @mis: Incoming state
1686 * @length: Length of packaged data to read
1688 * Returns: Negative values on error
1691 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1693 int ret;
1694 size_t length;
1695 QIOChannelBuffer *bioc;
1697 length = qemu_get_be32(mis->from_src_file);
1698 trace_loadvm_handle_cmd_packaged(length);
1700 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1701 error_report("Unreasonably large packaged state: %zu", length);
1702 return -1;
1705 bioc = qio_channel_buffer_new(length);
1706 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1707 ret = qemu_get_buffer(mis->from_src_file,
1708 bioc->data,
1709 length);
1710 if (ret != length) {
1711 object_unref(OBJECT(bioc));
1712 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1713 ret, length);
1714 return (ret < 0) ? ret : -EAGAIN;
1716 bioc->usage += length;
1717 trace_loadvm_handle_cmd_packaged_received(ret);
1719 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1721 ret = qemu_loadvm_state_main(packf, mis);
1722 trace_loadvm_handle_cmd_packaged_main(ret);
1723 qemu_fclose(packf);
1724 object_unref(OBJECT(bioc));
1726 return ret;
1730 * Process an incoming 'QEMU_VM_COMMAND'
1731 * 0 just a normal return
1732 * LOADVM_QUIT All good, but exit the loop
1733 * <0 Error
1735 static int loadvm_process_command(QEMUFile *f)
1737 MigrationIncomingState *mis = migration_incoming_get_current();
1738 uint16_t cmd;
1739 uint16_t len;
1740 uint32_t tmp32;
1742 cmd = qemu_get_be16(f);
1743 len = qemu_get_be16(f);
1745 trace_loadvm_process_command(cmd, len);
1746 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
1747 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
1748 return -EINVAL;
1751 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
1752 error_report("%s received with bad length - expecting %zu, got %d",
1753 mig_cmd_args[cmd].name,
1754 (size_t)mig_cmd_args[cmd].len, len);
1755 return -ERANGE;
1758 switch (cmd) {
1759 case MIG_CMD_OPEN_RETURN_PATH:
1760 if (mis->to_src_file) {
1761 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1762 /* Not really a problem, so don't give up */
1763 return 0;
1765 mis->to_src_file = qemu_file_get_return_path(f);
1766 if (!mis->to_src_file) {
1767 error_report("CMD_OPEN_RETURN_PATH failed");
1768 return -1;
1770 break;
1772 case MIG_CMD_PING:
1773 tmp32 = qemu_get_be32(f);
1774 trace_loadvm_process_command_ping(tmp32);
1775 if (!mis->to_src_file) {
1776 error_report("CMD_PING (0x%x) received with no return path",
1777 tmp32);
1778 return -1;
1780 migrate_send_rp_pong(mis, tmp32);
1781 break;
1783 case MIG_CMD_PACKAGED:
1784 return loadvm_handle_cmd_packaged(mis);
1786 case MIG_CMD_POSTCOPY_ADVISE:
1787 return loadvm_postcopy_handle_advise(mis);
1789 case MIG_CMD_POSTCOPY_LISTEN:
1790 return loadvm_postcopy_handle_listen(mis);
1792 case MIG_CMD_POSTCOPY_RUN:
1793 return loadvm_postcopy_handle_run(mis);
1795 case MIG_CMD_POSTCOPY_RAM_DISCARD:
1796 return loadvm_postcopy_ram_handle_discard(mis, len);
1799 return 0;
1803 * Read a footer off the wire and check that it matches the expected section
1805 * Returns: true if the footer was good
1806 * false if there is a problem (and calls error_report to say why)
1808 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
1810 uint8_t read_mark;
1811 uint32_t read_section_id;
1813 if (skip_section_footers) {
1814 /* No footer to check */
1815 return true;
1818 read_mark = qemu_get_byte(f);
1820 if (read_mark != QEMU_VM_SECTION_FOOTER) {
1821 error_report("Missing section footer for %s", se->idstr);
1822 return false;
1825 read_section_id = qemu_get_be32(f);
1826 if (read_section_id != se->load_section_id) {
1827 error_report("Mismatched section id in footer for %s -"
1828 " read 0x%x expected 0x%x",
1829 se->idstr, read_section_id, se->load_section_id);
1830 return false;
1833 /* All good */
1834 return true;
1837 static int
1838 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
1840 uint32_t instance_id, version_id, section_id;
1841 SaveStateEntry *se;
1842 char idstr[256];
1843 int ret;
1845 /* Read section start */
1846 section_id = qemu_get_be32(f);
1847 if (!qemu_get_counted_string(f, idstr)) {
1848 error_report("Unable to read ID string for section %u",
1849 section_id);
1850 return -EINVAL;
1852 instance_id = qemu_get_be32(f);
1853 version_id = qemu_get_be32(f);
1855 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
1856 instance_id, version_id);
1857 /* Find savevm section */
1858 se = find_se(idstr, instance_id);
1859 if (se == NULL) {
1860 error_report("Unknown savevm section or instance '%s' %d",
1861 idstr, instance_id);
1862 return -EINVAL;
1865 /* Validate version */
1866 if (version_id > se->version_id) {
1867 error_report("savevm: unsupported version %d for '%s' v%d",
1868 version_id, idstr, se->version_id);
1869 return -EINVAL;
1871 se->load_version_id = version_id;
1872 se->load_section_id = section_id;
1874 /* Validate if it is a device's state */
1875 if (xen_enabled() && se->is_ram) {
1876 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
1877 return -EINVAL;
1880 ret = vmstate_load(f, se);
1881 if (ret < 0) {
1882 error_report("error while loading state for instance 0x%x of"
1883 " device '%s'", instance_id, idstr);
1884 return ret;
1886 if (!check_section_footer(f, se)) {
1887 return -EINVAL;
1890 return 0;
1893 static int
1894 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
1896 uint32_t section_id;
1897 SaveStateEntry *se;
1898 int ret;
1900 section_id = qemu_get_be32(f);
1902 trace_qemu_loadvm_state_section_partend(section_id);
1903 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1904 if (se->load_section_id == section_id) {
1905 break;
1908 if (se == NULL) {
1909 error_report("Unknown savevm section %d", section_id);
1910 return -EINVAL;
1913 ret = vmstate_load(f, se);
1914 if (ret < 0) {
1915 error_report("error while loading state section id %d(%s)",
1916 section_id, se->idstr);
1917 return ret;
1919 if (!check_section_footer(f, se)) {
1920 return -EINVAL;
1923 return 0;
1926 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
1928 uint8_t section_type;
1929 int ret = 0;
1931 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
1932 ret = 0;
1933 trace_qemu_loadvm_state_section(section_type);
1934 switch (section_type) {
1935 case QEMU_VM_SECTION_START:
1936 case QEMU_VM_SECTION_FULL:
1937 ret = qemu_loadvm_section_start_full(f, mis);
1938 if (ret < 0) {
1939 goto out;
1941 break;
1942 case QEMU_VM_SECTION_PART:
1943 case QEMU_VM_SECTION_END:
1944 ret = qemu_loadvm_section_part_end(f, mis);
1945 if (ret < 0) {
1946 goto out;
1948 break;
1949 case QEMU_VM_COMMAND:
1950 ret = loadvm_process_command(f);
1951 trace_qemu_loadvm_state_section_command(ret);
1952 if ((ret < 0) || (ret & LOADVM_QUIT)) {
1953 goto out;
1955 break;
1956 default:
1957 error_report("Unknown savevm section type %d", section_type);
1958 ret = -EINVAL;
1959 goto out;
1963 out:
1964 if (ret < 0) {
1965 qemu_file_set_error(f, ret);
1967 return ret;
1970 int qemu_loadvm_state(QEMUFile *f)
1972 MigrationIncomingState *mis = migration_incoming_get_current();
1973 Error *local_err = NULL;
1974 unsigned int v;
1975 int ret;
1977 if (qemu_savevm_state_blocked(&local_err)) {
1978 error_report_err(local_err);
1979 return -EINVAL;
1982 v = qemu_get_be32(f);
1983 if (v != QEMU_VM_FILE_MAGIC) {
1984 error_report("Not a migration stream");
1985 return -EINVAL;
1988 v = qemu_get_be32(f);
1989 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
1990 error_report("SaveVM v2 format is obsolete and don't work anymore");
1991 return -ENOTSUP;
1993 if (v != QEMU_VM_FILE_VERSION) {
1994 error_report("Unsupported migration stream version");
1995 return -ENOTSUP;
1998 if (!savevm_state.skip_configuration || enforce_config_section()) {
1999 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2000 error_report("Configuration section missing");
2001 return -EINVAL;
2003 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2005 if (ret) {
2006 return ret;
2010 cpu_synchronize_all_pre_loadvm();
2012 ret = qemu_loadvm_state_main(f, mis);
2013 qemu_event_set(&mis->main_thread_load_event);
2015 trace_qemu_loadvm_state_post_main(ret);
2017 if (mis->have_listen_thread) {
2018 /* Listen thread still going, can't clean up yet */
2019 return ret;
2022 if (ret == 0) {
2023 ret = qemu_file_get_error(f);
2027 * Try to read in the VMDESC section as well, so that dumping tools that
2028 * intercept our migration stream have the chance to see it.
2031 /* We've got to be careful; if we don't read the data and just shut the fd
2032 * then the sender can error if we close while it's still sending.
2033 * We also mustn't read data that isn't there; some transports (RDMA)
2034 * will stall waiting for that data when the source has already closed.
2036 if (ret == 0 && should_send_vmdesc()) {
2037 uint8_t *buf;
2038 uint32_t size;
2039 uint8_t section_type = qemu_get_byte(f);
2041 if (section_type != QEMU_VM_VMDESCRIPTION) {
2042 error_report("Expected vmdescription section, but got %d",
2043 section_type);
2045 * It doesn't seem worth failing at this point since
2046 * we apparently have an otherwise valid VM state
2048 } else {
2049 buf = g_malloc(0x1000);
2050 size = qemu_get_be32(f);
2052 while (size > 0) {
2053 uint32_t read_chunk = MIN(size, 0x1000);
2054 qemu_get_buffer(f, buf, read_chunk);
2055 size -= read_chunk;
2057 g_free(buf);
2061 cpu_synchronize_all_post_init();
2063 return ret;
2066 int save_snapshot(const char *name, Error **errp)
2068 BlockDriverState *bs, *bs1;
2069 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2070 int ret = -1;
2071 QEMUFile *f;
2072 int saved_vm_running;
2073 uint64_t vm_state_size;
2074 qemu_timeval tv;
2075 struct tm tm;
2076 AioContext *aio_context;
2078 if (!bdrv_all_can_snapshot(&bs)) {
2079 error_setg(errp, "Device '%s' is writable but does not support "
2080 "snapshots", bdrv_get_device_name(bs));
2081 return ret;
2084 /* Delete old snapshots of the same name */
2085 if (name) {
2086 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2087 if (ret < 0) {
2088 error_prepend(errp, "Error while deleting snapshot on device "
2089 "'%s': ", bdrv_get_device_name(bs1));
2090 return ret;
2094 bs = bdrv_all_find_vmstate_bs();
2095 if (bs == NULL) {
2096 error_setg(errp, "No block device can accept snapshots");
2097 return ret;
2099 aio_context = bdrv_get_aio_context(bs);
2101 saved_vm_running = runstate_is_running();
2103 ret = global_state_store();
2104 if (ret) {
2105 error_setg(errp, "Error saving global state");
2106 return ret;
2108 vm_stop(RUN_STATE_SAVE_VM);
2110 bdrv_drain_all_begin();
2112 aio_context_acquire(aio_context);
2114 memset(sn, 0, sizeof(*sn));
2116 /* fill auxiliary fields */
2117 qemu_gettimeofday(&tv);
2118 sn->date_sec = tv.tv_sec;
2119 sn->date_nsec = tv.tv_usec * 1000;
2120 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2122 if (name) {
2123 ret = bdrv_snapshot_find(bs, old_sn, name);
2124 if (ret >= 0) {
2125 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2126 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2127 } else {
2128 pstrcpy(sn->name, sizeof(sn->name), name);
2130 } else {
2131 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2132 localtime_r((const time_t *)&tv.tv_sec, &tm);
2133 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2136 /* save the VM state */
2137 f = qemu_fopen_bdrv(bs, 1);
2138 if (!f) {
2139 error_setg(errp, "Could not open VM state file");
2140 goto the_end;
2142 ret = qemu_savevm_state(f, errp);
2143 vm_state_size = qemu_ftell(f);
2144 qemu_fclose(f);
2145 if (ret < 0) {
2146 goto the_end;
2149 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2150 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2151 * it only releases the lock once. Therefore synchronous I/O will deadlock
2152 * unless we release the AioContext before bdrv_all_create_snapshot().
2154 aio_context_release(aio_context);
2155 aio_context = NULL;
2157 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2158 if (ret < 0) {
2159 error_setg(errp, "Error while creating snapshot on '%s'",
2160 bdrv_get_device_name(bs));
2161 goto the_end;
2164 ret = 0;
2166 the_end:
2167 if (aio_context) {
2168 aio_context_release(aio_context);
2171 bdrv_drain_all_end();
2173 if (saved_vm_running) {
2174 vm_start();
2176 return ret;
2179 void qmp_xen_save_devices_state(const char *filename, Error **errp)
2181 QEMUFile *f;
2182 QIOChannelFile *ioc;
2183 int saved_vm_running;
2184 int ret;
2186 saved_vm_running = runstate_is_running();
2187 vm_stop(RUN_STATE_SAVE_VM);
2188 global_state_store_running();
2190 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2191 if (!ioc) {
2192 goto the_end;
2194 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2195 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2196 ret = qemu_save_device_state(f);
2197 qemu_fclose(f);
2198 if (ret < 0) {
2199 error_setg(errp, QERR_IO_ERROR);
2202 the_end:
2203 if (saved_vm_running) {
2204 vm_start();
2208 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2210 QEMUFile *f;
2211 QIOChannelFile *ioc;
2212 int ret;
2214 /* Guest must be paused before loading the device state; the RAM state
2215 * will already have been loaded by xc
2217 if (runstate_is_running()) {
2218 error_setg(errp, "Cannot update device state while vm is running");
2219 return;
2221 vm_stop(RUN_STATE_RESTORE_VM);
2223 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2224 if (!ioc) {
2225 return;
2227 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2228 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2230 ret = qemu_loadvm_state(f);
2231 qemu_fclose(f);
2232 if (ret < 0) {
2233 error_setg(errp, QERR_IO_ERROR);
2235 migration_incoming_state_destroy();
2238 int load_snapshot(const char *name, Error **errp)
2240 BlockDriverState *bs, *bs_vm_state;
2241 QEMUSnapshotInfo sn;
2242 QEMUFile *f;
2243 int ret;
2244 AioContext *aio_context;
2245 MigrationIncomingState *mis = migration_incoming_get_current();
2247 if (!bdrv_all_can_snapshot(&bs)) {
2248 error_setg(errp,
2249 "Device '%s' is writable but does not support snapshots",
2250 bdrv_get_device_name(bs));
2251 return -ENOTSUP;
2253 ret = bdrv_all_find_snapshot(name, &bs);
2254 if (ret < 0) {
2255 error_setg(errp,
2256 "Device '%s' does not have the requested snapshot '%s'",
2257 bdrv_get_device_name(bs), name);
2258 return ret;
2261 bs_vm_state = bdrv_all_find_vmstate_bs();
2262 if (!bs_vm_state) {
2263 error_setg(errp, "No block device supports snapshots");
2264 return -ENOTSUP;
2266 aio_context = bdrv_get_aio_context(bs_vm_state);
2268 /* Don't even try to load empty VM states */
2269 aio_context_acquire(aio_context);
2270 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2271 aio_context_release(aio_context);
2272 if (ret < 0) {
2273 return ret;
2274 } else if (sn.vm_state_size == 0) {
2275 error_setg(errp, "This is a disk-only snapshot. Revert to it "
2276 " offline using qemu-img");
2277 return -EINVAL;
2280 /* Flush all IO requests so they don't interfere with the new state. */
2281 bdrv_drain_all_begin();
2283 ret = bdrv_all_goto_snapshot(name, &bs);
2284 if (ret < 0) {
2285 error_setg(errp, "Error %d while activating snapshot '%s' on '%s'",
2286 ret, name, bdrv_get_device_name(bs));
2287 goto err_drain;
2290 /* restore the VM state */
2291 f = qemu_fopen_bdrv(bs_vm_state, 0);
2292 if (!f) {
2293 error_setg(errp, "Could not open VM state file");
2294 ret = -EINVAL;
2295 goto err_drain;
2298 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2299 mis->from_src_file = f;
2301 aio_context_acquire(aio_context);
2302 ret = qemu_loadvm_state(f);
2303 migration_incoming_state_destroy();
2304 aio_context_release(aio_context);
2306 bdrv_drain_all_end();
2308 if (ret < 0) {
2309 error_setg(errp, "Error %d while loading VM state", ret);
2310 return ret;
2313 return 0;
2315 err_drain:
2316 bdrv_drain_all_end();
2317 return ret;
2320 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2322 qemu_ram_set_idstr(mr->ram_block,
2323 memory_region_name(mr), dev);
2326 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2328 qemu_ram_unset_idstr(mr->ram_block);
2331 void vmstate_register_ram_global(MemoryRegion *mr)
2333 vmstate_register_ram(mr, NULL);
2336 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2338 /* check needed if --only-migratable is specified */
2339 if (!only_migratable) {
2340 return true;
2343 return !(vmsd && vmsd->unmigratable);