migration/rdma: Return -1 instead of negative errno code
[qemu/armbru.git] / migration / savevm.c
blob497ce02bd7bff08dd4149de9cf82f78ccf75dd1a
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 "net/net.h"
32 #include "migration.h"
33 #include "migration/snapshot.h"
34 #include "migration-stats.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
39 #include "migration/channel-block.h"
40 #include "ram.h"
41 #include "qemu-file.h"
42 #include "savevm.h"
43 #include "postcopy-ram.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/clone-visitor.h"
47 #include "qapi/qapi-builtin-visit.h"
48 #include "qapi/qmp/qerror.h"
49 #include "qemu/error-report.h"
50 #include "sysemu/cpus.h"
51 #include "exec/memory.h"
52 #include "exec/target_page.h"
53 #include "trace.h"
54 #include "qemu/iov.h"
55 #include "qemu/job.h"
56 #include "qemu/main-loop.h"
57 #include "block/snapshot.h"
58 #include "qemu/cutils.h"
59 #include "io/channel-buffer.h"
60 #include "io/channel-file.h"
61 #include "sysemu/replay.h"
62 #include "sysemu/runstate.h"
63 #include "sysemu/sysemu.h"
64 #include "sysemu/xen.h"
65 #include "migration/colo.h"
66 #include "qemu/bitmap.h"
67 #include "net/announce.h"
68 #include "qemu/yank.h"
69 #include "yank_functions.h"
70 #include "sysemu/qtest.h"
71 #include "options.h"
73 const unsigned int postcopy_ram_discard_version;
75 /* Subcommands for QEMU_VM_COMMAND */
76 enum qemu_vm_cmd {
77 MIG_CMD_INVALID = 0, /* Must be 0 */
78 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
79 MIG_CMD_PING, /* Request a PONG on the RP */
81 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
82 warn we might want to do PC */
83 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
84 pages as it's running. */
85 MIG_CMD_POSTCOPY_RUN, /* Start execution */
87 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
88 were previously sent during
89 precopy but are dirty. */
90 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
91 MIG_CMD_ENABLE_COLO, /* Enable COLO */
92 MIG_CMD_POSTCOPY_RESUME, /* resume postcopy on dest */
93 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
94 MIG_CMD_MAX
97 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
98 static struct mig_cmd_args {
99 ssize_t len; /* -1 = variable */
100 const char *name;
101 } mig_cmd_args[] = {
102 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
103 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
104 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
105 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
106 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
107 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
108 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
109 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
110 [MIG_CMD_POSTCOPY_RESUME] = { .len = 0, .name = "POSTCOPY_RESUME" },
111 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
112 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
113 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
116 /* Note for MIG_CMD_POSTCOPY_ADVISE:
117 * The format of arguments is depending on postcopy mode:
118 * - postcopy RAM only
119 * uint64_t host page size
120 * uint64_t target page size
122 * - postcopy RAM and postcopy dirty bitmaps
123 * format is the same as for postcopy RAM only
125 * - postcopy dirty bitmaps only
126 * Nothing. Command length field is 0.
128 * Be careful: adding a new postcopy entity with some other parameters should
129 * not break format self-description ability. Good way is to introduce some
130 * generic extendable format with an exception for two old entities.
133 /***********************************************************/
134 /* savevm/loadvm support */
136 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
138 if (is_writable) {
139 return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
140 } else {
141 return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
146 /* QEMUFile timer support.
147 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
150 void timer_put(QEMUFile *f, QEMUTimer *ts)
152 uint64_t expire_time;
154 expire_time = timer_expire_time_ns(ts);
155 qemu_put_be64(f, expire_time);
158 void timer_get(QEMUFile *f, QEMUTimer *ts)
160 uint64_t expire_time;
162 expire_time = qemu_get_be64(f);
163 if (expire_time != -1) {
164 timer_mod_ns(ts, expire_time);
165 } else {
166 timer_del(ts);
171 /* VMState timer support.
172 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
175 static int get_timer(QEMUFile *f, void *pv, size_t size,
176 const VMStateField *field)
178 QEMUTimer *v = pv;
179 timer_get(f, v);
180 return 0;
183 static int put_timer(QEMUFile *f, void *pv, size_t size,
184 const VMStateField *field, JSONWriter *vmdesc)
186 QEMUTimer *v = pv;
187 timer_put(f, v);
189 return 0;
192 const VMStateInfo vmstate_info_timer = {
193 .name = "timer",
194 .get = get_timer,
195 .put = put_timer,
199 typedef struct CompatEntry {
200 char idstr[256];
201 int instance_id;
202 } CompatEntry;
204 typedef struct SaveStateEntry {
205 QTAILQ_ENTRY(SaveStateEntry) entry;
206 char idstr[256];
207 uint32_t instance_id;
208 int alias_id;
209 int version_id;
210 /* version id read from the stream */
211 int load_version_id;
212 int section_id;
213 /* section id read from the stream */
214 int load_section_id;
215 const SaveVMHandlers *ops;
216 const VMStateDescription *vmsd;
217 void *opaque;
218 CompatEntry *compat;
219 int is_ram;
220 } SaveStateEntry;
222 typedef struct SaveState {
223 QTAILQ_HEAD(, SaveStateEntry) handlers;
224 SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
225 int global_section_id;
226 uint32_t len;
227 const char *name;
228 uint32_t target_page_bits;
229 uint32_t caps_count;
230 MigrationCapability *capabilities;
231 QemuUUID uuid;
232 } SaveState;
234 static SaveState savevm_state = {
235 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
236 .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
237 .global_section_id = 0,
240 static bool should_validate_capability(int capability)
242 assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
243 /* Validate only new capabilities to keep compatibility. */
244 switch (capability) {
245 case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
246 return true;
247 default:
248 return false;
252 static uint32_t get_validatable_capabilities_count(void)
254 MigrationState *s = migrate_get_current();
255 uint32_t result = 0;
256 int i;
257 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
258 if (should_validate_capability(i) && s->capabilities[i]) {
259 result++;
262 return result;
265 static int configuration_pre_save(void *opaque)
267 SaveState *state = opaque;
268 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
269 MigrationState *s = migrate_get_current();
270 int i, j;
272 state->len = strlen(current_name);
273 state->name = current_name;
274 state->target_page_bits = qemu_target_page_bits();
276 state->caps_count = get_validatable_capabilities_count();
277 state->capabilities = g_renew(MigrationCapability, state->capabilities,
278 state->caps_count);
279 for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
280 if (should_validate_capability(i) && s->capabilities[i]) {
281 state->capabilities[j++] = i;
284 state->uuid = qemu_uuid;
286 return 0;
289 static int configuration_post_save(void *opaque)
291 SaveState *state = opaque;
293 g_free(state->capabilities);
294 state->capabilities = NULL;
295 state->caps_count = 0;
296 return 0;
299 static int configuration_pre_load(void *opaque)
301 SaveState *state = opaque;
303 /* If there is no target-page-bits subsection it means the source
304 * predates the variable-target-page-bits support and is using the
305 * minimum possible value for this CPU.
307 state->target_page_bits = qemu_target_page_bits_min();
308 return 0;
311 static bool configuration_validate_capabilities(SaveState *state)
313 bool ret = true;
314 MigrationState *s = migrate_get_current();
315 unsigned long *source_caps_bm;
316 int i;
318 source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
319 for (i = 0; i < state->caps_count; i++) {
320 MigrationCapability capability = state->capabilities[i];
321 set_bit(capability, source_caps_bm);
324 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
325 bool source_state, target_state;
326 if (!should_validate_capability(i)) {
327 continue;
329 source_state = test_bit(i, source_caps_bm);
330 target_state = s->capabilities[i];
331 if (source_state != target_state) {
332 error_report("Capability %s is %s, but received capability is %s",
333 MigrationCapability_str(i),
334 target_state ? "on" : "off",
335 source_state ? "on" : "off");
336 ret = false;
337 /* Don't break here to report all failed capabilities */
341 g_free(source_caps_bm);
342 return ret;
345 static int configuration_post_load(void *opaque, int version_id)
347 SaveState *state = opaque;
348 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
349 int ret = 0;
351 if (strncmp(state->name, current_name, state->len) != 0) {
352 error_report("Machine type received is '%.*s' and local is '%s'",
353 (int) state->len, state->name, current_name);
354 ret = -EINVAL;
355 goto out;
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 ret = -EINVAL;
362 goto out;
365 if (!configuration_validate_capabilities(state)) {
366 ret = -EINVAL;
367 goto out;
370 out:
371 g_free((void *)state->name);
372 state->name = NULL;
373 state->len = 0;
374 g_free(state->capabilities);
375 state->capabilities = NULL;
376 state->caps_count = 0;
378 return ret;
381 static int get_capability(QEMUFile *f, void *pv, size_t size,
382 const VMStateField *field)
384 MigrationCapability *capability = pv;
385 char capability_str[UINT8_MAX + 1];
386 uint8_t len;
387 int i;
389 len = qemu_get_byte(f);
390 qemu_get_buffer(f, (uint8_t *)capability_str, len);
391 capability_str[len] = '\0';
392 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
393 if (!strcmp(MigrationCapability_str(i), capability_str)) {
394 *capability = i;
395 return 0;
398 error_report("Received unknown capability %s", capability_str);
399 return -EINVAL;
402 static int put_capability(QEMUFile *f, void *pv, size_t size,
403 const VMStateField *field, JSONWriter *vmdesc)
405 MigrationCapability *capability = pv;
406 const char *capability_str = MigrationCapability_str(*capability);
407 size_t len = strlen(capability_str);
408 assert(len <= UINT8_MAX);
410 qemu_put_byte(f, len);
411 qemu_put_buffer(f, (uint8_t *)capability_str, len);
412 return 0;
415 static const VMStateInfo vmstate_info_capability = {
416 .name = "capability",
417 .get = get_capability,
418 .put = put_capability,
421 /* The target-page-bits subsection is present only if the
422 * target page size is not the same as the default (ie the
423 * minimum page size for a variable-page-size guest CPU).
424 * If it is present then it contains the actual target page
425 * bits for the machine, and migration will fail if the
426 * two ends don't agree about it.
428 static bool vmstate_target_page_bits_needed(void *opaque)
430 return qemu_target_page_bits()
431 > qemu_target_page_bits_min();
434 static const VMStateDescription vmstate_target_page_bits = {
435 .name = "configuration/target-page-bits",
436 .version_id = 1,
437 .minimum_version_id = 1,
438 .needed = vmstate_target_page_bits_needed,
439 .fields = (VMStateField[]) {
440 VMSTATE_UINT32(target_page_bits, SaveState),
441 VMSTATE_END_OF_LIST()
445 static bool vmstate_capabilites_needed(void *opaque)
447 return get_validatable_capabilities_count() > 0;
450 static const VMStateDescription vmstate_capabilites = {
451 .name = "configuration/capabilities",
452 .version_id = 1,
453 .minimum_version_id = 1,
454 .needed = vmstate_capabilites_needed,
455 .fields = (VMStateField[]) {
456 VMSTATE_UINT32_V(caps_count, SaveState, 1),
457 VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
458 vmstate_info_capability,
459 MigrationCapability),
460 VMSTATE_END_OF_LIST()
464 static bool vmstate_uuid_needed(void *opaque)
466 return qemu_uuid_set && migrate_validate_uuid();
469 static int vmstate_uuid_post_load(void *opaque, int version_id)
471 SaveState *state = opaque;
472 char uuid_src[UUID_FMT_LEN + 1];
473 char uuid_dst[UUID_FMT_LEN + 1];
475 if (!qemu_uuid_set) {
477 * It's warning because user might not know UUID in some cases,
478 * e.g. load an old snapshot
480 qemu_uuid_unparse(&state->uuid, uuid_src);
481 warn_report("UUID is received %s, but local uuid isn't set",
482 uuid_src);
483 return 0;
485 if (!qemu_uuid_is_equal(&state->uuid, &qemu_uuid)) {
486 qemu_uuid_unparse(&state->uuid, uuid_src);
487 qemu_uuid_unparse(&qemu_uuid, uuid_dst);
488 error_report("UUID received is %s and local is %s", uuid_src, uuid_dst);
489 return -EINVAL;
491 return 0;
494 static const VMStateDescription vmstate_uuid = {
495 .name = "configuration/uuid",
496 .version_id = 1,
497 .minimum_version_id = 1,
498 .needed = vmstate_uuid_needed,
499 .post_load = vmstate_uuid_post_load,
500 .fields = (VMStateField[]) {
501 VMSTATE_UINT8_ARRAY_V(uuid.data, SaveState, sizeof(QemuUUID), 1),
502 VMSTATE_END_OF_LIST()
506 static const VMStateDescription vmstate_configuration = {
507 .name = "configuration",
508 .version_id = 1,
509 .pre_load = configuration_pre_load,
510 .post_load = configuration_post_load,
511 .pre_save = configuration_pre_save,
512 .post_save = configuration_post_save,
513 .fields = (VMStateField[]) {
514 VMSTATE_UINT32(len, SaveState),
515 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
516 VMSTATE_END_OF_LIST()
518 .subsections = (const VMStateDescription *[]) {
519 &vmstate_target_page_bits,
520 &vmstate_capabilites,
521 &vmstate_uuid,
522 NULL
526 static void dump_vmstate_vmsd(FILE *out_file,
527 const VMStateDescription *vmsd, int indent,
528 bool is_subsection);
530 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
531 int indent)
533 fprintf(out_file, "%*s{\n", indent, "");
534 indent += 2;
535 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
536 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
537 field->version_id);
538 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
539 field->field_exists ? "true" : "false");
540 if (field->flags & VMS_ARRAY) {
541 fprintf(out_file, "%*s\"num\": %d,\n", indent, "", field->num);
543 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
544 if (field->vmsd != NULL) {
545 fprintf(out_file, ",\n");
546 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
548 fprintf(out_file, "\n%*s}", indent - 2, "");
551 static void dump_vmstate_vmss(FILE *out_file,
552 const VMStateDescription **subsection,
553 int indent)
555 if (*subsection != NULL) {
556 dump_vmstate_vmsd(out_file, *subsection, indent, true);
560 static void dump_vmstate_vmsd(FILE *out_file,
561 const VMStateDescription *vmsd, int indent,
562 bool is_subsection)
564 if (is_subsection) {
565 fprintf(out_file, "%*s{\n", indent, "");
566 } else {
567 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
569 indent += 2;
570 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
571 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
572 vmsd->version_id);
573 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
574 vmsd->minimum_version_id);
575 if (vmsd->fields != NULL) {
576 const VMStateField *field = vmsd->fields;
577 bool first;
579 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
580 first = true;
581 while (field->name != NULL) {
582 if (field->flags & VMS_MUST_EXIST) {
583 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
584 field++;
585 continue;
587 if (!first) {
588 fprintf(out_file, ",\n");
590 dump_vmstate_vmsf(out_file, field, indent + 2);
591 field++;
592 first = false;
594 assert(field->flags == VMS_END);
595 fprintf(out_file, "\n%*s]", indent, "");
597 if (vmsd->subsections != NULL) {
598 const VMStateDescription **subsection = vmsd->subsections;
599 bool first;
601 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
602 first = true;
603 while (*subsection != NULL) {
604 if (!first) {
605 fprintf(out_file, ",\n");
607 dump_vmstate_vmss(out_file, subsection, indent + 2);
608 subsection++;
609 first = false;
611 fprintf(out_file, "\n%*s]", indent, "");
613 fprintf(out_file, "\n%*s}", indent - 2, "");
616 static void dump_machine_type(FILE *out_file)
618 MachineClass *mc;
620 mc = MACHINE_GET_CLASS(current_machine);
622 fprintf(out_file, " \"vmschkmachine\": {\n");
623 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
624 fprintf(out_file, " },\n");
627 void dump_vmstate_json_to_file(FILE *out_file)
629 GSList *list, *elt;
630 bool first;
632 fprintf(out_file, "{\n");
633 dump_machine_type(out_file);
635 first = true;
636 list = object_class_get_list(TYPE_DEVICE, true);
637 for (elt = list; elt; elt = elt->next) {
638 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
639 TYPE_DEVICE);
640 const char *name;
641 int indent = 2;
643 if (!dc->vmsd) {
644 continue;
647 if (!first) {
648 fprintf(out_file, ",\n");
650 name = object_class_get_name(OBJECT_CLASS(dc));
651 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
652 indent += 2;
653 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
654 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
655 dc->vmsd->version_id);
656 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
657 dc->vmsd->minimum_version_id);
659 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
661 fprintf(out_file, "\n%*s}", indent - 2, "");
662 first = false;
664 fprintf(out_file, "\n}\n");
665 fclose(out_file);
666 g_slist_free(list);
669 static uint32_t calculate_new_instance_id(const char *idstr)
671 SaveStateEntry *se;
672 uint32_t instance_id = 0;
674 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
675 if (strcmp(idstr, se->idstr) == 0
676 && instance_id <= se->instance_id) {
677 instance_id = se->instance_id + 1;
680 /* Make sure we never loop over without being noticed */
681 assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
682 return instance_id;
685 static int calculate_compat_instance_id(const char *idstr)
687 SaveStateEntry *se;
688 int instance_id = 0;
690 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
691 if (!se->compat) {
692 continue;
695 if (strcmp(idstr, se->compat->idstr) == 0
696 && instance_id <= se->compat->instance_id) {
697 instance_id = se->compat->instance_id + 1;
700 return instance_id;
703 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
705 if (se->vmsd) {
706 return se->vmsd->priority;
708 return MIG_PRI_DEFAULT;
711 static void savevm_state_handler_insert(SaveStateEntry *nse)
713 MigrationPriority priority = save_state_priority(nse);
714 SaveStateEntry *se;
715 int i;
717 assert(priority <= MIG_PRI_MAX);
719 for (i = priority - 1; i >= 0; i--) {
720 se = savevm_state.handler_pri_head[i];
721 if (se != NULL) {
722 assert(save_state_priority(se) < priority);
723 break;
727 if (i >= 0) {
728 QTAILQ_INSERT_BEFORE(se, nse, entry);
729 } else {
730 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
733 if (savevm_state.handler_pri_head[priority] == NULL) {
734 savevm_state.handler_pri_head[priority] = nse;
738 static void savevm_state_handler_remove(SaveStateEntry *se)
740 SaveStateEntry *next;
741 MigrationPriority priority = save_state_priority(se);
743 if (se == savevm_state.handler_pri_head[priority]) {
744 next = QTAILQ_NEXT(se, entry);
745 if (next != NULL && save_state_priority(next) == priority) {
746 savevm_state.handler_pri_head[priority] = next;
747 } else {
748 savevm_state.handler_pri_head[priority] = NULL;
751 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
754 /* TODO: Individual devices generally have very little idea about the rest
755 of the system, so instance_id should be removed/replaced.
756 Meanwhile pass -1 as instance_id if you do not already have a clearly
757 distinguishing id for all instances of your device class. */
758 int register_savevm_live(const char *idstr,
759 uint32_t instance_id,
760 int version_id,
761 const SaveVMHandlers *ops,
762 void *opaque)
764 SaveStateEntry *se;
766 se = g_new0(SaveStateEntry, 1);
767 se->version_id = version_id;
768 se->section_id = savevm_state.global_section_id++;
769 se->ops = ops;
770 se->opaque = opaque;
771 se->vmsd = NULL;
772 /* if this is a live_savem then set is_ram */
773 if (ops->save_setup != NULL) {
774 se->is_ram = 1;
777 pstrcat(se->idstr, sizeof(se->idstr), idstr);
779 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
780 se->instance_id = calculate_new_instance_id(se->idstr);
781 } else {
782 se->instance_id = instance_id;
784 assert(!se->compat || se->instance_id == 0);
785 savevm_state_handler_insert(se);
786 return 0;
789 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
791 SaveStateEntry *se, *new_se;
792 char id[256] = "";
794 if (obj) {
795 char *oid = vmstate_if_get_id(obj);
796 if (oid) {
797 pstrcpy(id, sizeof(id), oid);
798 pstrcat(id, sizeof(id), "/");
799 g_free(oid);
802 pstrcat(id, sizeof(id), idstr);
804 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
805 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
806 savevm_state_handler_remove(se);
807 g_free(se->compat);
808 g_free(se);
814 * Perform some basic checks on vmsd's at registration
815 * time.
817 static void vmstate_check(const VMStateDescription *vmsd)
819 const VMStateField *field = vmsd->fields;
820 const VMStateDescription **subsection = vmsd->subsections;
822 if (field) {
823 while (field->name) {
824 if (field->flags & (VMS_STRUCT | VMS_VSTRUCT)) {
825 /* Recurse to sub structures */
826 vmstate_check(field->vmsd);
828 /* Carry on */
829 field++;
831 /* Check for the end of field list canary */
832 if (field->flags != VMS_END) {
833 error_report("VMSTATE not ending with VMS_END: %s", vmsd->name);
834 g_assert_not_reached();
838 while (subsection && *subsection) {
840 * The name of a subsection should start with the name of the
841 * current object.
843 assert(!strncmp(vmsd->name, (*subsection)->name, strlen(vmsd->name)));
844 vmstate_check(*subsection);
845 subsection++;
849 int vmstate_register_with_alias_id(VMStateIf *obj, uint32_t instance_id,
850 const VMStateDescription *vmsd,
851 void *opaque, int alias_id,
852 int required_for_version,
853 Error **errp)
855 SaveStateEntry *se;
857 /* If this triggers, alias support can be dropped for the vmsd. */
858 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
860 se = g_new0(SaveStateEntry, 1);
861 se->version_id = vmsd->version_id;
862 se->section_id = savevm_state.global_section_id++;
863 se->opaque = opaque;
864 se->vmsd = vmsd;
865 se->alias_id = alias_id;
867 if (obj) {
868 char *id = vmstate_if_get_id(obj);
869 if (id) {
870 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
871 sizeof(se->idstr)) {
872 error_setg(errp, "Path too long for VMState (%s)", id);
873 g_free(id);
874 g_free(se);
876 return -1;
878 g_free(id);
880 se->compat = g_new0(CompatEntry, 1);
881 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
882 se->compat->instance_id = instance_id == VMSTATE_INSTANCE_ID_ANY ?
883 calculate_compat_instance_id(vmsd->name) : instance_id;
884 instance_id = VMSTATE_INSTANCE_ID_ANY;
887 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
889 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
890 se->instance_id = calculate_new_instance_id(se->idstr);
891 } else {
892 se->instance_id = instance_id;
895 /* Perform a recursive sanity check during the test runs */
896 if (qtest_enabled()) {
897 vmstate_check(vmsd);
899 assert(!se->compat || se->instance_id == 0);
900 savevm_state_handler_insert(se);
901 return 0;
904 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
905 void *opaque)
907 SaveStateEntry *se, *new_se;
909 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
910 if (se->vmsd == vmsd && se->opaque == opaque) {
911 savevm_state_handler_remove(se);
912 g_free(se->compat);
913 g_free(se);
918 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
920 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
921 if (!se->vmsd) { /* Old style */
922 return se->ops->load_state(f, se->opaque, se->load_version_id);
924 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
927 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
928 JSONWriter *vmdesc)
930 uint64_t old_offset = qemu_file_transferred_noflush(f);
931 se->ops->save_state(f, se->opaque);
932 uint64_t size = qemu_file_transferred_noflush(f) - old_offset;
934 if (vmdesc) {
935 json_writer_int64(vmdesc, "size", size);
936 json_writer_start_array(vmdesc, "fields");
937 json_writer_start_object(vmdesc, NULL);
938 json_writer_str(vmdesc, "name", "data");
939 json_writer_int64(vmdesc, "size", size);
940 json_writer_str(vmdesc, "type", "buffer");
941 json_writer_end_object(vmdesc);
942 json_writer_end_array(vmdesc);
947 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
949 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
950 uint8_t section_type)
952 qemu_put_byte(f, section_type);
953 qemu_put_be32(f, se->section_id);
955 if (section_type == QEMU_VM_SECTION_FULL ||
956 section_type == QEMU_VM_SECTION_START) {
957 /* ID string */
958 size_t len = strlen(se->idstr);
959 qemu_put_byte(f, len);
960 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
962 qemu_put_be32(f, se->instance_id);
963 qemu_put_be32(f, se->version_id);
968 * Write a footer onto device sections that catches cases misformatted device
969 * sections.
971 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
973 if (migrate_get_current()->send_section_footer) {
974 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
975 qemu_put_be32(f, se->section_id);
979 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, JSONWriter *vmdesc)
981 int ret;
982 Error *local_err = NULL;
983 MigrationState *s = migrate_get_current();
985 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
986 return 0;
988 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
989 trace_savevm_section_skip(se->idstr, se->section_id);
990 return 0;
993 trace_savevm_section_start(se->idstr, se->section_id);
994 save_section_header(f, se, QEMU_VM_SECTION_FULL);
995 if (vmdesc) {
996 json_writer_start_object(vmdesc, NULL);
997 json_writer_str(vmdesc, "name", se->idstr);
998 json_writer_int64(vmdesc, "instance_id", se->instance_id);
1001 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
1002 if (!se->vmsd) {
1003 vmstate_save_old_style(f, se, vmdesc);
1004 } else {
1005 ret = vmstate_save_state_with_err(f, se->vmsd, se->opaque, vmdesc, &local_err);
1006 if (ret) {
1007 migrate_set_error(s, local_err);
1008 error_report_err(local_err);
1009 return ret;
1013 trace_savevm_section_end(se->idstr, se->section_id, 0);
1014 save_section_footer(f, se);
1015 if (vmdesc) {
1016 json_writer_end_object(vmdesc);
1018 return 0;
1021 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
1022 * command and associated data.
1024 * @f: File to send command on
1025 * @command: Command type to send
1026 * @len: Length of associated data
1027 * @data: Data associated with command.
1029 static void qemu_savevm_command_send(QEMUFile *f,
1030 enum qemu_vm_cmd command,
1031 uint16_t len,
1032 uint8_t *data)
1034 trace_savevm_command_send(command, len);
1035 qemu_put_byte(f, QEMU_VM_COMMAND);
1036 qemu_put_be16(f, (uint16_t)command);
1037 qemu_put_be16(f, len);
1038 qemu_put_buffer(f, data, len);
1039 qemu_fflush(f);
1042 void qemu_savevm_send_colo_enable(QEMUFile *f)
1044 trace_savevm_send_colo_enable();
1045 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
1048 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
1050 uint32_t buf;
1052 trace_savevm_send_ping(value);
1053 buf = cpu_to_be32(value);
1054 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
1057 void qemu_savevm_send_open_return_path(QEMUFile *f)
1059 trace_savevm_send_open_return_path();
1060 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
1063 /* We have a buffer of data to send; we don't want that all to be loaded
1064 * by the command itself, so the command contains just the length of the
1065 * extra buffer that we then send straight after it.
1066 * TODO: Must be a better way to organise that
1068 * Returns:
1069 * 0 on success
1070 * -ve on error
1072 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
1074 uint32_t tmp;
1075 MigrationState *ms = migrate_get_current();
1076 Error *local_err = NULL;
1078 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1079 error_setg(&local_err, "%s: Unreasonably large packaged state: %zu",
1080 __func__, len);
1081 migrate_set_error(ms, local_err);
1082 error_report_err(local_err);
1083 return -1;
1086 tmp = cpu_to_be32(len);
1088 trace_qemu_savevm_send_packaged();
1089 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1091 qemu_put_buffer(f, buf, len);
1093 return 0;
1096 /* Send prior to any postcopy transfer */
1097 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1099 if (migrate_postcopy_ram()) {
1100 uint64_t tmp[2];
1101 tmp[0] = cpu_to_be64(ram_pagesize_summary());
1102 tmp[1] = cpu_to_be64(qemu_target_page_size());
1104 trace_qemu_savevm_send_postcopy_advise();
1105 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1106 16, (uint8_t *)tmp);
1107 } else {
1108 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1112 /* Sent prior to starting the destination running in postcopy, discard pages
1113 * that have already been sent but redirtied on the source.
1114 * CMD_POSTCOPY_RAM_DISCARD consist of:
1115 * byte version (0)
1116 * byte Length of name field (not including 0)
1117 * n x byte RAM block name
1118 * byte 0 terminator (just for safety)
1119 * n x Byte ranges within the named RAMBlock
1120 * be64 Start of the range
1121 * be64 Length
1123 * name: RAMBlock name that these entries are part of
1124 * len: Number of page entries
1125 * start_list: 'len' addresses
1126 * length_list: 'len' addresses
1129 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1130 uint16_t len,
1131 uint64_t *start_list,
1132 uint64_t *length_list)
1134 uint8_t *buf;
1135 uint16_t tmplen;
1136 uint16_t t;
1137 size_t name_len = strlen(name);
1139 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1140 assert(name_len < 256);
1141 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1142 buf[0] = postcopy_ram_discard_version;
1143 buf[1] = name_len;
1144 memcpy(buf + 2, name, name_len);
1145 tmplen = 2 + name_len;
1146 buf[tmplen++] = '\0';
1148 for (t = 0; t < len; t++) {
1149 stq_be_p(buf + tmplen, start_list[t]);
1150 tmplen += 8;
1151 stq_be_p(buf + tmplen, length_list[t]);
1152 tmplen += 8;
1154 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1155 g_free(buf);
1158 /* Get the destination into a state where it can receive postcopy data. */
1159 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1161 trace_savevm_send_postcopy_listen();
1162 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1165 /* Kick the destination into running */
1166 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1168 trace_savevm_send_postcopy_run();
1169 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1172 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1174 trace_savevm_send_postcopy_resume();
1175 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1178 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1180 size_t len;
1181 char buf[256];
1183 trace_savevm_send_recv_bitmap(block_name);
1185 buf[0] = len = strlen(block_name);
1186 memcpy(buf + 1, block_name, len);
1188 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1191 bool qemu_savevm_state_blocked(Error **errp)
1193 SaveStateEntry *se;
1195 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1196 if (se->vmsd && se->vmsd->unmigratable) {
1197 error_setg(errp, "State blocked by non-migratable device '%s'",
1198 se->idstr);
1199 return true;
1202 return false;
1205 void qemu_savevm_non_migratable_list(strList **reasons)
1207 SaveStateEntry *se;
1209 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1210 if (se->vmsd && se->vmsd->unmigratable) {
1211 QAPI_LIST_PREPEND(*reasons,
1212 g_strdup_printf("non-migratable device: %s",
1213 se->idstr));
1218 void qemu_savevm_state_header(QEMUFile *f)
1220 trace_savevm_state_header();
1221 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1222 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1224 if (migrate_get_current()->send_configuration) {
1225 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1226 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1230 bool qemu_savevm_state_guest_unplug_pending(void)
1232 SaveStateEntry *se;
1234 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1235 if (se->vmsd && se->vmsd->dev_unplug_pending &&
1236 se->vmsd->dev_unplug_pending(se->opaque)) {
1237 return true;
1241 return false;
1244 int qemu_savevm_state_prepare(Error **errp)
1246 SaveStateEntry *se;
1247 int ret;
1249 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1250 if (!se->ops || !se->ops->save_prepare) {
1251 continue;
1253 if (se->ops->is_active) {
1254 if (!se->ops->is_active(se->opaque)) {
1255 continue;
1259 ret = se->ops->save_prepare(se->opaque, errp);
1260 if (ret < 0) {
1261 return ret;
1265 return 0;
1268 void qemu_savevm_state_setup(QEMUFile *f)
1270 MigrationState *ms = migrate_get_current();
1271 SaveStateEntry *se;
1272 Error *local_err = NULL;
1273 int ret;
1275 ms->vmdesc = json_writer_new(false);
1276 json_writer_start_object(ms->vmdesc, NULL);
1277 json_writer_int64(ms->vmdesc, "page_size", qemu_target_page_size());
1278 json_writer_start_array(ms->vmdesc, "devices");
1280 trace_savevm_state_setup();
1281 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1282 if (se->vmsd && se->vmsd->early_setup) {
1283 ret = vmstate_save(f, se, ms->vmdesc);
1284 if (ret) {
1285 qemu_file_set_error(f, ret);
1286 break;
1288 continue;
1291 if (!se->ops || !se->ops->save_setup) {
1292 continue;
1294 if (se->ops->is_active) {
1295 if (!se->ops->is_active(se->opaque)) {
1296 continue;
1299 save_section_header(f, se, QEMU_VM_SECTION_START);
1301 ret = se->ops->save_setup(f, se->opaque);
1302 save_section_footer(f, se);
1303 if (ret < 0) {
1304 qemu_file_set_error(f, ret);
1305 break;
1309 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1310 error_report_err(local_err);
1314 int qemu_savevm_state_resume_prepare(MigrationState *s)
1316 SaveStateEntry *se;
1317 int ret;
1319 trace_savevm_state_resume_prepare();
1321 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1322 if (!se->ops || !se->ops->resume_prepare) {
1323 continue;
1325 if (se->ops->is_active) {
1326 if (!se->ops->is_active(se->opaque)) {
1327 continue;
1330 ret = se->ops->resume_prepare(s, se->opaque);
1331 if (ret < 0) {
1332 return ret;
1336 return 0;
1340 * this function has three return values:
1341 * negative: there was one error, and we have -errno.
1342 * 0 : We haven't finished, caller have to go again
1343 * 1 : We have finished, we can go to complete phase
1345 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1347 SaveStateEntry *se;
1348 int ret = 1;
1350 trace_savevm_state_iterate();
1351 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1352 if (!se->ops || !se->ops->save_live_iterate) {
1353 continue;
1355 if (se->ops->is_active &&
1356 !se->ops->is_active(se->opaque)) {
1357 continue;
1359 if (se->ops->is_active_iterate &&
1360 !se->ops->is_active_iterate(se->opaque)) {
1361 continue;
1364 * In the postcopy phase, any device that doesn't know how to
1365 * do postcopy should have saved it's state in the _complete
1366 * call that's already run, it might get confused if we call
1367 * iterate afterwards.
1369 if (postcopy &&
1370 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1371 continue;
1373 if (migration_rate_exceeded(f)) {
1374 return 0;
1376 trace_savevm_section_start(se->idstr, se->section_id);
1378 save_section_header(f, se, QEMU_VM_SECTION_PART);
1380 ret = se->ops->save_live_iterate(f, se->opaque);
1381 trace_savevm_section_end(se->idstr, se->section_id, ret);
1382 save_section_footer(f, se);
1384 if (ret < 0) {
1385 error_report("failed to save SaveStateEntry with id(name): "
1386 "%d(%s): %d",
1387 se->section_id, se->idstr, ret);
1388 qemu_file_set_error(f, ret);
1390 if (ret <= 0) {
1391 /* Do not proceed to the next vmstate before this one reported
1392 completion of the current stage. This serializes the migration
1393 and reduces the probability that a faster changing state is
1394 synchronized over and over again. */
1395 break;
1398 return ret;
1401 static bool should_send_vmdesc(void)
1403 MachineState *machine = MACHINE(qdev_get_machine());
1404 bool in_postcopy = migration_in_postcopy();
1405 return !machine->suppress_vmdesc && !in_postcopy;
1409 * Calls the save_live_complete_postcopy methods
1410 * causing the last few pages to be sent immediately and doing any associated
1411 * cleanup.
1412 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1413 * all the other devices, but that happens at the point we switch to postcopy.
1415 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1417 SaveStateEntry *se;
1418 int ret;
1420 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1421 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1422 continue;
1424 if (se->ops->is_active) {
1425 if (!se->ops->is_active(se->opaque)) {
1426 continue;
1429 trace_savevm_section_start(se->idstr, se->section_id);
1430 /* Section type */
1431 qemu_put_byte(f, QEMU_VM_SECTION_END);
1432 qemu_put_be32(f, se->section_id);
1434 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1435 trace_savevm_section_end(se->idstr, se->section_id, ret);
1436 save_section_footer(f, se);
1437 if (ret < 0) {
1438 qemu_file_set_error(f, ret);
1439 return;
1443 qemu_put_byte(f, QEMU_VM_EOF);
1444 qemu_fflush(f);
1447 static
1448 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1450 SaveStateEntry *se;
1451 int ret;
1453 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1454 if (!se->ops ||
1455 (in_postcopy && se->ops->has_postcopy &&
1456 se->ops->has_postcopy(se->opaque)) ||
1457 !se->ops->save_live_complete_precopy) {
1458 continue;
1461 if (se->ops->is_active) {
1462 if (!se->ops->is_active(se->opaque)) {
1463 continue;
1466 trace_savevm_section_start(se->idstr, se->section_id);
1468 save_section_header(f, se, QEMU_VM_SECTION_END);
1470 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1471 trace_savevm_section_end(se->idstr, se->section_id, ret);
1472 save_section_footer(f, se);
1473 if (ret < 0) {
1474 qemu_file_set_error(f, ret);
1475 return -1;
1479 return 0;
1482 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1483 bool in_postcopy,
1484 bool inactivate_disks)
1486 MigrationState *ms = migrate_get_current();
1487 JSONWriter *vmdesc = ms->vmdesc;
1488 int vmdesc_len;
1489 SaveStateEntry *se;
1490 int ret;
1492 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1493 if (se->vmsd && se->vmsd->early_setup) {
1494 /* Already saved during qemu_savevm_state_setup(). */
1495 continue;
1498 ret = vmstate_save(f, se, vmdesc);
1499 if (ret) {
1500 qemu_file_set_error(f, ret);
1501 return ret;
1505 if (inactivate_disks) {
1506 /* Inactivate before sending QEMU_VM_EOF so that the
1507 * bdrv_activate_all() on the other end won't fail. */
1508 ret = bdrv_inactivate_all();
1509 if (ret) {
1510 Error *local_err = NULL;
1511 error_setg(&local_err, "%s: bdrv_inactivate_all() failed (%d)",
1512 __func__, ret);
1513 migrate_set_error(ms, local_err);
1514 error_report_err(local_err);
1515 qemu_file_set_error(f, ret);
1516 return ret;
1519 if (!in_postcopy) {
1520 /* Postcopy stream will still be going */
1521 qemu_put_byte(f, QEMU_VM_EOF);
1524 json_writer_end_array(vmdesc);
1525 json_writer_end_object(vmdesc);
1526 vmdesc_len = strlen(json_writer_get(vmdesc));
1528 if (should_send_vmdesc()) {
1529 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1530 qemu_put_be32(f, vmdesc_len);
1531 qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1534 /* Free it now to detect any inconsistencies. */
1535 json_writer_free(vmdesc);
1536 ms->vmdesc = NULL;
1538 return 0;
1541 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1542 bool inactivate_disks)
1544 int ret;
1545 Error *local_err = NULL;
1546 bool in_postcopy = migration_in_postcopy();
1548 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1549 error_report_err(local_err);
1552 trace_savevm_state_complete_precopy();
1554 cpu_synchronize_all_states();
1556 if (!in_postcopy || iterable_only) {
1557 ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1558 if (ret) {
1559 return ret;
1563 if (iterable_only) {
1564 goto flush;
1567 ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1568 inactivate_disks);
1569 if (ret) {
1570 return ret;
1573 flush:
1574 qemu_fflush(f);
1575 return 0;
1578 /* Give an estimate of the amount left to be transferred,
1579 * the result is split into the amount for units that can and
1580 * for units that can't do postcopy.
1582 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1583 uint64_t *can_postcopy)
1585 SaveStateEntry *se;
1587 *must_precopy = 0;
1588 *can_postcopy = 0;
1590 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1591 if (!se->ops || !se->ops->state_pending_estimate) {
1592 continue;
1594 if (se->ops->is_active) {
1595 if (!se->ops->is_active(se->opaque)) {
1596 continue;
1599 se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1603 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1604 uint64_t *can_postcopy)
1606 SaveStateEntry *se;
1608 *must_precopy = 0;
1609 *can_postcopy = 0;
1611 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1612 if (!se->ops || !se->ops->state_pending_exact) {
1613 continue;
1615 if (se->ops->is_active) {
1616 if (!se->ops->is_active(se->opaque)) {
1617 continue;
1620 se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1624 void qemu_savevm_state_cleanup(void)
1626 SaveStateEntry *se;
1627 Error *local_err = NULL;
1629 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1630 error_report_err(local_err);
1633 trace_savevm_state_cleanup();
1634 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1635 if (se->ops && se->ops->save_cleanup) {
1636 se->ops->save_cleanup(se->opaque);
1641 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1643 int ret;
1644 MigrationState *ms = migrate_get_current();
1645 MigrationStatus status;
1647 if (migration_is_running(ms->state)) {
1648 error_setg(errp, QERR_MIGRATION_ACTIVE);
1649 return -EINVAL;
1652 if (migrate_block()) {
1653 error_setg(errp, "Block migration and snapshots are incompatible");
1654 return -EINVAL;
1657 ret = migrate_init(ms, errp);
1658 if (ret) {
1659 return ret;
1661 ms->to_dst_file = f;
1663 qemu_mutex_unlock_iothread();
1664 qemu_savevm_state_header(f);
1665 qemu_savevm_state_setup(f);
1666 qemu_mutex_lock_iothread();
1668 while (qemu_file_get_error(f) == 0) {
1669 if (qemu_savevm_state_iterate(f, false) > 0) {
1670 break;
1674 ret = qemu_file_get_error(f);
1675 if (ret == 0) {
1676 qemu_savevm_state_complete_precopy(f, false, false);
1677 ret = qemu_file_get_error(f);
1679 qemu_savevm_state_cleanup();
1680 if (ret != 0) {
1681 error_setg_errno(errp, -ret, "Error while writing VM state");
1684 if (ret != 0) {
1685 status = MIGRATION_STATUS_FAILED;
1686 } else {
1687 status = MIGRATION_STATUS_COMPLETED;
1689 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1691 /* f is outer parameter, it should not stay in global migration state after
1692 * this function finished */
1693 ms->to_dst_file = NULL;
1695 return ret;
1698 void qemu_savevm_live_state(QEMUFile *f)
1700 /* save QEMU_VM_SECTION_END section */
1701 qemu_savevm_state_complete_precopy(f, true, false);
1702 qemu_put_byte(f, QEMU_VM_EOF);
1705 int qemu_save_device_state(QEMUFile *f)
1707 SaveStateEntry *se;
1709 if (!migration_in_colo_state()) {
1710 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1711 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1713 cpu_synchronize_all_states();
1715 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1716 int ret;
1718 if (se->is_ram) {
1719 continue;
1721 ret = vmstate_save(f, se, NULL);
1722 if (ret) {
1723 return ret;
1727 qemu_put_byte(f, QEMU_VM_EOF);
1729 return qemu_file_get_error(f);
1732 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1734 SaveStateEntry *se;
1736 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1737 if (!strcmp(se->idstr, idstr) &&
1738 (instance_id == se->instance_id ||
1739 instance_id == se->alias_id))
1740 return se;
1741 /* Migrating from an older version? */
1742 if (strstr(se->idstr, idstr) && se->compat) {
1743 if (!strcmp(se->compat->idstr, idstr) &&
1744 (instance_id == se->compat->instance_id ||
1745 instance_id == se->alias_id))
1746 return se;
1749 return NULL;
1752 enum LoadVMExitCodes {
1753 /* Allow a command to quit all layers of nested loadvm loops */
1754 LOADVM_QUIT = 1,
1757 /* ------ incoming postcopy messages ------ */
1758 /* 'advise' arrives before any transfers just to tell us that a postcopy
1759 * *might* happen - it might be skipped if precopy transferred everything
1760 * quickly.
1762 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1763 uint16_t len)
1765 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1766 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1767 size_t page_size = qemu_target_page_size();
1768 Error *local_err = NULL;
1770 trace_loadvm_postcopy_handle_advise();
1771 if (ps != POSTCOPY_INCOMING_NONE) {
1772 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1773 return -1;
1776 switch (len) {
1777 case 0:
1778 if (migrate_postcopy_ram()) {
1779 error_report("RAM postcopy is enabled but have 0 byte advise");
1780 return -EINVAL;
1782 return 0;
1783 case 8 + 8:
1784 if (!migrate_postcopy_ram()) {
1785 error_report("RAM postcopy is disabled but have 16 byte advise");
1786 return -EINVAL;
1788 break;
1789 default:
1790 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1791 return -EINVAL;
1794 if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1795 error_report_err(local_err);
1796 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1797 return -1;
1800 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1801 local_pagesize_summary = ram_pagesize_summary();
1803 if (remote_pagesize_summary != local_pagesize_summary) {
1805 * This detects two potential causes of mismatch:
1806 * a) A mismatch in host page sizes
1807 * Some combinations of mismatch are probably possible but it gets
1808 * a bit more complicated. In particular we need to place whole
1809 * host pages on the dest at once, and we need to ensure that we
1810 * handle dirtying to make sure we never end up sending part of
1811 * a hostpage on it's own.
1812 * b) The use of different huge page sizes on source/destination
1813 * a more fine grain test is performed during RAM block migration
1814 * but this test here causes a nice early clear failure, and
1815 * also fails when passed to an older qemu that doesn't
1816 * do huge pages.
1818 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1819 " d=%" PRIx64 ")",
1820 remote_pagesize_summary, local_pagesize_summary);
1821 return -1;
1824 remote_tps = qemu_get_be64(mis->from_src_file);
1825 if (remote_tps != page_size) {
1827 * Again, some differences could be dealt with, but for now keep it
1828 * simple.
1830 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1831 (int)remote_tps, page_size);
1832 return -1;
1835 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1836 error_report_err(local_err);
1837 return -1;
1840 if (ram_postcopy_incoming_init(mis)) {
1841 return -1;
1844 return 0;
1847 /* After postcopy we will be told to throw some pages away since they're
1848 * dirty and will have to be demand fetched. Must happen before CPU is
1849 * started.
1850 * There can be 0..many of these messages, each encoding multiple pages.
1852 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1853 uint16_t len)
1855 int tmp;
1856 char ramid[256];
1857 PostcopyState ps = postcopy_state_get();
1859 trace_loadvm_postcopy_ram_handle_discard();
1861 switch (ps) {
1862 case POSTCOPY_INCOMING_ADVISE:
1863 /* 1st discard */
1864 tmp = postcopy_ram_prepare_discard(mis);
1865 if (tmp) {
1866 return tmp;
1868 break;
1870 case POSTCOPY_INCOMING_DISCARD:
1871 /* Expected state */
1872 break;
1874 default:
1875 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1876 ps);
1877 return -1;
1879 /* We're expecting a
1880 * Version (0)
1881 * a RAM ID string (length byte, name, 0 term)
1882 * then at least 1 16 byte chunk
1884 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1885 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1886 return -1;
1889 tmp = qemu_get_byte(mis->from_src_file);
1890 if (tmp != postcopy_ram_discard_version) {
1891 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1892 return -1;
1895 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1896 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1897 return -1;
1899 tmp = qemu_get_byte(mis->from_src_file);
1900 if (tmp != 0) {
1901 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1902 return -1;
1905 len -= 3 + strlen(ramid);
1906 if (len % 16) {
1907 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1908 return -1;
1910 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1911 while (len) {
1912 uint64_t start_addr, block_length;
1913 start_addr = qemu_get_be64(mis->from_src_file);
1914 block_length = qemu_get_be64(mis->from_src_file);
1916 len -= 16;
1917 int ret = ram_discard_range(ramid, start_addr, block_length);
1918 if (ret) {
1919 return ret;
1922 trace_loadvm_postcopy_ram_handle_discard_end();
1924 return 0;
1928 * Triggered by a postcopy_listen command; this thread takes over reading
1929 * the input stream, leaving the main thread free to carry on loading the rest
1930 * of the device state (from RAM).
1931 * (TODO:This could do with being in a postcopy file - but there again it's
1932 * just another input loop, not that postcopy specific)
1934 static void *postcopy_ram_listen_thread(void *opaque)
1936 MigrationIncomingState *mis = migration_incoming_get_current();
1937 QEMUFile *f = mis->from_src_file;
1938 int load_res;
1939 MigrationState *migr = migrate_get_current();
1941 object_ref(OBJECT(migr));
1943 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1944 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1945 qemu_sem_post(&mis->thread_sync_sem);
1946 trace_postcopy_ram_listen_thread_start();
1948 rcu_register_thread();
1950 * Because we're a thread and not a coroutine we can't yield
1951 * in qemu_file, and thus we must be blocking now.
1953 qemu_file_set_blocking(f, true);
1954 load_res = qemu_loadvm_state_main(f, mis);
1957 * This is tricky, but, mis->from_src_file can change after it
1958 * returns, when postcopy recovery happened. In the future, we may
1959 * want a wrapper for the QEMUFile handle.
1961 f = mis->from_src_file;
1963 /* And non-blocking again so we don't block in any cleanup */
1964 qemu_file_set_blocking(f, false);
1966 trace_postcopy_ram_listen_thread_exit();
1967 if (load_res < 0) {
1968 qemu_file_set_error(f, load_res);
1969 dirty_bitmap_mig_cancel_incoming();
1970 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
1971 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1973 error_report("%s: loadvm failed during postcopy: %d. All states "
1974 "are migrated except dirty bitmaps. Some dirty "
1975 "bitmaps may be lost, and present migrated dirty "
1976 "bitmaps are correctly migrated and valid.",
1977 __func__, load_res);
1978 load_res = 0; /* prevent further exit() */
1979 } else {
1980 error_report("%s: loadvm failed: %d", __func__, load_res);
1981 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1982 MIGRATION_STATUS_FAILED);
1985 if (load_res >= 0) {
1987 * This looks good, but it's possible that the device loading in the
1988 * main thread hasn't finished yet, and so we might not be in 'RUN'
1989 * state yet; wait for the end of the main thread.
1991 qemu_event_wait(&mis->main_thread_load_event);
1993 postcopy_ram_incoming_cleanup(mis);
1995 if (load_res < 0) {
1997 * If something went wrong then we have a bad state so exit;
1998 * depending how far we got it might be possible at this point
1999 * to leave the guest running and fire MCEs for pages that never
2000 * arrived as a desperate recovery step.
2002 rcu_unregister_thread();
2003 exit(EXIT_FAILURE);
2006 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2007 MIGRATION_STATUS_COMPLETED);
2009 * If everything has worked fine, then the main thread has waited
2010 * for us to start, and we're the last use of the mis.
2011 * (If something broke then qemu will have to exit anyway since it's
2012 * got a bad migration state).
2014 migration_incoming_state_destroy();
2015 qemu_loadvm_state_cleanup();
2017 rcu_unregister_thread();
2018 mis->have_listen_thread = false;
2019 postcopy_state_set(POSTCOPY_INCOMING_END);
2021 object_unref(OBJECT(migr));
2023 return NULL;
2026 /* After this message we must be able to immediately receive postcopy data */
2027 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2029 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2030 Error *local_err = NULL;
2032 trace_loadvm_postcopy_handle_listen("enter");
2034 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2035 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2036 return -1;
2038 if (ps == POSTCOPY_INCOMING_ADVISE) {
2040 * A rare case, we entered listen without having to do any discards,
2041 * so do the setup that's normally done at the time of the 1st discard.
2043 if (migrate_postcopy_ram()) {
2044 postcopy_ram_prepare_discard(mis);
2048 trace_loadvm_postcopy_handle_listen("after discard");
2051 * Sensitise RAM - can now generate requests for blocks that don't exist
2052 * However, at this point the CPU shouldn't be running, and the IO
2053 * shouldn't be doing anything yet so don't actually expect requests
2055 if (migrate_postcopy_ram()) {
2056 if (postcopy_ram_incoming_setup(mis)) {
2057 postcopy_ram_incoming_cleanup(mis);
2058 return -1;
2062 trace_loadvm_postcopy_handle_listen("after uffd");
2064 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2065 error_report_err(local_err);
2066 return -1;
2069 mis->have_listen_thread = true;
2070 postcopy_thread_create(mis, &mis->listen_thread, "postcopy/listen",
2071 postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2072 trace_loadvm_postcopy_handle_listen("return");
2074 return 0;
2077 static void loadvm_postcopy_handle_run_bh(void *opaque)
2079 Error *local_err = NULL;
2080 MigrationIncomingState *mis = opaque;
2082 trace_loadvm_postcopy_handle_run_bh("enter");
2084 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2085 * in migration.c
2087 cpu_synchronize_all_post_init();
2089 trace_loadvm_postcopy_handle_run_bh("after cpu sync");
2091 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2093 trace_loadvm_postcopy_handle_run_bh("after announce");
2095 /* Make sure all file formats throw away their mutable metadata.
2096 * If we get an error here, just don't restart the VM yet. */
2097 bdrv_activate_all(&local_err);
2098 if (local_err) {
2099 error_report_err(local_err);
2100 local_err = NULL;
2101 autostart = false;
2104 trace_loadvm_postcopy_handle_run_bh("after invalidate cache");
2106 dirty_bitmap_mig_before_vm_start();
2108 if (autostart) {
2109 /* Hold onto your hats, starting the CPU */
2110 vm_start();
2111 } else {
2112 /* leave it paused and let management decide when to start the CPU */
2113 runstate_set(RUN_STATE_PAUSED);
2116 qemu_bh_delete(mis->bh);
2118 trace_loadvm_postcopy_handle_run_bh("return");
2121 /* After all discards we can start running and asking for pages */
2122 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2124 PostcopyState ps = postcopy_state_get();
2126 trace_loadvm_postcopy_handle_run();
2127 if (ps != POSTCOPY_INCOMING_LISTENING) {
2128 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2129 return -1;
2132 postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2133 mis->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, mis);
2134 qemu_bh_schedule(mis->bh);
2136 /* We need to finish reading the stream from the package
2137 * and also stop reading anything more from the stream that loaded the
2138 * package (since it's now being read by the listener thread).
2139 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2141 return LOADVM_QUIT;
2144 /* We must be with page_request_mutex held */
2145 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2146 gpointer data)
2148 MigrationIncomingState *mis = data;
2149 void *host_addr = (void *) key;
2150 ram_addr_t rb_offset;
2151 RAMBlock *rb;
2152 int ret;
2154 rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2155 if (!rb) {
2157 * This should _never_ happen. However be nice for a migrating VM to
2158 * not crash/assert. Post an error (note: intended to not use *_once
2159 * because we do want to see all the illegal addresses; and this can
2160 * never be triggered by the guest so we're safe) and move on next.
2162 error_report("%s: illegal host addr %p", __func__, host_addr);
2163 /* Try the next entry */
2164 return FALSE;
2167 ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2168 if (ret) {
2169 /* Please refer to above comment. */
2170 error_report("%s: send rp message failed for addr %p",
2171 __func__, host_addr);
2172 return FALSE;
2175 trace_postcopy_page_req_sync(host_addr);
2177 return FALSE;
2180 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2182 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2183 g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2187 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2189 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2190 error_report("%s: illegal resume received", __func__);
2191 /* Don't fail the load, only for this. */
2192 return 0;
2196 * Reset the last_rb before we resend any page req to source again, since
2197 * the source should have it reset already.
2199 mis->last_rb = NULL;
2202 * This means source VM is ready to resume the postcopy migration.
2204 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2205 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2207 trace_loadvm_postcopy_handle_resume();
2209 /* Tell source that "we are ready" */
2210 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2213 * After a postcopy recovery, the source should have lost the postcopy
2214 * queue, or potentially the requested pages could have been lost during
2215 * the network down phase. Let's re-sync with the source VM by re-sending
2216 * all the pending pages that we eagerly need, so these threads won't get
2217 * blocked too long due to the recovery.
2219 * Without this procedure, the faulted destination VM threads (waiting for
2220 * page requests right before the postcopy is interrupted) can keep hanging
2221 * until the pages are sent by the source during the background copying of
2222 * pages, or another thread faulted on the same address accidentally.
2224 migrate_send_rp_req_pages_pending(mis);
2227 * It's time to switch state and release the fault thread to continue
2228 * service page faults. Note that this should be explicitly after the
2229 * above call to migrate_send_rp_req_pages_pending(). In short:
2230 * migrate_send_rp_message_req_pages() is not thread safe, yet.
2232 qemu_sem_post(&mis->postcopy_pause_sem_fault);
2234 if (migrate_postcopy_preempt()) {
2236 * The preempt channel will be created in async manner, now let's
2237 * wait for it and make sure it's created.
2239 qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2240 assert(mis->postcopy_qemufile_dst);
2241 /* Kick the fast ram load thread too */
2242 qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2245 return 0;
2249 * Immediately following this command is a blob of data containing an embedded
2250 * chunk of migration stream; read it and load it.
2252 * @mis: Incoming state
2253 * @length: Length of packaged data to read
2255 * Returns: Negative values on error
2258 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2260 int ret;
2261 size_t length;
2262 QIOChannelBuffer *bioc;
2264 length = qemu_get_be32(mis->from_src_file);
2265 trace_loadvm_handle_cmd_packaged(length);
2267 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2268 error_report("Unreasonably large packaged state: %zu", length);
2269 return -1;
2272 bioc = qio_channel_buffer_new(length);
2273 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2274 ret = qemu_get_buffer(mis->from_src_file,
2275 bioc->data,
2276 length);
2277 if (ret != length) {
2278 object_unref(OBJECT(bioc));
2279 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2280 ret, length);
2281 return (ret < 0) ? ret : -EAGAIN;
2283 bioc->usage += length;
2284 trace_loadvm_handle_cmd_packaged_received(ret);
2286 QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2288 ret = qemu_loadvm_state_main(packf, mis);
2289 trace_loadvm_handle_cmd_packaged_main(ret);
2290 qemu_fclose(packf);
2291 object_unref(OBJECT(bioc));
2293 return ret;
2297 * Handle request that source requests for recved_bitmap on
2298 * destination. Payload format:
2300 * len (1 byte) + ramblock_name (<255 bytes)
2302 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2303 uint16_t len)
2305 QEMUFile *file = mis->from_src_file;
2306 RAMBlock *rb;
2307 char block_name[256];
2308 size_t cnt;
2310 cnt = qemu_get_counted_string(file, block_name);
2311 if (!cnt) {
2312 error_report("%s: failed to read block name", __func__);
2313 return -EINVAL;
2316 /* Validate before using the data */
2317 if (qemu_file_get_error(file)) {
2318 return qemu_file_get_error(file);
2321 if (len != cnt + 1) {
2322 error_report("%s: invalid payload length (%d)", __func__, len);
2323 return -EINVAL;
2326 rb = qemu_ram_block_by_name(block_name);
2327 if (!rb) {
2328 error_report("%s: block '%s' not found", __func__, block_name);
2329 return -EINVAL;
2332 migrate_send_rp_recv_bitmap(mis, block_name);
2334 trace_loadvm_handle_recv_bitmap(block_name);
2336 return 0;
2339 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2341 int ret = migration_incoming_enable_colo();
2343 if (!ret) {
2344 ret = colo_init_ram_cache();
2345 if (ret) {
2346 migration_incoming_disable_colo();
2349 return ret;
2353 * Process an incoming 'QEMU_VM_COMMAND'
2354 * 0 just a normal return
2355 * LOADVM_QUIT All good, but exit the loop
2356 * <0 Error
2358 static int loadvm_process_command(QEMUFile *f)
2360 MigrationIncomingState *mis = migration_incoming_get_current();
2361 uint16_t cmd;
2362 uint16_t len;
2363 uint32_t tmp32;
2365 cmd = qemu_get_be16(f);
2366 len = qemu_get_be16(f);
2368 /* Check validity before continue processing of cmds */
2369 if (qemu_file_get_error(f)) {
2370 return qemu_file_get_error(f);
2373 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2374 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2375 return -EINVAL;
2378 trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2380 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2381 error_report("%s received with bad length - expecting %zu, got %d",
2382 mig_cmd_args[cmd].name,
2383 (size_t)mig_cmd_args[cmd].len, len);
2384 return -ERANGE;
2387 switch (cmd) {
2388 case MIG_CMD_OPEN_RETURN_PATH:
2389 if (mis->to_src_file) {
2390 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2391 /* Not really a problem, so don't give up */
2392 return 0;
2394 mis->to_src_file = qemu_file_get_return_path(f);
2395 if (!mis->to_src_file) {
2396 error_report("CMD_OPEN_RETURN_PATH failed");
2397 return -1;
2401 * Switchover ack is enabled but no device uses it, so send an ACK to
2402 * source that it's OK to switchover. Do it here, after return path has
2403 * been created.
2405 if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2406 int ret = migrate_send_rp_switchover_ack(mis);
2407 if (ret) {
2408 error_report(
2409 "Could not send switchover ack RP MSG, err %d (%s)", ret,
2410 strerror(-ret));
2411 return ret;
2414 break;
2416 case MIG_CMD_PING:
2417 tmp32 = qemu_get_be32(f);
2418 trace_loadvm_process_command_ping(tmp32);
2419 if (!mis->to_src_file) {
2420 error_report("CMD_PING (0x%x) received with no return path",
2421 tmp32);
2422 return -1;
2424 migrate_send_rp_pong(mis, tmp32);
2425 break;
2427 case MIG_CMD_PACKAGED:
2428 return loadvm_handle_cmd_packaged(mis);
2430 case MIG_CMD_POSTCOPY_ADVISE:
2431 return loadvm_postcopy_handle_advise(mis, len);
2433 case MIG_CMD_POSTCOPY_LISTEN:
2434 return loadvm_postcopy_handle_listen(mis);
2436 case MIG_CMD_POSTCOPY_RUN:
2437 return loadvm_postcopy_handle_run(mis);
2439 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2440 return loadvm_postcopy_ram_handle_discard(mis, len);
2442 case MIG_CMD_POSTCOPY_RESUME:
2443 return loadvm_postcopy_handle_resume(mis);
2445 case MIG_CMD_RECV_BITMAP:
2446 return loadvm_handle_recv_bitmap(mis, len);
2448 case MIG_CMD_ENABLE_COLO:
2449 return loadvm_process_enable_colo(mis);
2452 return 0;
2456 * Read a footer off the wire and check that it matches the expected section
2458 * Returns: true if the footer was good
2459 * false if there is a problem (and calls error_report to say why)
2461 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2463 int ret;
2464 uint8_t read_mark;
2465 uint32_t read_section_id;
2467 if (!migrate_get_current()->send_section_footer) {
2468 /* No footer to check */
2469 return true;
2472 read_mark = qemu_get_byte(f);
2474 ret = qemu_file_get_error(f);
2475 if (ret) {
2476 error_report("%s: Read section footer failed: %d",
2477 __func__, ret);
2478 return false;
2481 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2482 error_report("Missing section footer for %s", se->idstr);
2483 return false;
2486 read_section_id = qemu_get_be32(f);
2487 if (read_section_id != se->load_section_id) {
2488 error_report("Mismatched section id in footer for %s -"
2489 " read 0x%x expected 0x%x",
2490 se->idstr, read_section_id, se->load_section_id);
2491 return false;
2494 /* All good */
2495 return true;
2498 static int
2499 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2501 uint32_t instance_id, version_id, section_id;
2502 SaveStateEntry *se;
2503 char idstr[256];
2504 int ret;
2506 /* Read section start */
2507 section_id = qemu_get_be32(f);
2508 if (!qemu_get_counted_string(f, idstr)) {
2509 error_report("Unable to read ID string for section %u",
2510 section_id);
2511 return -EINVAL;
2513 instance_id = qemu_get_be32(f);
2514 version_id = qemu_get_be32(f);
2516 ret = qemu_file_get_error(f);
2517 if (ret) {
2518 error_report("%s: Failed to read instance/version ID: %d",
2519 __func__, ret);
2520 return ret;
2523 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2524 instance_id, version_id);
2525 /* Find savevm section */
2526 se = find_se(idstr, instance_id);
2527 if (se == NULL) {
2528 error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2529 "Make sure that your current VM setup matches your "
2530 "saved VM setup, including any hotplugged devices",
2531 idstr, instance_id);
2532 return -EINVAL;
2535 /* Validate version */
2536 if (version_id > se->version_id) {
2537 error_report("savevm: unsupported version %d for '%s' v%d",
2538 version_id, idstr, se->version_id);
2539 return -EINVAL;
2541 se->load_version_id = version_id;
2542 se->load_section_id = section_id;
2544 /* Validate if it is a device's state */
2545 if (xen_enabled() && se->is_ram) {
2546 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2547 return -EINVAL;
2550 ret = vmstate_load(f, se);
2551 if (ret < 0) {
2552 error_report("error while loading state for instance 0x%"PRIx32" of"
2553 " device '%s'", instance_id, idstr);
2554 return ret;
2556 if (!check_section_footer(f, se)) {
2557 return -EINVAL;
2560 return 0;
2563 static int
2564 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2566 uint32_t section_id;
2567 SaveStateEntry *se;
2568 int ret;
2570 section_id = qemu_get_be32(f);
2572 ret = qemu_file_get_error(f);
2573 if (ret) {
2574 error_report("%s: Failed to read section ID: %d",
2575 __func__, ret);
2576 return ret;
2579 trace_qemu_loadvm_state_section_partend(section_id);
2580 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2581 if (se->load_section_id == section_id) {
2582 break;
2585 if (se == NULL) {
2586 error_report("Unknown savevm section %d", section_id);
2587 return -EINVAL;
2590 ret = vmstate_load(f, se);
2591 if (ret < 0) {
2592 error_report("error while loading state section id %d(%s)",
2593 section_id, se->idstr);
2594 return ret;
2596 if (!check_section_footer(f, se)) {
2597 return -EINVAL;
2600 return 0;
2603 static int qemu_loadvm_state_header(QEMUFile *f)
2605 unsigned int v;
2606 int ret;
2608 v = qemu_get_be32(f);
2609 if (v != QEMU_VM_FILE_MAGIC) {
2610 error_report("Not a migration stream");
2611 return -EINVAL;
2614 v = qemu_get_be32(f);
2615 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2616 error_report("SaveVM v2 format is obsolete and don't work anymore");
2617 return -ENOTSUP;
2619 if (v != QEMU_VM_FILE_VERSION) {
2620 error_report("Unsupported migration stream version");
2621 return -ENOTSUP;
2624 if (migrate_get_current()->send_configuration) {
2625 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2626 error_report("Configuration section missing");
2627 qemu_loadvm_state_cleanup();
2628 return -EINVAL;
2630 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2632 if (ret) {
2633 qemu_loadvm_state_cleanup();
2634 return ret;
2637 return 0;
2640 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2642 SaveStateEntry *se;
2644 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2645 if (!se->ops || !se->ops->switchover_ack_needed) {
2646 continue;
2649 if (se->ops->switchover_ack_needed(se->opaque)) {
2650 mis->switchover_ack_pending_num++;
2654 trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2657 static int qemu_loadvm_state_setup(QEMUFile *f)
2659 SaveStateEntry *se;
2660 int ret;
2662 trace_loadvm_state_setup();
2663 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2664 if (!se->ops || !se->ops->load_setup) {
2665 continue;
2667 if (se->ops->is_active) {
2668 if (!se->ops->is_active(se->opaque)) {
2669 continue;
2673 ret = se->ops->load_setup(f, se->opaque);
2674 if (ret < 0) {
2675 qemu_file_set_error(f, ret);
2676 error_report("Load state of device %s failed", se->idstr);
2677 return ret;
2680 return 0;
2683 void qemu_loadvm_state_cleanup(void)
2685 SaveStateEntry *se;
2687 trace_loadvm_state_cleanup();
2688 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2689 if (se->ops && se->ops->load_cleanup) {
2690 se->ops->load_cleanup(se->opaque);
2695 /* Return true if we should continue the migration, or false. */
2696 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2698 int i;
2700 trace_postcopy_pause_incoming();
2702 assert(migrate_postcopy_ram());
2705 * Unregister yank with either from/to src would work, since ioc behind it
2706 * is the same
2708 migration_ioc_unregister_yank_from_file(mis->from_src_file);
2710 assert(mis->from_src_file);
2711 qemu_file_shutdown(mis->from_src_file);
2712 qemu_fclose(mis->from_src_file);
2713 mis->from_src_file = NULL;
2715 assert(mis->to_src_file);
2716 qemu_file_shutdown(mis->to_src_file);
2717 qemu_mutex_lock(&mis->rp_mutex);
2718 qemu_fclose(mis->to_src_file);
2719 mis->to_src_file = NULL;
2720 qemu_mutex_unlock(&mis->rp_mutex);
2723 * NOTE: this must happen before reset the PostcopyTmpPages below,
2724 * otherwise it's racy to reset those fields when the fast load thread
2725 * can be accessing it in parallel.
2727 if (mis->postcopy_qemufile_dst) {
2728 qemu_file_shutdown(mis->postcopy_qemufile_dst);
2729 /* Take the mutex to make sure the fast ram load thread halted */
2730 qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2731 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2732 qemu_fclose(mis->postcopy_qemufile_dst);
2733 mis->postcopy_qemufile_dst = NULL;
2734 qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2737 /* Current state can be either ACTIVE or RECOVER */
2738 migrate_set_state(&mis->state, mis->state,
2739 MIGRATION_STATUS_POSTCOPY_PAUSED);
2741 /* Notify the fault thread for the invalidated file handle */
2742 postcopy_fault_thread_notify(mis);
2745 * If network is interrupted, any temp page we received will be useless
2746 * because we didn't mark them as "received" in receivedmap. After a
2747 * proper recovery later (which will sync src dirty bitmap with receivedmap
2748 * on dest) these cached small pages will be resent again.
2750 for (i = 0; i < mis->postcopy_channels; i++) {
2751 postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2754 error_report("Detected IO failure for postcopy. "
2755 "Migration paused.");
2757 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2758 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2761 trace_postcopy_pause_incoming_continued();
2763 return true;
2766 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2768 uint8_t section_type;
2769 int ret = 0;
2771 retry:
2772 while (true) {
2773 section_type = qemu_get_byte(f);
2775 ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2776 if (ret) {
2777 break;
2780 trace_qemu_loadvm_state_section(section_type);
2781 switch (section_type) {
2782 case QEMU_VM_SECTION_START:
2783 case QEMU_VM_SECTION_FULL:
2784 ret = qemu_loadvm_section_start_full(f, mis);
2785 if (ret < 0) {
2786 goto out;
2788 break;
2789 case QEMU_VM_SECTION_PART:
2790 case QEMU_VM_SECTION_END:
2791 ret = qemu_loadvm_section_part_end(f, mis);
2792 if (ret < 0) {
2793 goto out;
2795 break;
2796 case QEMU_VM_COMMAND:
2797 ret = loadvm_process_command(f);
2798 trace_qemu_loadvm_state_section_command(ret);
2799 if ((ret < 0) || (ret == LOADVM_QUIT)) {
2800 goto out;
2802 break;
2803 case QEMU_VM_EOF:
2804 /* This is the end of migration */
2805 goto out;
2806 default:
2807 error_report("Unknown savevm section type %d", section_type);
2808 ret = -EINVAL;
2809 goto out;
2813 out:
2814 if (ret < 0) {
2815 qemu_file_set_error(f, ret);
2817 /* Cancel bitmaps incoming regardless of recovery */
2818 dirty_bitmap_mig_cancel_incoming();
2821 * If we are during an active postcopy, then we pause instead
2822 * of bail out to at least keep the VM's dirty data. Note
2823 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2824 * during which we're still receiving device states and we
2825 * still haven't yet started the VM on destination.
2827 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2828 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2829 * recovering.
2831 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2832 migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2833 /* Reset f to point to the newly created channel */
2834 f = mis->from_src_file;
2835 goto retry;
2838 return ret;
2841 int qemu_loadvm_state(QEMUFile *f)
2843 MigrationIncomingState *mis = migration_incoming_get_current();
2844 Error *local_err = NULL;
2845 int ret;
2847 if (qemu_savevm_state_blocked(&local_err)) {
2848 error_report_err(local_err);
2849 return -EINVAL;
2852 ret = qemu_loadvm_state_header(f);
2853 if (ret) {
2854 return ret;
2857 if (qemu_loadvm_state_setup(f) != 0) {
2858 return -EINVAL;
2861 if (migrate_switchover_ack()) {
2862 qemu_loadvm_state_switchover_ack_needed(mis);
2865 cpu_synchronize_all_pre_loadvm();
2867 ret = qemu_loadvm_state_main(f, mis);
2868 qemu_event_set(&mis->main_thread_load_event);
2870 trace_qemu_loadvm_state_post_main(ret);
2872 if (mis->have_listen_thread) {
2873 /* Listen thread still going, can't clean up yet */
2874 return ret;
2877 if (ret == 0) {
2878 ret = qemu_file_get_error(f);
2882 * Try to read in the VMDESC section as well, so that dumping tools that
2883 * intercept our migration stream have the chance to see it.
2886 /* We've got to be careful; if we don't read the data and just shut the fd
2887 * then the sender can error if we close while it's still sending.
2888 * We also mustn't read data that isn't there; some transports (RDMA)
2889 * will stall waiting for that data when the source has already closed.
2891 if (ret == 0 && should_send_vmdesc()) {
2892 uint8_t *buf;
2893 uint32_t size;
2894 uint8_t section_type = qemu_get_byte(f);
2896 if (section_type != QEMU_VM_VMDESCRIPTION) {
2897 error_report("Expected vmdescription section, but got %d",
2898 section_type);
2900 * It doesn't seem worth failing at this point since
2901 * we apparently have an otherwise valid VM state
2903 } else {
2904 buf = g_malloc(0x1000);
2905 size = qemu_get_be32(f);
2907 while (size > 0) {
2908 uint32_t read_chunk = MIN(size, 0x1000);
2909 qemu_get_buffer(f, buf, read_chunk);
2910 size -= read_chunk;
2912 g_free(buf);
2916 qemu_loadvm_state_cleanup();
2917 cpu_synchronize_all_post_init();
2919 return ret;
2922 int qemu_load_device_state(QEMUFile *f)
2924 MigrationIncomingState *mis = migration_incoming_get_current();
2925 int ret;
2927 /* Load QEMU_VM_SECTION_FULL section */
2928 ret = qemu_loadvm_state_main(f, mis);
2929 if (ret < 0) {
2930 error_report("Failed to load device state: %d", ret);
2931 return ret;
2934 cpu_synchronize_all_post_init();
2935 return 0;
2938 int qemu_loadvm_approve_switchover(void)
2940 MigrationIncomingState *mis = migration_incoming_get_current();
2942 if (!mis->switchover_ack_pending_num) {
2943 return -EINVAL;
2946 mis->switchover_ack_pending_num--;
2947 trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
2949 if (mis->switchover_ack_pending_num) {
2950 return 0;
2953 return migrate_send_rp_switchover_ack(mis);
2956 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
2957 bool has_devices, strList *devices, Error **errp)
2959 BlockDriverState *bs;
2960 QEMUSnapshotInfo sn1, *sn = &sn1;
2961 int ret = -1, ret2;
2962 QEMUFile *f;
2963 int saved_vm_running;
2964 uint64_t vm_state_size;
2965 g_autoptr(GDateTime) now = g_date_time_new_now_local();
2966 AioContext *aio_context;
2968 GLOBAL_STATE_CODE();
2970 if (migration_is_blocked(errp)) {
2971 return false;
2974 if (!replay_can_snapshot()) {
2975 error_setg(errp, "Record/replay does not allow making snapshot "
2976 "right now. Try once more later.");
2977 return false;
2980 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
2981 return false;
2984 /* Delete old snapshots of the same name */
2985 if (name) {
2986 if (overwrite) {
2987 if (bdrv_all_delete_snapshot(name, has_devices,
2988 devices, errp) < 0) {
2989 return false;
2991 } else {
2992 ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
2993 if (ret2 < 0) {
2994 return false;
2996 if (ret2 == 1) {
2997 error_setg(errp,
2998 "Snapshot '%s' already exists in one or more devices",
2999 name);
3000 return false;
3005 bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3006 if (bs == NULL) {
3007 return false;
3009 aio_context = bdrv_get_aio_context(bs);
3011 saved_vm_running = runstate_is_running();
3013 global_state_store();
3014 vm_stop(RUN_STATE_SAVE_VM);
3016 bdrv_drain_all_begin();
3018 aio_context_acquire(aio_context);
3020 memset(sn, 0, sizeof(*sn));
3022 /* fill auxiliary fields */
3023 sn->date_sec = g_date_time_to_unix(now);
3024 sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3025 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3026 if (replay_mode != REPLAY_MODE_NONE) {
3027 sn->icount = replay_get_current_icount();
3028 } else {
3029 sn->icount = -1ULL;
3032 if (name) {
3033 pstrcpy(sn->name, sizeof(sn->name), name);
3034 } else {
3035 g_autofree char *autoname = g_date_time_format(now, "vm-%Y%m%d%H%M%S");
3036 pstrcpy(sn->name, sizeof(sn->name), autoname);
3039 /* save the VM state */
3040 f = qemu_fopen_bdrv(bs, 1);
3041 if (!f) {
3042 error_setg(errp, "Could not open VM state file");
3043 goto the_end;
3045 ret = qemu_savevm_state(f, errp);
3046 vm_state_size = qemu_file_transferred_noflush(f);
3047 ret2 = qemu_fclose(f);
3048 if (ret < 0) {
3049 goto the_end;
3051 if (ret2 < 0) {
3052 ret = ret2;
3053 goto the_end;
3056 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
3057 * for itself. BDRV_POLL_WHILE() does not support nested locking because
3058 * it only releases the lock once. Therefore synchronous I/O will deadlock
3059 * unless we release the AioContext before bdrv_all_create_snapshot().
3061 aio_context_release(aio_context);
3062 aio_context = NULL;
3064 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3065 has_devices, devices, errp);
3066 if (ret < 0) {
3067 bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3068 goto the_end;
3071 ret = 0;
3073 the_end:
3074 if (aio_context) {
3075 aio_context_release(aio_context);
3078 bdrv_drain_all_end();
3080 if (saved_vm_running) {
3081 vm_start();
3083 return ret == 0;
3086 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3087 Error **errp)
3089 QEMUFile *f;
3090 QIOChannelFile *ioc;
3091 int saved_vm_running;
3092 int ret;
3094 if (!has_live) {
3095 /* live default to true so old version of Xen tool stack can have a
3096 * successful live migration */
3097 live = true;
3100 saved_vm_running = runstate_is_running();
3101 vm_stop(RUN_STATE_SAVE_VM);
3102 global_state_store_running();
3104 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3105 0660, errp);
3106 if (!ioc) {
3107 goto the_end;
3109 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3110 f = qemu_file_new_output(QIO_CHANNEL(ioc));
3111 object_unref(OBJECT(ioc));
3112 ret = qemu_save_device_state(f);
3113 if (ret < 0 || qemu_fclose(f) < 0) {
3114 error_setg(errp, QERR_IO_ERROR);
3115 } else {
3116 /* libxl calls the QMP command "stop" before calling
3117 * "xen-save-devices-state" and in case of migration failure, libxl
3118 * would call "cont".
3119 * So call bdrv_inactivate_all (release locks) here to let the other
3120 * side of the migration take control of the images.
3122 if (live && !saved_vm_running) {
3123 ret = bdrv_inactivate_all();
3124 if (ret) {
3125 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
3126 __func__, ret);
3131 the_end:
3132 if (saved_vm_running) {
3133 vm_start();
3137 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3139 QEMUFile *f;
3140 QIOChannelFile *ioc;
3141 int ret;
3143 /* Guest must be paused before loading the device state; the RAM state
3144 * will already have been loaded by xc
3146 if (runstate_is_running()) {
3147 error_setg(errp, "Cannot update device state while vm is running");
3148 return;
3150 vm_stop(RUN_STATE_RESTORE_VM);
3152 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3153 if (!ioc) {
3154 return;
3156 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3157 f = qemu_file_new_input(QIO_CHANNEL(ioc));
3158 object_unref(OBJECT(ioc));
3160 ret = qemu_loadvm_state(f);
3161 qemu_fclose(f);
3162 if (ret < 0) {
3163 error_setg(errp, QERR_IO_ERROR);
3165 migration_incoming_state_destroy();
3168 bool load_snapshot(const char *name, const char *vmstate,
3169 bool has_devices, strList *devices, Error **errp)
3171 BlockDriverState *bs_vm_state;
3172 QEMUSnapshotInfo sn;
3173 QEMUFile *f;
3174 int ret;
3175 AioContext *aio_context;
3176 MigrationIncomingState *mis = migration_incoming_get_current();
3178 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3179 return false;
3181 ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3182 if (ret < 0) {
3183 return false;
3185 if (ret == 0) {
3186 error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3187 name);
3188 return false;
3191 bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3192 if (!bs_vm_state) {
3193 return false;
3195 aio_context = bdrv_get_aio_context(bs_vm_state);
3197 /* Don't even try to load empty VM states */
3198 aio_context_acquire(aio_context);
3199 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3200 aio_context_release(aio_context);
3201 if (ret < 0) {
3202 return false;
3203 } else if (sn.vm_state_size == 0) {
3204 error_setg(errp, "This is a disk-only snapshot. Revert to it "
3205 " offline using qemu-img");
3206 return false;
3210 * Flush the record/replay queue. Now the VM state is going
3211 * to change. Therefore we don't need to preserve its consistency
3213 replay_flush_events();
3215 /* Flush all IO requests so they don't interfere with the new state. */
3216 bdrv_drain_all_begin();
3218 ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3219 if (ret < 0) {
3220 goto err_drain;
3223 /* restore the VM state */
3224 f = qemu_fopen_bdrv(bs_vm_state, 0);
3225 if (!f) {
3226 error_setg(errp, "Could not open VM state file");
3227 goto err_drain;
3230 qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3231 mis->from_src_file = f;
3233 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3234 ret = -EINVAL;
3235 goto err_drain;
3237 aio_context_acquire(aio_context);
3238 ret = qemu_loadvm_state(f);
3239 migration_incoming_state_destroy();
3240 aio_context_release(aio_context);
3242 bdrv_drain_all_end();
3244 if (ret < 0) {
3245 error_setg(errp, "Error %d while loading VM state", ret);
3246 return false;
3249 return true;
3251 err_drain:
3252 bdrv_drain_all_end();
3253 return false;
3256 bool delete_snapshot(const char *name, bool has_devices,
3257 strList *devices, Error **errp)
3259 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3260 return false;
3263 if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3264 return false;
3267 return true;
3270 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3272 qemu_ram_set_idstr(mr->ram_block,
3273 memory_region_name(mr), dev);
3274 qemu_ram_set_migratable(mr->ram_block);
3277 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3279 qemu_ram_unset_idstr(mr->ram_block);
3280 qemu_ram_unset_migratable(mr->ram_block);
3283 void vmstate_register_ram_global(MemoryRegion *mr)
3285 vmstate_register_ram(mr, NULL);
3288 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3290 /* check needed if --only-migratable is specified */
3291 if (!only_migratable) {
3292 return true;
3295 return !(vmsd && vmsd->unmigratable);
3298 typedef struct SnapshotJob {
3299 Job common;
3300 char *tag;
3301 char *vmstate;
3302 strList *devices;
3303 Coroutine *co;
3304 Error **errp;
3305 bool ret;
3306 } SnapshotJob;
3308 static void qmp_snapshot_job_free(SnapshotJob *s)
3310 g_free(s->tag);
3311 g_free(s->vmstate);
3312 qapi_free_strList(s->devices);
3316 static void snapshot_load_job_bh(void *opaque)
3318 Job *job = opaque;
3319 SnapshotJob *s = container_of(job, SnapshotJob, common);
3320 int orig_vm_running;
3322 job_progress_set_remaining(&s->common, 1);
3324 orig_vm_running = runstate_is_running();
3325 vm_stop(RUN_STATE_RESTORE_VM);
3327 s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3328 if (s->ret && orig_vm_running) {
3329 vm_start();
3332 job_progress_update(&s->common, 1);
3334 qmp_snapshot_job_free(s);
3335 aio_co_wake(s->co);
3338 static void snapshot_save_job_bh(void *opaque)
3340 Job *job = opaque;
3341 SnapshotJob *s = container_of(job, SnapshotJob, common);
3343 job_progress_set_remaining(&s->common, 1);
3344 s->ret = save_snapshot(s->tag, false, s->vmstate,
3345 true, s->devices, s->errp);
3346 job_progress_update(&s->common, 1);
3348 qmp_snapshot_job_free(s);
3349 aio_co_wake(s->co);
3352 static void snapshot_delete_job_bh(void *opaque)
3354 Job *job = opaque;
3355 SnapshotJob *s = container_of(job, SnapshotJob, common);
3357 job_progress_set_remaining(&s->common, 1);
3358 s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3359 job_progress_update(&s->common, 1);
3361 qmp_snapshot_job_free(s);
3362 aio_co_wake(s->co);
3365 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3367 SnapshotJob *s = container_of(job, SnapshotJob, common);
3368 s->errp = errp;
3369 s->co = qemu_coroutine_self();
3370 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3371 snapshot_save_job_bh, job);
3372 qemu_coroutine_yield();
3373 return s->ret ? 0 : -1;
3376 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3378 SnapshotJob *s = container_of(job, SnapshotJob, common);
3379 s->errp = errp;
3380 s->co = qemu_coroutine_self();
3381 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3382 snapshot_load_job_bh, job);
3383 qemu_coroutine_yield();
3384 return s->ret ? 0 : -1;
3387 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3389 SnapshotJob *s = container_of(job, SnapshotJob, common);
3390 s->errp = errp;
3391 s->co = qemu_coroutine_self();
3392 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3393 snapshot_delete_job_bh, job);
3394 qemu_coroutine_yield();
3395 return s->ret ? 0 : -1;
3399 static const JobDriver snapshot_load_job_driver = {
3400 .instance_size = sizeof(SnapshotJob),
3401 .job_type = JOB_TYPE_SNAPSHOT_LOAD,
3402 .run = snapshot_load_job_run,
3405 static const JobDriver snapshot_save_job_driver = {
3406 .instance_size = sizeof(SnapshotJob),
3407 .job_type = JOB_TYPE_SNAPSHOT_SAVE,
3408 .run = snapshot_save_job_run,
3411 static const JobDriver snapshot_delete_job_driver = {
3412 .instance_size = sizeof(SnapshotJob),
3413 .job_type = JOB_TYPE_SNAPSHOT_DELETE,
3414 .run = snapshot_delete_job_run,
3418 void qmp_snapshot_save(const char *job_id,
3419 const char *tag,
3420 const char *vmstate,
3421 strList *devices,
3422 Error **errp)
3424 SnapshotJob *s;
3426 s = job_create(job_id, &snapshot_save_job_driver, NULL,
3427 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3428 NULL, NULL, errp);
3429 if (!s) {
3430 return;
3433 s->tag = g_strdup(tag);
3434 s->vmstate = g_strdup(vmstate);
3435 s->devices = QAPI_CLONE(strList, devices);
3437 job_start(&s->common);
3440 void qmp_snapshot_load(const char *job_id,
3441 const char *tag,
3442 const char *vmstate,
3443 strList *devices,
3444 Error **errp)
3446 SnapshotJob *s;
3448 s = job_create(job_id, &snapshot_load_job_driver, NULL,
3449 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3450 NULL, NULL, errp);
3451 if (!s) {
3452 return;
3455 s->tag = g_strdup(tag);
3456 s->vmstate = g_strdup(vmstate);
3457 s->devices = QAPI_CLONE(strList, devices);
3459 job_start(&s->common);
3462 void qmp_snapshot_delete(const char *job_id,
3463 const char *tag,
3464 strList *devices,
3465 Error **errp)
3467 SnapshotJob *s;
3469 s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3470 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3471 NULL, NULL, errp);
3472 if (!s) {
3473 return;
3476 s->tag = g_strdup(tag);
3477 s->devices = QAPI_CLONE(strList, devices);
3479 job_start(&s->common);