pl050: switch over from update_irq() function to PS2 device gpio
[qemu/armbru.git] / migration / savevm.c
blobe8a1b96fcdb12af0e10f67a5a8fdb447cd2f193b
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/vmstate.h"
35 #include "migration/misc.h"
36 #include "migration/register.h"
37 #include "migration/global_state.h"
38 #include "migration/channel-block.h"
39 #include "ram.h"
40 #include "qemu-file.h"
41 #include "savevm.h"
42 #include "postcopy-ram.h"
43 #include "qapi/error.h"
44 #include "qapi/qapi-commands-migration.h"
45 #include "qapi/qmp/json-writer.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/main-loop.h"
56 #include "block/snapshot.h"
57 #include "qemu/cutils.h"
58 #include "io/channel-buffer.h"
59 #include "io/channel-file.h"
60 #include "sysemu/replay.h"
61 #include "sysemu/runstate.h"
62 #include "sysemu/sysemu.h"
63 #include "sysemu/xen.h"
64 #include "migration/colo.h"
65 #include "qemu/bitmap.h"
66 #include "net/announce.h"
67 #include "qemu/yank.h"
68 #include "yank_functions.h"
70 const unsigned int postcopy_ram_discard_version;
72 /* Subcommands for QEMU_VM_COMMAND */
73 enum qemu_vm_cmd {
74 MIG_CMD_INVALID = 0, /* Must be 0 */
75 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
76 MIG_CMD_PING, /* Request a PONG on the RP */
78 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
79 warn we might want to do PC */
80 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
81 pages as it's running. */
82 MIG_CMD_POSTCOPY_RUN, /* Start execution */
84 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
85 were previously sent during
86 precopy but are dirty. */
87 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
88 MIG_CMD_ENABLE_COLO, /* Enable COLO */
89 MIG_CMD_POSTCOPY_RESUME, /* resume postcopy on dest */
90 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
91 MIG_CMD_MAX
94 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
95 static struct mig_cmd_args {
96 ssize_t len; /* -1 = variable */
97 const char *name;
98 } mig_cmd_args[] = {
99 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
100 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
101 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
102 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
103 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
104 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
105 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
106 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
107 [MIG_CMD_POSTCOPY_RESUME] = { .len = 0, .name = "POSTCOPY_RESUME" },
108 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
109 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
110 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
113 /* Note for MIG_CMD_POSTCOPY_ADVISE:
114 * The format of arguments is depending on postcopy mode:
115 * - postcopy RAM only
116 * uint64_t host page size
117 * uint64_t taget page size
119 * - postcopy RAM and postcopy dirty bitmaps
120 * format is the same as for postcopy RAM only
122 * - postcopy dirty bitmaps only
123 * Nothing. Command length field is 0.
125 * Be careful: adding a new postcopy entity with some other parameters should
126 * not break format self-description ability. Good way is to introduce some
127 * generic extendable format with an exception for two old entities.
130 /***********************************************************/
131 /* savevm/loadvm support */
133 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
135 if (is_writable) {
136 return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
137 } else {
138 return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
143 /* QEMUFile timer support.
144 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
147 void timer_put(QEMUFile *f, QEMUTimer *ts)
149 uint64_t expire_time;
151 expire_time = timer_expire_time_ns(ts);
152 qemu_put_be64(f, expire_time);
155 void timer_get(QEMUFile *f, QEMUTimer *ts)
157 uint64_t expire_time;
159 expire_time = qemu_get_be64(f);
160 if (expire_time != -1) {
161 timer_mod_ns(ts, expire_time);
162 } else {
163 timer_del(ts);
168 /* VMState timer support.
169 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
172 static int get_timer(QEMUFile *f, void *pv, size_t size,
173 const VMStateField *field)
175 QEMUTimer *v = pv;
176 timer_get(f, v);
177 return 0;
180 static int put_timer(QEMUFile *f, void *pv, size_t size,
181 const VMStateField *field, JSONWriter *vmdesc)
183 QEMUTimer *v = pv;
184 timer_put(f, v);
186 return 0;
189 const VMStateInfo vmstate_info_timer = {
190 .name = "timer",
191 .get = get_timer,
192 .put = put_timer,
196 typedef struct CompatEntry {
197 char idstr[256];
198 int instance_id;
199 } CompatEntry;
201 typedef struct SaveStateEntry {
202 QTAILQ_ENTRY(SaveStateEntry) entry;
203 char idstr[256];
204 uint32_t instance_id;
205 int alias_id;
206 int version_id;
207 /* version id read from the stream */
208 int load_version_id;
209 int section_id;
210 /* section id read from the stream */
211 int load_section_id;
212 const SaveVMHandlers *ops;
213 const VMStateDescription *vmsd;
214 void *opaque;
215 CompatEntry *compat;
216 int is_ram;
217 } SaveStateEntry;
219 typedef struct SaveState {
220 QTAILQ_HEAD(, SaveStateEntry) handlers;
221 SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
222 int global_section_id;
223 uint32_t len;
224 const char *name;
225 uint32_t target_page_bits;
226 uint32_t caps_count;
227 MigrationCapability *capabilities;
228 QemuUUID uuid;
229 } SaveState;
231 static SaveState savevm_state = {
232 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
233 .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
234 .global_section_id = 0,
237 static bool should_validate_capability(int capability)
239 assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
240 /* Validate only new capabilities to keep compatibility. */
241 switch (capability) {
242 case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
243 return true;
244 default:
245 return false;
249 static uint32_t get_validatable_capabilities_count(void)
251 MigrationState *s = migrate_get_current();
252 uint32_t result = 0;
253 int i;
254 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
255 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
256 result++;
259 return result;
262 static int configuration_pre_save(void *opaque)
264 SaveState *state = opaque;
265 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
266 MigrationState *s = migrate_get_current();
267 int i, j;
269 state->len = strlen(current_name);
270 state->name = current_name;
271 state->target_page_bits = qemu_target_page_bits();
273 state->caps_count = get_validatable_capabilities_count();
274 state->capabilities = g_renew(MigrationCapability, state->capabilities,
275 state->caps_count);
276 for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
277 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
278 state->capabilities[j++] = i;
281 state->uuid = qemu_uuid;
283 return 0;
286 static int configuration_post_save(void *opaque)
288 SaveState *state = opaque;
290 g_free(state->capabilities);
291 state->capabilities = NULL;
292 state->caps_count = 0;
293 return 0;
296 static int configuration_pre_load(void *opaque)
298 SaveState *state = opaque;
300 /* If there is no target-page-bits subsection it means the source
301 * predates the variable-target-page-bits support and is using the
302 * minimum possible value for this CPU.
304 state->target_page_bits = qemu_target_page_bits_min();
305 return 0;
308 static bool configuration_validate_capabilities(SaveState *state)
310 bool ret = true;
311 MigrationState *s = migrate_get_current();
312 unsigned long *source_caps_bm;
313 int i;
315 source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
316 for (i = 0; i < state->caps_count; i++) {
317 MigrationCapability capability = state->capabilities[i];
318 set_bit(capability, source_caps_bm);
321 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
322 bool source_state, target_state;
323 if (!should_validate_capability(i)) {
324 continue;
326 source_state = test_bit(i, source_caps_bm);
327 target_state = s->enabled_capabilities[i];
328 if (source_state != target_state) {
329 error_report("Capability %s is %s, but received capability is %s",
330 MigrationCapability_str(i),
331 target_state ? "on" : "off",
332 source_state ? "on" : "off");
333 ret = false;
334 /* Don't break here to report all failed capabilities */
338 g_free(source_caps_bm);
339 return ret;
342 static int configuration_post_load(void *opaque, int version_id)
344 SaveState *state = opaque;
345 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
346 int ret = 0;
348 if (strncmp(state->name, current_name, state->len) != 0) {
349 error_report("Machine type received is '%.*s' and local is '%s'",
350 (int) state->len, state->name, current_name);
351 ret = -EINVAL;
352 goto out;
355 if (state->target_page_bits != qemu_target_page_bits()) {
356 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
357 state->target_page_bits, qemu_target_page_bits());
358 ret = -EINVAL;
359 goto out;
362 if (!configuration_validate_capabilities(state)) {
363 ret = -EINVAL;
364 goto out;
367 out:
368 g_free((void *)state->name);
369 state->name = NULL;
370 state->len = 0;
371 g_free(state->capabilities);
372 state->capabilities = NULL;
373 state->caps_count = 0;
375 return ret;
378 static int get_capability(QEMUFile *f, void *pv, size_t size,
379 const VMStateField *field)
381 MigrationCapability *capability = pv;
382 char capability_str[UINT8_MAX + 1];
383 uint8_t len;
384 int i;
386 len = qemu_get_byte(f);
387 qemu_get_buffer(f, (uint8_t *)capability_str, len);
388 capability_str[len] = '\0';
389 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
390 if (!strcmp(MigrationCapability_str(i), capability_str)) {
391 *capability = i;
392 return 0;
395 error_report("Received unknown capability %s", capability_str);
396 return -EINVAL;
399 static int put_capability(QEMUFile *f, void *pv, size_t size,
400 const VMStateField *field, JSONWriter *vmdesc)
402 MigrationCapability *capability = pv;
403 const char *capability_str = MigrationCapability_str(*capability);
404 size_t len = strlen(capability_str);
405 assert(len <= UINT8_MAX);
407 qemu_put_byte(f, len);
408 qemu_put_buffer(f, (uint8_t *)capability_str, len);
409 return 0;
412 static const VMStateInfo vmstate_info_capability = {
413 .name = "capability",
414 .get = get_capability,
415 .put = put_capability,
418 /* The target-page-bits subsection is present only if the
419 * target page size is not the same as the default (ie the
420 * minimum page size for a variable-page-size guest CPU).
421 * If it is present then it contains the actual target page
422 * bits for the machine, and migration will fail if the
423 * two ends don't agree about it.
425 static bool vmstate_target_page_bits_needed(void *opaque)
427 return qemu_target_page_bits()
428 > qemu_target_page_bits_min();
431 static const VMStateDescription vmstate_target_page_bits = {
432 .name = "configuration/target-page-bits",
433 .version_id = 1,
434 .minimum_version_id = 1,
435 .needed = vmstate_target_page_bits_needed,
436 .fields = (VMStateField[]) {
437 VMSTATE_UINT32(target_page_bits, SaveState),
438 VMSTATE_END_OF_LIST()
442 static bool vmstate_capabilites_needed(void *opaque)
444 return get_validatable_capabilities_count() > 0;
447 static const VMStateDescription vmstate_capabilites = {
448 .name = "configuration/capabilities",
449 .version_id = 1,
450 .minimum_version_id = 1,
451 .needed = vmstate_capabilites_needed,
452 .fields = (VMStateField[]) {
453 VMSTATE_UINT32_V(caps_count, SaveState, 1),
454 VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
455 vmstate_info_capability,
456 MigrationCapability),
457 VMSTATE_END_OF_LIST()
461 static bool vmstate_uuid_needed(void *opaque)
463 return qemu_uuid_set && migrate_validate_uuid();
466 static int vmstate_uuid_post_load(void *opaque, int version_id)
468 SaveState *state = opaque;
469 char uuid_src[UUID_FMT_LEN + 1];
470 char uuid_dst[UUID_FMT_LEN + 1];
472 if (!qemu_uuid_set) {
474 * It's warning because user might not know UUID in some cases,
475 * e.g. load an old snapshot
477 qemu_uuid_unparse(&state->uuid, uuid_src);
478 warn_report("UUID is received %s, but local uuid isn't set",
479 uuid_src);
480 return 0;
482 if (!qemu_uuid_is_equal(&state->uuid, &qemu_uuid)) {
483 qemu_uuid_unparse(&state->uuid, uuid_src);
484 qemu_uuid_unparse(&qemu_uuid, uuid_dst);
485 error_report("UUID received is %s and local is %s", uuid_src, uuid_dst);
486 return -EINVAL;
488 return 0;
491 static const VMStateDescription vmstate_uuid = {
492 .name = "configuration/uuid",
493 .version_id = 1,
494 .minimum_version_id = 1,
495 .needed = vmstate_uuid_needed,
496 .post_load = vmstate_uuid_post_load,
497 .fields = (VMStateField[]) {
498 VMSTATE_UINT8_ARRAY_V(uuid.data, SaveState, sizeof(QemuUUID), 1),
499 VMSTATE_END_OF_LIST()
503 static const VMStateDescription vmstate_configuration = {
504 .name = "configuration",
505 .version_id = 1,
506 .pre_load = configuration_pre_load,
507 .post_load = configuration_post_load,
508 .pre_save = configuration_pre_save,
509 .post_save = configuration_post_save,
510 .fields = (VMStateField[]) {
511 VMSTATE_UINT32(len, SaveState),
512 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
513 VMSTATE_END_OF_LIST()
515 .subsections = (const VMStateDescription *[]) {
516 &vmstate_target_page_bits,
517 &vmstate_capabilites,
518 &vmstate_uuid,
519 NULL
523 static void dump_vmstate_vmsd(FILE *out_file,
524 const VMStateDescription *vmsd, int indent,
525 bool is_subsection);
527 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
528 int indent)
530 fprintf(out_file, "%*s{\n", indent, "");
531 indent += 2;
532 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
533 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
534 field->version_id);
535 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
536 field->field_exists ? "true" : "false");
537 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
538 if (field->vmsd != NULL) {
539 fprintf(out_file, ",\n");
540 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
542 fprintf(out_file, "\n%*s}", indent - 2, "");
545 static void dump_vmstate_vmss(FILE *out_file,
546 const VMStateDescription **subsection,
547 int indent)
549 if (*subsection != NULL) {
550 dump_vmstate_vmsd(out_file, *subsection, indent, true);
554 static void dump_vmstate_vmsd(FILE *out_file,
555 const VMStateDescription *vmsd, int indent,
556 bool is_subsection)
558 if (is_subsection) {
559 fprintf(out_file, "%*s{\n", indent, "");
560 } else {
561 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
563 indent += 2;
564 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
565 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
566 vmsd->version_id);
567 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
568 vmsd->minimum_version_id);
569 if (vmsd->fields != NULL) {
570 const VMStateField *field = vmsd->fields;
571 bool first;
573 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
574 first = true;
575 while (field->name != NULL) {
576 if (field->flags & VMS_MUST_EXIST) {
577 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
578 field++;
579 continue;
581 if (!first) {
582 fprintf(out_file, ",\n");
584 dump_vmstate_vmsf(out_file, field, indent + 2);
585 field++;
586 first = false;
588 fprintf(out_file, "\n%*s]", indent, "");
590 if (vmsd->subsections != NULL) {
591 const VMStateDescription **subsection = vmsd->subsections;
592 bool first;
594 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
595 first = true;
596 while (*subsection != NULL) {
597 if (!first) {
598 fprintf(out_file, ",\n");
600 dump_vmstate_vmss(out_file, subsection, indent + 2);
601 subsection++;
602 first = false;
604 fprintf(out_file, "\n%*s]", indent, "");
606 fprintf(out_file, "\n%*s}", indent - 2, "");
609 static void dump_machine_type(FILE *out_file)
611 MachineClass *mc;
613 mc = MACHINE_GET_CLASS(current_machine);
615 fprintf(out_file, " \"vmschkmachine\": {\n");
616 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
617 fprintf(out_file, " },\n");
620 void dump_vmstate_json_to_file(FILE *out_file)
622 GSList *list, *elt;
623 bool first;
625 fprintf(out_file, "{\n");
626 dump_machine_type(out_file);
628 first = true;
629 list = object_class_get_list(TYPE_DEVICE, true);
630 for (elt = list; elt; elt = elt->next) {
631 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
632 TYPE_DEVICE);
633 const char *name;
634 int indent = 2;
636 if (!dc->vmsd) {
637 continue;
640 if (!first) {
641 fprintf(out_file, ",\n");
643 name = object_class_get_name(OBJECT_CLASS(dc));
644 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
645 indent += 2;
646 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
647 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
648 dc->vmsd->version_id);
649 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
650 dc->vmsd->minimum_version_id);
652 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
654 fprintf(out_file, "\n%*s}", indent - 2, "");
655 first = false;
657 fprintf(out_file, "\n}\n");
658 fclose(out_file);
659 g_slist_free(list);
662 static uint32_t calculate_new_instance_id(const char *idstr)
664 SaveStateEntry *se;
665 uint32_t instance_id = 0;
667 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
668 if (strcmp(idstr, se->idstr) == 0
669 && instance_id <= se->instance_id) {
670 instance_id = se->instance_id + 1;
673 /* Make sure we never loop over without being noticed */
674 assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
675 return instance_id;
678 static int calculate_compat_instance_id(const char *idstr)
680 SaveStateEntry *se;
681 int instance_id = 0;
683 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
684 if (!se->compat) {
685 continue;
688 if (strcmp(idstr, se->compat->idstr) == 0
689 && instance_id <= se->compat->instance_id) {
690 instance_id = se->compat->instance_id + 1;
693 return instance_id;
696 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
698 if (se->vmsd) {
699 return se->vmsd->priority;
701 return MIG_PRI_DEFAULT;
704 static void savevm_state_handler_insert(SaveStateEntry *nse)
706 MigrationPriority priority = save_state_priority(nse);
707 SaveStateEntry *se;
708 int i;
710 assert(priority <= MIG_PRI_MAX);
712 for (i = priority - 1; i >= 0; i--) {
713 se = savevm_state.handler_pri_head[i];
714 if (se != NULL) {
715 assert(save_state_priority(se) < priority);
716 break;
720 if (i >= 0) {
721 QTAILQ_INSERT_BEFORE(se, nse, entry);
722 } else {
723 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
726 if (savevm_state.handler_pri_head[priority] == NULL) {
727 savevm_state.handler_pri_head[priority] = nse;
731 static void savevm_state_handler_remove(SaveStateEntry *se)
733 SaveStateEntry *next;
734 MigrationPriority priority = save_state_priority(se);
736 if (se == savevm_state.handler_pri_head[priority]) {
737 next = QTAILQ_NEXT(se, entry);
738 if (next != NULL && save_state_priority(next) == priority) {
739 savevm_state.handler_pri_head[priority] = next;
740 } else {
741 savevm_state.handler_pri_head[priority] = NULL;
744 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
747 /* TODO: Individual devices generally have very little idea about the rest
748 of the system, so instance_id should be removed/replaced.
749 Meanwhile pass -1 as instance_id if you do not already have a clearly
750 distinguishing id for all instances of your device class. */
751 int register_savevm_live(const char *idstr,
752 uint32_t instance_id,
753 int version_id,
754 const SaveVMHandlers *ops,
755 void *opaque)
757 SaveStateEntry *se;
759 se = g_new0(SaveStateEntry, 1);
760 se->version_id = version_id;
761 se->section_id = savevm_state.global_section_id++;
762 se->ops = ops;
763 se->opaque = opaque;
764 se->vmsd = NULL;
765 /* if this is a live_savem then set is_ram */
766 if (ops->save_setup != NULL) {
767 se->is_ram = 1;
770 pstrcat(se->idstr, sizeof(se->idstr), idstr);
772 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
773 se->instance_id = calculate_new_instance_id(se->idstr);
774 } else {
775 se->instance_id = instance_id;
777 assert(!se->compat || se->instance_id == 0);
778 savevm_state_handler_insert(se);
779 return 0;
782 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
784 SaveStateEntry *se, *new_se;
785 char id[256] = "";
787 if (obj) {
788 char *oid = vmstate_if_get_id(obj);
789 if (oid) {
790 pstrcpy(id, sizeof(id), oid);
791 pstrcat(id, sizeof(id), "/");
792 g_free(oid);
795 pstrcat(id, sizeof(id), idstr);
797 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
798 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
799 savevm_state_handler_remove(se);
800 g_free(se->compat);
801 g_free(se);
806 int vmstate_register_with_alias_id(VMStateIf *obj, uint32_t instance_id,
807 const VMStateDescription *vmsd,
808 void *opaque, int alias_id,
809 int required_for_version,
810 Error **errp)
812 SaveStateEntry *se;
814 /* If this triggers, alias support can be dropped for the vmsd. */
815 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
817 se = g_new0(SaveStateEntry, 1);
818 se->version_id = vmsd->version_id;
819 se->section_id = savevm_state.global_section_id++;
820 se->opaque = opaque;
821 se->vmsd = vmsd;
822 se->alias_id = alias_id;
824 if (obj) {
825 char *id = vmstate_if_get_id(obj);
826 if (id) {
827 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
828 sizeof(se->idstr)) {
829 error_setg(errp, "Path too long for VMState (%s)", id);
830 g_free(id);
831 g_free(se);
833 return -1;
835 g_free(id);
837 se->compat = g_new0(CompatEntry, 1);
838 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
839 se->compat->instance_id = instance_id == VMSTATE_INSTANCE_ID_ANY ?
840 calculate_compat_instance_id(vmsd->name) : instance_id;
841 instance_id = VMSTATE_INSTANCE_ID_ANY;
844 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
846 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
847 se->instance_id = calculate_new_instance_id(se->idstr);
848 } else {
849 se->instance_id = instance_id;
851 assert(!se->compat || se->instance_id == 0);
852 savevm_state_handler_insert(se);
853 return 0;
856 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
857 void *opaque)
859 SaveStateEntry *se, *new_se;
861 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
862 if (se->vmsd == vmsd && se->opaque == opaque) {
863 savevm_state_handler_remove(se);
864 g_free(se->compat);
865 g_free(se);
870 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
872 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
873 if (!se->vmsd) { /* Old style */
874 return se->ops->load_state(f, se->opaque, se->load_version_id);
876 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
879 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
880 JSONWriter *vmdesc)
882 int64_t old_offset, size;
884 old_offset = qemu_file_total_transferred_fast(f);
885 se->ops->save_state(f, se->opaque);
886 size = qemu_file_total_transferred_fast(f) - old_offset;
888 if (vmdesc) {
889 json_writer_int64(vmdesc, "size", size);
890 json_writer_start_array(vmdesc, "fields");
891 json_writer_start_object(vmdesc, NULL);
892 json_writer_str(vmdesc, "name", "data");
893 json_writer_int64(vmdesc, "size", size);
894 json_writer_str(vmdesc, "type", "buffer");
895 json_writer_end_object(vmdesc);
896 json_writer_end_array(vmdesc);
900 static int vmstate_save(QEMUFile *f, SaveStateEntry *se,
901 JSONWriter *vmdesc)
903 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
904 if (!se->vmsd) {
905 vmstate_save_old_style(f, se, vmdesc);
906 return 0;
908 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
912 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
914 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
915 uint8_t section_type)
917 qemu_put_byte(f, section_type);
918 qemu_put_be32(f, se->section_id);
920 if (section_type == QEMU_VM_SECTION_FULL ||
921 section_type == QEMU_VM_SECTION_START) {
922 /* ID string */
923 size_t len = strlen(se->idstr);
924 qemu_put_byte(f, len);
925 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
927 qemu_put_be32(f, se->instance_id);
928 qemu_put_be32(f, se->version_id);
933 * Write a footer onto device sections that catches cases misformatted device
934 * sections.
936 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
938 if (migrate_get_current()->send_section_footer) {
939 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
940 qemu_put_be32(f, se->section_id);
945 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
946 * command and associated data.
948 * @f: File to send command on
949 * @command: Command type to send
950 * @len: Length of associated data
951 * @data: Data associated with command.
953 static void qemu_savevm_command_send(QEMUFile *f,
954 enum qemu_vm_cmd command,
955 uint16_t len,
956 uint8_t *data)
958 trace_savevm_command_send(command, len);
959 qemu_put_byte(f, QEMU_VM_COMMAND);
960 qemu_put_be16(f, (uint16_t)command);
961 qemu_put_be16(f, len);
962 qemu_put_buffer(f, data, len);
963 qemu_fflush(f);
966 void qemu_savevm_send_colo_enable(QEMUFile *f)
968 trace_savevm_send_colo_enable();
969 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
972 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
974 uint32_t buf;
976 trace_savevm_send_ping(value);
977 buf = cpu_to_be32(value);
978 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
981 void qemu_savevm_send_open_return_path(QEMUFile *f)
983 trace_savevm_send_open_return_path();
984 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
987 /* We have a buffer of data to send; we don't want that all to be loaded
988 * by the command itself, so the command contains just the length of the
989 * extra buffer that we then send straight after it.
990 * TODO: Must be a better way to organise that
992 * Returns:
993 * 0 on success
994 * -ve on error
996 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
998 uint32_t tmp;
1000 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1001 error_report("%s: Unreasonably large packaged state: %zu",
1002 __func__, len);
1003 return -1;
1006 tmp = cpu_to_be32(len);
1008 trace_qemu_savevm_send_packaged();
1009 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1011 qemu_put_buffer(f, buf, len);
1013 return 0;
1016 /* Send prior to any postcopy transfer */
1017 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1019 if (migrate_postcopy_ram()) {
1020 uint64_t tmp[2];
1021 tmp[0] = cpu_to_be64(ram_pagesize_summary());
1022 tmp[1] = cpu_to_be64(qemu_target_page_size());
1024 trace_qemu_savevm_send_postcopy_advise();
1025 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1026 16, (uint8_t *)tmp);
1027 } else {
1028 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1032 /* Sent prior to starting the destination running in postcopy, discard pages
1033 * that have already been sent but redirtied on the source.
1034 * CMD_POSTCOPY_RAM_DISCARD consist of:
1035 * byte version (0)
1036 * byte Length of name field (not including 0)
1037 * n x byte RAM block name
1038 * byte 0 terminator (just for safety)
1039 * n x Byte ranges within the named RAMBlock
1040 * be64 Start of the range
1041 * be64 Length
1043 * name: RAMBlock name that these entries are part of
1044 * len: Number of page entries
1045 * start_list: 'len' addresses
1046 * length_list: 'len' addresses
1049 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1050 uint16_t len,
1051 uint64_t *start_list,
1052 uint64_t *length_list)
1054 uint8_t *buf;
1055 uint16_t tmplen;
1056 uint16_t t;
1057 size_t name_len = strlen(name);
1059 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1060 assert(name_len < 256);
1061 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1062 buf[0] = postcopy_ram_discard_version;
1063 buf[1] = name_len;
1064 memcpy(buf + 2, name, name_len);
1065 tmplen = 2 + name_len;
1066 buf[tmplen++] = '\0';
1068 for (t = 0; t < len; t++) {
1069 stq_be_p(buf + tmplen, start_list[t]);
1070 tmplen += 8;
1071 stq_be_p(buf + tmplen, length_list[t]);
1072 tmplen += 8;
1074 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1075 g_free(buf);
1078 /* Get the destination into a state where it can receive postcopy data. */
1079 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1081 trace_savevm_send_postcopy_listen();
1082 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1085 /* Kick the destination into running */
1086 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1088 trace_savevm_send_postcopy_run();
1089 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1092 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1094 trace_savevm_send_postcopy_resume();
1095 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1098 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1100 size_t len;
1101 char buf[256];
1103 trace_savevm_send_recv_bitmap(block_name);
1105 buf[0] = len = strlen(block_name);
1106 memcpy(buf + 1, block_name, len);
1108 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1111 bool qemu_savevm_state_blocked(Error **errp)
1113 SaveStateEntry *se;
1115 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1116 if (se->vmsd && se->vmsd->unmigratable) {
1117 error_setg(errp, "State blocked by non-migratable device '%s'",
1118 se->idstr);
1119 return true;
1122 return false;
1125 void qemu_savevm_non_migratable_list(strList **reasons)
1127 SaveStateEntry *se;
1129 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1130 if (se->vmsd && se->vmsd->unmigratable) {
1131 QAPI_LIST_PREPEND(*reasons,
1132 g_strdup_printf("non-migratable device: %s",
1133 se->idstr));
1138 void qemu_savevm_state_header(QEMUFile *f)
1140 trace_savevm_state_header();
1141 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1142 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1144 if (migrate_get_current()->send_configuration) {
1145 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1146 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1150 bool qemu_savevm_state_guest_unplug_pending(void)
1152 SaveStateEntry *se;
1154 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1155 if (se->vmsd && se->vmsd->dev_unplug_pending &&
1156 se->vmsd->dev_unplug_pending(se->opaque)) {
1157 return true;
1161 return false;
1164 void qemu_savevm_state_setup(QEMUFile *f)
1166 SaveStateEntry *se;
1167 Error *local_err = NULL;
1168 int ret;
1170 trace_savevm_state_setup();
1171 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1172 if (!se->ops || !se->ops->save_setup) {
1173 continue;
1175 if (se->ops->is_active) {
1176 if (!se->ops->is_active(se->opaque)) {
1177 continue;
1180 save_section_header(f, se, QEMU_VM_SECTION_START);
1182 ret = se->ops->save_setup(f, se->opaque);
1183 save_section_footer(f, se);
1184 if (ret < 0) {
1185 qemu_file_set_error(f, ret);
1186 break;
1190 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1191 error_report_err(local_err);
1195 int qemu_savevm_state_resume_prepare(MigrationState *s)
1197 SaveStateEntry *se;
1198 int ret;
1200 trace_savevm_state_resume_prepare();
1202 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1203 if (!se->ops || !se->ops->resume_prepare) {
1204 continue;
1206 if (se->ops->is_active) {
1207 if (!se->ops->is_active(se->opaque)) {
1208 continue;
1211 ret = se->ops->resume_prepare(s, se->opaque);
1212 if (ret < 0) {
1213 return ret;
1217 return 0;
1221 * this function has three return values:
1222 * negative: there was one error, and we have -errno.
1223 * 0 : We haven't finished, caller have to go again
1224 * 1 : We have finished, we can go to complete phase
1226 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1228 SaveStateEntry *se;
1229 int ret = 1;
1231 trace_savevm_state_iterate();
1232 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1233 if (!se->ops || !se->ops->save_live_iterate) {
1234 continue;
1236 if (se->ops->is_active &&
1237 !se->ops->is_active(se->opaque)) {
1238 continue;
1240 if (se->ops->is_active_iterate &&
1241 !se->ops->is_active_iterate(se->opaque)) {
1242 continue;
1245 * In the postcopy phase, any device that doesn't know how to
1246 * do postcopy should have saved it's state in the _complete
1247 * call that's already run, it might get confused if we call
1248 * iterate afterwards.
1250 if (postcopy &&
1251 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1252 continue;
1254 if (qemu_file_rate_limit(f)) {
1255 return 0;
1257 trace_savevm_section_start(se->idstr, se->section_id);
1259 save_section_header(f, se, QEMU_VM_SECTION_PART);
1261 ret = se->ops->save_live_iterate(f, se->opaque);
1262 trace_savevm_section_end(se->idstr, se->section_id, ret);
1263 save_section_footer(f, se);
1265 if (ret < 0) {
1266 error_report("failed to save SaveStateEntry with id(name): "
1267 "%d(%s): %d",
1268 se->section_id, se->idstr, ret);
1269 qemu_file_set_error(f, ret);
1271 if (ret <= 0) {
1272 /* Do not proceed to the next vmstate before this one reported
1273 completion of the current stage. This serializes the migration
1274 and reduces the probability that a faster changing state is
1275 synchronized over and over again. */
1276 break;
1279 return ret;
1282 static bool should_send_vmdesc(void)
1284 MachineState *machine = MACHINE(qdev_get_machine());
1285 bool in_postcopy = migration_in_postcopy();
1286 return !machine->suppress_vmdesc && !in_postcopy;
1290 * Calls the save_live_complete_postcopy methods
1291 * causing the last few pages to be sent immediately and doing any associated
1292 * cleanup.
1293 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1294 * all the other devices, but that happens at the point we switch to postcopy.
1296 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1298 SaveStateEntry *se;
1299 int ret;
1301 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1302 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1303 continue;
1305 if (se->ops->is_active) {
1306 if (!se->ops->is_active(se->opaque)) {
1307 continue;
1310 trace_savevm_section_start(se->idstr, se->section_id);
1311 /* Section type */
1312 qemu_put_byte(f, QEMU_VM_SECTION_END);
1313 qemu_put_be32(f, se->section_id);
1315 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1316 trace_savevm_section_end(se->idstr, se->section_id, ret);
1317 save_section_footer(f, se);
1318 if (ret < 0) {
1319 qemu_file_set_error(f, ret);
1320 return;
1324 qemu_put_byte(f, QEMU_VM_EOF);
1325 qemu_fflush(f);
1328 static
1329 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1331 SaveStateEntry *se;
1332 int ret;
1334 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1335 if (!se->ops ||
1336 (in_postcopy && se->ops->has_postcopy &&
1337 se->ops->has_postcopy(se->opaque)) ||
1338 !se->ops->save_live_complete_precopy) {
1339 continue;
1342 if (se->ops->is_active) {
1343 if (!se->ops->is_active(se->opaque)) {
1344 continue;
1347 trace_savevm_section_start(se->idstr, se->section_id);
1349 save_section_header(f, se, QEMU_VM_SECTION_END);
1351 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1352 trace_savevm_section_end(se->idstr, se->section_id, ret);
1353 save_section_footer(f, se);
1354 if (ret < 0) {
1355 qemu_file_set_error(f, ret);
1356 return -1;
1360 return 0;
1363 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1364 bool in_postcopy,
1365 bool inactivate_disks)
1367 g_autoptr(JSONWriter) vmdesc = NULL;
1368 int vmdesc_len;
1369 SaveStateEntry *se;
1370 int ret;
1372 vmdesc = json_writer_new(false);
1373 json_writer_start_object(vmdesc, NULL);
1374 json_writer_int64(vmdesc, "page_size", qemu_target_page_size());
1375 json_writer_start_array(vmdesc, "devices");
1376 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1378 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1379 continue;
1381 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1382 trace_savevm_section_skip(se->idstr, se->section_id);
1383 continue;
1386 trace_savevm_section_start(se->idstr, se->section_id);
1388 json_writer_start_object(vmdesc, NULL);
1389 json_writer_str(vmdesc, "name", se->idstr);
1390 json_writer_int64(vmdesc, "instance_id", se->instance_id);
1392 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1393 ret = vmstate_save(f, se, vmdesc);
1394 if (ret) {
1395 qemu_file_set_error(f, ret);
1396 return ret;
1398 trace_savevm_section_end(se->idstr, se->section_id, 0);
1399 save_section_footer(f, se);
1401 json_writer_end_object(vmdesc);
1404 if (inactivate_disks) {
1405 /* Inactivate before sending QEMU_VM_EOF so that the
1406 * bdrv_activate_all() on the other end won't fail. */
1407 ret = bdrv_inactivate_all();
1408 if (ret) {
1409 error_report("%s: bdrv_inactivate_all() failed (%d)",
1410 __func__, ret);
1411 qemu_file_set_error(f, ret);
1412 return ret;
1415 if (!in_postcopy) {
1416 /* Postcopy stream will still be going */
1417 qemu_put_byte(f, QEMU_VM_EOF);
1420 json_writer_end_array(vmdesc);
1421 json_writer_end_object(vmdesc);
1422 vmdesc_len = strlen(json_writer_get(vmdesc));
1424 if (should_send_vmdesc()) {
1425 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1426 qemu_put_be32(f, vmdesc_len);
1427 qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1430 return 0;
1433 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1434 bool inactivate_disks)
1436 int ret;
1437 Error *local_err = NULL;
1438 bool in_postcopy = migration_in_postcopy();
1440 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1441 error_report_err(local_err);
1444 trace_savevm_state_complete_precopy();
1446 cpu_synchronize_all_states();
1448 if (!in_postcopy || iterable_only) {
1449 ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1450 if (ret) {
1451 return ret;
1455 if (iterable_only) {
1456 goto flush;
1459 ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1460 inactivate_disks);
1461 if (ret) {
1462 return ret;
1465 flush:
1466 qemu_fflush(f);
1467 return 0;
1470 /* Give an estimate of the amount left to be transferred,
1471 * the result is split into the amount for units that can and
1472 * for units that can't do postcopy.
1474 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1475 uint64_t *res_precopy_only,
1476 uint64_t *res_compatible,
1477 uint64_t *res_postcopy_only)
1479 SaveStateEntry *se;
1481 *res_precopy_only = 0;
1482 *res_compatible = 0;
1483 *res_postcopy_only = 0;
1486 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1487 if (!se->ops || !se->ops->save_live_pending) {
1488 continue;
1490 if (se->ops->is_active) {
1491 if (!se->ops->is_active(se->opaque)) {
1492 continue;
1495 se->ops->save_live_pending(f, se->opaque, threshold_size,
1496 res_precopy_only, res_compatible,
1497 res_postcopy_only);
1501 void qemu_savevm_state_cleanup(void)
1503 SaveStateEntry *se;
1504 Error *local_err = NULL;
1506 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1507 error_report_err(local_err);
1510 trace_savevm_state_cleanup();
1511 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1512 if (se->ops && se->ops->save_cleanup) {
1513 se->ops->save_cleanup(se->opaque);
1518 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1520 int ret;
1521 MigrationState *ms = migrate_get_current();
1522 MigrationStatus status;
1524 if (migration_is_running(ms->state)) {
1525 error_setg(errp, QERR_MIGRATION_ACTIVE);
1526 return -EINVAL;
1529 if (migrate_use_block()) {
1530 error_setg(errp, "Block migration and snapshots are incompatible");
1531 return -EINVAL;
1534 migrate_init(ms);
1535 memset(&ram_counters, 0, sizeof(ram_counters));
1536 memset(&compression_counters, 0, sizeof(compression_counters));
1537 ms->to_dst_file = f;
1539 qemu_mutex_unlock_iothread();
1540 qemu_savevm_state_header(f);
1541 qemu_savevm_state_setup(f);
1542 qemu_mutex_lock_iothread();
1544 while (qemu_file_get_error(f) == 0) {
1545 if (qemu_savevm_state_iterate(f, false) > 0) {
1546 break;
1550 ret = qemu_file_get_error(f);
1551 if (ret == 0) {
1552 qemu_savevm_state_complete_precopy(f, false, false);
1553 ret = qemu_file_get_error(f);
1555 qemu_savevm_state_cleanup();
1556 if (ret != 0) {
1557 error_setg_errno(errp, -ret, "Error while writing VM state");
1560 if (ret != 0) {
1561 status = MIGRATION_STATUS_FAILED;
1562 } else {
1563 status = MIGRATION_STATUS_COMPLETED;
1565 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1567 /* f is outer parameter, it should not stay in global migration state after
1568 * this function finished */
1569 ms->to_dst_file = NULL;
1571 return ret;
1574 void qemu_savevm_live_state(QEMUFile *f)
1576 /* save QEMU_VM_SECTION_END section */
1577 qemu_savevm_state_complete_precopy(f, true, false);
1578 qemu_put_byte(f, QEMU_VM_EOF);
1581 int qemu_save_device_state(QEMUFile *f)
1583 SaveStateEntry *se;
1585 if (!migration_in_colo_state()) {
1586 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1587 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1589 cpu_synchronize_all_states();
1591 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1592 int ret;
1594 if (se->is_ram) {
1595 continue;
1597 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1598 continue;
1600 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1601 continue;
1604 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1606 ret = vmstate_save(f, se, NULL);
1607 if (ret) {
1608 return ret;
1611 save_section_footer(f, se);
1614 qemu_put_byte(f, QEMU_VM_EOF);
1616 return qemu_file_get_error(f);
1619 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1621 SaveStateEntry *se;
1623 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1624 if (!strcmp(se->idstr, idstr) &&
1625 (instance_id == se->instance_id ||
1626 instance_id == se->alias_id))
1627 return se;
1628 /* Migrating from an older version? */
1629 if (strstr(se->idstr, idstr) && se->compat) {
1630 if (!strcmp(se->compat->idstr, idstr) &&
1631 (instance_id == se->compat->instance_id ||
1632 instance_id == se->alias_id))
1633 return se;
1636 return NULL;
1639 enum LoadVMExitCodes {
1640 /* Allow a command to quit all layers of nested loadvm loops */
1641 LOADVM_QUIT = 1,
1644 /* ------ incoming postcopy messages ------ */
1645 /* 'advise' arrives before any transfers just to tell us that a postcopy
1646 * *might* happen - it might be skipped if precopy transferred everything
1647 * quickly.
1649 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1650 uint16_t len)
1652 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1653 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1654 size_t page_size = qemu_target_page_size();
1655 Error *local_err = NULL;
1657 trace_loadvm_postcopy_handle_advise();
1658 if (ps != POSTCOPY_INCOMING_NONE) {
1659 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1660 return -1;
1663 switch (len) {
1664 case 0:
1665 if (migrate_postcopy_ram()) {
1666 error_report("RAM postcopy is enabled but have 0 byte advise");
1667 return -EINVAL;
1669 return 0;
1670 case 8 + 8:
1671 if (!migrate_postcopy_ram()) {
1672 error_report("RAM postcopy is disabled but have 16 byte advise");
1673 return -EINVAL;
1675 break;
1676 default:
1677 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1678 return -EINVAL;
1681 if (!postcopy_ram_supported_by_host(mis)) {
1682 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1683 return -1;
1686 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1687 local_pagesize_summary = ram_pagesize_summary();
1689 if (remote_pagesize_summary != local_pagesize_summary) {
1691 * This detects two potential causes of mismatch:
1692 * a) A mismatch in host page sizes
1693 * Some combinations of mismatch are probably possible but it gets
1694 * a bit more complicated. In particular we need to place whole
1695 * host pages on the dest at once, and we need to ensure that we
1696 * handle dirtying to make sure we never end up sending part of
1697 * a hostpage on it's own.
1698 * b) The use of different huge page sizes on source/destination
1699 * a more fine grain test is performed during RAM block migration
1700 * but this test here causes a nice early clear failure, and
1701 * also fails when passed to an older qemu that doesn't
1702 * do huge pages.
1704 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1705 " d=%" PRIx64 ")",
1706 remote_pagesize_summary, local_pagesize_summary);
1707 return -1;
1710 remote_tps = qemu_get_be64(mis->from_src_file);
1711 if (remote_tps != page_size) {
1713 * Again, some differences could be dealt with, but for now keep it
1714 * simple.
1716 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1717 (int)remote_tps, page_size);
1718 return -1;
1721 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1722 error_report_err(local_err);
1723 return -1;
1726 if (ram_postcopy_incoming_init(mis)) {
1727 return -1;
1730 return 0;
1733 /* After postcopy we will be told to throw some pages away since they're
1734 * dirty and will have to be demand fetched. Must happen before CPU is
1735 * started.
1736 * There can be 0..many of these messages, each encoding multiple pages.
1738 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1739 uint16_t len)
1741 int tmp;
1742 char ramid[256];
1743 PostcopyState ps = postcopy_state_get();
1745 trace_loadvm_postcopy_ram_handle_discard();
1747 switch (ps) {
1748 case POSTCOPY_INCOMING_ADVISE:
1749 /* 1st discard */
1750 tmp = postcopy_ram_prepare_discard(mis);
1751 if (tmp) {
1752 return tmp;
1754 break;
1756 case POSTCOPY_INCOMING_DISCARD:
1757 /* Expected state */
1758 break;
1760 default:
1761 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1762 ps);
1763 return -1;
1765 /* We're expecting a
1766 * Version (0)
1767 * a RAM ID string (length byte, name, 0 term)
1768 * then at least 1 16 byte chunk
1770 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1771 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1772 return -1;
1775 tmp = qemu_get_byte(mis->from_src_file);
1776 if (tmp != postcopy_ram_discard_version) {
1777 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1778 return -1;
1781 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1782 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1783 return -1;
1785 tmp = qemu_get_byte(mis->from_src_file);
1786 if (tmp != 0) {
1787 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1788 return -1;
1791 len -= 3 + strlen(ramid);
1792 if (len % 16) {
1793 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1794 return -1;
1796 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1797 while (len) {
1798 uint64_t start_addr, block_length;
1799 start_addr = qemu_get_be64(mis->from_src_file);
1800 block_length = qemu_get_be64(mis->from_src_file);
1802 len -= 16;
1803 int ret = ram_discard_range(ramid, start_addr, block_length);
1804 if (ret) {
1805 return ret;
1808 trace_loadvm_postcopy_ram_handle_discard_end();
1810 return 0;
1814 * Triggered by a postcopy_listen command; this thread takes over reading
1815 * the input stream, leaving the main thread free to carry on loading the rest
1816 * of the device state (from RAM).
1817 * (TODO:This could do with being in a postcopy file - but there again it's
1818 * just another input loop, not that postcopy specific)
1820 static void *postcopy_ram_listen_thread(void *opaque)
1822 MigrationIncomingState *mis = migration_incoming_get_current();
1823 QEMUFile *f = mis->from_src_file;
1824 int load_res;
1825 MigrationState *migr = migrate_get_current();
1827 object_ref(OBJECT(migr));
1829 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1830 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1831 qemu_sem_post(&mis->thread_sync_sem);
1832 trace_postcopy_ram_listen_thread_start();
1834 rcu_register_thread();
1836 * Because we're a thread and not a coroutine we can't yield
1837 * in qemu_file, and thus we must be blocking now.
1839 qemu_file_set_blocking(f, true);
1840 load_res = qemu_loadvm_state_main(f, mis);
1843 * This is tricky, but, mis->from_src_file can change after it
1844 * returns, when postcopy recovery happened. In the future, we may
1845 * want a wrapper for the QEMUFile handle.
1847 f = mis->from_src_file;
1849 /* And non-blocking again so we don't block in any cleanup */
1850 qemu_file_set_blocking(f, false);
1852 trace_postcopy_ram_listen_thread_exit();
1853 if (load_res < 0) {
1854 qemu_file_set_error(f, load_res);
1855 dirty_bitmap_mig_cancel_incoming();
1856 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
1857 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1859 error_report("%s: loadvm failed during postcopy: %d. All states "
1860 "are migrated except dirty bitmaps. Some dirty "
1861 "bitmaps may be lost, and present migrated dirty "
1862 "bitmaps are correctly migrated and valid.",
1863 __func__, load_res);
1864 load_res = 0; /* prevent further exit() */
1865 } else {
1866 error_report("%s: loadvm failed: %d", __func__, load_res);
1867 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1868 MIGRATION_STATUS_FAILED);
1871 if (load_res >= 0) {
1873 * This looks good, but it's possible that the device loading in the
1874 * main thread hasn't finished yet, and so we might not be in 'RUN'
1875 * state yet; wait for the end of the main thread.
1877 qemu_event_wait(&mis->main_thread_load_event);
1879 postcopy_ram_incoming_cleanup(mis);
1881 if (load_res < 0) {
1883 * If something went wrong then we have a bad state so exit;
1884 * depending how far we got it might be possible at this point
1885 * to leave the guest running and fire MCEs for pages that never
1886 * arrived as a desperate recovery step.
1888 rcu_unregister_thread();
1889 exit(EXIT_FAILURE);
1892 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1893 MIGRATION_STATUS_COMPLETED);
1895 * If everything has worked fine, then the main thread has waited
1896 * for us to start, and we're the last use of the mis.
1897 * (If something broke then qemu will have to exit anyway since it's
1898 * got a bad migration state).
1900 migration_incoming_state_destroy();
1901 qemu_loadvm_state_cleanup();
1903 rcu_unregister_thread();
1904 mis->have_listen_thread = false;
1905 postcopy_state_set(POSTCOPY_INCOMING_END);
1907 object_unref(OBJECT(migr));
1909 return NULL;
1912 /* After this message we must be able to immediately receive postcopy data */
1913 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1915 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1916 Error *local_err = NULL;
1918 trace_loadvm_postcopy_handle_listen("enter");
1920 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1921 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1922 return -1;
1924 if (ps == POSTCOPY_INCOMING_ADVISE) {
1926 * A rare case, we entered listen without having to do any discards,
1927 * so do the setup that's normally done at the time of the 1st discard.
1929 if (migrate_postcopy_ram()) {
1930 postcopy_ram_prepare_discard(mis);
1934 trace_loadvm_postcopy_handle_listen("after discard");
1937 * Sensitise RAM - can now generate requests for blocks that don't exist
1938 * However, at this point the CPU shouldn't be running, and the IO
1939 * shouldn't be doing anything yet so don't actually expect requests
1941 if (migrate_postcopy_ram()) {
1942 if (postcopy_ram_incoming_setup(mis)) {
1943 postcopy_ram_incoming_cleanup(mis);
1944 return -1;
1948 trace_loadvm_postcopy_handle_listen("after uffd");
1950 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1951 error_report_err(local_err);
1952 return -1;
1955 mis->have_listen_thread = true;
1956 postcopy_thread_create(mis, &mis->listen_thread, "postcopy/listen",
1957 postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
1958 trace_loadvm_postcopy_handle_listen("return");
1960 return 0;
1963 static void loadvm_postcopy_handle_run_bh(void *opaque)
1965 Error *local_err = NULL;
1966 MigrationIncomingState *mis = opaque;
1968 trace_loadvm_postcopy_handle_run_bh("enter");
1970 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1971 * in migration.c
1973 cpu_synchronize_all_post_init();
1975 trace_loadvm_postcopy_handle_run_bh("after cpu sync");
1977 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
1979 trace_loadvm_postcopy_handle_run_bh("after announce");
1981 /* Make sure all file formats throw away their mutable metadata.
1982 * If we get an error here, just don't restart the VM yet. */
1983 bdrv_activate_all(&local_err);
1984 if (local_err) {
1985 error_report_err(local_err);
1986 local_err = NULL;
1987 autostart = false;
1990 trace_loadvm_postcopy_handle_run_bh("after invalidate cache");
1992 dirty_bitmap_mig_before_vm_start();
1994 if (autostart) {
1995 /* Hold onto your hats, starting the CPU */
1996 vm_start();
1997 } else {
1998 /* leave it paused and let management decide when to start the CPU */
1999 runstate_set(RUN_STATE_PAUSED);
2002 qemu_bh_delete(mis->bh);
2004 trace_loadvm_postcopy_handle_run_bh("return");
2007 /* After all discards we can start running and asking for pages */
2008 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2010 PostcopyState ps = postcopy_state_get();
2012 trace_loadvm_postcopy_handle_run();
2013 if (ps != POSTCOPY_INCOMING_LISTENING) {
2014 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2015 return -1;
2018 postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2019 mis->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, mis);
2020 qemu_bh_schedule(mis->bh);
2022 /* We need to finish reading the stream from the package
2023 * and also stop reading anything more from the stream that loaded the
2024 * package (since it's now being read by the listener thread).
2025 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2027 return LOADVM_QUIT;
2030 /* We must be with page_request_mutex held */
2031 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2032 gpointer data)
2034 MigrationIncomingState *mis = data;
2035 void *host_addr = (void *) key;
2036 ram_addr_t rb_offset;
2037 RAMBlock *rb;
2038 int ret;
2040 rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2041 if (!rb) {
2043 * This should _never_ happen. However be nice for a migrating VM to
2044 * not crash/assert. Post an error (note: intended to not use *_once
2045 * because we do want to see all the illegal addresses; and this can
2046 * never be triggered by the guest so we're safe) and move on next.
2048 error_report("%s: illegal host addr %p", __func__, host_addr);
2049 /* Try the next entry */
2050 return FALSE;
2053 ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2054 if (ret) {
2055 /* Please refer to above comment. */
2056 error_report("%s: send rp message failed for addr %p",
2057 __func__, host_addr);
2058 return FALSE;
2061 trace_postcopy_page_req_sync(host_addr);
2063 return FALSE;
2066 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2068 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2069 g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2073 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2075 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2076 error_report("%s: illegal resume received", __func__);
2077 /* Don't fail the load, only for this. */
2078 return 0;
2082 * Reset the last_rb before we resend any page req to source again, since
2083 * the source should have it reset already.
2085 mis->last_rb = NULL;
2088 * This means source VM is ready to resume the postcopy migration.
2090 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2091 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2093 trace_loadvm_postcopy_handle_resume();
2095 /* Tell source that "we are ready" */
2096 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2099 * After a postcopy recovery, the source should have lost the postcopy
2100 * queue, or potentially the requested pages could have been lost during
2101 * the network down phase. Let's re-sync with the source VM by re-sending
2102 * all the pending pages that we eagerly need, so these threads won't get
2103 * blocked too long due to the recovery.
2105 * Without this procedure, the faulted destination VM threads (waiting for
2106 * page requests right before the postcopy is interrupted) can keep hanging
2107 * until the pages are sent by the source during the background copying of
2108 * pages, or another thread faulted on the same address accidentally.
2110 migrate_send_rp_req_pages_pending(mis);
2113 * It's time to switch state and release the fault thread to continue
2114 * service page faults. Note that this should be explicitly after the
2115 * above call to migrate_send_rp_req_pages_pending(). In short:
2116 * migrate_send_rp_message_req_pages() is not thread safe, yet.
2118 qemu_sem_post(&mis->postcopy_pause_sem_fault);
2120 return 0;
2124 * Immediately following this command is a blob of data containing an embedded
2125 * chunk of migration stream; read it and load it.
2127 * @mis: Incoming state
2128 * @length: Length of packaged data to read
2130 * Returns: Negative values on error
2133 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2135 int ret;
2136 size_t length;
2137 QIOChannelBuffer *bioc;
2139 length = qemu_get_be32(mis->from_src_file);
2140 trace_loadvm_handle_cmd_packaged(length);
2142 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2143 error_report("Unreasonably large packaged state: %zu", length);
2144 return -1;
2147 bioc = qio_channel_buffer_new(length);
2148 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2149 ret = qemu_get_buffer(mis->from_src_file,
2150 bioc->data,
2151 length);
2152 if (ret != length) {
2153 object_unref(OBJECT(bioc));
2154 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2155 ret, length);
2156 return (ret < 0) ? ret : -EAGAIN;
2158 bioc->usage += length;
2159 trace_loadvm_handle_cmd_packaged_received(ret);
2161 QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2163 ret = qemu_loadvm_state_main(packf, mis);
2164 trace_loadvm_handle_cmd_packaged_main(ret);
2165 qemu_fclose(packf);
2166 object_unref(OBJECT(bioc));
2168 return ret;
2172 * Handle request that source requests for recved_bitmap on
2173 * destination. Payload format:
2175 * len (1 byte) + ramblock_name (<255 bytes)
2177 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2178 uint16_t len)
2180 QEMUFile *file = mis->from_src_file;
2181 RAMBlock *rb;
2182 char block_name[256];
2183 size_t cnt;
2185 cnt = qemu_get_counted_string(file, block_name);
2186 if (!cnt) {
2187 error_report("%s: failed to read block name", __func__);
2188 return -EINVAL;
2191 /* Validate before using the data */
2192 if (qemu_file_get_error(file)) {
2193 return qemu_file_get_error(file);
2196 if (len != cnt + 1) {
2197 error_report("%s: invalid payload length (%d)", __func__, len);
2198 return -EINVAL;
2201 rb = qemu_ram_block_by_name(block_name);
2202 if (!rb) {
2203 error_report("%s: block '%s' not found", __func__, block_name);
2204 return -EINVAL;
2207 migrate_send_rp_recv_bitmap(mis, block_name);
2209 trace_loadvm_handle_recv_bitmap(block_name);
2211 return 0;
2214 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2216 int ret = migration_incoming_enable_colo();
2218 if (!ret) {
2219 ret = colo_init_ram_cache();
2220 if (ret) {
2221 migration_incoming_disable_colo();
2224 return ret;
2228 * Process an incoming 'QEMU_VM_COMMAND'
2229 * 0 just a normal return
2230 * LOADVM_QUIT All good, but exit the loop
2231 * <0 Error
2233 static int loadvm_process_command(QEMUFile *f)
2235 MigrationIncomingState *mis = migration_incoming_get_current();
2236 uint16_t cmd;
2237 uint16_t len;
2238 uint32_t tmp32;
2240 cmd = qemu_get_be16(f);
2241 len = qemu_get_be16(f);
2243 /* Check validity before continue processing of cmds */
2244 if (qemu_file_get_error(f)) {
2245 return qemu_file_get_error(f);
2248 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2249 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2250 return -EINVAL;
2253 trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2255 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2256 error_report("%s received with bad length - expecting %zu, got %d",
2257 mig_cmd_args[cmd].name,
2258 (size_t)mig_cmd_args[cmd].len, len);
2259 return -ERANGE;
2262 switch (cmd) {
2263 case MIG_CMD_OPEN_RETURN_PATH:
2264 if (mis->to_src_file) {
2265 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2266 /* Not really a problem, so don't give up */
2267 return 0;
2269 mis->to_src_file = qemu_file_get_return_path(f);
2270 if (!mis->to_src_file) {
2271 error_report("CMD_OPEN_RETURN_PATH failed");
2272 return -1;
2274 break;
2276 case MIG_CMD_PING:
2277 tmp32 = qemu_get_be32(f);
2278 trace_loadvm_process_command_ping(tmp32);
2279 if (!mis->to_src_file) {
2280 error_report("CMD_PING (0x%x) received with no return path",
2281 tmp32);
2282 return -1;
2284 migrate_send_rp_pong(mis, tmp32);
2285 break;
2287 case MIG_CMD_PACKAGED:
2288 return loadvm_handle_cmd_packaged(mis);
2290 case MIG_CMD_POSTCOPY_ADVISE:
2291 return loadvm_postcopy_handle_advise(mis, len);
2293 case MIG_CMD_POSTCOPY_LISTEN:
2294 return loadvm_postcopy_handle_listen(mis);
2296 case MIG_CMD_POSTCOPY_RUN:
2297 return loadvm_postcopy_handle_run(mis);
2299 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2300 return loadvm_postcopy_ram_handle_discard(mis, len);
2302 case MIG_CMD_POSTCOPY_RESUME:
2303 return loadvm_postcopy_handle_resume(mis);
2305 case MIG_CMD_RECV_BITMAP:
2306 return loadvm_handle_recv_bitmap(mis, len);
2308 case MIG_CMD_ENABLE_COLO:
2309 return loadvm_process_enable_colo(mis);
2312 return 0;
2316 * Read a footer off the wire and check that it matches the expected section
2318 * Returns: true if the footer was good
2319 * false if there is a problem (and calls error_report to say why)
2321 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2323 int ret;
2324 uint8_t read_mark;
2325 uint32_t read_section_id;
2327 if (!migrate_get_current()->send_section_footer) {
2328 /* No footer to check */
2329 return true;
2332 read_mark = qemu_get_byte(f);
2334 ret = qemu_file_get_error(f);
2335 if (ret) {
2336 error_report("%s: Read section footer failed: %d",
2337 __func__, ret);
2338 return false;
2341 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2342 error_report("Missing section footer for %s", se->idstr);
2343 return false;
2346 read_section_id = qemu_get_be32(f);
2347 if (read_section_id != se->load_section_id) {
2348 error_report("Mismatched section id in footer for %s -"
2349 " read 0x%x expected 0x%x",
2350 se->idstr, read_section_id, se->load_section_id);
2351 return false;
2354 /* All good */
2355 return true;
2358 static int
2359 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2361 uint32_t instance_id, version_id, section_id;
2362 SaveStateEntry *se;
2363 char idstr[256];
2364 int ret;
2366 /* Read section start */
2367 section_id = qemu_get_be32(f);
2368 if (!qemu_get_counted_string(f, idstr)) {
2369 error_report("Unable to read ID string for section %u",
2370 section_id);
2371 return -EINVAL;
2373 instance_id = qemu_get_be32(f);
2374 version_id = qemu_get_be32(f);
2376 ret = qemu_file_get_error(f);
2377 if (ret) {
2378 error_report("%s: Failed to read instance/version ID: %d",
2379 __func__, ret);
2380 return ret;
2383 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2384 instance_id, version_id);
2385 /* Find savevm section */
2386 se = find_se(idstr, instance_id);
2387 if (se == NULL) {
2388 error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2389 "Make sure that your current VM setup matches your "
2390 "saved VM setup, including any hotplugged devices",
2391 idstr, instance_id);
2392 return -EINVAL;
2395 /* Validate version */
2396 if (version_id > se->version_id) {
2397 error_report("savevm: unsupported version %d for '%s' v%d",
2398 version_id, idstr, se->version_id);
2399 return -EINVAL;
2401 se->load_version_id = version_id;
2402 se->load_section_id = section_id;
2404 /* Validate if it is a device's state */
2405 if (xen_enabled() && se->is_ram) {
2406 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2407 return -EINVAL;
2410 ret = vmstate_load(f, se);
2411 if (ret < 0) {
2412 error_report("error while loading state for instance 0x%"PRIx32" of"
2413 " device '%s'", instance_id, idstr);
2414 return ret;
2416 if (!check_section_footer(f, se)) {
2417 return -EINVAL;
2420 return 0;
2423 static int
2424 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2426 uint32_t section_id;
2427 SaveStateEntry *se;
2428 int ret;
2430 section_id = qemu_get_be32(f);
2432 ret = qemu_file_get_error(f);
2433 if (ret) {
2434 error_report("%s: Failed to read section ID: %d",
2435 __func__, ret);
2436 return ret;
2439 trace_qemu_loadvm_state_section_partend(section_id);
2440 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2441 if (se->load_section_id == section_id) {
2442 break;
2445 if (se == NULL) {
2446 error_report("Unknown savevm section %d", section_id);
2447 return -EINVAL;
2450 ret = vmstate_load(f, se);
2451 if (ret < 0) {
2452 error_report("error while loading state section id %d(%s)",
2453 section_id, se->idstr);
2454 return ret;
2456 if (!check_section_footer(f, se)) {
2457 return -EINVAL;
2460 return 0;
2463 static int qemu_loadvm_state_header(QEMUFile *f)
2465 unsigned int v;
2466 int ret;
2468 v = qemu_get_be32(f);
2469 if (v != QEMU_VM_FILE_MAGIC) {
2470 error_report("Not a migration stream");
2471 return -EINVAL;
2474 v = qemu_get_be32(f);
2475 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2476 error_report("SaveVM v2 format is obsolete and don't work anymore");
2477 return -ENOTSUP;
2479 if (v != QEMU_VM_FILE_VERSION) {
2480 error_report("Unsupported migration stream version");
2481 return -ENOTSUP;
2484 if (migrate_get_current()->send_configuration) {
2485 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2486 error_report("Configuration section missing");
2487 qemu_loadvm_state_cleanup();
2488 return -EINVAL;
2490 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2492 if (ret) {
2493 qemu_loadvm_state_cleanup();
2494 return ret;
2497 return 0;
2500 static int qemu_loadvm_state_setup(QEMUFile *f)
2502 SaveStateEntry *se;
2503 int ret;
2505 trace_loadvm_state_setup();
2506 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2507 if (!se->ops || !se->ops->load_setup) {
2508 continue;
2510 if (se->ops->is_active) {
2511 if (!se->ops->is_active(se->opaque)) {
2512 continue;
2516 ret = se->ops->load_setup(f, se->opaque);
2517 if (ret < 0) {
2518 qemu_file_set_error(f, ret);
2519 error_report("Load state of device %s failed", se->idstr);
2520 return ret;
2523 return 0;
2526 void qemu_loadvm_state_cleanup(void)
2528 SaveStateEntry *se;
2530 trace_loadvm_state_cleanup();
2531 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2532 if (se->ops && se->ops->load_cleanup) {
2533 se->ops->load_cleanup(se->opaque);
2538 /* Return true if we should continue the migration, or false. */
2539 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2541 int i;
2544 * If network is interrupted, any temp page we received will be useless
2545 * because we didn't mark them as "received" in receivedmap. After a
2546 * proper recovery later (which will sync src dirty bitmap with receivedmap
2547 * on dest) these cached small pages will be resent again.
2549 for (i = 0; i < mis->postcopy_channels; i++) {
2550 postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2553 trace_postcopy_pause_incoming();
2555 assert(migrate_postcopy_ram());
2558 * Unregister yank with either from/to src would work, since ioc behind it
2559 * is the same
2561 migration_ioc_unregister_yank_from_file(mis->from_src_file);
2563 assert(mis->from_src_file);
2564 qemu_file_shutdown(mis->from_src_file);
2565 qemu_fclose(mis->from_src_file);
2566 mis->from_src_file = NULL;
2568 assert(mis->to_src_file);
2569 qemu_file_shutdown(mis->to_src_file);
2570 qemu_mutex_lock(&mis->rp_mutex);
2571 qemu_fclose(mis->to_src_file);
2572 mis->to_src_file = NULL;
2573 qemu_mutex_unlock(&mis->rp_mutex);
2575 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2576 MIGRATION_STATUS_POSTCOPY_PAUSED);
2578 /* Notify the fault thread for the invalidated file handle */
2579 postcopy_fault_thread_notify(mis);
2581 error_report("Detected IO failure for postcopy. "
2582 "Migration paused.");
2584 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2585 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2588 trace_postcopy_pause_incoming_continued();
2590 return true;
2593 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2595 uint8_t section_type;
2596 int ret = 0;
2598 retry:
2599 while (true) {
2600 section_type = qemu_get_byte(f);
2602 if (qemu_file_get_error(f)) {
2603 ret = qemu_file_get_error(f);
2604 break;
2607 trace_qemu_loadvm_state_section(section_type);
2608 switch (section_type) {
2609 case QEMU_VM_SECTION_START:
2610 case QEMU_VM_SECTION_FULL:
2611 ret = qemu_loadvm_section_start_full(f, mis);
2612 if (ret < 0) {
2613 goto out;
2615 break;
2616 case QEMU_VM_SECTION_PART:
2617 case QEMU_VM_SECTION_END:
2618 ret = qemu_loadvm_section_part_end(f, mis);
2619 if (ret < 0) {
2620 goto out;
2622 break;
2623 case QEMU_VM_COMMAND:
2624 ret = loadvm_process_command(f);
2625 trace_qemu_loadvm_state_section_command(ret);
2626 if ((ret < 0) || (ret == LOADVM_QUIT)) {
2627 goto out;
2629 break;
2630 case QEMU_VM_EOF:
2631 /* This is the end of migration */
2632 goto out;
2633 default:
2634 error_report("Unknown savevm section type %d", section_type);
2635 ret = -EINVAL;
2636 goto out;
2640 out:
2641 if (ret < 0) {
2642 qemu_file_set_error(f, ret);
2644 /* Cancel bitmaps incoming regardless of recovery */
2645 dirty_bitmap_mig_cancel_incoming();
2648 * If we are during an active postcopy, then we pause instead
2649 * of bail out to at least keep the VM's dirty data. Note
2650 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2651 * during which we're still receiving device states and we
2652 * still haven't yet started the VM on destination.
2654 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2655 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2656 * recovering.
2658 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2659 migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2660 /* Reset f to point to the newly created channel */
2661 f = mis->from_src_file;
2662 goto retry;
2665 return ret;
2668 int qemu_loadvm_state(QEMUFile *f)
2670 MigrationIncomingState *mis = migration_incoming_get_current();
2671 Error *local_err = NULL;
2672 int ret;
2674 if (qemu_savevm_state_blocked(&local_err)) {
2675 error_report_err(local_err);
2676 return -EINVAL;
2679 ret = qemu_loadvm_state_header(f);
2680 if (ret) {
2681 return ret;
2684 if (qemu_loadvm_state_setup(f) != 0) {
2685 return -EINVAL;
2688 cpu_synchronize_all_pre_loadvm();
2690 ret = qemu_loadvm_state_main(f, mis);
2691 qemu_event_set(&mis->main_thread_load_event);
2693 trace_qemu_loadvm_state_post_main(ret);
2695 if (mis->have_listen_thread) {
2696 /* Listen thread still going, can't clean up yet */
2697 return ret;
2700 if (ret == 0) {
2701 ret = qemu_file_get_error(f);
2705 * Try to read in the VMDESC section as well, so that dumping tools that
2706 * intercept our migration stream have the chance to see it.
2709 /* We've got to be careful; if we don't read the data and just shut the fd
2710 * then the sender can error if we close while it's still sending.
2711 * We also mustn't read data that isn't there; some transports (RDMA)
2712 * will stall waiting for that data when the source has already closed.
2714 if (ret == 0 && should_send_vmdesc()) {
2715 uint8_t *buf;
2716 uint32_t size;
2717 uint8_t section_type = qemu_get_byte(f);
2719 if (section_type != QEMU_VM_VMDESCRIPTION) {
2720 error_report("Expected vmdescription section, but got %d",
2721 section_type);
2723 * It doesn't seem worth failing at this point since
2724 * we apparently have an otherwise valid VM state
2726 } else {
2727 buf = g_malloc(0x1000);
2728 size = qemu_get_be32(f);
2730 while (size > 0) {
2731 uint32_t read_chunk = MIN(size, 0x1000);
2732 qemu_get_buffer(f, buf, read_chunk);
2733 size -= read_chunk;
2735 g_free(buf);
2739 qemu_loadvm_state_cleanup();
2740 cpu_synchronize_all_post_init();
2742 return ret;
2745 int qemu_load_device_state(QEMUFile *f)
2747 MigrationIncomingState *mis = migration_incoming_get_current();
2748 int ret;
2750 /* Load QEMU_VM_SECTION_FULL section */
2751 ret = qemu_loadvm_state_main(f, mis);
2752 if (ret < 0) {
2753 error_report("Failed to load device state: %d", ret);
2754 return ret;
2757 cpu_synchronize_all_post_init();
2758 return 0;
2761 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
2762 bool has_devices, strList *devices, Error **errp)
2764 BlockDriverState *bs;
2765 QEMUSnapshotInfo sn1, *sn = &sn1;
2766 int ret = -1, ret2;
2767 QEMUFile *f;
2768 int saved_vm_running;
2769 uint64_t vm_state_size;
2770 g_autoptr(GDateTime) now = g_date_time_new_now_local();
2771 AioContext *aio_context;
2773 GLOBAL_STATE_CODE();
2775 if (migration_is_blocked(errp)) {
2776 return false;
2779 if (!replay_can_snapshot()) {
2780 error_setg(errp, "Record/replay does not allow making snapshot "
2781 "right now. Try once more later.");
2782 return false;
2785 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
2786 return false;
2789 /* Delete old snapshots of the same name */
2790 if (name) {
2791 if (overwrite) {
2792 if (bdrv_all_delete_snapshot(name, has_devices,
2793 devices, errp) < 0) {
2794 return false;
2796 } else {
2797 ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
2798 if (ret2 < 0) {
2799 return false;
2801 if (ret2 == 1) {
2802 error_setg(errp,
2803 "Snapshot '%s' already exists in one or more devices",
2804 name);
2805 return false;
2810 bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
2811 if (bs == NULL) {
2812 return false;
2814 aio_context = bdrv_get_aio_context(bs);
2816 saved_vm_running = runstate_is_running();
2818 ret = global_state_store();
2819 if (ret) {
2820 error_setg(errp, "Error saving global state");
2821 return false;
2823 vm_stop(RUN_STATE_SAVE_VM);
2825 bdrv_drain_all_begin();
2827 aio_context_acquire(aio_context);
2829 memset(sn, 0, sizeof(*sn));
2831 /* fill auxiliary fields */
2832 sn->date_sec = g_date_time_to_unix(now);
2833 sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
2834 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2835 if (replay_mode != REPLAY_MODE_NONE) {
2836 sn->icount = replay_get_current_icount();
2837 } else {
2838 sn->icount = -1ULL;
2841 if (name) {
2842 pstrcpy(sn->name, sizeof(sn->name), name);
2843 } else {
2844 g_autofree char *autoname = g_date_time_format(now, "vm-%Y%m%d%H%M%S");
2845 pstrcpy(sn->name, sizeof(sn->name), autoname);
2848 /* save the VM state */
2849 f = qemu_fopen_bdrv(bs, 1);
2850 if (!f) {
2851 error_setg(errp, "Could not open VM state file");
2852 goto the_end;
2854 ret = qemu_savevm_state(f, errp);
2855 vm_state_size = qemu_file_total_transferred(f);
2856 ret2 = qemu_fclose(f);
2857 if (ret < 0) {
2858 goto the_end;
2860 if (ret2 < 0) {
2861 ret = ret2;
2862 goto the_end;
2865 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2866 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2867 * it only releases the lock once. Therefore synchronous I/O will deadlock
2868 * unless we release the AioContext before bdrv_all_create_snapshot().
2870 aio_context_release(aio_context);
2871 aio_context = NULL;
2873 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
2874 has_devices, devices, errp);
2875 if (ret < 0) {
2876 bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
2877 goto the_end;
2880 ret = 0;
2882 the_end:
2883 if (aio_context) {
2884 aio_context_release(aio_context);
2887 bdrv_drain_all_end();
2889 if (saved_vm_running) {
2890 vm_start();
2892 return ret == 0;
2895 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2896 Error **errp)
2898 QEMUFile *f;
2899 QIOChannelFile *ioc;
2900 int saved_vm_running;
2901 int ret;
2903 if (!has_live) {
2904 /* live default to true so old version of Xen tool stack can have a
2905 * successful live migration */
2906 live = true;
2909 saved_vm_running = runstate_is_running();
2910 vm_stop(RUN_STATE_SAVE_VM);
2911 global_state_store_running();
2913 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
2914 0660, errp);
2915 if (!ioc) {
2916 goto the_end;
2918 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2919 f = qemu_file_new_output(QIO_CHANNEL(ioc));
2920 object_unref(OBJECT(ioc));
2921 ret = qemu_save_device_state(f);
2922 if (ret < 0 || qemu_fclose(f) < 0) {
2923 error_setg(errp, QERR_IO_ERROR);
2924 } else {
2925 /* libxl calls the QMP command "stop" before calling
2926 * "xen-save-devices-state" and in case of migration failure, libxl
2927 * would call "cont".
2928 * So call bdrv_inactivate_all (release locks) here to let the other
2929 * side of the migration take control of the images.
2931 if (live && !saved_vm_running) {
2932 ret = bdrv_inactivate_all();
2933 if (ret) {
2934 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2935 __func__, ret);
2940 the_end:
2941 if (saved_vm_running) {
2942 vm_start();
2946 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2948 QEMUFile *f;
2949 QIOChannelFile *ioc;
2950 int ret;
2952 /* Guest must be paused before loading the device state; the RAM state
2953 * will already have been loaded by xc
2955 if (runstate_is_running()) {
2956 error_setg(errp, "Cannot update device state while vm is running");
2957 return;
2959 vm_stop(RUN_STATE_RESTORE_VM);
2961 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2962 if (!ioc) {
2963 return;
2965 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2966 f = qemu_file_new_input(QIO_CHANNEL(ioc));
2967 object_unref(OBJECT(ioc));
2969 ret = qemu_loadvm_state(f);
2970 qemu_fclose(f);
2971 if (ret < 0) {
2972 error_setg(errp, QERR_IO_ERROR);
2974 migration_incoming_state_destroy();
2977 bool load_snapshot(const char *name, const char *vmstate,
2978 bool has_devices, strList *devices, Error **errp)
2980 BlockDriverState *bs_vm_state;
2981 QEMUSnapshotInfo sn;
2982 QEMUFile *f;
2983 int ret;
2984 AioContext *aio_context;
2985 MigrationIncomingState *mis = migration_incoming_get_current();
2987 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
2988 return false;
2990 ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
2991 if (ret < 0) {
2992 return false;
2994 if (ret == 0) {
2995 error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
2996 name);
2997 return false;
3000 bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3001 if (!bs_vm_state) {
3002 return false;
3004 aio_context = bdrv_get_aio_context(bs_vm_state);
3006 /* Don't even try to load empty VM states */
3007 aio_context_acquire(aio_context);
3008 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3009 aio_context_release(aio_context);
3010 if (ret < 0) {
3011 return false;
3012 } else if (sn.vm_state_size == 0) {
3013 error_setg(errp, "This is a disk-only snapshot. Revert to it "
3014 " offline using qemu-img");
3015 return false;
3019 * Flush the record/replay queue. Now the VM state is going
3020 * to change. Therefore we don't need to preserve its consistency
3022 replay_flush_events();
3024 /* Flush all IO requests so they don't interfere with the new state. */
3025 bdrv_drain_all_begin();
3027 ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3028 if (ret < 0) {
3029 goto err_drain;
3032 /* restore the VM state */
3033 f = qemu_fopen_bdrv(bs_vm_state, 0);
3034 if (!f) {
3035 error_setg(errp, "Could not open VM state file");
3036 goto err_drain;
3039 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3040 mis->from_src_file = f;
3042 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3043 ret = -EINVAL;
3044 goto err_drain;
3046 aio_context_acquire(aio_context);
3047 ret = qemu_loadvm_state(f);
3048 migration_incoming_state_destroy();
3049 aio_context_release(aio_context);
3051 bdrv_drain_all_end();
3053 if (ret < 0) {
3054 error_setg(errp, "Error %d while loading VM state", ret);
3055 return false;
3058 return true;
3060 err_drain:
3061 bdrv_drain_all_end();
3062 return false;
3065 bool delete_snapshot(const char *name, bool has_devices,
3066 strList *devices, Error **errp)
3068 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3069 return false;
3072 if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3073 return false;
3076 return true;
3079 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3081 qemu_ram_set_idstr(mr->ram_block,
3082 memory_region_name(mr), dev);
3083 qemu_ram_set_migratable(mr->ram_block);
3086 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3088 qemu_ram_unset_idstr(mr->ram_block);
3089 qemu_ram_unset_migratable(mr->ram_block);
3092 void vmstate_register_ram_global(MemoryRegion *mr)
3094 vmstate_register_ram(mr, NULL);
3097 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3099 /* check needed if --only-migratable is specified */
3100 if (!only_migratable) {
3101 return true;
3104 return !(vmsd && vmsd->unmigratable);
3107 typedef struct SnapshotJob {
3108 Job common;
3109 char *tag;
3110 char *vmstate;
3111 strList *devices;
3112 Coroutine *co;
3113 Error **errp;
3114 bool ret;
3115 } SnapshotJob;
3117 static void qmp_snapshot_job_free(SnapshotJob *s)
3119 g_free(s->tag);
3120 g_free(s->vmstate);
3121 qapi_free_strList(s->devices);
3125 static void snapshot_load_job_bh(void *opaque)
3127 Job *job = opaque;
3128 SnapshotJob *s = container_of(job, SnapshotJob, common);
3129 int orig_vm_running;
3131 job_progress_set_remaining(&s->common, 1);
3133 orig_vm_running = runstate_is_running();
3134 vm_stop(RUN_STATE_RESTORE_VM);
3136 s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3137 if (s->ret && orig_vm_running) {
3138 vm_start();
3141 job_progress_update(&s->common, 1);
3143 qmp_snapshot_job_free(s);
3144 aio_co_wake(s->co);
3147 static void snapshot_save_job_bh(void *opaque)
3149 Job *job = opaque;
3150 SnapshotJob *s = container_of(job, SnapshotJob, common);
3152 job_progress_set_remaining(&s->common, 1);
3153 s->ret = save_snapshot(s->tag, false, s->vmstate,
3154 true, s->devices, s->errp);
3155 job_progress_update(&s->common, 1);
3157 qmp_snapshot_job_free(s);
3158 aio_co_wake(s->co);
3161 static void snapshot_delete_job_bh(void *opaque)
3163 Job *job = opaque;
3164 SnapshotJob *s = container_of(job, SnapshotJob, common);
3166 job_progress_set_remaining(&s->common, 1);
3167 s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3168 job_progress_update(&s->common, 1);
3170 qmp_snapshot_job_free(s);
3171 aio_co_wake(s->co);
3174 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3176 SnapshotJob *s = container_of(job, SnapshotJob, common);
3177 s->errp = errp;
3178 s->co = qemu_coroutine_self();
3179 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3180 snapshot_save_job_bh, job);
3181 qemu_coroutine_yield();
3182 return s->ret ? 0 : -1;
3185 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3187 SnapshotJob *s = container_of(job, SnapshotJob, common);
3188 s->errp = errp;
3189 s->co = qemu_coroutine_self();
3190 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3191 snapshot_load_job_bh, job);
3192 qemu_coroutine_yield();
3193 return s->ret ? 0 : -1;
3196 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3198 SnapshotJob *s = container_of(job, SnapshotJob, common);
3199 s->errp = errp;
3200 s->co = qemu_coroutine_self();
3201 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3202 snapshot_delete_job_bh, job);
3203 qemu_coroutine_yield();
3204 return s->ret ? 0 : -1;
3208 static const JobDriver snapshot_load_job_driver = {
3209 .instance_size = sizeof(SnapshotJob),
3210 .job_type = JOB_TYPE_SNAPSHOT_LOAD,
3211 .run = snapshot_load_job_run,
3214 static const JobDriver snapshot_save_job_driver = {
3215 .instance_size = sizeof(SnapshotJob),
3216 .job_type = JOB_TYPE_SNAPSHOT_SAVE,
3217 .run = snapshot_save_job_run,
3220 static const JobDriver snapshot_delete_job_driver = {
3221 .instance_size = sizeof(SnapshotJob),
3222 .job_type = JOB_TYPE_SNAPSHOT_DELETE,
3223 .run = snapshot_delete_job_run,
3227 void qmp_snapshot_save(const char *job_id,
3228 const char *tag,
3229 const char *vmstate,
3230 strList *devices,
3231 Error **errp)
3233 SnapshotJob *s;
3235 s = job_create(job_id, &snapshot_save_job_driver, NULL,
3236 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3237 NULL, NULL, errp);
3238 if (!s) {
3239 return;
3242 s->tag = g_strdup(tag);
3243 s->vmstate = g_strdup(vmstate);
3244 s->devices = QAPI_CLONE(strList, devices);
3246 job_start(&s->common);
3249 void qmp_snapshot_load(const char *job_id,
3250 const char *tag,
3251 const char *vmstate,
3252 strList *devices,
3253 Error **errp)
3255 SnapshotJob *s;
3257 s = job_create(job_id, &snapshot_load_job_driver, NULL,
3258 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3259 NULL, NULL, errp);
3260 if (!s) {
3261 return;
3264 s->tag = g_strdup(tag);
3265 s->vmstate = g_strdup(vmstate);
3266 s->devices = QAPI_CLONE(strList, devices);
3268 job_start(&s->common);
3271 void qmp_snapshot_delete(const char *job_id,
3272 const char *tag,
3273 strList *devices,
3274 Error **errp)
3276 SnapshotJob *s;
3278 s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3279 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3280 NULL, NULL, errp);
3281 if (!s) {
3282 return;
3285 s->tag = g_strdup(tag);
3286 s->devices = QAPI_CLONE(strList, devices);
3288 job_start(&s->common);