migration: new cmd MIG_CMD_RECV_BITMAP
[qemu/ar7.git] / migration / savevm.c
blob9f4a95d411246893d920eeeaa3805bf3f1f4a3a8
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"
59 #ifndef ETH_P_RARP
60 #define ETH_P_RARP 0x8035
61 #endif
62 #define ARP_HTYPE_ETH 0x0001
63 #define ARP_PTYPE_IP 0x0800
64 #define ARP_OP_REQUEST_REV 0x3
66 const unsigned int postcopy_ram_discard_version = 0;
68 /* Subcommands for QEMU_VM_COMMAND */
69 enum qemu_vm_cmd {
70 MIG_CMD_INVALID = 0, /* Must be 0 */
71 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
72 MIG_CMD_PING, /* Request a PONG on the RP */
74 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
75 warn we might want to do PC */
76 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
77 pages as it's running. */
78 MIG_CMD_POSTCOPY_RUN, /* Start execution */
80 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
81 were previously sent during
82 precopy but are dirty. */
83 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
84 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
85 MIG_CMD_MAX
88 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
89 static struct mig_cmd_args {
90 ssize_t len; /* -1 = variable */
91 const char *name;
92 } mig_cmd_args[] = {
93 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
94 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
95 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
96 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
97 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
98 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
99 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
100 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
101 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
102 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
103 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
106 /* Note for MIG_CMD_POSTCOPY_ADVISE:
107 * The format of arguments is depending on postcopy mode:
108 * - postcopy RAM only
109 * uint64_t host page size
110 * uint64_t taget page size
112 * - postcopy RAM and postcopy dirty bitmaps
113 * format is the same as for postcopy RAM only
115 * - postcopy dirty bitmaps only
116 * Nothing. Command length field is 0.
118 * Be careful: adding a new postcopy entity with some other parameters should
119 * not break format self-description ability. Good way is to introduce some
120 * generic extendable format with an exception for two old entities.
123 static int announce_self_create(uint8_t *buf,
124 uint8_t *mac_addr)
126 /* Ethernet header. */
127 memset(buf, 0xff, 6); /* destination MAC addr */
128 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
129 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
131 /* RARP header. */
132 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
133 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
134 *(buf + 18) = 6; /* hardware addr length (ethernet) */
135 *(buf + 19) = 4; /* protocol addr length (IPv4) */
136 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
137 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
138 memset(buf + 28, 0x00, 4); /* source protocol addr */
139 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
140 memset(buf + 38, 0x00, 4); /* target protocol addr */
142 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
143 memset(buf + 42, 0x00, 18);
145 return 60; /* len (FCS will be added by hardware) */
148 static void qemu_announce_self_iter(NICState *nic, void *opaque)
150 uint8_t buf[60];
151 int len;
153 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic->conf->macaddr));
154 len = announce_self_create(buf, nic->conf->macaddr.a);
156 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
160 static void qemu_announce_self_once(void *opaque)
162 static int count = SELF_ANNOUNCE_ROUNDS;
163 QEMUTimer *timer = *(QEMUTimer **)opaque;
165 qemu_foreach_nic(qemu_announce_self_iter, NULL);
167 if (--count) {
168 /* delay 50ms, 150ms, 250ms, ... */
169 timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
170 self_announce_delay(count));
171 } else {
172 timer_del(timer);
173 timer_free(timer);
177 void qemu_announce_self(void)
179 static QEMUTimer *timer;
180 timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
181 qemu_announce_self_once(&timer);
184 /***********************************************************/
185 /* savevm/loadvm support */
187 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
188 int64_t pos)
190 int ret;
191 QEMUIOVector qiov;
193 qemu_iovec_init_external(&qiov, iov, iovcnt);
194 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
195 if (ret < 0) {
196 return ret;
199 return qiov.size;
202 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
203 size_t size)
205 return bdrv_load_vmstate(opaque, buf, pos, size);
208 static int bdrv_fclose(void *opaque)
210 return bdrv_flush(opaque);
213 static const QEMUFileOps bdrv_read_ops = {
214 .get_buffer = block_get_buffer,
215 .close = bdrv_fclose
218 static const QEMUFileOps bdrv_write_ops = {
219 .writev_buffer = block_writev_buffer,
220 .close = bdrv_fclose
223 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
225 if (is_writable) {
226 return qemu_fopen_ops(bs, &bdrv_write_ops);
228 return qemu_fopen_ops(bs, &bdrv_read_ops);
232 /* QEMUFile timer support.
233 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
236 void timer_put(QEMUFile *f, QEMUTimer *ts)
238 uint64_t expire_time;
240 expire_time = timer_expire_time_ns(ts);
241 qemu_put_be64(f, expire_time);
244 void timer_get(QEMUFile *f, QEMUTimer *ts)
246 uint64_t expire_time;
248 expire_time = qemu_get_be64(f);
249 if (expire_time != -1) {
250 timer_mod_ns(ts, expire_time);
251 } else {
252 timer_del(ts);
257 /* VMState timer support.
258 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
261 static int get_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field)
263 QEMUTimer *v = pv;
264 timer_get(f, v);
265 return 0;
268 static int put_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field,
269 QJSON *vmdesc)
271 QEMUTimer *v = pv;
272 timer_put(f, v);
274 return 0;
277 const VMStateInfo vmstate_info_timer = {
278 .name = "timer",
279 .get = get_timer,
280 .put = put_timer,
284 typedef struct CompatEntry {
285 char idstr[256];
286 int instance_id;
287 } CompatEntry;
289 typedef struct SaveStateEntry {
290 QTAILQ_ENTRY(SaveStateEntry) entry;
291 char idstr[256];
292 int instance_id;
293 int alias_id;
294 int version_id;
295 /* version id read from the stream */
296 int load_version_id;
297 int section_id;
298 /* section id read from the stream */
299 int load_section_id;
300 SaveVMHandlers *ops;
301 const VMStateDescription *vmsd;
302 void *opaque;
303 CompatEntry *compat;
304 int is_ram;
305 } SaveStateEntry;
307 typedef struct SaveState {
308 QTAILQ_HEAD(, SaveStateEntry) handlers;
309 int global_section_id;
310 uint32_t len;
311 const char *name;
312 uint32_t target_page_bits;
313 } SaveState;
315 static SaveState savevm_state = {
316 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
317 .global_section_id = 0,
320 static int configuration_pre_save(void *opaque)
322 SaveState *state = opaque;
323 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
325 state->len = strlen(current_name);
326 state->name = current_name;
327 state->target_page_bits = qemu_target_page_bits();
329 return 0;
332 static int configuration_pre_load(void *opaque)
334 SaveState *state = opaque;
336 /* If there is no target-page-bits subsection it means the source
337 * predates the variable-target-page-bits support and is using the
338 * minimum possible value for this CPU.
340 state->target_page_bits = qemu_target_page_bits_min();
341 return 0;
344 static int configuration_post_load(void *opaque, int version_id)
346 SaveState *state = opaque;
347 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
349 if (strncmp(state->name, current_name, state->len) != 0) {
350 error_report("Machine type received is '%.*s' and local is '%s'",
351 (int) state->len, state->name, current_name);
352 return -EINVAL;
355 if (state->target_page_bits != qemu_target_page_bits()) {
356 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
357 state->target_page_bits, qemu_target_page_bits());
358 return -EINVAL;
361 return 0;
364 /* The target-page-bits subsection is present only if the
365 * target page size is not the same as the default (ie the
366 * minimum page size for a variable-page-size guest CPU).
367 * If it is present then it contains the actual target page
368 * bits for the machine, and migration will fail if the
369 * two ends don't agree about it.
371 static bool vmstate_target_page_bits_needed(void *opaque)
373 return qemu_target_page_bits()
374 > qemu_target_page_bits_min();
377 static const VMStateDescription vmstate_target_page_bits = {
378 .name = "configuration/target-page-bits",
379 .version_id = 1,
380 .minimum_version_id = 1,
381 .needed = vmstate_target_page_bits_needed,
382 .fields = (VMStateField[]) {
383 VMSTATE_UINT32(target_page_bits, SaveState),
384 VMSTATE_END_OF_LIST()
388 static const VMStateDescription vmstate_configuration = {
389 .name = "configuration",
390 .version_id = 1,
391 .pre_load = configuration_pre_load,
392 .post_load = configuration_post_load,
393 .pre_save = configuration_pre_save,
394 .fields = (VMStateField[]) {
395 VMSTATE_UINT32(len, SaveState),
396 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
397 VMSTATE_END_OF_LIST()
399 .subsections = (const VMStateDescription*[]) {
400 &vmstate_target_page_bits,
401 NULL
405 static void dump_vmstate_vmsd(FILE *out_file,
406 const VMStateDescription *vmsd, int indent,
407 bool is_subsection);
409 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
410 int indent)
412 fprintf(out_file, "%*s{\n", indent, "");
413 indent += 2;
414 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
415 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
416 field->version_id);
417 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
418 field->field_exists ? "true" : "false");
419 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
420 if (field->vmsd != NULL) {
421 fprintf(out_file, ",\n");
422 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
424 fprintf(out_file, "\n%*s}", indent - 2, "");
427 static void dump_vmstate_vmss(FILE *out_file,
428 const VMStateDescription **subsection,
429 int indent)
431 if (*subsection != NULL) {
432 dump_vmstate_vmsd(out_file, *subsection, indent, true);
436 static void dump_vmstate_vmsd(FILE *out_file,
437 const VMStateDescription *vmsd, int indent,
438 bool is_subsection)
440 if (is_subsection) {
441 fprintf(out_file, "%*s{\n", indent, "");
442 } else {
443 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
445 indent += 2;
446 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
447 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
448 vmsd->version_id);
449 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
450 vmsd->minimum_version_id);
451 if (vmsd->fields != NULL) {
452 const VMStateField *field = vmsd->fields;
453 bool first;
455 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
456 first = true;
457 while (field->name != NULL) {
458 if (field->flags & VMS_MUST_EXIST) {
459 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
460 field++;
461 continue;
463 if (!first) {
464 fprintf(out_file, ",\n");
466 dump_vmstate_vmsf(out_file, field, indent + 2);
467 field++;
468 first = false;
470 fprintf(out_file, "\n%*s]", indent, "");
472 if (vmsd->subsections != NULL) {
473 const VMStateDescription **subsection = vmsd->subsections;
474 bool first;
476 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
477 first = true;
478 while (*subsection != NULL) {
479 if (!first) {
480 fprintf(out_file, ",\n");
482 dump_vmstate_vmss(out_file, subsection, indent + 2);
483 subsection++;
484 first = false;
486 fprintf(out_file, "\n%*s]", indent, "");
488 fprintf(out_file, "\n%*s}", indent - 2, "");
491 static void dump_machine_type(FILE *out_file)
493 MachineClass *mc;
495 mc = MACHINE_GET_CLASS(current_machine);
497 fprintf(out_file, " \"vmschkmachine\": {\n");
498 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
499 fprintf(out_file, " },\n");
502 void dump_vmstate_json_to_file(FILE *out_file)
504 GSList *list, *elt;
505 bool first;
507 fprintf(out_file, "{\n");
508 dump_machine_type(out_file);
510 first = true;
511 list = object_class_get_list(TYPE_DEVICE, true);
512 for (elt = list; elt; elt = elt->next) {
513 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
514 TYPE_DEVICE);
515 const char *name;
516 int indent = 2;
518 if (!dc->vmsd) {
519 continue;
522 if (!first) {
523 fprintf(out_file, ",\n");
525 name = object_class_get_name(OBJECT_CLASS(dc));
526 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
527 indent += 2;
528 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
529 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
530 dc->vmsd->version_id);
531 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
532 dc->vmsd->minimum_version_id);
534 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
536 fprintf(out_file, "\n%*s}", indent - 2, "");
537 first = false;
539 fprintf(out_file, "\n}\n");
540 fclose(out_file);
543 static int calculate_new_instance_id(const char *idstr)
545 SaveStateEntry *se;
546 int instance_id = 0;
548 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
549 if (strcmp(idstr, se->idstr) == 0
550 && instance_id <= se->instance_id) {
551 instance_id = se->instance_id + 1;
554 return instance_id;
557 static int calculate_compat_instance_id(const char *idstr)
559 SaveStateEntry *se;
560 int instance_id = 0;
562 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
563 if (!se->compat) {
564 continue;
567 if (strcmp(idstr, se->compat->idstr) == 0
568 && instance_id <= se->compat->instance_id) {
569 instance_id = se->compat->instance_id + 1;
572 return instance_id;
575 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
577 if (se->vmsd) {
578 return se->vmsd->priority;
580 return MIG_PRI_DEFAULT;
583 static void savevm_state_handler_insert(SaveStateEntry *nse)
585 MigrationPriority priority = save_state_priority(nse);
586 SaveStateEntry *se;
588 assert(priority <= MIG_PRI_MAX);
590 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
591 if (save_state_priority(se) < priority) {
592 break;
596 if (se) {
597 QTAILQ_INSERT_BEFORE(se, nse, entry);
598 } else {
599 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
603 /* TODO: Individual devices generally have very little idea about the rest
604 of the system, so instance_id should be removed/replaced.
605 Meanwhile pass -1 as instance_id if you do not already have a clearly
606 distinguishing id for all instances of your device class. */
607 int register_savevm_live(DeviceState *dev,
608 const char *idstr,
609 int instance_id,
610 int version_id,
611 SaveVMHandlers *ops,
612 void *opaque)
614 SaveStateEntry *se;
616 se = g_new0(SaveStateEntry, 1);
617 se->version_id = version_id;
618 se->section_id = savevm_state.global_section_id++;
619 se->ops = ops;
620 se->opaque = opaque;
621 se->vmsd = NULL;
622 /* if this is a live_savem then set is_ram */
623 if (ops->save_setup != NULL) {
624 se->is_ram = 1;
627 if (dev) {
628 char *id = qdev_get_dev_path(dev);
629 if (id) {
630 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
631 sizeof(se->idstr)) {
632 error_report("Path too long for VMState (%s)", id);
633 g_free(id);
634 g_free(se);
636 return -1;
638 g_free(id);
640 se->compat = g_new0(CompatEntry, 1);
641 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
642 se->compat->instance_id = instance_id == -1 ?
643 calculate_compat_instance_id(idstr) : instance_id;
644 instance_id = -1;
647 pstrcat(se->idstr, sizeof(se->idstr), idstr);
649 if (instance_id == -1) {
650 se->instance_id = calculate_new_instance_id(se->idstr);
651 } else {
652 se->instance_id = instance_id;
654 assert(!se->compat || se->instance_id == 0);
655 savevm_state_handler_insert(se);
656 return 0;
659 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
661 SaveStateEntry *se, *new_se;
662 char id[256] = "";
664 if (dev) {
665 char *path = qdev_get_dev_path(dev);
666 if (path) {
667 pstrcpy(id, sizeof(id), path);
668 pstrcat(id, sizeof(id), "/");
669 g_free(path);
672 pstrcat(id, sizeof(id), idstr);
674 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
675 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
676 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
677 g_free(se->compat);
678 g_free(se);
683 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
684 const VMStateDescription *vmsd,
685 void *opaque, int alias_id,
686 int required_for_version,
687 Error **errp)
689 SaveStateEntry *se;
691 /* If this triggers, alias support can be dropped for the vmsd. */
692 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
694 se = g_new0(SaveStateEntry, 1);
695 se->version_id = vmsd->version_id;
696 se->section_id = savevm_state.global_section_id++;
697 se->opaque = opaque;
698 se->vmsd = vmsd;
699 se->alias_id = alias_id;
701 if (dev) {
702 char *id = qdev_get_dev_path(dev);
703 if (id) {
704 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
705 sizeof(se->idstr)) {
706 error_setg(errp, "Path too long for VMState (%s)", id);
707 g_free(id);
708 g_free(se);
710 return -1;
712 g_free(id);
714 se->compat = g_new0(CompatEntry, 1);
715 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
716 se->compat->instance_id = instance_id == -1 ?
717 calculate_compat_instance_id(vmsd->name) : instance_id;
718 instance_id = -1;
721 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
723 if (instance_id == -1) {
724 se->instance_id = calculate_new_instance_id(se->idstr);
725 } else {
726 se->instance_id = instance_id;
728 assert(!se->compat || se->instance_id == 0);
729 savevm_state_handler_insert(se);
730 return 0;
733 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
734 void *opaque)
736 SaveStateEntry *se, *new_se;
738 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
739 if (se->vmsd == vmsd && se->opaque == opaque) {
740 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
741 g_free(se->compat);
742 g_free(se);
747 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
749 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
750 if (!se->vmsd) { /* Old style */
751 return se->ops->load_state(f, se->opaque, se->load_version_id);
753 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
756 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
758 int64_t old_offset, size;
760 old_offset = qemu_ftell_fast(f);
761 se->ops->save_state(f, se->opaque);
762 size = qemu_ftell_fast(f) - old_offset;
764 if (vmdesc) {
765 json_prop_int(vmdesc, "size", size);
766 json_start_array(vmdesc, "fields");
767 json_start_object(vmdesc, NULL);
768 json_prop_str(vmdesc, "name", "data");
769 json_prop_int(vmdesc, "size", size);
770 json_prop_str(vmdesc, "type", "buffer");
771 json_end_object(vmdesc);
772 json_end_array(vmdesc);
776 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
778 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
779 if (!se->vmsd) {
780 vmstate_save_old_style(f, se, vmdesc);
781 return 0;
783 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
787 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
789 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
790 uint8_t section_type)
792 qemu_put_byte(f, section_type);
793 qemu_put_be32(f, se->section_id);
795 if (section_type == QEMU_VM_SECTION_FULL ||
796 section_type == QEMU_VM_SECTION_START) {
797 /* ID string */
798 size_t len = strlen(se->idstr);
799 qemu_put_byte(f, len);
800 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
802 qemu_put_be32(f, se->instance_id);
803 qemu_put_be32(f, se->version_id);
808 * Write a footer onto device sections that catches cases misformatted device
809 * sections.
811 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
813 if (migrate_get_current()->send_section_footer) {
814 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
815 qemu_put_be32(f, se->section_id);
820 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
821 * command and associated data.
823 * @f: File to send command on
824 * @command: Command type to send
825 * @len: Length of associated data
826 * @data: Data associated with command.
828 static void qemu_savevm_command_send(QEMUFile *f,
829 enum qemu_vm_cmd command,
830 uint16_t len,
831 uint8_t *data)
833 trace_savevm_command_send(command, len);
834 qemu_put_byte(f, QEMU_VM_COMMAND);
835 qemu_put_be16(f, (uint16_t)command);
836 qemu_put_be16(f, len);
837 qemu_put_buffer(f, data, len);
838 qemu_fflush(f);
841 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
843 uint32_t buf;
845 trace_savevm_send_ping(value);
846 buf = cpu_to_be32(value);
847 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
850 void qemu_savevm_send_open_return_path(QEMUFile *f)
852 trace_savevm_send_open_return_path();
853 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
856 /* We have a buffer of data to send; we don't want that all to be loaded
857 * by the command itself, so the command contains just the length of the
858 * extra buffer that we then send straight after it.
859 * TODO: Must be a better way to organise that
861 * Returns:
862 * 0 on success
863 * -ve on error
865 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
867 uint32_t tmp;
869 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
870 error_report("%s: Unreasonably large packaged state: %zu",
871 __func__, len);
872 return -1;
875 tmp = cpu_to_be32(len);
877 trace_qemu_savevm_send_packaged();
878 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
880 qemu_put_buffer(f, buf, len);
882 return 0;
885 /* Send prior to any postcopy transfer */
886 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
888 if (migrate_postcopy_ram()) {
889 uint64_t tmp[2];
890 tmp[0] = cpu_to_be64(ram_pagesize_summary());
891 tmp[1] = cpu_to_be64(qemu_target_page_size());
893 trace_qemu_savevm_send_postcopy_advise();
894 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
895 16, (uint8_t *)tmp);
896 } else {
897 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
901 /* Sent prior to starting the destination running in postcopy, discard pages
902 * that have already been sent but redirtied on the source.
903 * CMD_POSTCOPY_RAM_DISCARD consist of:
904 * byte version (0)
905 * byte Length of name field (not including 0)
906 * n x byte RAM block name
907 * byte 0 terminator (just for safety)
908 * n x Byte ranges within the named RAMBlock
909 * be64 Start of the range
910 * be64 Length
912 * name: RAMBlock name that these entries are part of
913 * len: Number of page entries
914 * start_list: 'len' addresses
915 * length_list: 'len' addresses
918 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
919 uint16_t len,
920 uint64_t *start_list,
921 uint64_t *length_list)
923 uint8_t *buf;
924 uint16_t tmplen;
925 uint16_t t;
926 size_t name_len = strlen(name);
928 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
929 assert(name_len < 256);
930 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
931 buf[0] = postcopy_ram_discard_version;
932 buf[1] = name_len;
933 memcpy(buf + 2, name, name_len);
934 tmplen = 2 + name_len;
935 buf[tmplen++] = '\0';
937 for (t = 0; t < len; t++) {
938 stq_be_p(buf + tmplen, start_list[t]);
939 tmplen += 8;
940 stq_be_p(buf + tmplen, length_list[t]);
941 tmplen += 8;
943 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
944 g_free(buf);
947 /* Get the destination into a state where it can receive postcopy data. */
948 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
950 trace_savevm_send_postcopy_listen();
951 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
954 /* Kick the destination into running */
955 void qemu_savevm_send_postcopy_run(QEMUFile *f)
957 trace_savevm_send_postcopy_run();
958 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
961 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
963 size_t len;
964 char buf[256];
966 trace_savevm_send_recv_bitmap(block_name);
968 buf[0] = len = strlen(block_name);
969 memcpy(buf + 1, block_name, len);
971 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
974 bool qemu_savevm_state_blocked(Error **errp)
976 SaveStateEntry *se;
978 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
979 if (se->vmsd && se->vmsd->unmigratable) {
980 error_setg(errp, "State blocked by non-migratable device '%s'",
981 se->idstr);
982 return true;
985 return false;
988 void qemu_savevm_state_header(QEMUFile *f)
990 trace_savevm_state_header();
991 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
992 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
994 if (migrate_get_current()->send_configuration) {
995 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
996 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1000 void qemu_savevm_state_setup(QEMUFile *f)
1002 SaveStateEntry *se;
1003 int ret;
1005 trace_savevm_state_setup();
1006 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1007 if (!se->ops || !se->ops->save_setup) {
1008 continue;
1010 if (se->ops && se->ops->is_active) {
1011 if (!se->ops->is_active(se->opaque)) {
1012 continue;
1015 save_section_header(f, se, QEMU_VM_SECTION_START);
1017 ret = se->ops->save_setup(f, se->opaque);
1018 save_section_footer(f, se);
1019 if (ret < 0) {
1020 qemu_file_set_error(f, ret);
1021 break;
1027 * this function has three return values:
1028 * negative: there was one error, and we have -errno.
1029 * 0 : We haven't finished, caller have to go again
1030 * 1 : We have finished, we can go to complete phase
1032 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1034 SaveStateEntry *se;
1035 int ret = 1;
1037 trace_savevm_state_iterate();
1038 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1039 if (!se->ops || !se->ops->save_live_iterate) {
1040 continue;
1042 if (se->ops && se->ops->is_active) {
1043 if (!se->ops->is_active(se->opaque)) {
1044 continue;
1047 if (se->ops && se->ops->is_active_iterate) {
1048 if (!se->ops->is_active_iterate(se->opaque)) {
1049 continue;
1053 * In the postcopy phase, any device that doesn't know how to
1054 * do postcopy should have saved it's state in the _complete
1055 * call that's already run, it might get confused if we call
1056 * iterate afterwards.
1058 if (postcopy &&
1059 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1060 continue;
1062 if (qemu_file_rate_limit(f)) {
1063 return 0;
1065 trace_savevm_section_start(se->idstr, se->section_id);
1067 save_section_header(f, se, QEMU_VM_SECTION_PART);
1069 ret = se->ops->save_live_iterate(f, se->opaque);
1070 trace_savevm_section_end(se->idstr, se->section_id, ret);
1071 save_section_footer(f, se);
1073 if (ret < 0) {
1074 qemu_file_set_error(f, ret);
1076 if (ret <= 0) {
1077 /* Do not proceed to the next vmstate before this one reported
1078 completion of the current stage. This serializes the migration
1079 and reduces the probability that a faster changing state is
1080 synchronized over and over again. */
1081 break;
1084 return ret;
1087 static bool should_send_vmdesc(void)
1089 MachineState *machine = MACHINE(qdev_get_machine());
1090 bool in_postcopy = migration_in_postcopy();
1091 return !machine->suppress_vmdesc && !in_postcopy;
1095 * Calls the save_live_complete_postcopy methods
1096 * causing the last few pages to be sent immediately and doing any associated
1097 * cleanup.
1098 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1099 * all the other devices, but that happens at the point we switch to postcopy.
1101 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1103 SaveStateEntry *se;
1104 int ret;
1106 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1107 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1108 continue;
1110 if (se->ops && se->ops->is_active) {
1111 if (!se->ops->is_active(se->opaque)) {
1112 continue;
1115 trace_savevm_section_start(se->idstr, se->section_id);
1116 /* Section type */
1117 qemu_put_byte(f, QEMU_VM_SECTION_END);
1118 qemu_put_be32(f, se->section_id);
1120 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1121 trace_savevm_section_end(se->idstr, se->section_id, ret);
1122 save_section_footer(f, se);
1123 if (ret < 0) {
1124 qemu_file_set_error(f, ret);
1125 return;
1129 qemu_put_byte(f, QEMU_VM_EOF);
1130 qemu_fflush(f);
1133 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1134 bool inactivate_disks)
1136 QJSON *vmdesc;
1137 int vmdesc_len;
1138 SaveStateEntry *se;
1139 int ret;
1140 bool in_postcopy = migration_in_postcopy();
1142 trace_savevm_state_complete_precopy();
1144 cpu_synchronize_all_states();
1146 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1147 if (!se->ops ||
1148 (in_postcopy && se->ops->has_postcopy &&
1149 se->ops->has_postcopy(se->opaque)) ||
1150 (in_postcopy && !iterable_only) ||
1151 !se->ops->save_live_complete_precopy) {
1152 continue;
1155 if (se->ops && se->ops->is_active) {
1156 if (!se->ops->is_active(se->opaque)) {
1157 continue;
1160 trace_savevm_section_start(se->idstr, se->section_id);
1162 save_section_header(f, se, QEMU_VM_SECTION_END);
1164 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1165 trace_savevm_section_end(se->idstr, se->section_id, ret);
1166 save_section_footer(f, se);
1167 if (ret < 0) {
1168 qemu_file_set_error(f, ret);
1169 return -1;
1173 if (iterable_only) {
1174 return 0;
1177 vmdesc = qjson_new();
1178 json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1179 json_start_array(vmdesc, "devices");
1180 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1182 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1183 continue;
1185 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1186 trace_savevm_section_skip(se->idstr, se->section_id);
1187 continue;
1190 trace_savevm_section_start(se->idstr, se->section_id);
1192 json_start_object(vmdesc, NULL);
1193 json_prop_str(vmdesc, "name", se->idstr);
1194 json_prop_int(vmdesc, "instance_id", se->instance_id);
1196 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1197 ret = vmstate_save(f, se, vmdesc);
1198 if (ret) {
1199 qemu_file_set_error(f, ret);
1200 return ret;
1202 trace_savevm_section_end(se->idstr, se->section_id, 0);
1203 save_section_footer(f, se);
1205 json_end_object(vmdesc);
1208 if (inactivate_disks) {
1209 /* Inactivate before sending QEMU_VM_EOF so that the
1210 * bdrv_invalidate_cache_all() on the other end won't fail. */
1211 ret = bdrv_inactivate_all();
1212 if (ret) {
1213 error_report("%s: bdrv_inactivate_all() failed (%d)",
1214 __func__, ret);
1215 qemu_file_set_error(f, ret);
1216 return ret;
1219 if (!in_postcopy) {
1220 /* Postcopy stream will still be going */
1221 qemu_put_byte(f, QEMU_VM_EOF);
1224 json_end_array(vmdesc);
1225 qjson_finish(vmdesc);
1226 vmdesc_len = strlen(qjson_get_str(vmdesc));
1228 if (should_send_vmdesc()) {
1229 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1230 qemu_put_be32(f, vmdesc_len);
1231 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1233 qjson_destroy(vmdesc);
1235 qemu_fflush(f);
1236 return 0;
1239 /* Give an estimate of the amount left to be transferred,
1240 * the result is split into the amount for units that can and
1241 * for units that can't do postcopy.
1243 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1244 uint64_t *res_precopy_only,
1245 uint64_t *res_compatible,
1246 uint64_t *res_postcopy_only)
1248 SaveStateEntry *se;
1250 *res_precopy_only = 0;
1251 *res_compatible = 0;
1252 *res_postcopy_only = 0;
1255 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1256 if (!se->ops || !se->ops->save_live_pending) {
1257 continue;
1259 if (se->ops && se->ops->is_active) {
1260 if (!se->ops->is_active(se->opaque)) {
1261 continue;
1264 se->ops->save_live_pending(f, se->opaque, threshold_size,
1265 res_precopy_only, res_compatible,
1266 res_postcopy_only);
1270 void qemu_savevm_state_cleanup(void)
1272 SaveStateEntry *se;
1274 trace_savevm_state_cleanup();
1275 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1276 if (se->ops && se->ops->save_cleanup) {
1277 se->ops->save_cleanup(se->opaque);
1282 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1284 int ret;
1285 MigrationState *ms = migrate_get_current();
1286 MigrationStatus status;
1288 migrate_init(ms);
1290 ms->to_dst_file = f;
1292 if (migration_is_blocked(errp)) {
1293 ret = -EINVAL;
1294 goto done;
1297 if (migrate_use_block()) {
1298 error_setg(errp, "Block migration and snapshots are incompatible");
1299 ret = -EINVAL;
1300 goto done;
1303 qemu_mutex_unlock_iothread();
1304 qemu_savevm_state_header(f);
1305 qemu_savevm_state_setup(f);
1306 qemu_mutex_lock_iothread();
1308 while (qemu_file_get_error(f) == 0) {
1309 if (qemu_savevm_state_iterate(f, false) > 0) {
1310 break;
1314 ret = qemu_file_get_error(f);
1315 if (ret == 0) {
1316 qemu_savevm_state_complete_precopy(f, false, false);
1317 ret = qemu_file_get_error(f);
1319 qemu_savevm_state_cleanup();
1320 if (ret != 0) {
1321 error_setg_errno(errp, -ret, "Error while writing VM state");
1324 done:
1325 if (ret != 0) {
1326 status = MIGRATION_STATUS_FAILED;
1327 } else {
1328 status = MIGRATION_STATUS_COMPLETED;
1330 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1332 /* f is outer parameter, it should not stay in global migration state after
1333 * this function finished */
1334 ms->to_dst_file = NULL;
1336 return ret;
1339 static int qemu_save_device_state(QEMUFile *f)
1341 SaveStateEntry *se;
1343 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1344 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1346 cpu_synchronize_all_states();
1348 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1349 int ret;
1351 if (se->is_ram) {
1352 continue;
1354 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1355 continue;
1357 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1358 continue;
1361 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1363 ret = vmstate_save(f, se, NULL);
1364 if (ret) {
1365 return ret;
1368 save_section_footer(f, se);
1371 qemu_put_byte(f, QEMU_VM_EOF);
1373 return qemu_file_get_error(f);
1376 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1378 SaveStateEntry *se;
1380 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1381 if (!strcmp(se->idstr, idstr) &&
1382 (instance_id == se->instance_id ||
1383 instance_id == se->alias_id))
1384 return se;
1385 /* Migrating from an older version? */
1386 if (strstr(se->idstr, idstr) && se->compat) {
1387 if (!strcmp(se->compat->idstr, idstr) &&
1388 (instance_id == se->compat->instance_id ||
1389 instance_id == se->alias_id))
1390 return se;
1393 return NULL;
1396 enum LoadVMExitCodes {
1397 /* Allow a command to quit all layers of nested loadvm loops */
1398 LOADVM_QUIT = 1,
1401 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
1403 /* ------ incoming postcopy messages ------ */
1404 /* 'advise' arrives before any transfers just to tell us that a postcopy
1405 * *might* happen - it might be skipped if precopy transferred everything
1406 * quickly.
1408 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1409 uint16_t len)
1411 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1412 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1413 Error *local_err = NULL;
1415 trace_loadvm_postcopy_handle_advise();
1416 if (ps != POSTCOPY_INCOMING_NONE) {
1417 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1418 return -1;
1421 switch (len) {
1422 case 0:
1423 if (migrate_postcopy_ram()) {
1424 error_report("RAM postcopy is enabled but have 0 byte advise");
1425 return -EINVAL;
1427 return 0;
1428 case 8 + 8:
1429 if (!migrate_postcopy_ram()) {
1430 error_report("RAM postcopy is disabled but have 16 byte advise");
1431 return -EINVAL;
1433 break;
1434 default:
1435 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1436 return -EINVAL;
1439 if (!postcopy_ram_supported_by_host(mis)) {
1440 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1441 return -1;
1444 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1445 local_pagesize_summary = ram_pagesize_summary();
1447 if (remote_pagesize_summary != local_pagesize_summary) {
1449 * This detects two potential causes of mismatch:
1450 * a) A mismatch in host page sizes
1451 * Some combinations of mismatch are probably possible but it gets
1452 * a bit more complicated. In particular we need to place whole
1453 * host pages on the dest at once, and we need to ensure that we
1454 * handle dirtying to make sure we never end up sending part of
1455 * a hostpage on it's own.
1456 * b) The use of different huge page sizes on source/destination
1457 * a more fine grain test is performed during RAM block migration
1458 * but this test here causes a nice early clear failure, and
1459 * also fails when passed to an older qemu that doesn't
1460 * do huge pages.
1462 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1463 " d=%" PRIx64 ")",
1464 remote_pagesize_summary, local_pagesize_summary);
1465 return -1;
1468 remote_tps = qemu_get_be64(mis->from_src_file);
1469 if (remote_tps != qemu_target_page_size()) {
1471 * Again, some differences could be dealt with, but for now keep it
1472 * simple.
1474 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1475 (int)remote_tps, qemu_target_page_size());
1476 return -1;
1479 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1480 error_report_err(local_err);
1481 return -1;
1484 if (ram_postcopy_incoming_init(mis)) {
1485 return -1;
1488 postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1490 return 0;
1493 /* After postcopy we will be told to throw some pages away since they're
1494 * dirty and will have to be demand fetched. Must happen before CPU is
1495 * started.
1496 * There can be 0..many of these messages, each encoding multiple pages.
1498 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1499 uint16_t len)
1501 int tmp;
1502 char ramid[256];
1503 PostcopyState ps = postcopy_state_get();
1505 trace_loadvm_postcopy_ram_handle_discard();
1507 switch (ps) {
1508 case POSTCOPY_INCOMING_ADVISE:
1509 /* 1st discard */
1510 tmp = postcopy_ram_prepare_discard(mis);
1511 if (tmp) {
1512 return tmp;
1514 break;
1516 case POSTCOPY_INCOMING_DISCARD:
1517 /* Expected state */
1518 break;
1520 default:
1521 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1522 ps);
1523 return -1;
1525 /* We're expecting a
1526 * Version (0)
1527 * a RAM ID string (length byte, name, 0 term)
1528 * then at least 1 16 byte chunk
1530 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1531 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1532 return -1;
1535 tmp = qemu_get_byte(mis->from_src_file);
1536 if (tmp != postcopy_ram_discard_version) {
1537 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1538 return -1;
1541 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1542 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1543 return -1;
1545 tmp = qemu_get_byte(mis->from_src_file);
1546 if (tmp != 0) {
1547 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1548 return -1;
1551 len -= 3 + strlen(ramid);
1552 if (len % 16) {
1553 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1554 return -1;
1556 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1557 while (len) {
1558 uint64_t start_addr, block_length;
1559 start_addr = qemu_get_be64(mis->from_src_file);
1560 block_length = qemu_get_be64(mis->from_src_file);
1562 len -= 16;
1563 int ret = ram_discard_range(ramid, start_addr, block_length);
1564 if (ret) {
1565 return ret;
1568 trace_loadvm_postcopy_ram_handle_discard_end();
1570 return 0;
1574 * Triggered by a postcopy_listen command; this thread takes over reading
1575 * the input stream, leaving the main thread free to carry on loading the rest
1576 * of the device state (from RAM).
1577 * (TODO:This could do with being in a postcopy file - but there again it's
1578 * just another input loop, not that postcopy specific)
1580 static void *postcopy_ram_listen_thread(void *opaque)
1582 MigrationIncomingState *mis = migration_incoming_get_current();
1583 QEMUFile *f = mis->from_src_file;
1584 int load_res;
1586 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1587 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1588 qemu_sem_post(&mis->listen_thread_sem);
1589 trace_postcopy_ram_listen_thread_start();
1592 * Because we're a thread and not a coroutine we can't yield
1593 * in qemu_file, and thus we must be blocking now.
1595 qemu_file_set_blocking(f, true);
1596 load_res = qemu_loadvm_state_main(f, mis);
1599 * This is tricky, but, mis->from_src_file can change after it
1600 * returns, when postcopy recovery happened. In the future, we may
1601 * want a wrapper for the QEMUFile handle.
1603 f = mis->from_src_file;
1605 /* And non-blocking again so we don't block in any cleanup */
1606 qemu_file_set_blocking(f, false);
1608 trace_postcopy_ram_listen_thread_exit();
1609 if (load_res < 0) {
1610 error_report("%s: loadvm failed: %d", __func__, load_res);
1611 qemu_file_set_error(f, load_res);
1612 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1613 MIGRATION_STATUS_FAILED);
1614 } else {
1616 * This looks good, but it's possible that the device loading in the
1617 * main thread hasn't finished yet, and so we might not be in 'RUN'
1618 * state yet; wait for the end of the main thread.
1620 qemu_event_wait(&mis->main_thread_load_event);
1622 postcopy_ram_incoming_cleanup(mis);
1624 if (load_res < 0) {
1626 * If something went wrong then we have a bad state so exit;
1627 * depending how far we got it might be possible at this point
1628 * to leave the guest running and fire MCEs for pages that never
1629 * arrived as a desperate recovery step.
1631 exit(EXIT_FAILURE);
1634 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1635 MIGRATION_STATUS_COMPLETED);
1637 * If everything has worked fine, then the main thread has waited
1638 * for us to start, and we're the last use of the mis.
1639 * (If something broke then qemu will have to exit anyway since it's
1640 * got a bad migration state).
1642 migration_incoming_state_destroy();
1643 qemu_loadvm_state_cleanup();
1645 return NULL;
1648 /* After this message we must be able to immediately receive postcopy data */
1649 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1651 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1652 trace_loadvm_postcopy_handle_listen();
1653 Error *local_err = NULL;
1655 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1656 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1657 return -1;
1659 if (ps == POSTCOPY_INCOMING_ADVISE) {
1661 * A rare case, we entered listen without having to do any discards,
1662 * so do the setup that's normally done at the time of the 1st discard.
1664 if (migrate_postcopy_ram()) {
1665 postcopy_ram_prepare_discard(mis);
1670 * Sensitise RAM - can now generate requests for blocks that don't exist
1671 * However, at this point the CPU shouldn't be running, and the IO
1672 * shouldn't be doing anything yet so don't actually expect requests
1674 if (migrate_postcopy_ram()) {
1675 if (postcopy_ram_enable_notify(mis)) {
1676 return -1;
1680 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1681 error_report_err(local_err);
1682 return -1;
1685 if (mis->have_listen_thread) {
1686 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1687 return -1;
1690 mis->have_listen_thread = true;
1691 /* Start up the listening thread and wait for it to signal ready */
1692 qemu_sem_init(&mis->listen_thread_sem, 0);
1693 qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1694 postcopy_ram_listen_thread, NULL,
1695 QEMU_THREAD_DETACHED);
1696 qemu_sem_wait(&mis->listen_thread_sem);
1697 qemu_sem_destroy(&mis->listen_thread_sem);
1699 return 0;
1703 typedef struct {
1704 QEMUBH *bh;
1705 } HandleRunBhData;
1707 static void loadvm_postcopy_handle_run_bh(void *opaque)
1709 Error *local_err = NULL;
1710 HandleRunBhData *data = opaque;
1712 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1713 * in migration.c
1715 cpu_synchronize_all_post_init();
1717 qemu_announce_self();
1719 /* Make sure all file formats flush their mutable metadata.
1720 * If we get an error here, just don't restart the VM yet. */
1721 bdrv_invalidate_cache_all(&local_err);
1722 if (local_err) {
1723 error_report_err(local_err);
1724 local_err = NULL;
1725 autostart = false;
1728 trace_loadvm_postcopy_handle_run_cpu_sync();
1729 cpu_synchronize_all_post_init();
1731 trace_loadvm_postcopy_handle_run_vmstart();
1733 dirty_bitmap_mig_before_vm_start();
1735 if (autostart) {
1736 /* Hold onto your hats, starting the CPU */
1737 vm_start();
1738 } else {
1739 /* leave it paused and let management decide when to start the CPU */
1740 runstate_set(RUN_STATE_PAUSED);
1743 qemu_bh_delete(data->bh);
1744 g_free(data);
1747 /* After all discards we can start running and asking for pages */
1748 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1750 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1751 HandleRunBhData *data;
1753 trace_loadvm_postcopy_handle_run();
1754 if (ps != POSTCOPY_INCOMING_LISTENING) {
1755 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1756 return -1;
1759 data = g_new(HandleRunBhData, 1);
1760 data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1761 qemu_bh_schedule(data->bh);
1763 /* We need to finish reading the stream from the package
1764 * and also stop reading anything more from the stream that loaded the
1765 * package (since it's now being read by the listener thread).
1766 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1768 return LOADVM_QUIT;
1772 * Immediately following this command is a blob of data containing an embedded
1773 * chunk of migration stream; read it and load it.
1775 * @mis: Incoming state
1776 * @length: Length of packaged data to read
1778 * Returns: Negative values on error
1781 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1783 int ret;
1784 size_t length;
1785 QIOChannelBuffer *bioc;
1787 length = qemu_get_be32(mis->from_src_file);
1788 trace_loadvm_handle_cmd_packaged(length);
1790 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1791 error_report("Unreasonably large packaged state: %zu", length);
1792 return -1;
1795 bioc = qio_channel_buffer_new(length);
1796 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1797 ret = qemu_get_buffer(mis->from_src_file,
1798 bioc->data,
1799 length);
1800 if (ret != length) {
1801 object_unref(OBJECT(bioc));
1802 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1803 ret, length);
1804 return (ret < 0) ? ret : -EAGAIN;
1806 bioc->usage += length;
1807 trace_loadvm_handle_cmd_packaged_received(ret);
1809 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1811 ret = qemu_loadvm_state_main(packf, mis);
1812 trace_loadvm_handle_cmd_packaged_main(ret);
1813 qemu_fclose(packf);
1814 object_unref(OBJECT(bioc));
1816 return ret;
1820 * Handle request that source requests for recved_bitmap on
1821 * destination. Payload format:
1823 * len (1 byte) + ramblock_name (<255 bytes)
1825 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
1826 uint16_t len)
1828 QEMUFile *file = mis->from_src_file;
1829 RAMBlock *rb;
1830 char block_name[256];
1831 size_t cnt;
1833 cnt = qemu_get_counted_string(file, block_name);
1834 if (!cnt) {
1835 error_report("%s: failed to read block name", __func__);
1836 return -EINVAL;
1839 /* Validate before using the data */
1840 if (qemu_file_get_error(file)) {
1841 return qemu_file_get_error(file);
1844 if (len != cnt + 1) {
1845 error_report("%s: invalid payload length (%d)", __func__, len);
1846 return -EINVAL;
1849 rb = qemu_ram_block_by_name(block_name);
1850 if (!rb) {
1851 error_report("%s: block '%s' not found", __func__, block_name);
1852 return -EINVAL;
1855 /* TODO: send the bitmap back to source */
1857 trace_loadvm_handle_recv_bitmap(block_name);
1859 return 0;
1863 * Process an incoming 'QEMU_VM_COMMAND'
1864 * 0 just a normal return
1865 * LOADVM_QUIT All good, but exit the loop
1866 * <0 Error
1868 static int loadvm_process_command(QEMUFile *f)
1870 MigrationIncomingState *mis = migration_incoming_get_current();
1871 uint16_t cmd;
1872 uint16_t len;
1873 uint32_t tmp32;
1875 cmd = qemu_get_be16(f);
1876 len = qemu_get_be16(f);
1878 /* Check validity before continue processing of cmds */
1879 if (qemu_file_get_error(f)) {
1880 return qemu_file_get_error(f);
1883 trace_loadvm_process_command(cmd, len);
1884 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
1885 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
1886 return -EINVAL;
1889 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
1890 error_report("%s received with bad length - expecting %zu, got %d",
1891 mig_cmd_args[cmd].name,
1892 (size_t)mig_cmd_args[cmd].len, len);
1893 return -ERANGE;
1896 switch (cmd) {
1897 case MIG_CMD_OPEN_RETURN_PATH:
1898 if (mis->to_src_file) {
1899 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1900 /* Not really a problem, so don't give up */
1901 return 0;
1903 mis->to_src_file = qemu_file_get_return_path(f);
1904 if (!mis->to_src_file) {
1905 error_report("CMD_OPEN_RETURN_PATH failed");
1906 return -1;
1908 break;
1910 case MIG_CMD_PING:
1911 tmp32 = qemu_get_be32(f);
1912 trace_loadvm_process_command_ping(tmp32);
1913 if (!mis->to_src_file) {
1914 error_report("CMD_PING (0x%x) received with no return path",
1915 tmp32);
1916 return -1;
1918 migrate_send_rp_pong(mis, tmp32);
1919 break;
1921 case MIG_CMD_PACKAGED:
1922 return loadvm_handle_cmd_packaged(mis);
1924 case MIG_CMD_POSTCOPY_ADVISE:
1925 return loadvm_postcopy_handle_advise(mis, len);
1927 case MIG_CMD_POSTCOPY_LISTEN:
1928 return loadvm_postcopy_handle_listen(mis);
1930 case MIG_CMD_POSTCOPY_RUN:
1931 return loadvm_postcopy_handle_run(mis);
1933 case MIG_CMD_POSTCOPY_RAM_DISCARD:
1934 return loadvm_postcopy_ram_handle_discard(mis, len);
1936 case MIG_CMD_RECV_BITMAP:
1937 return loadvm_handle_recv_bitmap(mis, len);
1940 return 0;
1944 * Read a footer off the wire and check that it matches the expected section
1946 * Returns: true if the footer was good
1947 * false if there is a problem (and calls error_report to say why)
1949 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
1951 int ret;
1952 uint8_t read_mark;
1953 uint32_t read_section_id;
1955 if (!migrate_get_current()->send_section_footer) {
1956 /* No footer to check */
1957 return true;
1960 read_mark = qemu_get_byte(f);
1962 ret = qemu_file_get_error(f);
1963 if (ret) {
1964 error_report("%s: Read section footer failed: %d",
1965 __func__, ret);
1966 return false;
1969 if (read_mark != QEMU_VM_SECTION_FOOTER) {
1970 error_report("Missing section footer for %s", se->idstr);
1971 return false;
1974 read_section_id = qemu_get_be32(f);
1975 if (read_section_id != se->load_section_id) {
1976 error_report("Mismatched section id in footer for %s -"
1977 " read 0x%x expected 0x%x",
1978 se->idstr, read_section_id, se->load_section_id);
1979 return false;
1982 /* All good */
1983 return true;
1986 static int
1987 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
1989 uint32_t instance_id, version_id, section_id;
1990 SaveStateEntry *se;
1991 char idstr[256];
1992 int ret;
1994 /* Read section start */
1995 section_id = qemu_get_be32(f);
1996 if (!qemu_get_counted_string(f, idstr)) {
1997 error_report("Unable to read ID string for section %u",
1998 section_id);
1999 return -EINVAL;
2001 instance_id = qemu_get_be32(f);
2002 version_id = qemu_get_be32(f);
2004 ret = qemu_file_get_error(f);
2005 if (ret) {
2006 error_report("%s: Failed to read instance/version ID: %d",
2007 __func__, ret);
2008 return ret;
2011 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2012 instance_id, version_id);
2013 /* Find savevm section */
2014 se = find_se(idstr, instance_id);
2015 if (se == NULL) {
2016 error_report("Unknown savevm section or instance '%s' %d",
2017 idstr, instance_id);
2018 return -EINVAL;
2021 /* Validate version */
2022 if (version_id > se->version_id) {
2023 error_report("savevm: unsupported version %d for '%s' v%d",
2024 version_id, idstr, se->version_id);
2025 return -EINVAL;
2027 se->load_version_id = version_id;
2028 se->load_section_id = section_id;
2030 /* Validate if it is a device's state */
2031 if (xen_enabled() && se->is_ram) {
2032 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2033 return -EINVAL;
2036 ret = vmstate_load(f, se);
2037 if (ret < 0) {
2038 error_report("error while loading state for instance 0x%x of"
2039 " device '%s'", instance_id, idstr);
2040 return ret;
2042 if (!check_section_footer(f, se)) {
2043 return -EINVAL;
2046 return 0;
2049 static int
2050 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2052 uint32_t section_id;
2053 SaveStateEntry *se;
2054 int ret;
2056 section_id = qemu_get_be32(f);
2058 ret = qemu_file_get_error(f);
2059 if (ret) {
2060 error_report("%s: Failed to read section ID: %d",
2061 __func__, ret);
2062 return ret;
2065 trace_qemu_loadvm_state_section_partend(section_id);
2066 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2067 if (se->load_section_id == section_id) {
2068 break;
2071 if (se == NULL) {
2072 error_report("Unknown savevm section %d", section_id);
2073 return -EINVAL;
2076 ret = vmstate_load(f, se);
2077 if (ret < 0) {
2078 error_report("error while loading state section id %d(%s)",
2079 section_id, se->idstr);
2080 return ret;
2082 if (!check_section_footer(f, se)) {
2083 return -EINVAL;
2086 return 0;
2089 static int qemu_loadvm_state_setup(QEMUFile *f)
2091 SaveStateEntry *se;
2092 int ret;
2094 trace_loadvm_state_setup();
2095 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2096 if (!se->ops || !se->ops->load_setup) {
2097 continue;
2099 if (se->ops && se->ops->is_active) {
2100 if (!se->ops->is_active(se->opaque)) {
2101 continue;
2105 ret = se->ops->load_setup(f, se->opaque);
2106 if (ret < 0) {
2107 qemu_file_set_error(f, ret);
2108 error_report("Load state of device %s failed", se->idstr);
2109 return ret;
2112 return 0;
2115 void qemu_loadvm_state_cleanup(void)
2117 SaveStateEntry *se;
2119 trace_loadvm_state_cleanup();
2120 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2121 if (se->ops && se->ops->load_cleanup) {
2122 se->ops->load_cleanup(se->opaque);
2127 /* Return true if we should continue the migration, or false. */
2128 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2130 trace_postcopy_pause_incoming();
2132 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2133 MIGRATION_STATUS_POSTCOPY_PAUSED);
2135 assert(mis->from_src_file);
2136 qemu_file_shutdown(mis->from_src_file);
2137 qemu_fclose(mis->from_src_file);
2138 mis->from_src_file = NULL;
2140 assert(mis->to_src_file);
2141 qemu_file_shutdown(mis->to_src_file);
2142 qemu_mutex_lock(&mis->rp_mutex);
2143 qemu_fclose(mis->to_src_file);
2144 mis->to_src_file = NULL;
2145 qemu_mutex_unlock(&mis->rp_mutex);
2147 /* Notify the fault thread for the invalidated file handle */
2148 postcopy_fault_thread_notify(mis);
2150 error_report("Detected IO failure for postcopy. "
2151 "Migration paused.");
2153 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2154 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2157 trace_postcopy_pause_incoming_continued();
2159 return true;
2162 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2164 uint8_t section_type;
2165 int ret = 0;
2167 retry:
2168 while (true) {
2169 section_type = qemu_get_byte(f);
2171 if (qemu_file_get_error(f)) {
2172 ret = qemu_file_get_error(f);
2173 break;
2176 trace_qemu_loadvm_state_section(section_type);
2177 switch (section_type) {
2178 case QEMU_VM_SECTION_START:
2179 case QEMU_VM_SECTION_FULL:
2180 ret = qemu_loadvm_section_start_full(f, mis);
2181 if (ret < 0) {
2182 goto out;
2184 break;
2185 case QEMU_VM_SECTION_PART:
2186 case QEMU_VM_SECTION_END:
2187 ret = qemu_loadvm_section_part_end(f, mis);
2188 if (ret < 0) {
2189 goto out;
2191 break;
2192 case QEMU_VM_COMMAND:
2193 ret = loadvm_process_command(f);
2194 trace_qemu_loadvm_state_section_command(ret);
2195 if ((ret < 0) || (ret & LOADVM_QUIT)) {
2196 goto out;
2198 break;
2199 case QEMU_VM_EOF:
2200 /* This is the end of migration */
2201 goto out;
2202 default:
2203 error_report("Unknown savevm section type %d", section_type);
2204 ret = -EINVAL;
2205 goto out;
2209 out:
2210 if (ret < 0) {
2211 qemu_file_set_error(f, ret);
2214 * Detect whether it is:
2216 * 1. postcopy running (after receiving all device data, which
2217 * must be in POSTCOPY_INCOMING_RUNNING state. Note that
2218 * POSTCOPY_INCOMING_LISTENING is still not enough, it's
2219 * still receiving device states).
2220 * 2. network failure (-EIO)
2222 * If so, we try to wait for a recovery.
2224 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2225 ret == -EIO && postcopy_pause_incoming(mis)) {
2226 /* Reset f to point to the newly created channel */
2227 f = mis->from_src_file;
2228 goto retry;
2231 return ret;
2234 int qemu_loadvm_state(QEMUFile *f)
2236 MigrationIncomingState *mis = migration_incoming_get_current();
2237 Error *local_err = NULL;
2238 unsigned int v;
2239 int ret;
2241 if (qemu_savevm_state_blocked(&local_err)) {
2242 error_report_err(local_err);
2243 return -EINVAL;
2246 v = qemu_get_be32(f);
2247 if (v != QEMU_VM_FILE_MAGIC) {
2248 error_report("Not a migration stream");
2249 return -EINVAL;
2252 v = qemu_get_be32(f);
2253 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2254 error_report("SaveVM v2 format is obsolete and don't work anymore");
2255 return -ENOTSUP;
2257 if (v != QEMU_VM_FILE_VERSION) {
2258 error_report("Unsupported migration stream version");
2259 return -ENOTSUP;
2262 if (qemu_loadvm_state_setup(f) != 0) {
2263 return -EINVAL;
2266 if (migrate_get_current()->send_configuration) {
2267 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2268 error_report("Configuration section missing");
2269 return -EINVAL;
2271 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2273 if (ret) {
2274 return ret;
2278 cpu_synchronize_all_pre_loadvm();
2280 ret = qemu_loadvm_state_main(f, mis);
2281 qemu_event_set(&mis->main_thread_load_event);
2283 trace_qemu_loadvm_state_post_main(ret);
2285 if (mis->have_listen_thread) {
2286 /* Listen thread still going, can't clean up yet */
2287 return ret;
2290 if (ret == 0) {
2291 ret = qemu_file_get_error(f);
2295 * Try to read in the VMDESC section as well, so that dumping tools that
2296 * intercept our migration stream have the chance to see it.
2299 /* We've got to be careful; if we don't read the data and just shut the fd
2300 * then the sender can error if we close while it's still sending.
2301 * We also mustn't read data that isn't there; some transports (RDMA)
2302 * will stall waiting for that data when the source has already closed.
2304 if (ret == 0 && should_send_vmdesc()) {
2305 uint8_t *buf;
2306 uint32_t size;
2307 uint8_t section_type = qemu_get_byte(f);
2309 if (section_type != QEMU_VM_VMDESCRIPTION) {
2310 error_report("Expected vmdescription section, but got %d",
2311 section_type);
2313 * It doesn't seem worth failing at this point since
2314 * we apparently have an otherwise valid VM state
2316 } else {
2317 buf = g_malloc(0x1000);
2318 size = qemu_get_be32(f);
2320 while (size > 0) {
2321 uint32_t read_chunk = MIN(size, 0x1000);
2322 qemu_get_buffer(f, buf, read_chunk);
2323 size -= read_chunk;
2325 g_free(buf);
2329 qemu_loadvm_state_cleanup();
2330 cpu_synchronize_all_post_init();
2332 return ret;
2335 int save_snapshot(const char *name, Error **errp)
2337 BlockDriverState *bs, *bs1;
2338 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2339 int ret = -1;
2340 QEMUFile *f;
2341 int saved_vm_running;
2342 uint64_t vm_state_size;
2343 qemu_timeval tv;
2344 struct tm tm;
2345 AioContext *aio_context;
2347 if (!replay_can_snapshot()) {
2348 error_report("Record/replay does not allow making snapshot "
2349 "right now. Try once more later.");
2350 return ret;
2353 if (!bdrv_all_can_snapshot(&bs)) {
2354 error_setg(errp, "Device '%s' is writable but does not support "
2355 "snapshots", bdrv_get_device_name(bs));
2356 return ret;
2359 /* Delete old snapshots of the same name */
2360 if (name) {
2361 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2362 if (ret < 0) {
2363 error_prepend(errp, "Error while deleting snapshot on device "
2364 "'%s': ", bdrv_get_device_name(bs1));
2365 return ret;
2369 bs = bdrv_all_find_vmstate_bs();
2370 if (bs == NULL) {
2371 error_setg(errp, "No block device can accept snapshots");
2372 return ret;
2374 aio_context = bdrv_get_aio_context(bs);
2376 saved_vm_running = runstate_is_running();
2378 ret = global_state_store();
2379 if (ret) {
2380 error_setg(errp, "Error saving global state");
2381 return ret;
2383 vm_stop(RUN_STATE_SAVE_VM);
2385 bdrv_drain_all_begin();
2387 aio_context_acquire(aio_context);
2389 memset(sn, 0, sizeof(*sn));
2391 /* fill auxiliary fields */
2392 qemu_gettimeofday(&tv);
2393 sn->date_sec = tv.tv_sec;
2394 sn->date_nsec = tv.tv_usec * 1000;
2395 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2397 if (name) {
2398 ret = bdrv_snapshot_find(bs, old_sn, name);
2399 if (ret >= 0) {
2400 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2401 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2402 } else {
2403 pstrcpy(sn->name, sizeof(sn->name), name);
2405 } else {
2406 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2407 localtime_r((const time_t *)&tv.tv_sec, &tm);
2408 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2411 /* save the VM state */
2412 f = qemu_fopen_bdrv(bs, 1);
2413 if (!f) {
2414 error_setg(errp, "Could not open VM state file");
2415 goto the_end;
2417 ret = qemu_savevm_state(f, errp);
2418 vm_state_size = qemu_ftell(f);
2419 qemu_fclose(f);
2420 if (ret < 0) {
2421 goto the_end;
2424 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2425 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2426 * it only releases the lock once. Therefore synchronous I/O will deadlock
2427 * unless we release the AioContext before bdrv_all_create_snapshot().
2429 aio_context_release(aio_context);
2430 aio_context = NULL;
2432 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2433 if (ret < 0) {
2434 error_setg(errp, "Error while creating snapshot on '%s'",
2435 bdrv_get_device_name(bs));
2436 goto the_end;
2439 ret = 0;
2441 the_end:
2442 if (aio_context) {
2443 aio_context_release(aio_context);
2446 bdrv_drain_all_end();
2448 if (saved_vm_running) {
2449 vm_start();
2451 return ret;
2454 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2455 Error **errp)
2457 QEMUFile *f;
2458 QIOChannelFile *ioc;
2459 int saved_vm_running;
2460 int ret;
2462 if (!has_live) {
2463 /* live default to true so old version of Xen tool stack can have a
2464 * successfull live migration */
2465 live = true;
2468 saved_vm_running = runstate_is_running();
2469 vm_stop(RUN_STATE_SAVE_VM);
2470 global_state_store_running();
2472 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2473 if (!ioc) {
2474 goto the_end;
2476 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2477 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2478 object_unref(OBJECT(ioc));
2479 ret = qemu_save_device_state(f);
2480 if (ret < 0 || qemu_fclose(f) < 0) {
2481 error_setg(errp, QERR_IO_ERROR);
2482 } else {
2483 /* libxl calls the QMP command "stop" before calling
2484 * "xen-save-devices-state" and in case of migration failure, libxl
2485 * would call "cont".
2486 * So call bdrv_inactivate_all (release locks) here to let the other
2487 * side of the migration take controle of the images.
2489 if (live && !saved_vm_running) {
2490 ret = bdrv_inactivate_all();
2491 if (ret) {
2492 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2493 __func__, ret);
2498 the_end:
2499 if (saved_vm_running) {
2500 vm_start();
2504 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2506 QEMUFile *f;
2507 QIOChannelFile *ioc;
2508 int ret;
2510 /* Guest must be paused before loading the device state; the RAM state
2511 * will already have been loaded by xc
2513 if (runstate_is_running()) {
2514 error_setg(errp, "Cannot update device state while vm is running");
2515 return;
2517 vm_stop(RUN_STATE_RESTORE_VM);
2519 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2520 if (!ioc) {
2521 return;
2523 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2524 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2525 object_unref(OBJECT(ioc));
2527 ret = qemu_loadvm_state(f);
2528 qemu_fclose(f);
2529 if (ret < 0) {
2530 error_setg(errp, QERR_IO_ERROR);
2532 migration_incoming_state_destroy();
2535 int load_snapshot(const char *name, Error **errp)
2537 BlockDriverState *bs, *bs_vm_state;
2538 QEMUSnapshotInfo sn;
2539 QEMUFile *f;
2540 int ret;
2541 AioContext *aio_context;
2542 MigrationIncomingState *mis = migration_incoming_get_current();
2544 if (!replay_can_snapshot()) {
2545 error_report("Record/replay does not allow loading snapshot "
2546 "right now. Try once more later.");
2547 return -EINVAL;
2550 if (!bdrv_all_can_snapshot(&bs)) {
2551 error_setg(errp,
2552 "Device '%s' is writable but does not support snapshots",
2553 bdrv_get_device_name(bs));
2554 return -ENOTSUP;
2556 ret = bdrv_all_find_snapshot(name, &bs);
2557 if (ret < 0) {
2558 error_setg(errp,
2559 "Device '%s' does not have the requested snapshot '%s'",
2560 bdrv_get_device_name(bs), name);
2561 return ret;
2564 bs_vm_state = bdrv_all_find_vmstate_bs();
2565 if (!bs_vm_state) {
2566 error_setg(errp, "No block device supports snapshots");
2567 return -ENOTSUP;
2569 aio_context = bdrv_get_aio_context(bs_vm_state);
2571 /* Don't even try to load empty VM states */
2572 aio_context_acquire(aio_context);
2573 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2574 aio_context_release(aio_context);
2575 if (ret < 0) {
2576 return ret;
2577 } else if (sn.vm_state_size == 0) {
2578 error_setg(errp, "This is a disk-only snapshot. Revert to it "
2579 " offline using qemu-img");
2580 return -EINVAL;
2583 /* Flush all IO requests so they don't interfere with the new state. */
2584 bdrv_drain_all_begin();
2586 ret = bdrv_all_goto_snapshot(name, &bs, errp);
2587 if (ret < 0) {
2588 error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
2589 name, bdrv_get_device_name(bs));
2590 goto err_drain;
2593 /* restore the VM state */
2594 f = qemu_fopen_bdrv(bs_vm_state, 0);
2595 if (!f) {
2596 error_setg(errp, "Could not open VM state file");
2597 ret = -EINVAL;
2598 goto err_drain;
2601 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2602 mis->from_src_file = f;
2604 aio_context_acquire(aio_context);
2605 ret = qemu_loadvm_state(f);
2606 migration_incoming_state_destroy();
2607 aio_context_release(aio_context);
2609 bdrv_drain_all_end();
2611 if (ret < 0) {
2612 error_setg(errp, "Error %d while loading VM state", ret);
2613 return ret;
2616 return 0;
2618 err_drain:
2619 bdrv_drain_all_end();
2620 return ret;
2623 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2625 qemu_ram_set_idstr(mr->ram_block,
2626 memory_region_name(mr), dev);
2629 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2631 qemu_ram_unset_idstr(mr->ram_block);
2634 void vmstate_register_ram_global(MemoryRegion *mr)
2636 vmstate_register_ram(mr, NULL);
2639 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2641 /* check needed if --only-migratable is specified */
2642 if (!migrate_get_current()->only_migratable) {
2643 return true;
2646 return !(vmsd && vmsd->unmigratable);