target/arm: Implement SVE Integer Compare - Scalars Group
[qemu.git] / migration / savevm.c
blobc2f34ffc7cd7df031d203daa8e34f4fce7943810
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/error.h"
44 #include "qapi/qapi-commands-migration.h"
45 #include "qapi/qapi-commands-misc.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qemu/error-report.h"
48 #include "sysemu/cpus.h"
49 #include "exec/memory.h"
50 #include "exec/target_page.h"
51 #include "trace.h"
52 #include "qemu/iov.h"
53 #include "block/snapshot.h"
54 #include "qemu/cutils.h"
55 #include "io/channel-buffer.h"
56 #include "io/channel-file.h"
57 #include "sysemu/replay.h"
58 #include "qjson.h"
60 #ifndef ETH_P_RARP
61 #define ETH_P_RARP 0x8035
62 #endif
63 #define ARP_HTYPE_ETH 0x0001
64 #define ARP_PTYPE_IP 0x0800
65 #define ARP_OP_REQUEST_REV 0x3
67 const unsigned int postcopy_ram_discard_version = 0;
69 /* Subcommands for QEMU_VM_COMMAND */
70 enum qemu_vm_cmd {
71 MIG_CMD_INVALID = 0, /* Must be 0 */
72 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
73 MIG_CMD_PING, /* Request a PONG on the RP */
75 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
76 warn we might want to do PC */
77 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
78 pages as it's running. */
79 MIG_CMD_POSTCOPY_RUN, /* Start execution */
81 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
82 were previously sent during
83 precopy but are dirty. */
84 MIG_CMD_POSTCOPY_RESUME, /* resume postcopy on dest */
85 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
86 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
87 MIG_CMD_MAX
90 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
91 static struct mig_cmd_args {
92 ssize_t len; /* -1 = variable */
93 const char *name;
94 } mig_cmd_args[] = {
95 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
96 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
97 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
98 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
99 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
100 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
101 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
102 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
103 [MIG_CMD_POSTCOPY_RESUME] = { .len = 0, .name = "POSTCOPY_RESUME" },
104 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
105 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
106 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
109 /* Note for MIG_CMD_POSTCOPY_ADVISE:
110 * The format of arguments is depending on postcopy mode:
111 * - postcopy RAM only
112 * uint64_t host page size
113 * uint64_t taget page size
115 * - postcopy RAM and postcopy dirty bitmaps
116 * format is the same as for postcopy RAM only
118 * - postcopy dirty bitmaps only
119 * Nothing. Command length field is 0.
121 * Be careful: adding a new postcopy entity with some other parameters should
122 * not break format self-description ability. Good way is to introduce some
123 * generic extendable format with an exception for two old entities.
126 static int announce_self_create(uint8_t *buf,
127 uint8_t *mac_addr)
129 /* Ethernet header. */
130 memset(buf, 0xff, 6); /* destination MAC addr */
131 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
132 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
134 /* RARP header. */
135 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
136 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
137 *(buf + 18) = 6; /* hardware addr length (ethernet) */
138 *(buf + 19) = 4; /* protocol addr length (IPv4) */
139 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
140 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
141 memset(buf + 28, 0x00, 4); /* source protocol addr */
142 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
143 memset(buf + 38, 0x00, 4); /* target protocol addr */
145 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
146 memset(buf + 42, 0x00, 18);
148 return 60; /* len (FCS will be added by hardware) */
151 static void qemu_announce_self_iter(NICState *nic, void *opaque)
153 uint8_t buf[60];
154 int len;
156 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic->conf->macaddr));
157 len = announce_self_create(buf, nic->conf->macaddr.a);
159 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
163 static void qemu_announce_self_once(void *opaque)
165 static int count = SELF_ANNOUNCE_ROUNDS;
166 QEMUTimer *timer = *(QEMUTimer **)opaque;
168 qemu_foreach_nic(qemu_announce_self_iter, NULL);
170 if (--count) {
171 /* delay 50ms, 150ms, 250ms, ... */
172 timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
173 self_announce_delay(count));
174 } else {
175 timer_del(timer);
176 timer_free(timer);
180 void qemu_announce_self(void)
182 static QEMUTimer *timer;
183 timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
184 qemu_announce_self_once(&timer);
187 /***********************************************************/
188 /* savevm/loadvm support */
190 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
191 int64_t pos)
193 int ret;
194 QEMUIOVector qiov;
196 qemu_iovec_init_external(&qiov, iov, iovcnt);
197 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
198 if (ret < 0) {
199 return ret;
202 return qiov.size;
205 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
206 size_t size)
208 return bdrv_load_vmstate(opaque, buf, pos, size);
211 static int bdrv_fclose(void *opaque)
213 return bdrv_flush(opaque);
216 static const QEMUFileOps bdrv_read_ops = {
217 .get_buffer = block_get_buffer,
218 .close = bdrv_fclose
221 static const QEMUFileOps bdrv_write_ops = {
222 .writev_buffer = block_writev_buffer,
223 .close = bdrv_fclose
226 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
228 if (is_writable) {
229 return qemu_fopen_ops(bs, &bdrv_write_ops);
231 return qemu_fopen_ops(bs, &bdrv_read_ops);
235 /* QEMUFile timer support.
236 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
239 void timer_put(QEMUFile *f, QEMUTimer *ts)
241 uint64_t expire_time;
243 expire_time = timer_expire_time_ns(ts);
244 qemu_put_be64(f, expire_time);
247 void timer_get(QEMUFile *f, QEMUTimer *ts)
249 uint64_t expire_time;
251 expire_time = qemu_get_be64(f);
252 if (expire_time != -1) {
253 timer_mod_ns(ts, expire_time);
254 } else {
255 timer_del(ts);
260 /* VMState timer support.
261 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
264 static int get_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field)
266 QEMUTimer *v = pv;
267 timer_get(f, v);
268 return 0;
271 static int put_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field,
272 QJSON *vmdesc)
274 QEMUTimer *v = pv;
275 timer_put(f, v);
277 return 0;
280 const VMStateInfo vmstate_info_timer = {
281 .name = "timer",
282 .get = get_timer,
283 .put = put_timer,
287 typedef struct CompatEntry {
288 char idstr[256];
289 int instance_id;
290 } CompatEntry;
292 typedef struct SaveStateEntry {
293 QTAILQ_ENTRY(SaveStateEntry) entry;
294 char idstr[256];
295 int instance_id;
296 int alias_id;
297 int version_id;
298 /* version id read from the stream */
299 int load_version_id;
300 int section_id;
301 /* section id read from the stream */
302 int load_section_id;
303 SaveVMHandlers *ops;
304 const VMStateDescription *vmsd;
305 void *opaque;
306 CompatEntry *compat;
307 int is_ram;
308 } SaveStateEntry;
310 typedef struct SaveState {
311 QTAILQ_HEAD(, SaveStateEntry) handlers;
312 int global_section_id;
313 uint32_t len;
314 const char *name;
315 uint32_t target_page_bits;
316 } SaveState;
318 static SaveState savevm_state = {
319 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
320 .global_section_id = 0,
323 static int configuration_pre_save(void *opaque)
325 SaveState *state = opaque;
326 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
328 state->len = strlen(current_name);
329 state->name = current_name;
330 state->target_page_bits = qemu_target_page_bits();
332 return 0;
335 static int configuration_pre_load(void *opaque)
337 SaveState *state = opaque;
339 /* If there is no target-page-bits subsection it means the source
340 * predates the variable-target-page-bits support and is using the
341 * minimum possible value for this CPU.
343 state->target_page_bits = qemu_target_page_bits_min();
344 return 0;
347 static int configuration_post_load(void *opaque, int version_id)
349 SaveState *state = opaque;
350 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
352 if (strncmp(state->name, current_name, state->len) != 0) {
353 error_report("Machine type received is '%.*s' and local is '%s'",
354 (int) state->len, state->name, current_name);
355 return -EINVAL;
358 if (state->target_page_bits != qemu_target_page_bits()) {
359 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
360 state->target_page_bits, qemu_target_page_bits());
361 return -EINVAL;
364 return 0;
367 /* The target-page-bits subsection is present only if the
368 * target page size is not the same as the default (ie the
369 * minimum page size for a variable-page-size guest CPU).
370 * If it is present then it contains the actual target page
371 * bits for the machine, and migration will fail if the
372 * two ends don't agree about it.
374 static bool vmstate_target_page_bits_needed(void *opaque)
376 return qemu_target_page_bits()
377 > qemu_target_page_bits_min();
380 static const VMStateDescription vmstate_target_page_bits = {
381 .name = "configuration/target-page-bits",
382 .version_id = 1,
383 .minimum_version_id = 1,
384 .needed = vmstate_target_page_bits_needed,
385 .fields = (VMStateField[]) {
386 VMSTATE_UINT32(target_page_bits, SaveState),
387 VMSTATE_END_OF_LIST()
391 static const VMStateDescription vmstate_configuration = {
392 .name = "configuration",
393 .version_id = 1,
394 .pre_load = configuration_pre_load,
395 .post_load = configuration_post_load,
396 .pre_save = configuration_pre_save,
397 .fields = (VMStateField[]) {
398 VMSTATE_UINT32(len, SaveState),
399 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
400 VMSTATE_END_OF_LIST()
402 .subsections = (const VMStateDescription*[]) {
403 &vmstate_target_page_bits,
404 NULL
408 static void dump_vmstate_vmsd(FILE *out_file,
409 const VMStateDescription *vmsd, int indent,
410 bool is_subsection);
412 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
413 int indent)
415 fprintf(out_file, "%*s{\n", indent, "");
416 indent += 2;
417 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
418 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
419 field->version_id);
420 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
421 field->field_exists ? "true" : "false");
422 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
423 if (field->vmsd != NULL) {
424 fprintf(out_file, ",\n");
425 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
427 fprintf(out_file, "\n%*s}", indent - 2, "");
430 static void dump_vmstate_vmss(FILE *out_file,
431 const VMStateDescription **subsection,
432 int indent)
434 if (*subsection != NULL) {
435 dump_vmstate_vmsd(out_file, *subsection, indent, true);
439 static void dump_vmstate_vmsd(FILE *out_file,
440 const VMStateDescription *vmsd, int indent,
441 bool is_subsection)
443 if (is_subsection) {
444 fprintf(out_file, "%*s{\n", indent, "");
445 } else {
446 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
448 indent += 2;
449 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
450 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
451 vmsd->version_id);
452 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
453 vmsd->minimum_version_id);
454 if (vmsd->fields != NULL) {
455 const VMStateField *field = vmsd->fields;
456 bool first;
458 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
459 first = true;
460 while (field->name != NULL) {
461 if (field->flags & VMS_MUST_EXIST) {
462 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
463 field++;
464 continue;
466 if (!first) {
467 fprintf(out_file, ",\n");
469 dump_vmstate_vmsf(out_file, field, indent + 2);
470 field++;
471 first = false;
473 fprintf(out_file, "\n%*s]", indent, "");
475 if (vmsd->subsections != NULL) {
476 const VMStateDescription **subsection = vmsd->subsections;
477 bool first;
479 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
480 first = true;
481 while (*subsection != NULL) {
482 if (!first) {
483 fprintf(out_file, ",\n");
485 dump_vmstate_vmss(out_file, subsection, indent + 2);
486 subsection++;
487 first = false;
489 fprintf(out_file, "\n%*s]", indent, "");
491 fprintf(out_file, "\n%*s}", indent - 2, "");
494 static void dump_machine_type(FILE *out_file)
496 MachineClass *mc;
498 mc = MACHINE_GET_CLASS(current_machine);
500 fprintf(out_file, " \"vmschkmachine\": {\n");
501 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
502 fprintf(out_file, " },\n");
505 void dump_vmstate_json_to_file(FILE *out_file)
507 GSList *list, *elt;
508 bool first;
510 fprintf(out_file, "{\n");
511 dump_machine_type(out_file);
513 first = true;
514 list = object_class_get_list(TYPE_DEVICE, true);
515 for (elt = list; elt; elt = elt->next) {
516 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
517 TYPE_DEVICE);
518 const char *name;
519 int indent = 2;
521 if (!dc->vmsd) {
522 continue;
525 if (!first) {
526 fprintf(out_file, ",\n");
528 name = object_class_get_name(OBJECT_CLASS(dc));
529 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
530 indent += 2;
531 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
532 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
533 dc->vmsd->version_id);
534 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
535 dc->vmsd->minimum_version_id);
537 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
539 fprintf(out_file, "\n%*s}", indent - 2, "");
540 first = false;
542 fprintf(out_file, "\n}\n");
543 fclose(out_file);
546 static int calculate_new_instance_id(const char *idstr)
548 SaveStateEntry *se;
549 int instance_id = 0;
551 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
552 if (strcmp(idstr, se->idstr) == 0
553 && instance_id <= se->instance_id) {
554 instance_id = se->instance_id + 1;
557 return instance_id;
560 static int calculate_compat_instance_id(const char *idstr)
562 SaveStateEntry *se;
563 int instance_id = 0;
565 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
566 if (!se->compat) {
567 continue;
570 if (strcmp(idstr, se->compat->idstr) == 0
571 && instance_id <= se->compat->instance_id) {
572 instance_id = se->compat->instance_id + 1;
575 return instance_id;
578 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
580 if (se->vmsd) {
581 return se->vmsd->priority;
583 return MIG_PRI_DEFAULT;
586 static void savevm_state_handler_insert(SaveStateEntry *nse)
588 MigrationPriority priority = save_state_priority(nse);
589 SaveStateEntry *se;
591 assert(priority <= MIG_PRI_MAX);
593 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
594 if (save_state_priority(se) < priority) {
595 break;
599 if (se) {
600 QTAILQ_INSERT_BEFORE(se, nse, entry);
601 } else {
602 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
606 /* TODO: Individual devices generally have very little idea about the rest
607 of the system, so instance_id should be removed/replaced.
608 Meanwhile pass -1 as instance_id if you do not already have a clearly
609 distinguishing id for all instances of your device class. */
610 int register_savevm_live(DeviceState *dev,
611 const char *idstr,
612 int instance_id,
613 int version_id,
614 SaveVMHandlers *ops,
615 void *opaque)
617 SaveStateEntry *se;
619 se = g_new0(SaveStateEntry, 1);
620 se->version_id = version_id;
621 se->section_id = savevm_state.global_section_id++;
622 se->ops = ops;
623 se->opaque = opaque;
624 se->vmsd = NULL;
625 /* if this is a live_savem then set is_ram */
626 if (ops->save_setup != NULL) {
627 se->is_ram = 1;
630 if (dev) {
631 char *id = qdev_get_dev_path(dev);
632 if (id) {
633 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
634 sizeof(se->idstr)) {
635 error_report("Path too long for VMState (%s)", id);
636 g_free(id);
637 g_free(se);
639 return -1;
641 g_free(id);
643 se->compat = g_new0(CompatEntry, 1);
644 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
645 se->compat->instance_id = instance_id == -1 ?
646 calculate_compat_instance_id(idstr) : instance_id;
647 instance_id = -1;
650 pstrcat(se->idstr, sizeof(se->idstr), idstr);
652 if (instance_id == -1) {
653 se->instance_id = calculate_new_instance_id(se->idstr);
654 } else {
655 se->instance_id = instance_id;
657 assert(!se->compat || se->instance_id == 0);
658 savevm_state_handler_insert(se);
659 return 0;
662 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
664 SaveStateEntry *se, *new_se;
665 char id[256] = "";
667 if (dev) {
668 char *path = qdev_get_dev_path(dev);
669 if (path) {
670 pstrcpy(id, sizeof(id), path);
671 pstrcat(id, sizeof(id), "/");
672 g_free(path);
675 pstrcat(id, sizeof(id), idstr);
677 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
678 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
679 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
680 g_free(se->compat);
681 g_free(se);
686 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
687 const VMStateDescription *vmsd,
688 void *opaque, int alias_id,
689 int required_for_version,
690 Error **errp)
692 SaveStateEntry *se;
694 /* If this triggers, alias support can be dropped for the vmsd. */
695 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
697 se = g_new0(SaveStateEntry, 1);
698 se->version_id = vmsd->version_id;
699 se->section_id = savevm_state.global_section_id++;
700 se->opaque = opaque;
701 se->vmsd = vmsd;
702 se->alias_id = alias_id;
704 if (dev) {
705 char *id = qdev_get_dev_path(dev);
706 if (id) {
707 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
708 sizeof(se->idstr)) {
709 error_setg(errp, "Path too long for VMState (%s)", id);
710 g_free(id);
711 g_free(se);
713 return -1;
715 g_free(id);
717 se->compat = g_new0(CompatEntry, 1);
718 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
719 se->compat->instance_id = instance_id == -1 ?
720 calculate_compat_instance_id(vmsd->name) : instance_id;
721 instance_id = -1;
724 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
726 if (instance_id == -1) {
727 se->instance_id = calculate_new_instance_id(se->idstr);
728 } else {
729 se->instance_id = instance_id;
731 assert(!se->compat || se->instance_id == 0);
732 savevm_state_handler_insert(se);
733 return 0;
736 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
737 void *opaque)
739 SaveStateEntry *se, *new_se;
741 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
742 if (se->vmsd == vmsd && se->opaque == opaque) {
743 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
744 g_free(se->compat);
745 g_free(se);
750 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
752 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
753 if (!se->vmsd) { /* Old style */
754 return se->ops->load_state(f, se->opaque, se->load_version_id);
756 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
759 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
761 int64_t old_offset, size;
763 old_offset = qemu_ftell_fast(f);
764 se->ops->save_state(f, se->opaque);
765 size = qemu_ftell_fast(f) - old_offset;
767 if (vmdesc) {
768 json_prop_int(vmdesc, "size", size);
769 json_start_array(vmdesc, "fields");
770 json_start_object(vmdesc, NULL);
771 json_prop_str(vmdesc, "name", "data");
772 json_prop_int(vmdesc, "size", size);
773 json_prop_str(vmdesc, "type", "buffer");
774 json_end_object(vmdesc);
775 json_end_array(vmdesc);
779 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
781 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
782 if (!se->vmsd) {
783 vmstate_save_old_style(f, se, vmdesc);
784 return 0;
786 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
790 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
792 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
793 uint8_t section_type)
795 qemu_put_byte(f, section_type);
796 qemu_put_be32(f, se->section_id);
798 if (section_type == QEMU_VM_SECTION_FULL ||
799 section_type == QEMU_VM_SECTION_START) {
800 /* ID string */
801 size_t len = strlen(se->idstr);
802 qemu_put_byte(f, len);
803 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
805 qemu_put_be32(f, se->instance_id);
806 qemu_put_be32(f, se->version_id);
811 * Write a footer onto device sections that catches cases misformatted device
812 * sections.
814 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
816 if (migrate_get_current()->send_section_footer) {
817 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
818 qemu_put_be32(f, se->section_id);
823 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
824 * command and associated data.
826 * @f: File to send command on
827 * @command: Command type to send
828 * @len: Length of associated data
829 * @data: Data associated with command.
831 static void qemu_savevm_command_send(QEMUFile *f,
832 enum qemu_vm_cmd command,
833 uint16_t len,
834 uint8_t *data)
836 trace_savevm_command_send(command, len);
837 qemu_put_byte(f, QEMU_VM_COMMAND);
838 qemu_put_be16(f, (uint16_t)command);
839 qemu_put_be16(f, len);
840 qemu_put_buffer(f, data, len);
841 qemu_fflush(f);
844 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
846 uint32_t buf;
848 trace_savevm_send_ping(value);
849 buf = cpu_to_be32(value);
850 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
853 void qemu_savevm_send_open_return_path(QEMUFile *f)
855 trace_savevm_send_open_return_path();
856 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
859 /* We have a buffer of data to send; we don't want that all to be loaded
860 * by the command itself, so the command contains just the length of the
861 * extra buffer that we then send straight after it.
862 * TODO: Must be a better way to organise that
864 * Returns:
865 * 0 on success
866 * -ve on error
868 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
870 uint32_t tmp;
872 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
873 error_report("%s: Unreasonably large packaged state: %zu",
874 __func__, len);
875 return -1;
878 tmp = cpu_to_be32(len);
880 trace_qemu_savevm_send_packaged();
881 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
883 qemu_put_buffer(f, buf, len);
885 return 0;
888 /* Send prior to any postcopy transfer */
889 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
891 if (migrate_postcopy_ram()) {
892 uint64_t tmp[2];
893 tmp[0] = cpu_to_be64(ram_pagesize_summary());
894 tmp[1] = cpu_to_be64(qemu_target_page_size());
896 trace_qemu_savevm_send_postcopy_advise();
897 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
898 16, (uint8_t *)tmp);
899 } else {
900 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
904 /* Sent prior to starting the destination running in postcopy, discard pages
905 * that have already been sent but redirtied on the source.
906 * CMD_POSTCOPY_RAM_DISCARD consist of:
907 * byte version (0)
908 * byte Length of name field (not including 0)
909 * n x byte RAM block name
910 * byte 0 terminator (just for safety)
911 * n x Byte ranges within the named RAMBlock
912 * be64 Start of the range
913 * be64 Length
915 * name: RAMBlock name that these entries are part of
916 * len: Number of page entries
917 * start_list: 'len' addresses
918 * length_list: 'len' addresses
921 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
922 uint16_t len,
923 uint64_t *start_list,
924 uint64_t *length_list)
926 uint8_t *buf;
927 uint16_t tmplen;
928 uint16_t t;
929 size_t name_len = strlen(name);
931 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
932 assert(name_len < 256);
933 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
934 buf[0] = postcopy_ram_discard_version;
935 buf[1] = name_len;
936 memcpy(buf + 2, name, name_len);
937 tmplen = 2 + name_len;
938 buf[tmplen++] = '\0';
940 for (t = 0; t < len; t++) {
941 stq_be_p(buf + tmplen, start_list[t]);
942 tmplen += 8;
943 stq_be_p(buf + tmplen, length_list[t]);
944 tmplen += 8;
946 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
947 g_free(buf);
950 /* Get the destination into a state where it can receive postcopy data. */
951 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
953 trace_savevm_send_postcopy_listen();
954 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
957 /* Kick the destination into running */
958 void qemu_savevm_send_postcopy_run(QEMUFile *f)
960 trace_savevm_send_postcopy_run();
961 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
964 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
966 trace_savevm_send_postcopy_resume();
967 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
970 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
972 size_t len;
973 char buf[256];
975 trace_savevm_send_recv_bitmap(block_name);
977 buf[0] = len = strlen(block_name);
978 memcpy(buf + 1, block_name, len);
980 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
983 bool qemu_savevm_state_blocked(Error **errp)
985 SaveStateEntry *se;
987 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
988 if (se->vmsd && se->vmsd->unmigratable) {
989 error_setg(errp, "State blocked by non-migratable device '%s'",
990 se->idstr);
991 return true;
994 return false;
997 void qemu_savevm_state_header(QEMUFile *f)
999 trace_savevm_state_header();
1000 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1001 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1003 if (migrate_get_current()->send_configuration) {
1004 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1005 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1009 void qemu_savevm_state_setup(QEMUFile *f)
1011 SaveStateEntry *se;
1012 int ret;
1014 trace_savevm_state_setup();
1015 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1016 if (!se->ops || !se->ops->save_setup) {
1017 continue;
1019 if (se->ops && se->ops->is_active) {
1020 if (!se->ops->is_active(se->opaque)) {
1021 continue;
1024 save_section_header(f, se, QEMU_VM_SECTION_START);
1026 ret = se->ops->save_setup(f, se->opaque);
1027 save_section_footer(f, se);
1028 if (ret < 0) {
1029 qemu_file_set_error(f, ret);
1030 break;
1035 int qemu_savevm_state_resume_prepare(MigrationState *s)
1037 SaveStateEntry *se;
1038 int ret;
1040 trace_savevm_state_resume_prepare();
1042 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1043 if (!se->ops || !se->ops->resume_prepare) {
1044 continue;
1046 if (se->ops && se->ops->is_active) {
1047 if (!se->ops->is_active(se->opaque)) {
1048 continue;
1051 ret = se->ops->resume_prepare(s, se->opaque);
1052 if (ret < 0) {
1053 return ret;
1057 return 0;
1061 * this function has three return values:
1062 * negative: there was one error, and we have -errno.
1063 * 0 : We haven't finished, caller have to go again
1064 * 1 : We have finished, we can go to complete phase
1066 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1068 SaveStateEntry *se;
1069 int ret = 1;
1071 trace_savevm_state_iterate();
1072 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1073 if (!se->ops || !se->ops->save_live_iterate) {
1074 continue;
1076 if (se->ops && se->ops->is_active) {
1077 if (!se->ops->is_active(se->opaque)) {
1078 continue;
1081 if (se->ops && se->ops->is_active_iterate) {
1082 if (!se->ops->is_active_iterate(se->opaque)) {
1083 continue;
1087 * In the postcopy phase, any device that doesn't know how to
1088 * do postcopy should have saved it's state in the _complete
1089 * call that's already run, it might get confused if we call
1090 * iterate afterwards.
1092 if (postcopy &&
1093 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1094 continue;
1096 if (qemu_file_rate_limit(f)) {
1097 return 0;
1099 trace_savevm_section_start(se->idstr, se->section_id);
1101 save_section_header(f, se, QEMU_VM_SECTION_PART);
1103 ret = se->ops->save_live_iterate(f, se->opaque);
1104 trace_savevm_section_end(se->idstr, se->section_id, ret);
1105 save_section_footer(f, se);
1107 if (ret < 0) {
1108 qemu_file_set_error(f, ret);
1110 if (ret <= 0) {
1111 /* Do not proceed to the next vmstate before this one reported
1112 completion of the current stage. This serializes the migration
1113 and reduces the probability that a faster changing state is
1114 synchronized over and over again. */
1115 break;
1118 return ret;
1121 static bool should_send_vmdesc(void)
1123 MachineState *machine = MACHINE(qdev_get_machine());
1124 bool in_postcopy = migration_in_postcopy();
1125 return !machine->suppress_vmdesc && !in_postcopy;
1129 * Calls the save_live_complete_postcopy methods
1130 * causing the last few pages to be sent immediately and doing any associated
1131 * cleanup.
1132 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1133 * all the other devices, but that happens at the point we switch to postcopy.
1135 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1137 SaveStateEntry *se;
1138 int ret;
1140 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1141 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1142 continue;
1144 if (se->ops && se->ops->is_active) {
1145 if (!se->ops->is_active(se->opaque)) {
1146 continue;
1149 trace_savevm_section_start(se->idstr, se->section_id);
1150 /* Section type */
1151 qemu_put_byte(f, QEMU_VM_SECTION_END);
1152 qemu_put_be32(f, se->section_id);
1154 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1155 trace_savevm_section_end(se->idstr, se->section_id, ret);
1156 save_section_footer(f, se);
1157 if (ret < 0) {
1158 qemu_file_set_error(f, ret);
1159 return;
1163 qemu_put_byte(f, QEMU_VM_EOF);
1164 qemu_fflush(f);
1167 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1168 bool inactivate_disks)
1170 QJSON *vmdesc;
1171 int vmdesc_len;
1172 SaveStateEntry *se;
1173 int ret;
1174 bool in_postcopy = migration_in_postcopy();
1176 trace_savevm_state_complete_precopy();
1178 cpu_synchronize_all_states();
1180 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1181 if (!se->ops ||
1182 (in_postcopy && se->ops->has_postcopy &&
1183 se->ops->has_postcopy(se->opaque)) ||
1184 (in_postcopy && !iterable_only) ||
1185 !se->ops->save_live_complete_precopy) {
1186 continue;
1189 if (se->ops && se->ops->is_active) {
1190 if (!se->ops->is_active(se->opaque)) {
1191 continue;
1194 trace_savevm_section_start(se->idstr, se->section_id);
1196 save_section_header(f, se, QEMU_VM_SECTION_END);
1198 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1199 trace_savevm_section_end(se->idstr, se->section_id, ret);
1200 save_section_footer(f, se);
1201 if (ret < 0) {
1202 qemu_file_set_error(f, ret);
1203 return -1;
1207 if (iterable_only) {
1208 return 0;
1211 vmdesc = qjson_new();
1212 json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1213 json_start_array(vmdesc, "devices");
1214 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1216 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1217 continue;
1219 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1220 trace_savevm_section_skip(se->idstr, se->section_id);
1221 continue;
1224 trace_savevm_section_start(se->idstr, se->section_id);
1226 json_start_object(vmdesc, NULL);
1227 json_prop_str(vmdesc, "name", se->idstr);
1228 json_prop_int(vmdesc, "instance_id", se->instance_id);
1230 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1231 ret = vmstate_save(f, se, vmdesc);
1232 if (ret) {
1233 qemu_file_set_error(f, ret);
1234 return ret;
1236 trace_savevm_section_end(se->idstr, se->section_id, 0);
1237 save_section_footer(f, se);
1239 json_end_object(vmdesc);
1242 if (inactivate_disks) {
1243 /* Inactivate before sending QEMU_VM_EOF so that the
1244 * bdrv_invalidate_cache_all() on the other end won't fail. */
1245 ret = bdrv_inactivate_all();
1246 if (ret) {
1247 error_report("%s: bdrv_inactivate_all() failed (%d)",
1248 __func__, ret);
1249 qemu_file_set_error(f, ret);
1250 return ret;
1253 if (!in_postcopy) {
1254 /* Postcopy stream will still be going */
1255 qemu_put_byte(f, QEMU_VM_EOF);
1258 json_end_array(vmdesc);
1259 qjson_finish(vmdesc);
1260 vmdesc_len = strlen(qjson_get_str(vmdesc));
1262 if (should_send_vmdesc()) {
1263 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1264 qemu_put_be32(f, vmdesc_len);
1265 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1267 qjson_destroy(vmdesc);
1269 qemu_fflush(f);
1270 return 0;
1273 /* Give an estimate of the amount left to be transferred,
1274 * the result is split into the amount for units that can and
1275 * for units that can't do postcopy.
1277 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1278 uint64_t *res_precopy_only,
1279 uint64_t *res_compatible,
1280 uint64_t *res_postcopy_only)
1282 SaveStateEntry *se;
1284 *res_precopy_only = 0;
1285 *res_compatible = 0;
1286 *res_postcopy_only = 0;
1289 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1290 if (!se->ops || !se->ops->save_live_pending) {
1291 continue;
1293 if (se->ops && se->ops->is_active) {
1294 if (!se->ops->is_active(se->opaque)) {
1295 continue;
1298 se->ops->save_live_pending(f, se->opaque, threshold_size,
1299 res_precopy_only, res_compatible,
1300 res_postcopy_only);
1304 void qemu_savevm_state_cleanup(void)
1306 SaveStateEntry *se;
1308 trace_savevm_state_cleanup();
1309 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1310 if (se->ops && se->ops->save_cleanup) {
1311 se->ops->save_cleanup(se->opaque);
1316 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1318 int ret;
1319 MigrationState *ms = migrate_get_current();
1320 MigrationStatus status;
1322 migrate_init(ms);
1324 ms->to_dst_file = f;
1326 if (migration_is_blocked(errp)) {
1327 ret = -EINVAL;
1328 goto done;
1331 if (migrate_use_block()) {
1332 error_setg(errp, "Block migration and snapshots are incompatible");
1333 ret = -EINVAL;
1334 goto done;
1337 qemu_mutex_unlock_iothread();
1338 qemu_savevm_state_header(f);
1339 qemu_savevm_state_setup(f);
1340 qemu_mutex_lock_iothread();
1342 while (qemu_file_get_error(f) == 0) {
1343 if (qemu_savevm_state_iterate(f, false) > 0) {
1344 break;
1348 ret = qemu_file_get_error(f);
1349 if (ret == 0) {
1350 qemu_savevm_state_complete_precopy(f, false, false);
1351 ret = qemu_file_get_error(f);
1353 qemu_savevm_state_cleanup();
1354 if (ret != 0) {
1355 error_setg_errno(errp, -ret, "Error while writing VM state");
1358 done:
1359 if (ret != 0) {
1360 status = MIGRATION_STATUS_FAILED;
1361 } else {
1362 status = MIGRATION_STATUS_COMPLETED;
1364 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1366 /* f is outer parameter, it should not stay in global migration state after
1367 * this function finished */
1368 ms->to_dst_file = NULL;
1370 return ret;
1373 static int qemu_save_device_state(QEMUFile *f)
1375 SaveStateEntry *se;
1377 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1378 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1380 cpu_synchronize_all_states();
1382 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1383 int ret;
1385 if (se->is_ram) {
1386 continue;
1388 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1389 continue;
1391 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1392 continue;
1395 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1397 ret = vmstate_save(f, se, NULL);
1398 if (ret) {
1399 return ret;
1402 save_section_footer(f, se);
1405 qemu_put_byte(f, QEMU_VM_EOF);
1407 return qemu_file_get_error(f);
1410 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1412 SaveStateEntry *se;
1414 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1415 if (!strcmp(se->idstr, idstr) &&
1416 (instance_id == se->instance_id ||
1417 instance_id == se->alias_id))
1418 return se;
1419 /* Migrating from an older version? */
1420 if (strstr(se->idstr, idstr) && se->compat) {
1421 if (!strcmp(se->compat->idstr, idstr) &&
1422 (instance_id == se->compat->instance_id ||
1423 instance_id == se->alias_id))
1424 return se;
1427 return NULL;
1430 enum LoadVMExitCodes {
1431 /* Allow a command to quit all layers of nested loadvm loops */
1432 LOADVM_QUIT = 1,
1435 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
1437 /* ------ incoming postcopy messages ------ */
1438 /* 'advise' arrives before any transfers just to tell us that a postcopy
1439 * *might* happen - it might be skipped if precopy transferred everything
1440 * quickly.
1442 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1443 uint16_t len)
1445 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1446 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1447 Error *local_err = NULL;
1449 trace_loadvm_postcopy_handle_advise();
1450 if (ps != POSTCOPY_INCOMING_NONE) {
1451 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1452 return -1;
1455 switch (len) {
1456 case 0:
1457 if (migrate_postcopy_ram()) {
1458 error_report("RAM postcopy is enabled but have 0 byte advise");
1459 return -EINVAL;
1461 return 0;
1462 case 8 + 8:
1463 if (!migrate_postcopy_ram()) {
1464 error_report("RAM postcopy is disabled but have 16 byte advise");
1465 return -EINVAL;
1467 break;
1468 default:
1469 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1470 return -EINVAL;
1473 if (!postcopy_ram_supported_by_host(mis)) {
1474 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1475 return -1;
1478 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1479 local_pagesize_summary = ram_pagesize_summary();
1481 if (remote_pagesize_summary != local_pagesize_summary) {
1483 * This detects two potential causes of mismatch:
1484 * a) A mismatch in host page sizes
1485 * Some combinations of mismatch are probably possible but it gets
1486 * a bit more complicated. In particular we need to place whole
1487 * host pages on the dest at once, and we need to ensure that we
1488 * handle dirtying to make sure we never end up sending part of
1489 * a hostpage on it's own.
1490 * b) The use of different huge page sizes on source/destination
1491 * a more fine grain test is performed during RAM block migration
1492 * but this test here causes a nice early clear failure, and
1493 * also fails when passed to an older qemu that doesn't
1494 * do huge pages.
1496 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1497 " d=%" PRIx64 ")",
1498 remote_pagesize_summary, local_pagesize_summary);
1499 return -1;
1502 remote_tps = qemu_get_be64(mis->from_src_file);
1503 if (remote_tps != qemu_target_page_size()) {
1505 * Again, some differences could be dealt with, but for now keep it
1506 * simple.
1508 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1509 (int)remote_tps, qemu_target_page_size());
1510 return -1;
1513 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1514 error_report_err(local_err);
1515 return -1;
1518 if (ram_postcopy_incoming_init(mis)) {
1519 return -1;
1522 postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1524 return 0;
1527 /* After postcopy we will be told to throw some pages away since they're
1528 * dirty and will have to be demand fetched. Must happen before CPU is
1529 * started.
1530 * There can be 0..many of these messages, each encoding multiple pages.
1532 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1533 uint16_t len)
1535 int tmp;
1536 char ramid[256];
1537 PostcopyState ps = postcopy_state_get();
1539 trace_loadvm_postcopy_ram_handle_discard();
1541 switch (ps) {
1542 case POSTCOPY_INCOMING_ADVISE:
1543 /* 1st discard */
1544 tmp = postcopy_ram_prepare_discard(mis);
1545 if (tmp) {
1546 return tmp;
1548 break;
1550 case POSTCOPY_INCOMING_DISCARD:
1551 /* Expected state */
1552 break;
1554 default:
1555 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1556 ps);
1557 return -1;
1559 /* We're expecting a
1560 * Version (0)
1561 * a RAM ID string (length byte, name, 0 term)
1562 * then at least 1 16 byte chunk
1564 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1565 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1566 return -1;
1569 tmp = qemu_get_byte(mis->from_src_file);
1570 if (tmp != postcopy_ram_discard_version) {
1571 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1572 return -1;
1575 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1576 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1577 return -1;
1579 tmp = qemu_get_byte(mis->from_src_file);
1580 if (tmp != 0) {
1581 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1582 return -1;
1585 len -= 3 + strlen(ramid);
1586 if (len % 16) {
1587 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1588 return -1;
1590 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1591 while (len) {
1592 uint64_t start_addr, block_length;
1593 start_addr = qemu_get_be64(mis->from_src_file);
1594 block_length = qemu_get_be64(mis->from_src_file);
1596 len -= 16;
1597 int ret = ram_discard_range(ramid, start_addr, block_length);
1598 if (ret) {
1599 return ret;
1602 trace_loadvm_postcopy_ram_handle_discard_end();
1604 return 0;
1608 * Triggered by a postcopy_listen command; this thread takes over reading
1609 * the input stream, leaving the main thread free to carry on loading the rest
1610 * of the device state (from RAM).
1611 * (TODO:This could do with being in a postcopy file - but there again it's
1612 * just another input loop, not that postcopy specific)
1614 static void *postcopy_ram_listen_thread(void *opaque)
1616 MigrationIncomingState *mis = migration_incoming_get_current();
1617 QEMUFile *f = mis->from_src_file;
1618 int load_res;
1620 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1621 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1622 qemu_sem_post(&mis->listen_thread_sem);
1623 trace_postcopy_ram_listen_thread_start();
1626 * Because we're a thread and not a coroutine we can't yield
1627 * in qemu_file, and thus we must be blocking now.
1629 qemu_file_set_blocking(f, true);
1630 load_res = qemu_loadvm_state_main(f, mis);
1633 * This is tricky, but, mis->from_src_file can change after it
1634 * returns, when postcopy recovery happened. In the future, we may
1635 * want a wrapper for the QEMUFile handle.
1637 f = mis->from_src_file;
1639 /* And non-blocking again so we don't block in any cleanup */
1640 qemu_file_set_blocking(f, false);
1642 trace_postcopy_ram_listen_thread_exit();
1643 if (load_res < 0) {
1644 error_report("%s: loadvm failed: %d", __func__, load_res);
1645 qemu_file_set_error(f, load_res);
1646 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1647 MIGRATION_STATUS_FAILED);
1648 } else {
1650 * This looks good, but it's possible that the device loading in the
1651 * main thread hasn't finished yet, and so we might not be in 'RUN'
1652 * state yet; wait for the end of the main thread.
1654 qemu_event_wait(&mis->main_thread_load_event);
1656 postcopy_ram_incoming_cleanup(mis);
1658 if (load_res < 0) {
1660 * If something went wrong then we have a bad state so exit;
1661 * depending how far we got it might be possible at this point
1662 * to leave the guest running and fire MCEs for pages that never
1663 * arrived as a desperate recovery step.
1665 exit(EXIT_FAILURE);
1668 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1669 MIGRATION_STATUS_COMPLETED);
1671 * If everything has worked fine, then the main thread has waited
1672 * for us to start, and we're the last use of the mis.
1673 * (If something broke then qemu will have to exit anyway since it's
1674 * got a bad migration state).
1676 migration_incoming_state_destroy();
1677 qemu_loadvm_state_cleanup();
1679 return NULL;
1682 /* After this message we must be able to immediately receive postcopy data */
1683 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1685 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1686 trace_loadvm_postcopy_handle_listen();
1687 Error *local_err = NULL;
1689 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1690 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1691 return -1;
1693 if (ps == POSTCOPY_INCOMING_ADVISE) {
1695 * A rare case, we entered listen without having to do any discards,
1696 * so do the setup that's normally done at the time of the 1st discard.
1698 if (migrate_postcopy_ram()) {
1699 postcopy_ram_prepare_discard(mis);
1704 * Sensitise RAM - can now generate requests for blocks that don't exist
1705 * However, at this point the CPU shouldn't be running, and the IO
1706 * shouldn't be doing anything yet so don't actually expect requests
1708 if (migrate_postcopy_ram()) {
1709 if (postcopy_ram_enable_notify(mis)) {
1710 return -1;
1714 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1715 error_report_err(local_err);
1716 return -1;
1719 if (mis->have_listen_thread) {
1720 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1721 return -1;
1724 mis->have_listen_thread = true;
1725 /* Start up the listening thread and wait for it to signal ready */
1726 qemu_sem_init(&mis->listen_thread_sem, 0);
1727 qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1728 postcopy_ram_listen_thread, NULL,
1729 QEMU_THREAD_DETACHED);
1730 qemu_sem_wait(&mis->listen_thread_sem);
1731 qemu_sem_destroy(&mis->listen_thread_sem);
1733 return 0;
1737 typedef struct {
1738 QEMUBH *bh;
1739 } HandleRunBhData;
1741 static void loadvm_postcopy_handle_run_bh(void *opaque)
1743 Error *local_err = NULL;
1744 HandleRunBhData *data = opaque;
1746 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1747 * in migration.c
1749 cpu_synchronize_all_post_init();
1751 qemu_announce_self();
1753 /* Make sure all file formats flush their mutable metadata.
1754 * If we get an error here, just don't restart the VM yet. */
1755 bdrv_invalidate_cache_all(&local_err);
1756 if (local_err) {
1757 error_report_err(local_err);
1758 local_err = NULL;
1759 autostart = false;
1762 trace_loadvm_postcopy_handle_run_cpu_sync();
1763 cpu_synchronize_all_post_init();
1765 trace_loadvm_postcopy_handle_run_vmstart();
1767 dirty_bitmap_mig_before_vm_start();
1769 if (autostart) {
1770 /* Hold onto your hats, starting the CPU */
1771 vm_start();
1772 } else {
1773 /* leave it paused and let management decide when to start the CPU */
1774 runstate_set(RUN_STATE_PAUSED);
1777 qemu_bh_delete(data->bh);
1778 g_free(data);
1781 /* After all discards we can start running and asking for pages */
1782 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1784 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1785 HandleRunBhData *data;
1787 trace_loadvm_postcopy_handle_run();
1788 if (ps != POSTCOPY_INCOMING_LISTENING) {
1789 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1790 return -1;
1793 data = g_new(HandleRunBhData, 1);
1794 data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1795 qemu_bh_schedule(data->bh);
1797 /* We need to finish reading the stream from the package
1798 * and also stop reading anything more from the stream that loaded the
1799 * package (since it's now being read by the listener thread).
1800 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1802 return LOADVM_QUIT;
1805 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
1807 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
1808 error_report("%s: illegal resume received", __func__);
1809 /* Don't fail the load, only for this. */
1810 return 0;
1814 * This means source VM is ready to resume the postcopy migration.
1815 * It's time to switch state and release the fault thread to
1816 * continue service page faults.
1818 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1819 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1820 qemu_sem_post(&mis->postcopy_pause_sem_fault);
1822 trace_loadvm_postcopy_handle_resume();
1824 /* Tell source that "we are ready" */
1825 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
1827 return 0;
1831 * Immediately following this command is a blob of data containing an embedded
1832 * chunk of migration stream; read it and load it.
1834 * @mis: Incoming state
1835 * @length: Length of packaged data to read
1837 * Returns: Negative values on error
1840 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1842 int ret;
1843 size_t length;
1844 QIOChannelBuffer *bioc;
1846 length = qemu_get_be32(mis->from_src_file);
1847 trace_loadvm_handle_cmd_packaged(length);
1849 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1850 error_report("Unreasonably large packaged state: %zu", length);
1851 return -1;
1854 bioc = qio_channel_buffer_new(length);
1855 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1856 ret = qemu_get_buffer(mis->from_src_file,
1857 bioc->data,
1858 length);
1859 if (ret != length) {
1860 object_unref(OBJECT(bioc));
1861 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1862 ret, length);
1863 return (ret < 0) ? ret : -EAGAIN;
1865 bioc->usage += length;
1866 trace_loadvm_handle_cmd_packaged_received(ret);
1868 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1870 ret = qemu_loadvm_state_main(packf, mis);
1871 trace_loadvm_handle_cmd_packaged_main(ret);
1872 qemu_fclose(packf);
1873 object_unref(OBJECT(bioc));
1875 return ret;
1879 * Handle request that source requests for recved_bitmap on
1880 * destination. Payload format:
1882 * len (1 byte) + ramblock_name (<255 bytes)
1884 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
1885 uint16_t len)
1887 QEMUFile *file = mis->from_src_file;
1888 RAMBlock *rb;
1889 char block_name[256];
1890 size_t cnt;
1892 cnt = qemu_get_counted_string(file, block_name);
1893 if (!cnt) {
1894 error_report("%s: failed to read block name", __func__);
1895 return -EINVAL;
1898 /* Validate before using the data */
1899 if (qemu_file_get_error(file)) {
1900 return qemu_file_get_error(file);
1903 if (len != cnt + 1) {
1904 error_report("%s: invalid payload length (%d)", __func__, len);
1905 return -EINVAL;
1908 rb = qemu_ram_block_by_name(block_name);
1909 if (!rb) {
1910 error_report("%s: block '%s' not found", __func__, block_name);
1911 return -EINVAL;
1914 migrate_send_rp_recv_bitmap(mis, block_name);
1916 trace_loadvm_handle_recv_bitmap(block_name);
1918 return 0;
1922 * Process an incoming 'QEMU_VM_COMMAND'
1923 * 0 just a normal return
1924 * LOADVM_QUIT All good, but exit the loop
1925 * <0 Error
1927 static int loadvm_process_command(QEMUFile *f)
1929 MigrationIncomingState *mis = migration_incoming_get_current();
1930 uint16_t cmd;
1931 uint16_t len;
1932 uint32_t tmp32;
1934 cmd = qemu_get_be16(f);
1935 len = qemu_get_be16(f);
1937 /* Check validity before continue processing of cmds */
1938 if (qemu_file_get_error(f)) {
1939 return qemu_file_get_error(f);
1942 trace_loadvm_process_command(cmd, len);
1943 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
1944 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
1945 return -EINVAL;
1948 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
1949 error_report("%s received with bad length - expecting %zu, got %d",
1950 mig_cmd_args[cmd].name,
1951 (size_t)mig_cmd_args[cmd].len, len);
1952 return -ERANGE;
1955 switch (cmd) {
1956 case MIG_CMD_OPEN_RETURN_PATH:
1957 if (mis->to_src_file) {
1958 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1959 /* Not really a problem, so don't give up */
1960 return 0;
1962 mis->to_src_file = qemu_file_get_return_path(f);
1963 if (!mis->to_src_file) {
1964 error_report("CMD_OPEN_RETURN_PATH failed");
1965 return -1;
1967 break;
1969 case MIG_CMD_PING:
1970 tmp32 = qemu_get_be32(f);
1971 trace_loadvm_process_command_ping(tmp32);
1972 if (!mis->to_src_file) {
1973 error_report("CMD_PING (0x%x) received with no return path",
1974 tmp32);
1975 return -1;
1977 migrate_send_rp_pong(mis, tmp32);
1978 break;
1980 case MIG_CMD_PACKAGED:
1981 return loadvm_handle_cmd_packaged(mis);
1983 case MIG_CMD_POSTCOPY_ADVISE:
1984 return loadvm_postcopy_handle_advise(mis, len);
1986 case MIG_CMD_POSTCOPY_LISTEN:
1987 return loadvm_postcopy_handle_listen(mis);
1989 case MIG_CMD_POSTCOPY_RUN:
1990 return loadvm_postcopy_handle_run(mis);
1992 case MIG_CMD_POSTCOPY_RAM_DISCARD:
1993 return loadvm_postcopy_ram_handle_discard(mis, len);
1995 case MIG_CMD_POSTCOPY_RESUME:
1996 return loadvm_postcopy_handle_resume(mis);
1998 case MIG_CMD_RECV_BITMAP:
1999 return loadvm_handle_recv_bitmap(mis, len);
2002 return 0;
2006 * Read a footer off the wire and check that it matches the expected section
2008 * Returns: true if the footer was good
2009 * false if there is a problem (and calls error_report to say why)
2011 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2013 int ret;
2014 uint8_t read_mark;
2015 uint32_t read_section_id;
2017 if (!migrate_get_current()->send_section_footer) {
2018 /* No footer to check */
2019 return true;
2022 read_mark = qemu_get_byte(f);
2024 ret = qemu_file_get_error(f);
2025 if (ret) {
2026 error_report("%s: Read section footer failed: %d",
2027 __func__, ret);
2028 return false;
2031 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2032 error_report("Missing section footer for %s", se->idstr);
2033 return false;
2036 read_section_id = qemu_get_be32(f);
2037 if (read_section_id != se->load_section_id) {
2038 error_report("Mismatched section id in footer for %s -"
2039 " read 0x%x expected 0x%x",
2040 se->idstr, read_section_id, se->load_section_id);
2041 return false;
2044 /* All good */
2045 return true;
2048 static int
2049 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2051 uint32_t instance_id, version_id, section_id;
2052 SaveStateEntry *se;
2053 char idstr[256];
2054 int ret;
2056 /* Read section start */
2057 section_id = qemu_get_be32(f);
2058 if (!qemu_get_counted_string(f, idstr)) {
2059 error_report("Unable to read ID string for section %u",
2060 section_id);
2061 return -EINVAL;
2063 instance_id = qemu_get_be32(f);
2064 version_id = qemu_get_be32(f);
2066 ret = qemu_file_get_error(f);
2067 if (ret) {
2068 error_report("%s: Failed to read instance/version ID: %d",
2069 __func__, ret);
2070 return ret;
2073 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2074 instance_id, version_id);
2075 /* Find savevm section */
2076 se = find_se(idstr, instance_id);
2077 if (se == NULL) {
2078 error_report("Unknown savevm section or instance '%s' %d",
2079 idstr, instance_id);
2080 return -EINVAL;
2083 /* Validate version */
2084 if (version_id > se->version_id) {
2085 error_report("savevm: unsupported version %d for '%s' v%d",
2086 version_id, idstr, se->version_id);
2087 return -EINVAL;
2089 se->load_version_id = version_id;
2090 se->load_section_id = section_id;
2092 /* Validate if it is a device's state */
2093 if (xen_enabled() && se->is_ram) {
2094 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2095 return -EINVAL;
2098 ret = vmstate_load(f, se);
2099 if (ret < 0) {
2100 error_report("error while loading state for instance 0x%x of"
2101 " device '%s'", instance_id, idstr);
2102 return ret;
2104 if (!check_section_footer(f, se)) {
2105 return -EINVAL;
2108 return 0;
2111 static int
2112 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2114 uint32_t section_id;
2115 SaveStateEntry *se;
2116 int ret;
2118 section_id = qemu_get_be32(f);
2120 ret = qemu_file_get_error(f);
2121 if (ret) {
2122 error_report("%s: Failed to read section ID: %d",
2123 __func__, ret);
2124 return ret;
2127 trace_qemu_loadvm_state_section_partend(section_id);
2128 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2129 if (se->load_section_id == section_id) {
2130 break;
2133 if (se == NULL) {
2134 error_report("Unknown savevm section %d", section_id);
2135 return -EINVAL;
2138 ret = vmstate_load(f, se);
2139 if (ret < 0) {
2140 error_report("error while loading state section id %d(%s)",
2141 section_id, se->idstr);
2142 return ret;
2144 if (!check_section_footer(f, se)) {
2145 return -EINVAL;
2148 return 0;
2151 static int qemu_loadvm_state_setup(QEMUFile *f)
2153 SaveStateEntry *se;
2154 int ret;
2156 trace_loadvm_state_setup();
2157 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2158 if (!se->ops || !se->ops->load_setup) {
2159 continue;
2161 if (se->ops && se->ops->is_active) {
2162 if (!se->ops->is_active(se->opaque)) {
2163 continue;
2167 ret = se->ops->load_setup(f, se->opaque);
2168 if (ret < 0) {
2169 qemu_file_set_error(f, ret);
2170 error_report("Load state of device %s failed", se->idstr);
2171 return ret;
2174 return 0;
2177 void qemu_loadvm_state_cleanup(void)
2179 SaveStateEntry *se;
2181 trace_loadvm_state_cleanup();
2182 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2183 if (se->ops && se->ops->load_cleanup) {
2184 se->ops->load_cleanup(se->opaque);
2189 /* Return true if we should continue the migration, or false. */
2190 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2192 trace_postcopy_pause_incoming();
2194 /* Clear the triggered bit to allow one recovery */
2195 mis->postcopy_recover_triggered = false;
2197 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2198 MIGRATION_STATUS_POSTCOPY_PAUSED);
2200 assert(mis->from_src_file);
2201 qemu_file_shutdown(mis->from_src_file);
2202 qemu_fclose(mis->from_src_file);
2203 mis->from_src_file = NULL;
2205 assert(mis->to_src_file);
2206 qemu_file_shutdown(mis->to_src_file);
2207 qemu_mutex_lock(&mis->rp_mutex);
2208 qemu_fclose(mis->to_src_file);
2209 mis->to_src_file = NULL;
2210 qemu_mutex_unlock(&mis->rp_mutex);
2212 /* Notify the fault thread for the invalidated file handle */
2213 postcopy_fault_thread_notify(mis);
2215 error_report("Detected IO failure for postcopy. "
2216 "Migration paused.");
2218 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2219 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2222 trace_postcopy_pause_incoming_continued();
2224 return true;
2227 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2229 uint8_t section_type;
2230 int ret = 0;
2232 retry:
2233 while (true) {
2234 section_type = qemu_get_byte(f);
2236 if (qemu_file_get_error(f)) {
2237 ret = qemu_file_get_error(f);
2238 break;
2241 trace_qemu_loadvm_state_section(section_type);
2242 switch (section_type) {
2243 case QEMU_VM_SECTION_START:
2244 case QEMU_VM_SECTION_FULL:
2245 ret = qemu_loadvm_section_start_full(f, mis);
2246 if (ret < 0) {
2247 goto out;
2249 break;
2250 case QEMU_VM_SECTION_PART:
2251 case QEMU_VM_SECTION_END:
2252 ret = qemu_loadvm_section_part_end(f, mis);
2253 if (ret < 0) {
2254 goto out;
2256 break;
2257 case QEMU_VM_COMMAND:
2258 ret = loadvm_process_command(f);
2259 trace_qemu_loadvm_state_section_command(ret);
2260 if ((ret < 0) || (ret & LOADVM_QUIT)) {
2261 goto out;
2263 break;
2264 case QEMU_VM_EOF:
2265 /* This is the end of migration */
2266 goto out;
2267 default:
2268 error_report("Unknown savevm section type %d", section_type);
2269 ret = -EINVAL;
2270 goto out;
2274 out:
2275 if (ret < 0) {
2276 qemu_file_set_error(f, ret);
2279 * Detect whether it is:
2281 * 1. postcopy running (after receiving all device data, which
2282 * must be in POSTCOPY_INCOMING_RUNNING state. Note that
2283 * POSTCOPY_INCOMING_LISTENING is still not enough, it's
2284 * still receiving device states).
2285 * 2. network failure (-EIO)
2287 * If so, we try to wait for a recovery.
2289 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2290 ret == -EIO && postcopy_pause_incoming(mis)) {
2291 /* Reset f to point to the newly created channel */
2292 f = mis->from_src_file;
2293 goto retry;
2296 return ret;
2299 int qemu_loadvm_state(QEMUFile *f)
2301 MigrationIncomingState *mis = migration_incoming_get_current();
2302 Error *local_err = NULL;
2303 unsigned int v;
2304 int ret;
2306 if (qemu_savevm_state_blocked(&local_err)) {
2307 error_report_err(local_err);
2308 return -EINVAL;
2311 v = qemu_get_be32(f);
2312 if (v != QEMU_VM_FILE_MAGIC) {
2313 error_report("Not a migration stream");
2314 return -EINVAL;
2317 v = qemu_get_be32(f);
2318 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2319 error_report("SaveVM v2 format is obsolete and don't work anymore");
2320 return -ENOTSUP;
2322 if (v != QEMU_VM_FILE_VERSION) {
2323 error_report("Unsupported migration stream version");
2324 return -ENOTSUP;
2327 if (qemu_loadvm_state_setup(f) != 0) {
2328 return -EINVAL;
2331 if (migrate_get_current()->send_configuration) {
2332 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2333 error_report("Configuration section missing");
2334 return -EINVAL;
2336 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2338 if (ret) {
2339 return ret;
2343 cpu_synchronize_all_pre_loadvm();
2345 ret = qemu_loadvm_state_main(f, mis);
2346 qemu_event_set(&mis->main_thread_load_event);
2348 trace_qemu_loadvm_state_post_main(ret);
2350 if (mis->have_listen_thread) {
2351 /* Listen thread still going, can't clean up yet */
2352 return ret;
2355 if (ret == 0) {
2356 ret = qemu_file_get_error(f);
2360 * Try to read in the VMDESC section as well, so that dumping tools that
2361 * intercept our migration stream have the chance to see it.
2364 /* We've got to be careful; if we don't read the data and just shut the fd
2365 * then the sender can error if we close while it's still sending.
2366 * We also mustn't read data that isn't there; some transports (RDMA)
2367 * will stall waiting for that data when the source has already closed.
2369 if (ret == 0 && should_send_vmdesc()) {
2370 uint8_t *buf;
2371 uint32_t size;
2372 uint8_t section_type = qemu_get_byte(f);
2374 if (section_type != QEMU_VM_VMDESCRIPTION) {
2375 error_report("Expected vmdescription section, but got %d",
2376 section_type);
2378 * It doesn't seem worth failing at this point since
2379 * we apparently have an otherwise valid VM state
2381 } else {
2382 buf = g_malloc(0x1000);
2383 size = qemu_get_be32(f);
2385 while (size > 0) {
2386 uint32_t read_chunk = MIN(size, 0x1000);
2387 qemu_get_buffer(f, buf, read_chunk);
2388 size -= read_chunk;
2390 g_free(buf);
2394 qemu_loadvm_state_cleanup();
2395 cpu_synchronize_all_post_init();
2397 return ret;
2400 int save_snapshot(const char *name, Error **errp)
2402 BlockDriverState *bs, *bs1;
2403 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2404 int ret = -1;
2405 QEMUFile *f;
2406 int saved_vm_running;
2407 uint64_t vm_state_size;
2408 qemu_timeval tv;
2409 struct tm tm;
2410 AioContext *aio_context;
2412 if (!replay_can_snapshot()) {
2413 error_report("Record/replay does not allow making snapshot "
2414 "right now. Try once more later.");
2415 return ret;
2418 if (!bdrv_all_can_snapshot(&bs)) {
2419 error_setg(errp, "Device '%s' is writable but does not support "
2420 "snapshots", bdrv_get_device_name(bs));
2421 return ret;
2424 /* Delete old snapshots of the same name */
2425 if (name) {
2426 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2427 if (ret < 0) {
2428 error_prepend(errp, "Error while deleting snapshot on device "
2429 "'%s': ", bdrv_get_device_name(bs1));
2430 return ret;
2434 bs = bdrv_all_find_vmstate_bs();
2435 if (bs == NULL) {
2436 error_setg(errp, "No block device can accept snapshots");
2437 return ret;
2439 aio_context = bdrv_get_aio_context(bs);
2441 saved_vm_running = runstate_is_running();
2443 ret = global_state_store();
2444 if (ret) {
2445 error_setg(errp, "Error saving global state");
2446 return ret;
2448 vm_stop(RUN_STATE_SAVE_VM);
2450 bdrv_drain_all_begin();
2452 aio_context_acquire(aio_context);
2454 memset(sn, 0, sizeof(*sn));
2456 /* fill auxiliary fields */
2457 qemu_gettimeofday(&tv);
2458 sn->date_sec = tv.tv_sec;
2459 sn->date_nsec = tv.tv_usec * 1000;
2460 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2462 if (name) {
2463 ret = bdrv_snapshot_find(bs, old_sn, name);
2464 if (ret >= 0) {
2465 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2466 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2467 } else {
2468 pstrcpy(sn->name, sizeof(sn->name), name);
2470 } else {
2471 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2472 localtime_r((const time_t *)&tv.tv_sec, &tm);
2473 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2476 /* save the VM state */
2477 f = qemu_fopen_bdrv(bs, 1);
2478 if (!f) {
2479 error_setg(errp, "Could not open VM state file");
2480 goto the_end;
2482 ret = qemu_savevm_state(f, errp);
2483 vm_state_size = qemu_ftell(f);
2484 qemu_fclose(f);
2485 if (ret < 0) {
2486 goto the_end;
2489 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2490 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2491 * it only releases the lock once. Therefore synchronous I/O will deadlock
2492 * unless we release the AioContext before bdrv_all_create_snapshot().
2494 aio_context_release(aio_context);
2495 aio_context = NULL;
2497 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2498 if (ret < 0) {
2499 error_setg(errp, "Error while creating snapshot on '%s'",
2500 bdrv_get_device_name(bs));
2501 goto the_end;
2504 ret = 0;
2506 the_end:
2507 if (aio_context) {
2508 aio_context_release(aio_context);
2511 bdrv_drain_all_end();
2513 if (saved_vm_running) {
2514 vm_start();
2516 return ret;
2519 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2520 Error **errp)
2522 QEMUFile *f;
2523 QIOChannelFile *ioc;
2524 int saved_vm_running;
2525 int ret;
2527 if (!has_live) {
2528 /* live default to true so old version of Xen tool stack can have a
2529 * successfull live migration */
2530 live = true;
2533 saved_vm_running = runstate_is_running();
2534 vm_stop(RUN_STATE_SAVE_VM);
2535 global_state_store_running();
2537 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2538 if (!ioc) {
2539 goto the_end;
2541 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2542 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2543 object_unref(OBJECT(ioc));
2544 ret = qemu_save_device_state(f);
2545 if (ret < 0 || qemu_fclose(f) < 0) {
2546 error_setg(errp, QERR_IO_ERROR);
2547 } else {
2548 /* libxl calls the QMP command "stop" before calling
2549 * "xen-save-devices-state" and in case of migration failure, libxl
2550 * would call "cont".
2551 * So call bdrv_inactivate_all (release locks) here to let the other
2552 * side of the migration take controle of the images.
2554 if (live && !saved_vm_running) {
2555 ret = bdrv_inactivate_all();
2556 if (ret) {
2557 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2558 __func__, ret);
2563 the_end:
2564 if (saved_vm_running) {
2565 vm_start();
2569 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2571 QEMUFile *f;
2572 QIOChannelFile *ioc;
2573 int ret;
2575 /* Guest must be paused before loading the device state; the RAM state
2576 * will already have been loaded by xc
2578 if (runstate_is_running()) {
2579 error_setg(errp, "Cannot update device state while vm is running");
2580 return;
2582 vm_stop(RUN_STATE_RESTORE_VM);
2584 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2585 if (!ioc) {
2586 return;
2588 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2589 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2590 object_unref(OBJECT(ioc));
2592 ret = qemu_loadvm_state(f);
2593 qemu_fclose(f);
2594 if (ret < 0) {
2595 error_setg(errp, QERR_IO_ERROR);
2597 migration_incoming_state_destroy();
2600 int load_snapshot(const char *name, Error **errp)
2602 BlockDriverState *bs, *bs_vm_state;
2603 QEMUSnapshotInfo sn;
2604 QEMUFile *f;
2605 int ret;
2606 AioContext *aio_context;
2607 MigrationIncomingState *mis = migration_incoming_get_current();
2609 if (!replay_can_snapshot()) {
2610 error_report("Record/replay does not allow loading snapshot "
2611 "right now. Try once more later.");
2612 return -EINVAL;
2615 if (!bdrv_all_can_snapshot(&bs)) {
2616 error_setg(errp,
2617 "Device '%s' is writable but does not support snapshots",
2618 bdrv_get_device_name(bs));
2619 return -ENOTSUP;
2621 ret = bdrv_all_find_snapshot(name, &bs);
2622 if (ret < 0) {
2623 error_setg(errp,
2624 "Device '%s' does not have the requested snapshot '%s'",
2625 bdrv_get_device_name(bs), name);
2626 return ret;
2629 bs_vm_state = bdrv_all_find_vmstate_bs();
2630 if (!bs_vm_state) {
2631 error_setg(errp, "No block device supports snapshots");
2632 return -ENOTSUP;
2634 aio_context = bdrv_get_aio_context(bs_vm_state);
2636 /* Don't even try to load empty VM states */
2637 aio_context_acquire(aio_context);
2638 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2639 aio_context_release(aio_context);
2640 if (ret < 0) {
2641 return ret;
2642 } else if (sn.vm_state_size == 0) {
2643 error_setg(errp, "This is a disk-only snapshot. Revert to it "
2644 " offline using qemu-img");
2645 return -EINVAL;
2648 /* Flush all IO requests so they don't interfere with the new state. */
2649 bdrv_drain_all_begin();
2651 ret = bdrv_all_goto_snapshot(name, &bs, errp);
2652 if (ret < 0) {
2653 error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
2654 name, bdrv_get_device_name(bs));
2655 goto err_drain;
2658 /* restore the VM state */
2659 f = qemu_fopen_bdrv(bs_vm_state, 0);
2660 if (!f) {
2661 error_setg(errp, "Could not open VM state file");
2662 ret = -EINVAL;
2663 goto err_drain;
2666 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2667 mis->from_src_file = f;
2669 aio_context_acquire(aio_context);
2670 ret = qemu_loadvm_state(f);
2671 migration_incoming_state_destroy();
2672 aio_context_release(aio_context);
2674 bdrv_drain_all_end();
2676 if (ret < 0) {
2677 error_setg(errp, "Error %d while loading VM state", ret);
2678 return ret;
2681 return 0;
2683 err_drain:
2684 bdrv_drain_all_end();
2685 return ret;
2688 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2690 qemu_ram_set_idstr(mr->ram_block,
2691 memory_region_name(mr), dev);
2692 qemu_ram_set_migratable(mr->ram_block);
2695 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2697 qemu_ram_unset_idstr(mr->ram_block);
2698 qemu_ram_unset_migratable(mr->ram_block);
2701 void vmstate_register_ram_global(MemoryRegion *mr)
2703 vmstate_register_ram(mr, NULL);
2706 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2708 /* check needed if --only-migratable is specified */
2709 if (!migrate_get_current()->only_migratable) {
2710 return true;
2713 return !(vmsd && vmsd->unmigratable);