]> git.proxmox.com Git - mirror_qemu.git/blob - migration/savevm.c
migration: Move more initializations to migrate_init()
[mirror_qemu.git] / migration / savevm.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
6 *
7 * Authors:
8 * Juan Quintela <quintela@redhat.com>
9 *
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:
16 *
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
19 *
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.
27 */
28
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"
72
73 const unsigned int postcopy_ram_discard_version;
74
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 */
80
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 */
86
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
95 };
96
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" },
114 };
115
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
121 *
122 * - postcopy RAM and postcopy dirty bitmaps
123 * format is the same as for postcopy RAM only
124 *
125 * - postcopy dirty bitmaps only
126 * Nothing. Command length field is 0.
127 *
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.
131 */
132
133 /***********************************************************/
134 /* savevm/loadvm support */
135
136 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
137 {
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)));
142 }
143 }
144
145
146 /* QEMUFile timer support.
147 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
148 */
149
150 void timer_put(QEMUFile *f, QEMUTimer *ts)
151 {
152 uint64_t expire_time;
153
154 expire_time = timer_expire_time_ns(ts);
155 qemu_put_be64(f, expire_time);
156 }
157
158 void timer_get(QEMUFile *f, QEMUTimer *ts)
159 {
160 uint64_t expire_time;
161
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);
167 }
168 }
169
170
171 /* VMState timer support.
172 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
173 */
174
175 static int get_timer(QEMUFile *f, void *pv, size_t size,
176 const VMStateField *field)
177 {
178 QEMUTimer *v = pv;
179 timer_get(f, v);
180 return 0;
181 }
182
183 static int put_timer(QEMUFile *f, void *pv, size_t size,
184 const VMStateField *field, JSONWriter *vmdesc)
185 {
186 QEMUTimer *v = pv;
187 timer_put(f, v);
188
189 return 0;
190 }
191
192 const VMStateInfo vmstate_info_timer = {
193 .name = "timer",
194 .get = get_timer,
195 .put = put_timer,
196 };
197
198
199 typedef struct CompatEntry {
200 char idstr[256];
201 int instance_id;
202 } CompatEntry;
203
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;
221
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;
233
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,
238 };
239
240 static bool should_validate_capability(int capability)
241 {
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;
249 }
250 }
251
252 static uint32_t get_validatable_capabilities_count(void)
253 {
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++;
260 }
261 }
262 return result;
263 }
264
265 static int configuration_pre_save(void *opaque)
266 {
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;
271
272 state->len = strlen(current_name);
273 state->name = current_name;
274 state->target_page_bits = qemu_target_page_bits();
275
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;
282 }
283 }
284 state->uuid = qemu_uuid;
285
286 return 0;
287 }
288
289 static int configuration_post_save(void *opaque)
290 {
291 SaveState *state = opaque;
292
293 g_free(state->capabilities);
294 state->capabilities = NULL;
295 state->caps_count = 0;
296 return 0;
297 }
298
299 static int configuration_pre_load(void *opaque)
300 {
301 SaveState *state = opaque;
302
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.
306 */
307 state->target_page_bits = qemu_target_page_bits_min();
308 return 0;
309 }
310
311 static bool configuration_validate_capabilities(SaveState *state)
312 {
313 bool ret = true;
314 MigrationState *s = migrate_get_current();
315 unsigned long *source_caps_bm;
316 int i;
317
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);
322 }
323
324 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
325 bool source_state, target_state;
326 if (!should_validate_capability(i)) {
327 continue;
328 }
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 */
338 }
339 }
340
341 g_free(source_caps_bm);
342 return ret;
343 }
344
345 static int configuration_post_load(void *opaque, int version_id)
346 {
347 SaveState *state = opaque;
348 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
349 int ret = 0;
350
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;
356 }
357
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;
363 }
364
365 if (!configuration_validate_capabilities(state)) {
366 ret = -EINVAL;
367 goto out;
368 }
369
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;
377
378 return ret;
379 }
380
381 static int get_capability(QEMUFile *f, void *pv, size_t size,
382 const VMStateField *field)
383 {
384 MigrationCapability *capability = pv;
385 char capability_str[UINT8_MAX + 1];
386 uint8_t len;
387 int i;
388
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;
396 }
397 }
398 error_report("Received unknown capability %s", capability_str);
399 return -EINVAL;
400 }
401
402 static int put_capability(QEMUFile *f, void *pv, size_t size,
403 const VMStateField *field, JSONWriter *vmdesc)
404 {
405 MigrationCapability *capability = pv;
406 const char *capability_str = MigrationCapability_str(*capability);
407 size_t len = strlen(capability_str);
408 assert(len <= UINT8_MAX);
409
410 qemu_put_byte(f, len);
411 qemu_put_buffer(f, (uint8_t *)capability_str, len);
412 return 0;
413 }
414
415 static const VMStateInfo vmstate_info_capability = {
416 .name = "capability",
417 .get = get_capability,
418 .put = put_capability,
419 };
420
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.
427 */
428 static bool vmstate_target_page_bits_needed(void *opaque)
429 {
430 return qemu_target_page_bits()
431 > qemu_target_page_bits_min();
432 }
433
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()
442 }
443 };
444
445 static bool vmstate_capabilites_needed(void *opaque)
446 {
447 return get_validatable_capabilities_count() > 0;
448 }
449
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()
461 }
462 };
463
464 static bool vmstate_uuid_needed(void *opaque)
465 {
466 return qemu_uuid_set && migrate_validate_uuid();
467 }
468
469 static int vmstate_uuid_post_load(void *opaque, int version_id)
470 {
471 SaveState *state = opaque;
472 char uuid_src[UUID_FMT_LEN + 1];
473 char uuid_dst[UUID_FMT_LEN + 1];
474
475 if (!qemu_uuid_set) {
476 /*
477 * It's warning because user might not know UUID in some cases,
478 * e.g. load an old snapshot
479 */
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;
484 }
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;
490 }
491 return 0;
492 }
493
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()
503 }
504 };
505
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()
517 },
518 .subsections = (const VMStateDescription *[]) {
519 &vmstate_target_page_bits,
520 &vmstate_capabilites,
521 &vmstate_uuid,
522 NULL
523 }
524 };
525
526 static void dump_vmstate_vmsd(FILE *out_file,
527 const VMStateDescription *vmsd, int indent,
528 bool is_subsection);
529
530 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
531 int indent)
532 {
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);
542 }
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);
547 }
548 fprintf(out_file, "\n%*s}", indent - 2, "");
549 }
550
551 static void dump_vmstate_vmss(FILE *out_file,
552 const VMStateDescription **subsection,
553 int indent)
554 {
555 if (*subsection != NULL) {
556 dump_vmstate_vmsd(out_file, *subsection, indent, true);
557 }
558 }
559
560 static void dump_vmstate_vmsd(FILE *out_file,
561 const VMStateDescription *vmsd, int indent,
562 bool is_subsection)
563 {
564 if (is_subsection) {
565 fprintf(out_file, "%*s{\n", indent, "");
566 } else {
567 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
568 }
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;
578
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;
586 }
587 if (!first) {
588 fprintf(out_file, ",\n");
589 }
590 dump_vmstate_vmsf(out_file, field, indent + 2);
591 field++;
592 first = false;
593 }
594 assert(field->flags == VMS_END);
595 fprintf(out_file, "\n%*s]", indent, "");
596 }
597 if (vmsd->subsections != NULL) {
598 const VMStateDescription **subsection = vmsd->subsections;
599 bool first;
600
601 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
602 first = true;
603 while (*subsection != NULL) {
604 if (!first) {
605 fprintf(out_file, ",\n");
606 }
607 dump_vmstate_vmss(out_file, subsection, indent + 2);
608 subsection++;
609 first = false;
610 }
611 fprintf(out_file, "\n%*s]", indent, "");
612 }
613 fprintf(out_file, "\n%*s}", indent - 2, "");
614 }
615
616 static void dump_machine_type(FILE *out_file)
617 {
618 MachineClass *mc;
619
620 mc = MACHINE_GET_CLASS(current_machine);
621
622 fprintf(out_file, " \"vmschkmachine\": {\n");
623 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
624 fprintf(out_file, " },\n");
625 }
626
627 void dump_vmstate_json_to_file(FILE *out_file)
628 {
629 GSList *list, *elt;
630 bool first;
631
632 fprintf(out_file, "{\n");
633 dump_machine_type(out_file);
634
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;
642
643 if (!dc->vmsd) {
644 continue;
645 }
646
647 if (!first) {
648 fprintf(out_file, ",\n");
649 }
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);
658
659 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
660
661 fprintf(out_file, "\n%*s}", indent - 2, "");
662 first = false;
663 }
664 fprintf(out_file, "\n}\n");
665 fclose(out_file);
666 g_slist_free(list);
667 }
668
669 static uint32_t calculate_new_instance_id(const char *idstr)
670 {
671 SaveStateEntry *se;
672 uint32_t instance_id = 0;
673
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;
678 }
679 }
680 /* Make sure we never loop over without being noticed */
681 assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
682 return instance_id;
683 }
684
685 static int calculate_compat_instance_id(const char *idstr)
686 {
687 SaveStateEntry *se;
688 int instance_id = 0;
689
690 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
691 if (!se->compat) {
692 continue;
693 }
694
695 if (strcmp(idstr, se->compat->idstr) == 0
696 && instance_id <= se->compat->instance_id) {
697 instance_id = se->compat->instance_id + 1;
698 }
699 }
700 return instance_id;
701 }
702
703 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
704 {
705 if (se->vmsd) {
706 return se->vmsd->priority;
707 }
708 return MIG_PRI_DEFAULT;
709 }
710
711 static void savevm_state_handler_insert(SaveStateEntry *nse)
712 {
713 MigrationPriority priority = save_state_priority(nse);
714 SaveStateEntry *se;
715 int i;
716
717 assert(priority <= MIG_PRI_MAX);
718
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;
724 }
725 }
726
727 if (i >= 0) {
728 QTAILQ_INSERT_BEFORE(se, nse, entry);
729 } else {
730 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
731 }
732
733 if (savevm_state.handler_pri_head[priority] == NULL) {
734 savevm_state.handler_pri_head[priority] = nse;
735 }
736 }
737
738 static void savevm_state_handler_remove(SaveStateEntry *se)
739 {
740 SaveStateEntry *next;
741 MigrationPriority priority = save_state_priority(se);
742
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;
749 }
750 }
751 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
752 }
753
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)
763 {
764 SaveStateEntry *se;
765
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;
775 }
776
777 pstrcat(se->idstr, sizeof(se->idstr), idstr);
778
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;
783 }
784 assert(!se->compat || se->instance_id == 0);
785 savevm_state_handler_insert(se);
786 return 0;
787 }
788
789 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
790 {
791 SaveStateEntry *se, *new_se;
792 char id[256] = "";
793
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);
800 }
801 }
802 pstrcat(id, sizeof(id), idstr);
803
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);
809 }
810 }
811 }
812
813 /*
814 * Perform some basic checks on vmsd's at registration
815 * time.
816 */
817 static void vmstate_check(const VMStateDescription *vmsd)
818 {
819 const VMStateField *field = vmsd->fields;
820 const VMStateDescription **subsection = vmsd->subsections;
821
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);
827 }
828 /* Carry on */
829 field++;
830 }
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();
835 }
836 }
837
838 while (subsection && *subsection) {
839 /*
840 * The name of a subsection should start with the name of the
841 * current object.
842 */
843 assert(!strncmp(vmsd->name, (*subsection)->name, strlen(vmsd->name)));
844 vmstate_check(*subsection);
845 subsection++;
846 }
847 }
848
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)
854 {
855 SaveStateEntry *se;
856
857 /* If this triggers, alias support can be dropped for the vmsd. */
858 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
859
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;
866
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);
875
876 return -1;
877 }
878 g_free(id);
879
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;
885 }
886 }
887 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
888
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;
893 }
894
895 /* Perform a recursive sanity check during the test runs */
896 if (qtest_enabled()) {
897 vmstate_check(vmsd);
898 }
899 assert(!se->compat || se->instance_id == 0);
900 savevm_state_handler_insert(se);
901 return 0;
902 }
903
904 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
905 void *opaque)
906 {
907 SaveStateEntry *se, *new_se;
908
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);
914 }
915 }
916 }
917
918 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
919 {
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);
923 }
924 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
925 }
926
927 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
928 JSONWriter *vmdesc)
929 {
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;
933
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);
943 }
944 }
945
946 /*
947 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
948 */
949 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
950 uint8_t section_type)
951 {
952 qemu_put_byte(f, section_type);
953 qemu_put_be32(f, se->section_id);
954
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);
961
962 qemu_put_be32(f, se->instance_id);
963 qemu_put_be32(f, se->version_id);
964 }
965 }
966
967 /*
968 * Write a footer onto device sections that catches cases misformatted device
969 * sections.
970 */
971 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
972 {
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);
976 }
977 }
978
979 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, JSONWriter *vmdesc)
980 {
981 int ret;
982
983 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
984 return 0;
985 }
986 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
987 trace_savevm_section_skip(se->idstr, se->section_id);
988 return 0;
989 }
990
991 trace_savevm_section_start(se->idstr, se->section_id);
992 save_section_header(f, se, QEMU_VM_SECTION_FULL);
993 if (vmdesc) {
994 json_writer_start_object(vmdesc, NULL);
995 json_writer_str(vmdesc, "name", se->idstr);
996 json_writer_int64(vmdesc, "instance_id", se->instance_id);
997 }
998
999 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
1000 if (!se->vmsd) {
1001 vmstate_save_old_style(f, se, vmdesc);
1002 } else {
1003 ret = vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
1004 if (ret) {
1005 return ret;
1006 }
1007 }
1008
1009 trace_savevm_section_end(se->idstr, se->section_id, 0);
1010 save_section_footer(f, se);
1011 if (vmdesc) {
1012 json_writer_end_object(vmdesc);
1013 }
1014 return 0;
1015 }
1016 /**
1017 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
1018 * command and associated data.
1019 *
1020 * @f: File to send command on
1021 * @command: Command type to send
1022 * @len: Length of associated data
1023 * @data: Data associated with command.
1024 */
1025 static void qemu_savevm_command_send(QEMUFile *f,
1026 enum qemu_vm_cmd command,
1027 uint16_t len,
1028 uint8_t *data)
1029 {
1030 trace_savevm_command_send(command, len);
1031 qemu_put_byte(f, QEMU_VM_COMMAND);
1032 qemu_put_be16(f, (uint16_t)command);
1033 qemu_put_be16(f, len);
1034 qemu_put_buffer(f, data, len);
1035 qemu_fflush(f);
1036 }
1037
1038 void qemu_savevm_send_colo_enable(QEMUFile *f)
1039 {
1040 trace_savevm_send_colo_enable();
1041 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
1042 }
1043
1044 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
1045 {
1046 uint32_t buf;
1047
1048 trace_savevm_send_ping(value);
1049 buf = cpu_to_be32(value);
1050 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
1051 }
1052
1053 void qemu_savevm_send_open_return_path(QEMUFile *f)
1054 {
1055 trace_savevm_send_open_return_path();
1056 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
1057 }
1058
1059 /* We have a buffer of data to send; we don't want that all to be loaded
1060 * by the command itself, so the command contains just the length of the
1061 * extra buffer that we then send straight after it.
1062 * TODO: Must be a better way to organise that
1063 *
1064 * Returns:
1065 * 0 on success
1066 * -ve on error
1067 */
1068 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
1069 {
1070 uint32_t tmp;
1071
1072 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1073 error_report("%s: Unreasonably large packaged state: %zu",
1074 __func__, len);
1075 return -1;
1076 }
1077
1078 tmp = cpu_to_be32(len);
1079
1080 trace_qemu_savevm_send_packaged();
1081 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1082
1083 qemu_put_buffer(f, buf, len);
1084
1085 return 0;
1086 }
1087
1088 /* Send prior to any postcopy transfer */
1089 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1090 {
1091 if (migrate_postcopy_ram()) {
1092 uint64_t tmp[2];
1093 tmp[0] = cpu_to_be64(ram_pagesize_summary());
1094 tmp[1] = cpu_to_be64(qemu_target_page_size());
1095
1096 trace_qemu_savevm_send_postcopy_advise();
1097 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1098 16, (uint8_t *)tmp);
1099 } else {
1100 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1101 }
1102 }
1103
1104 /* Sent prior to starting the destination running in postcopy, discard pages
1105 * that have already been sent but redirtied on the source.
1106 * CMD_POSTCOPY_RAM_DISCARD consist of:
1107 * byte version (0)
1108 * byte Length of name field (not including 0)
1109 * n x byte RAM block name
1110 * byte 0 terminator (just for safety)
1111 * n x Byte ranges within the named RAMBlock
1112 * be64 Start of the range
1113 * be64 Length
1114 *
1115 * name: RAMBlock name that these entries are part of
1116 * len: Number of page entries
1117 * start_list: 'len' addresses
1118 * length_list: 'len' addresses
1119 *
1120 */
1121 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1122 uint16_t len,
1123 uint64_t *start_list,
1124 uint64_t *length_list)
1125 {
1126 uint8_t *buf;
1127 uint16_t tmplen;
1128 uint16_t t;
1129 size_t name_len = strlen(name);
1130
1131 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1132 assert(name_len < 256);
1133 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1134 buf[0] = postcopy_ram_discard_version;
1135 buf[1] = name_len;
1136 memcpy(buf + 2, name, name_len);
1137 tmplen = 2 + name_len;
1138 buf[tmplen++] = '\0';
1139
1140 for (t = 0; t < len; t++) {
1141 stq_be_p(buf + tmplen, start_list[t]);
1142 tmplen += 8;
1143 stq_be_p(buf + tmplen, length_list[t]);
1144 tmplen += 8;
1145 }
1146 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1147 g_free(buf);
1148 }
1149
1150 /* Get the destination into a state where it can receive postcopy data. */
1151 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1152 {
1153 trace_savevm_send_postcopy_listen();
1154 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1155 }
1156
1157 /* Kick the destination into running */
1158 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1159 {
1160 trace_savevm_send_postcopy_run();
1161 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1162 }
1163
1164 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1165 {
1166 trace_savevm_send_postcopy_resume();
1167 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1168 }
1169
1170 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1171 {
1172 size_t len;
1173 char buf[256];
1174
1175 trace_savevm_send_recv_bitmap(block_name);
1176
1177 buf[0] = len = strlen(block_name);
1178 memcpy(buf + 1, block_name, len);
1179
1180 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1181 }
1182
1183 bool qemu_savevm_state_blocked(Error **errp)
1184 {
1185 SaveStateEntry *se;
1186
1187 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1188 if (se->vmsd && se->vmsd->unmigratable) {
1189 error_setg(errp, "State blocked by non-migratable device '%s'",
1190 se->idstr);
1191 return true;
1192 }
1193 }
1194 return false;
1195 }
1196
1197 void qemu_savevm_non_migratable_list(strList **reasons)
1198 {
1199 SaveStateEntry *se;
1200
1201 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1202 if (se->vmsd && se->vmsd->unmigratable) {
1203 QAPI_LIST_PREPEND(*reasons,
1204 g_strdup_printf("non-migratable device: %s",
1205 se->idstr));
1206 }
1207 }
1208 }
1209
1210 void qemu_savevm_state_header(QEMUFile *f)
1211 {
1212 trace_savevm_state_header();
1213 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1214 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1215
1216 if (migrate_get_current()->send_configuration) {
1217 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1218 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1219 }
1220 }
1221
1222 bool qemu_savevm_state_guest_unplug_pending(void)
1223 {
1224 SaveStateEntry *se;
1225
1226 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1227 if (se->vmsd && se->vmsd->dev_unplug_pending &&
1228 se->vmsd->dev_unplug_pending(se->opaque)) {
1229 return true;
1230 }
1231 }
1232
1233 return false;
1234 }
1235
1236 void qemu_savevm_state_setup(QEMUFile *f)
1237 {
1238 MigrationState *ms = migrate_get_current();
1239 SaveStateEntry *se;
1240 Error *local_err = NULL;
1241 int ret;
1242
1243 ms->vmdesc = json_writer_new(false);
1244 json_writer_start_object(ms->vmdesc, NULL);
1245 json_writer_int64(ms->vmdesc, "page_size", qemu_target_page_size());
1246 json_writer_start_array(ms->vmdesc, "devices");
1247
1248 trace_savevm_state_setup();
1249 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1250 if (se->vmsd && se->vmsd->early_setup) {
1251 ret = vmstate_save(f, se, ms->vmdesc);
1252 if (ret) {
1253 qemu_file_set_error(f, ret);
1254 break;
1255 }
1256 continue;
1257 }
1258
1259 if (!se->ops || !se->ops->save_setup) {
1260 continue;
1261 }
1262 if (se->ops->is_active) {
1263 if (!se->ops->is_active(se->opaque)) {
1264 continue;
1265 }
1266 }
1267 save_section_header(f, se, QEMU_VM_SECTION_START);
1268
1269 ret = se->ops->save_setup(f, se->opaque);
1270 save_section_footer(f, se);
1271 if (ret < 0) {
1272 qemu_file_set_error(f, ret);
1273 break;
1274 }
1275 }
1276
1277 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1278 error_report_err(local_err);
1279 }
1280 }
1281
1282 int qemu_savevm_state_resume_prepare(MigrationState *s)
1283 {
1284 SaveStateEntry *se;
1285 int ret;
1286
1287 trace_savevm_state_resume_prepare();
1288
1289 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1290 if (!se->ops || !se->ops->resume_prepare) {
1291 continue;
1292 }
1293 if (se->ops->is_active) {
1294 if (!se->ops->is_active(se->opaque)) {
1295 continue;
1296 }
1297 }
1298 ret = se->ops->resume_prepare(s, se->opaque);
1299 if (ret < 0) {
1300 return ret;
1301 }
1302 }
1303
1304 return 0;
1305 }
1306
1307 /*
1308 * this function has three return values:
1309 * negative: there was one error, and we have -errno.
1310 * 0 : We haven't finished, caller have to go again
1311 * 1 : We have finished, we can go to complete phase
1312 */
1313 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1314 {
1315 SaveStateEntry *se;
1316 int ret = 1;
1317
1318 trace_savevm_state_iterate();
1319 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1320 if (!se->ops || !se->ops->save_live_iterate) {
1321 continue;
1322 }
1323 if (se->ops->is_active &&
1324 !se->ops->is_active(se->opaque)) {
1325 continue;
1326 }
1327 if (se->ops->is_active_iterate &&
1328 !se->ops->is_active_iterate(se->opaque)) {
1329 continue;
1330 }
1331 /*
1332 * In the postcopy phase, any device that doesn't know how to
1333 * do postcopy should have saved it's state in the _complete
1334 * call that's already run, it might get confused if we call
1335 * iterate afterwards.
1336 */
1337 if (postcopy &&
1338 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1339 continue;
1340 }
1341 if (migration_rate_exceeded(f)) {
1342 return 0;
1343 }
1344 trace_savevm_section_start(se->idstr, se->section_id);
1345
1346 save_section_header(f, se, QEMU_VM_SECTION_PART);
1347
1348 ret = se->ops->save_live_iterate(f, se->opaque);
1349 trace_savevm_section_end(se->idstr, se->section_id, ret);
1350 save_section_footer(f, se);
1351
1352 if (ret < 0) {
1353 error_report("failed to save SaveStateEntry with id(name): "
1354 "%d(%s): %d",
1355 se->section_id, se->idstr, ret);
1356 qemu_file_set_error(f, ret);
1357 }
1358 if (ret <= 0) {
1359 /* Do not proceed to the next vmstate before this one reported
1360 completion of the current stage. This serializes the migration
1361 and reduces the probability that a faster changing state is
1362 synchronized over and over again. */
1363 break;
1364 }
1365 }
1366 return ret;
1367 }
1368
1369 static bool should_send_vmdesc(void)
1370 {
1371 MachineState *machine = MACHINE(qdev_get_machine());
1372 bool in_postcopy = migration_in_postcopy();
1373 return !machine->suppress_vmdesc && !in_postcopy;
1374 }
1375
1376 /*
1377 * Calls the save_live_complete_postcopy methods
1378 * causing the last few pages to be sent immediately and doing any associated
1379 * cleanup.
1380 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1381 * all the other devices, but that happens at the point we switch to postcopy.
1382 */
1383 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1384 {
1385 SaveStateEntry *se;
1386 int ret;
1387
1388 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1389 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1390 continue;
1391 }
1392 if (se->ops->is_active) {
1393 if (!se->ops->is_active(se->opaque)) {
1394 continue;
1395 }
1396 }
1397 trace_savevm_section_start(se->idstr, se->section_id);
1398 /* Section type */
1399 qemu_put_byte(f, QEMU_VM_SECTION_END);
1400 qemu_put_be32(f, se->section_id);
1401
1402 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1403 trace_savevm_section_end(se->idstr, se->section_id, ret);
1404 save_section_footer(f, se);
1405 if (ret < 0) {
1406 qemu_file_set_error(f, ret);
1407 return;
1408 }
1409 }
1410
1411 qemu_put_byte(f, QEMU_VM_EOF);
1412 qemu_fflush(f);
1413 }
1414
1415 static
1416 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1417 {
1418 SaveStateEntry *se;
1419 int ret;
1420
1421 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1422 if (!se->ops ||
1423 (in_postcopy && se->ops->has_postcopy &&
1424 se->ops->has_postcopy(se->opaque)) ||
1425 !se->ops->save_live_complete_precopy) {
1426 continue;
1427 }
1428
1429 if (se->ops->is_active) {
1430 if (!se->ops->is_active(se->opaque)) {
1431 continue;
1432 }
1433 }
1434 trace_savevm_section_start(se->idstr, se->section_id);
1435
1436 save_section_header(f, se, QEMU_VM_SECTION_END);
1437
1438 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1439 trace_savevm_section_end(se->idstr, se->section_id, ret);
1440 save_section_footer(f, se);
1441 if (ret < 0) {
1442 qemu_file_set_error(f, ret);
1443 return -1;
1444 }
1445 }
1446
1447 return 0;
1448 }
1449
1450 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1451 bool in_postcopy,
1452 bool inactivate_disks)
1453 {
1454 MigrationState *ms = migrate_get_current();
1455 JSONWriter *vmdesc = ms->vmdesc;
1456 int vmdesc_len;
1457 SaveStateEntry *se;
1458 int ret;
1459
1460 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1461 if (se->vmsd && se->vmsd->early_setup) {
1462 /* Already saved during qemu_savevm_state_setup(). */
1463 continue;
1464 }
1465
1466 ret = vmstate_save(f, se, vmdesc);
1467 if (ret) {
1468 qemu_file_set_error(f, ret);
1469 return ret;
1470 }
1471 }
1472
1473 if (inactivate_disks) {
1474 /* Inactivate before sending QEMU_VM_EOF so that the
1475 * bdrv_activate_all() on the other end won't fail. */
1476 ret = bdrv_inactivate_all();
1477 if (ret) {
1478 error_report("%s: bdrv_inactivate_all() failed (%d)",
1479 __func__, ret);
1480 qemu_file_set_error(f, ret);
1481 return ret;
1482 }
1483 }
1484 if (!in_postcopy) {
1485 /* Postcopy stream will still be going */
1486 qemu_put_byte(f, QEMU_VM_EOF);
1487 }
1488
1489 json_writer_end_array(vmdesc);
1490 json_writer_end_object(vmdesc);
1491 vmdesc_len = strlen(json_writer_get(vmdesc));
1492
1493 if (should_send_vmdesc()) {
1494 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1495 qemu_put_be32(f, vmdesc_len);
1496 qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1497 }
1498
1499 /* Free it now to detect any inconsistencies. */
1500 json_writer_free(vmdesc);
1501 ms->vmdesc = NULL;
1502
1503 return 0;
1504 }
1505
1506 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1507 bool inactivate_disks)
1508 {
1509 int ret;
1510 Error *local_err = NULL;
1511 bool in_postcopy = migration_in_postcopy();
1512
1513 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1514 error_report_err(local_err);
1515 }
1516
1517 trace_savevm_state_complete_precopy();
1518
1519 cpu_synchronize_all_states();
1520
1521 if (!in_postcopy || iterable_only) {
1522 ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1523 if (ret) {
1524 return ret;
1525 }
1526 }
1527
1528 if (iterable_only) {
1529 goto flush;
1530 }
1531
1532 ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1533 inactivate_disks);
1534 if (ret) {
1535 return ret;
1536 }
1537
1538 flush:
1539 qemu_fflush(f);
1540 return 0;
1541 }
1542
1543 /* Give an estimate of the amount left to be transferred,
1544 * the result is split into the amount for units that can and
1545 * for units that can't do postcopy.
1546 */
1547 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1548 uint64_t *can_postcopy)
1549 {
1550 SaveStateEntry *se;
1551
1552 *must_precopy = 0;
1553 *can_postcopy = 0;
1554
1555 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1556 if (!se->ops || !se->ops->state_pending_estimate) {
1557 continue;
1558 }
1559 if (se->ops->is_active) {
1560 if (!se->ops->is_active(se->opaque)) {
1561 continue;
1562 }
1563 }
1564 se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1565 }
1566 }
1567
1568 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1569 uint64_t *can_postcopy)
1570 {
1571 SaveStateEntry *se;
1572
1573 *must_precopy = 0;
1574 *can_postcopy = 0;
1575
1576 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1577 if (!se->ops || !se->ops->state_pending_exact) {
1578 continue;
1579 }
1580 if (se->ops->is_active) {
1581 if (!se->ops->is_active(se->opaque)) {
1582 continue;
1583 }
1584 }
1585 se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1586 }
1587 }
1588
1589 void qemu_savevm_state_cleanup(void)
1590 {
1591 SaveStateEntry *se;
1592 Error *local_err = NULL;
1593
1594 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1595 error_report_err(local_err);
1596 }
1597
1598 trace_savevm_state_cleanup();
1599 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1600 if (se->ops && se->ops->save_cleanup) {
1601 se->ops->save_cleanup(se->opaque);
1602 }
1603 }
1604 }
1605
1606 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1607 {
1608 int ret;
1609 MigrationState *ms = migrate_get_current();
1610 MigrationStatus status;
1611
1612 if (migration_is_running(ms->state)) {
1613 error_setg(errp, QERR_MIGRATION_ACTIVE);
1614 return -EINVAL;
1615 }
1616
1617 if (migrate_block()) {
1618 error_setg(errp, "Block migration and snapshots are incompatible");
1619 return -EINVAL;
1620 }
1621
1622 migrate_init(ms);
1623 ms->to_dst_file = f;
1624
1625 qemu_mutex_unlock_iothread();
1626 qemu_savevm_state_header(f);
1627 qemu_savevm_state_setup(f);
1628 qemu_mutex_lock_iothread();
1629
1630 while (qemu_file_get_error(f) == 0) {
1631 if (qemu_savevm_state_iterate(f, false) > 0) {
1632 break;
1633 }
1634 }
1635
1636 ret = qemu_file_get_error(f);
1637 if (ret == 0) {
1638 qemu_savevm_state_complete_precopy(f, false, false);
1639 ret = qemu_file_get_error(f);
1640 }
1641 qemu_savevm_state_cleanup();
1642 if (ret != 0) {
1643 error_setg_errno(errp, -ret, "Error while writing VM state");
1644 }
1645
1646 if (ret != 0) {
1647 status = MIGRATION_STATUS_FAILED;
1648 } else {
1649 status = MIGRATION_STATUS_COMPLETED;
1650 }
1651 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1652
1653 /* f is outer parameter, it should not stay in global migration state after
1654 * this function finished */
1655 ms->to_dst_file = NULL;
1656
1657 return ret;
1658 }
1659
1660 void qemu_savevm_live_state(QEMUFile *f)
1661 {
1662 /* save QEMU_VM_SECTION_END section */
1663 qemu_savevm_state_complete_precopy(f, true, false);
1664 qemu_put_byte(f, QEMU_VM_EOF);
1665 }
1666
1667 int qemu_save_device_state(QEMUFile *f)
1668 {
1669 SaveStateEntry *se;
1670
1671 if (!migration_in_colo_state()) {
1672 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1673 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1674 }
1675 cpu_synchronize_all_states();
1676
1677 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1678 int ret;
1679
1680 if (se->is_ram) {
1681 continue;
1682 }
1683 ret = vmstate_save(f, se, NULL);
1684 if (ret) {
1685 return ret;
1686 }
1687 }
1688
1689 qemu_put_byte(f, QEMU_VM_EOF);
1690
1691 return qemu_file_get_error(f);
1692 }
1693
1694 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1695 {
1696 SaveStateEntry *se;
1697
1698 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1699 if (!strcmp(se->idstr, idstr) &&
1700 (instance_id == se->instance_id ||
1701 instance_id == se->alias_id))
1702 return se;
1703 /* Migrating from an older version? */
1704 if (strstr(se->idstr, idstr) && se->compat) {
1705 if (!strcmp(se->compat->idstr, idstr) &&
1706 (instance_id == se->compat->instance_id ||
1707 instance_id == se->alias_id))
1708 return se;
1709 }
1710 }
1711 return NULL;
1712 }
1713
1714 enum LoadVMExitCodes {
1715 /* Allow a command to quit all layers of nested loadvm loops */
1716 LOADVM_QUIT = 1,
1717 };
1718
1719 /* ------ incoming postcopy messages ------ */
1720 /* 'advise' arrives before any transfers just to tell us that a postcopy
1721 * *might* happen - it might be skipped if precopy transferred everything
1722 * quickly.
1723 */
1724 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1725 uint16_t len)
1726 {
1727 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1728 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1729 size_t page_size = qemu_target_page_size();
1730 Error *local_err = NULL;
1731
1732 trace_loadvm_postcopy_handle_advise();
1733 if (ps != POSTCOPY_INCOMING_NONE) {
1734 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1735 return -1;
1736 }
1737
1738 switch (len) {
1739 case 0:
1740 if (migrate_postcopy_ram()) {
1741 error_report("RAM postcopy is enabled but have 0 byte advise");
1742 return -EINVAL;
1743 }
1744 return 0;
1745 case 8 + 8:
1746 if (!migrate_postcopy_ram()) {
1747 error_report("RAM postcopy is disabled but have 16 byte advise");
1748 return -EINVAL;
1749 }
1750 break;
1751 default:
1752 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1753 return -EINVAL;
1754 }
1755
1756 if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1757 error_report_err(local_err);
1758 postcopy_state_set(POSTCOPY_INCOMING_NONE);
1759 return -1;
1760 }
1761
1762 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1763 local_pagesize_summary = ram_pagesize_summary();
1764
1765 if (remote_pagesize_summary != local_pagesize_summary) {
1766 /*
1767 * This detects two potential causes of mismatch:
1768 * a) A mismatch in host page sizes
1769 * Some combinations of mismatch are probably possible but it gets
1770 * a bit more complicated. In particular we need to place whole
1771 * host pages on the dest at once, and we need to ensure that we
1772 * handle dirtying to make sure we never end up sending part of
1773 * a hostpage on it's own.
1774 * b) The use of different huge page sizes on source/destination
1775 * a more fine grain test is performed during RAM block migration
1776 * but this test here causes a nice early clear failure, and
1777 * also fails when passed to an older qemu that doesn't
1778 * do huge pages.
1779 */
1780 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1781 " d=%" PRIx64 ")",
1782 remote_pagesize_summary, local_pagesize_summary);
1783 return -1;
1784 }
1785
1786 remote_tps = qemu_get_be64(mis->from_src_file);
1787 if (remote_tps != page_size) {
1788 /*
1789 * Again, some differences could be dealt with, but for now keep it
1790 * simple.
1791 */
1792 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1793 (int)remote_tps, page_size);
1794 return -1;
1795 }
1796
1797 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1798 error_report_err(local_err);
1799 return -1;
1800 }
1801
1802 if (ram_postcopy_incoming_init(mis)) {
1803 return -1;
1804 }
1805
1806 return 0;
1807 }
1808
1809 /* After postcopy we will be told to throw some pages away since they're
1810 * dirty and will have to be demand fetched. Must happen before CPU is
1811 * started.
1812 * There can be 0..many of these messages, each encoding multiple pages.
1813 */
1814 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1815 uint16_t len)
1816 {
1817 int tmp;
1818 char ramid[256];
1819 PostcopyState ps = postcopy_state_get();
1820
1821 trace_loadvm_postcopy_ram_handle_discard();
1822
1823 switch (ps) {
1824 case POSTCOPY_INCOMING_ADVISE:
1825 /* 1st discard */
1826 tmp = postcopy_ram_prepare_discard(mis);
1827 if (tmp) {
1828 return tmp;
1829 }
1830 break;
1831
1832 case POSTCOPY_INCOMING_DISCARD:
1833 /* Expected state */
1834 break;
1835
1836 default:
1837 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1838 ps);
1839 return -1;
1840 }
1841 /* We're expecting a
1842 * Version (0)
1843 * a RAM ID string (length byte, name, 0 term)
1844 * then at least 1 16 byte chunk
1845 */
1846 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1847 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1848 return -1;
1849 }
1850
1851 tmp = qemu_get_byte(mis->from_src_file);
1852 if (tmp != postcopy_ram_discard_version) {
1853 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1854 return -1;
1855 }
1856
1857 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1858 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1859 return -1;
1860 }
1861 tmp = qemu_get_byte(mis->from_src_file);
1862 if (tmp != 0) {
1863 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1864 return -1;
1865 }
1866
1867 len -= 3 + strlen(ramid);
1868 if (len % 16) {
1869 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1870 return -1;
1871 }
1872 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1873 while (len) {
1874 uint64_t start_addr, block_length;
1875 start_addr = qemu_get_be64(mis->from_src_file);
1876 block_length = qemu_get_be64(mis->from_src_file);
1877
1878 len -= 16;
1879 int ret = ram_discard_range(ramid, start_addr, block_length);
1880 if (ret) {
1881 return ret;
1882 }
1883 }
1884 trace_loadvm_postcopy_ram_handle_discard_end();
1885
1886 return 0;
1887 }
1888
1889 /*
1890 * Triggered by a postcopy_listen command; this thread takes over reading
1891 * the input stream, leaving the main thread free to carry on loading the rest
1892 * of the device state (from RAM).
1893 * (TODO:This could do with being in a postcopy file - but there again it's
1894 * just another input loop, not that postcopy specific)
1895 */
1896 static void *postcopy_ram_listen_thread(void *opaque)
1897 {
1898 MigrationIncomingState *mis = migration_incoming_get_current();
1899 QEMUFile *f = mis->from_src_file;
1900 int load_res;
1901 MigrationState *migr = migrate_get_current();
1902
1903 object_ref(OBJECT(migr));
1904
1905 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1906 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1907 qemu_sem_post(&mis->thread_sync_sem);
1908 trace_postcopy_ram_listen_thread_start();
1909
1910 rcu_register_thread();
1911 /*
1912 * Because we're a thread and not a coroutine we can't yield
1913 * in qemu_file, and thus we must be blocking now.
1914 */
1915 qemu_file_set_blocking(f, true);
1916 load_res = qemu_loadvm_state_main(f, mis);
1917
1918 /*
1919 * This is tricky, but, mis->from_src_file can change after it
1920 * returns, when postcopy recovery happened. In the future, we may
1921 * want a wrapper for the QEMUFile handle.
1922 */
1923 f = mis->from_src_file;
1924
1925 /* And non-blocking again so we don't block in any cleanup */
1926 qemu_file_set_blocking(f, false);
1927
1928 trace_postcopy_ram_listen_thread_exit();
1929 if (load_res < 0) {
1930 qemu_file_set_error(f, load_res);
1931 dirty_bitmap_mig_cancel_incoming();
1932 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
1933 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1934 {
1935 error_report("%s: loadvm failed during postcopy: %d. All states "
1936 "are migrated except dirty bitmaps. Some dirty "
1937 "bitmaps may be lost, and present migrated dirty "
1938 "bitmaps are correctly migrated and valid.",
1939 __func__, load_res);
1940 load_res = 0; /* prevent further exit() */
1941 } else {
1942 error_report("%s: loadvm failed: %d", __func__, load_res);
1943 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1944 MIGRATION_STATUS_FAILED);
1945 }
1946 }
1947 if (load_res >= 0) {
1948 /*
1949 * This looks good, but it's possible that the device loading in the
1950 * main thread hasn't finished yet, and so we might not be in 'RUN'
1951 * state yet; wait for the end of the main thread.
1952 */
1953 qemu_event_wait(&mis->main_thread_load_event);
1954 }
1955 postcopy_ram_incoming_cleanup(mis);
1956
1957 if (load_res < 0) {
1958 /*
1959 * If something went wrong then we have a bad state so exit;
1960 * depending how far we got it might be possible at this point
1961 * to leave the guest running and fire MCEs for pages that never
1962 * arrived as a desperate recovery step.
1963 */
1964 rcu_unregister_thread();
1965 exit(EXIT_FAILURE);
1966 }
1967
1968 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1969 MIGRATION_STATUS_COMPLETED);
1970 /*
1971 * If everything has worked fine, then the main thread has waited
1972 * for us to start, and we're the last use of the mis.
1973 * (If something broke then qemu will have to exit anyway since it's
1974 * got a bad migration state).
1975 */
1976 migration_incoming_state_destroy();
1977 qemu_loadvm_state_cleanup();
1978
1979 rcu_unregister_thread();
1980 mis->have_listen_thread = false;
1981 postcopy_state_set(POSTCOPY_INCOMING_END);
1982
1983 object_unref(OBJECT(migr));
1984
1985 return NULL;
1986 }
1987
1988 /* After this message we must be able to immediately receive postcopy data */
1989 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1990 {
1991 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1992 Error *local_err = NULL;
1993
1994 trace_loadvm_postcopy_handle_listen("enter");
1995
1996 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1997 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1998 return -1;
1999 }
2000 if (ps == POSTCOPY_INCOMING_ADVISE) {
2001 /*
2002 * A rare case, we entered listen without having to do any discards,
2003 * so do the setup that's normally done at the time of the 1st discard.
2004 */
2005 if (migrate_postcopy_ram()) {
2006 postcopy_ram_prepare_discard(mis);
2007 }
2008 }
2009
2010 trace_loadvm_postcopy_handle_listen("after discard");
2011
2012 /*
2013 * Sensitise RAM - can now generate requests for blocks that don't exist
2014 * However, at this point the CPU shouldn't be running, and the IO
2015 * shouldn't be doing anything yet so don't actually expect requests
2016 */
2017 if (migrate_postcopy_ram()) {
2018 if (postcopy_ram_incoming_setup(mis)) {
2019 postcopy_ram_incoming_cleanup(mis);
2020 return -1;
2021 }
2022 }
2023
2024 trace_loadvm_postcopy_handle_listen("after uffd");
2025
2026 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2027 error_report_err(local_err);
2028 return -1;
2029 }
2030
2031 mis->have_listen_thread = true;
2032 postcopy_thread_create(mis, &mis->listen_thread, "postcopy/listen",
2033 postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2034 trace_loadvm_postcopy_handle_listen("return");
2035
2036 return 0;
2037 }
2038
2039 static void loadvm_postcopy_handle_run_bh(void *opaque)
2040 {
2041 Error *local_err = NULL;
2042 MigrationIncomingState *mis = opaque;
2043
2044 trace_loadvm_postcopy_handle_run_bh("enter");
2045
2046 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2047 * in migration.c
2048 */
2049 cpu_synchronize_all_post_init();
2050
2051 trace_loadvm_postcopy_handle_run_bh("after cpu sync");
2052
2053 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2054
2055 trace_loadvm_postcopy_handle_run_bh("after announce");
2056
2057 /* Make sure all file formats throw away their mutable metadata.
2058 * If we get an error here, just don't restart the VM yet. */
2059 bdrv_activate_all(&local_err);
2060 if (local_err) {
2061 error_report_err(local_err);
2062 local_err = NULL;
2063 autostart = false;
2064 }
2065
2066 trace_loadvm_postcopy_handle_run_bh("after invalidate cache");
2067
2068 dirty_bitmap_mig_before_vm_start();
2069
2070 if (autostart) {
2071 /* Hold onto your hats, starting the CPU */
2072 vm_start();
2073 } else {
2074 /* leave it paused and let management decide when to start the CPU */
2075 runstate_set(RUN_STATE_PAUSED);
2076 }
2077
2078 qemu_bh_delete(mis->bh);
2079
2080 trace_loadvm_postcopy_handle_run_bh("return");
2081 }
2082
2083 /* After all discards we can start running and asking for pages */
2084 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2085 {
2086 PostcopyState ps = postcopy_state_get();
2087
2088 trace_loadvm_postcopy_handle_run();
2089 if (ps != POSTCOPY_INCOMING_LISTENING) {
2090 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2091 return -1;
2092 }
2093
2094 postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2095 mis->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, mis);
2096 qemu_bh_schedule(mis->bh);
2097
2098 /* We need to finish reading the stream from the package
2099 * and also stop reading anything more from the stream that loaded the
2100 * package (since it's now being read by the listener thread).
2101 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2102 */
2103 return LOADVM_QUIT;
2104 }
2105
2106 /* We must be with page_request_mutex held */
2107 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2108 gpointer data)
2109 {
2110 MigrationIncomingState *mis = data;
2111 void *host_addr = (void *) key;
2112 ram_addr_t rb_offset;
2113 RAMBlock *rb;
2114 int ret;
2115
2116 rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2117 if (!rb) {
2118 /*
2119 * This should _never_ happen. However be nice for a migrating VM to
2120 * not crash/assert. Post an error (note: intended to not use *_once
2121 * because we do want to see all the illegal addresses; and this can
2122 * never be triggered by the guest so we're safe) and move on next.
2123 */
2124 error_report("%s: illegal host addr %p", __func__, host_addr);
2125 /* Try the next entry */
2126 return FALSE;
2127 }
2128
2129 ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2130 if (ret) {
2131 /* Please refer to above comment. */
2132 error_report("%s: send rp message failed for addr %p",
2133 __func__, host_addr);
2134 return FALSE;
2135 }
2136
2137 trace_postcopy_page_req_sync(host_addr);
2138
2139 return FALSE;
2140 }
2141
2142 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2143 {
2144 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2145 g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2146 }
2147 }
2148
2149 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2150 {
2151 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2152 error_report("%s: illegal resume received", __func__);
2153 /* Don't fail the load, only for this. */
2154 return 0;
2155 }
2156
2157 /*
2158 * Reset the last_rb before we resend any page req to source again, since
2159 * the source should have it reset already.
2160 */
2161 mis->last_rb = NULL;
2162
2163 /*
2164 * This means source VM is ready to resume the postcopy migration.
2165 */
2166 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2167 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2168
2169 trace_loadvm_postcopy_handle_resume();
2170
2171 /* Tell source that "we are ready" */
2172 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2173
2174 /*
2175 * After a postcopy recovery, the source should have lost the postcopy
2176 * queue, or potentially the requested pages could have been lost during
2177 * the network down phase. Let's re-sync with the source VM by re-sending
2178 * all the pending pages that we eagerly need, so these threads won't get
2179 * blocked too long due to the recovery.
2180 *
2181 * Without this procedure, the faulted destination VM threads (waiting for
2182 * page requests right before the postcopy is interrupted) can keep hanging
2183 * until the pages are sent by the source during the background copying of
2184 * pages, or another thread faulted on the same address accidentally.
2185 */
2186 migrate_send_rp_req_pages_pending(mis);
2187
2188 /*
2189 * It's time to switch state and release the fault thread to continue
2190 * service page faults. Note that this should be explicitly after the
2191 * above call to migrate_send_rp_req_pages_pending(). In short:
2192 * migrate_send_rp_message_req_pages() is not thread safe, yet.
2193 */
2194 qemu_sem_post(&mis->postcopy_pause_sem_fault);
2195
2196 if (migrate_postcopy_preempt()) {
2197 /*
2198 * The preempt channel will be created in async manner, now let's
2199 * wait for it and make sure it's created.
2200 */
2201 qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2202 assert(mis->postcopy_qemufile_dst);
2203 /* Kick the fast ram load thread too */
2204 qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2205 }
2206
2207 return 0;
2208 }
2209
2210 /**
2211 * Immediately following this command is a blob of data containing an embedded
2212 * chunk of migration stream; read it and load it.
2213 *
2214 * @mis: Incoming state
2215 * @length: Length of packaged data to read
2216 *
2217 * Returns: Negative values on error
2218 *
2219 */
2220 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2221 {
2222 int ret;
2223 size_t length;
2224 QIOChannelBuffer *bioc;
2225
2226 length = qemu_get_be32(mis->from_src_file);
2227 trace_loadvm_handle_cmd_packaged(length);
2228
2229 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2230 error_report("Unreasonably large packaged state: %zu", length);
2231 return -1;
2232 }
2233
2234 bioc = qio_channel_buffer_new(length);
2235 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2236 ret = qemu_get_buffer(mis->from_src_file,
2237 bioc->data,
2238 length);
2239 if (ret != length) {
2240 object_unref(OBJECT(bioc));
2241 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2242 ret, length);
2243 return (ret < 0) ? ret : -EAGAIN;
2244 }
2245 bioc->usage += length;
2246 trace_loadvm_handle_cmd_packaged_received(ret);
2247
2248 QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2249
2250 ret = qemu_loadvm_state_main(packf, mis);
2251 trace_loadvm_handle_cmd_packaged_main(ret);
2252 qemu_fclose(packf);
2253 object_unref(OBJECT(bioc));
2254
2255 return ret;
2256 }
2257
2258 /*
2259 * Handle request that source requests for recved_bitmap on
2260 * destination. Payload format:
2261 *
2262 * len (1 byte) + ramblock_name (<255 bytes)
2263 */
2264 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2265 uint16_t len)
2266 {
2267 QEMUFile *file = mis->from_src_file;
2268 RAMBlock *rb;
2269 char block_name[256];
2270 size_t cnt;
2271
2272 cnt = qemu_get_counted_string(file, block_name);
2273 if (!cnt) {
2274 error_report("%s: failed to read block name", __func__);
2275 return -EINVAL;
2276 }
2277
2278 /* Validate before using the data */
2279 if (qemu_file_get_error(file)) {
2280 return qemu_file_get_error(file);
2281 }
2282
2283 if (len != cnt + 1) {
2284 error_report("%s: invalid payload length (%d)", __func__, len);
2285 return -EINVAL;
2286 }
2287
2288 rb = qemu_ram_block_by_name(block_name);
2289 if (!rb) {
2290 error_report("%s: block '%s' not found", __func__, block_name);
2291 return -EINVAL;
2292 }
2293
2294 migrate_send_rp_recv_bitmap(mis, block_name);
2295
2296 trace_loadvm_handle_recv_bitmap(block_name);
2297
2298 return 0;
2299 }
2300
2301 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2302 {
2303 int ret = migration_incoming_enable_colo();
2304
2305 if (!ret) {
2306 ret = colo_init_ram_cache();
2307 if (ret) {
2308 migration_incoming_disable_colo();
2309 }
2310 }
2311 return ret;
2312 }
2313
2314 /*
2315 * Process an incoming 'QEMU_VM_COMMAND'
2316 * 0 just a normal return
2317 * LOADVM_QUIT All good, but exit the loop
2318 * <0 Error
2319 */
2320 static int loadvm_process_command(QEMUFile *f)
2321 {
2322 MigrationIncomingState *mis = migration_incoming_get_current();
2323 uint16_t cmd;
2324 uint16_t len;
2325 uint32_t tmp32;
2326
2327 cmd = qemu_get_be16(f);
2328 len = qemu_get_be16(f);
2329
2330 /* Check validity before continue processing of cmds */
2331 if (qemu_file_get_error(f)) {
2332 return qemu_file_get_error(f);
2333 }
2334
2335 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2336 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2337 return -EINVAL;
2338 }
2339
2340 trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2341
2342 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2343 error_report("%s received with bad length - expecting %zu, got %d",
2344 mig_cmd_args[cmd].name,
2345 (size_t)mig_cmd_args[cmd].len, len);
2346 return -ERANGE;
2347 }
2348
2349 switch (cmd) {
2350 case MIG_CMD_OPEN_RETURN_PATH:
2351 if (mis->to_src_file) {
2352 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2353 /* Not really a problem, so don't give up */
2354 return 0;
2355 }
2356 mis->to_src_file = qemu_file_get_return_path(f);
2357 if (!mis->to_src_file) {
2358 error_report("CMD_OPEN_RETURN_PATH failed");
2359 return -1;
2360 }
2361
2362 /*
2363 * Switchover ack is enabled but no device uses it, so send an ACK to
2364 * source that it's OK to switchover. Do it here, after return path has
2365 * been created.
2366 */
2367 if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2368 int ret = migrate_send_rp_switchover_ack(mis);
2369 if (ret) {
2370 error_report(
2371 "Could not send switchover ack RP MSG, err %d (%s)", ret,
2372 strerror(-ret));
2373 return ret;
2374 }
2375 }
2376 break;
2377
2378 case MIG_CMD_PING:
2379 tmp32 = qemu_get_be32(f);
2380 trace_loadvm_process_command_ping(tmp32);
2381 if (!mis->to_src_file) {
2382 error_report("CMD_PING (0x%x) received with no return path",
2383 tmp32);
2384 return -1;
2385 }
2386 migrate_send_rp_pong(mis, tmp32);
2387 break;
2388
2389 case MIG_CMD_PACKAGED:
2390 return loadvm_handle_cmd_packaged(mis);
2391
2392 case MIG_CMD_POSTCOPY_ADVISE:
2393 return loadvm_postcopy_handle_advise(mis, len);
2394
2395 case MIG_CMD_POSTCOPY_LISTEN:
2396 return loadvm_postcopy_handle_listen(mis);
2397
2398 case MIG_CMD_POSTCOPY_RUN:
2399 return loadvm_postcopy_handle_run(mis);
2400
2401 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2402 return loadvm_postcopy_ram_handle_discard(mis, len);
2403
2404 case MIG_CMD_POSTCOPY_RESUME:
2405 return loadvm_postcopy_handle_resume(mis);
2406
2407 case MIG_CMD_RECV_BITMAP:
2408 return loadvm_handle_recv_bitmap(mis, len);
2409
2410 case MIG_CMD_ENABLE_COLO:
2411 return loadvm_process_enable_colo(mis);
2412 }
2413
2414 return 0;
2415 }
2416
2417 /*
2418 * Read a footer off the wire and check that it matches the expected section
2419 *
2420 * Returns: true if the footer was good
2421 * false if there is a problem (and calls error_report to say why)
2422 */
2423 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2424 {
2425 int ret;
2426 uint8_t read_mark;
2427 uint32_t read_section_id;
2428
2429 if (!migrate_get_current()->send_section_footer) {
2430 /* No footer to check */
2431 return true;
2432 }
2433
2434 read_mark = qemu_get_byte(f);
2435
2436 ret = qemu_file_get_error(f);
2437 if (ret) {
2438 error_report("%s: Read section footer failed: %d",
2439 __func__, ret);
2440 return false;
2441 }
2442
2443 if (read_mark != QEMU_VM_SECTION_FOOTER) {
2444 error_report("Missing section footer for %s", se->idstr);
2445 return false;
2446 }
2447
2448 read_section_id = qemu_get_be32(f);
2449 if (read_section_id != se->load_section_id) {
2450 error_report("Mismatched section id in footer for %s -"
2451 " read 0x%x expected 0x%x",
2452 se->idstr, read_section_id, se->load_section_id);
2453 return false;
2454 }
2455
2456 /* All good */
2457 return true;
2458 }
2459
2460 static int
2461 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2462 {
2463 uint32_t instance_id, version_id, section_id;
2464 SaveStateEntry *se;
2465 char idstr[256];
2466 int ret;
2467
2468 /* Read section start */
2469 section_id = qemu_get_be32(f);
2470 if (!qemu_get_counted_string(f, idstr)) {
2471 error_report("Unable to read ID string for section %u",
2472 section_id);
2473 return -EINVAL;
2474 }
2475 instance_id = qemu_get_be32(f);
2476 version_id = qemu_get_be32(f);
2477
2478 ret = qemu_file_get_error(f);
2479 if (ret) {
2480 error_report("%s: Failed to read instance/version ID: %d",
2481 __func__, ret);
2482 return ret;
2483 }
2484
2485 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2486 instance_id, version_id);
2487 /* Find savevm section */
2488 se = find_se(idstr, instance_id);
2489 if (se == NULL) {
2490 error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2491 "Make sure that your current VM setup matches your "
2492 "saved VM setup, including any hotplugged devices",
2493 idstr, instance_id);
2494 return -EINVAL;
2495 }
2496
2497 /* Validate version */
2498 if (version_id > se->version_id) {
2499 error_report("savevm: unsupported version %d for '%s' v%d",
2500 version_id, idstr, se->version_id);
2501 return -EINVAL;
2502 }
2503 se->load_version_id = version_id;
2504 se->load_section_id = section_id;
2505
2506 /* Validate if it is a device's state */
2507 if (xen_enabled() && se->is_ram) {
2508 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2509 return -EINVAL;
2510 }
2511
2512 ret = vmstate_load(f, se);
2513 if (ret < 0) {
2514 error_report("error while loading state for instance 0x%"PRIx32" of"
2515 " device '%s'", instance_id, idstr);
2516 return ret;
2517 }
2518 if (!check_section_footer(f, se)) {
2519 return -EINVAL;
2520 }
2521
2522 return 0;
2523 }
2524
2525 static int
2526 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2527 {
2528 uint32_t section_id;
2529 SaveStateEntry *se;
2530 int ret;
2531
2532 section_id = qemu_get_be32(f);
2533
2534 ret = qemu_file_get_error(f);
2535 if (ret) {
2536 error_report("%s: Failed to read section ID: %d",
2537 __func__, ret);
2538 return ret;
2539 }
2540
2541 trace_qemu_loadvm_state_section_partend(section_id);
2542 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2543 if (se->load_section_id == section_id) {
2544 break;
2545 }
2546 }
2547 if (se == NULL) {
2548 error_report("Unknown savevm section %d", section_id);
2549 return -EINVAL;
2550 }
2551
2552 ret = vmstate_load(f, se);
2553 if (ret < 0) {
2554 error_report("error while loading state section id %d(%s)",
2555 section_id, se->idstr);
2556 return ret;
2557 }
2558 if (!check_section_footer(f, se)) {
2559 return -EINVAL;
2560 }
2561
2562 return 0;
2563 }
2564
2565 static int qemu_loadvm_state_header(QEMUFile *f)
2566 {
2567 unsigned int v;
2568 int ret;
2569
2570 v = qemu_get_be32(f);
2571 if (v != QEMU_VM_FILE_MAGIC) {
2572 error_report("Not a migration stream");
2573 return -EINVAL;
2574 }
2575
2576 v = qemu_get_be32(f);
2577 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2578 error_report("SaveVM v2 format is obsolete and don't work anymore");
2579 return -ENOTSUP;
2580 }
2581 if (v != QEMU_VM_FILE_VERSION) {
2582 error_report("Unsupported migration stream version");
2583 return -ENOTSUP;
2584 }
2585
2586 if (migrate_get_current()->send_configuration) {
2587 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2588 error_report("Configuration section missing");
2589 qemu_loadvm_state_cleanup();
2590 return -EINVAL;
2591 }
2592 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2593
2594 if (ret) {
2595 qemu_loadvm_state_cleanup();
2596 return ret;
2597 }
2598 }
2599 return 0;
2600 }
2601
2602 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2603 {
2604 SaveStateEntry *se;
2605
2606 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2607 if (!se->ops || !se->ops->switchover_ack_needed) {
2608 continue;
2609 }
2610
2611 if (se->ops->switchover_ack_needed(se->opaque)) {
2612 mis->switchover_ack_pending_num++;
2613 }
2614 }
2615
2616 trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2617 }
2618
2619 static int qemu_loadvm_state_setup(QEMUFile *f)
2620 {
2621 SaveStateEntry *se;
2622 int ret;
2623
2624 trace_loadvm_state_setup();
2625 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2626 if (!se->ops || !se->ops->load_setup) {
2627 continue;
2628 }
2629 if (se->ops->is_active) {
2630 if (!se->ops->is_active(se->opaque)) {
2631 continue;
2632 }
2633 }
2634
2635 ret = se->ops->load_setup(f, se->opaque);
2636 if (ret < 0) {
2637 qemu_file_set_error(f, ret);
2638 error_report("Load state of device %s failed", se->idstr);
2639 return ret;
2640 }
2641 }
2642 return 0;
2643 }
2644
2645 void qemu_loadvm_state_cleanup(void)
2646 {
2647 SaveStateEntry *se;
2648
2649 trace_loadvm_state_cleanup();
2650 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2651 if (se->ops && se->ops->load_cleanup) {
2652 se->ops->load_cleanup(se->opaque);
2653 }
2654 }
2655 }
2656
2657 /* Return true if we should continue the migration, or false. */
2658 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2659 {
2660 int i;
2661
2662 trace_postcopy_pause_incoming();
2663
2664 assert(migrate_postcopy_ram());
2665
2666 /*
2667 * Unregister yank with either from/to src would work, since ioc behind it
2668 * is the same
2669 */
2670 migration_ioc_unregister_yank_from_file(mis->from_src_file);
2671
2672 assert(mis->from_src_file);
2673 qemu_file_shutdown(mis->from_src_file);
2674 qemu_fclose(mis->from_src_file);
2675 mis->from_src_file = NULL;
2676
2677 assert(mis->to_src_file);
2678 qemu_file_shutdown(mis->to_src_file);
2679 qemu_mutex_lock(&mis->rp_mutex);
2680 qemu_fclose(mis->to_src_file);
2681 mis->to_src_file = NULL;
2682 qemu_mutex_unlock(&mis->rp_mutex);
2683
2684 /*
2685 * NOTE: this must happen before reset the PostcopyTmpPages below,
2686 * otherwise it's racy to reset those fields when the fast load thread
2687 * can be accessing it in parallel.
2688 */
2689 if (mis->postcopy_qemufile_dst) {
2690 qemu_file_shutdown(mis->postcopy_qemufile_dst);
2691 /* Take the mutex to make sure the fast ram load thread halted */
2692 qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2693 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2694 qemu_fclose(mis->postcopy_qemufile_dst);
2695 mis->postcopy_qemufile_dst = NULL;
2696 qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2697 }
2698
2699 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2700 MIGRATION_STATUS_POSTCOPY_PAUSED);
2701
2702 /* Notify the fault thread for the invalidated file handle */
2703 postcopy_fault_thread_notify(mis);
2704
2705 /*
2706 * If network is interrupted, any temp page we received will be useless
2707 * because we didn't mark them as "received" in receivedmap. After a
2708 * proper recovery later (which will sync src dirty bitmap with receivedmap
2709 * on dest) these cached small pages will be resent again.
2710 */
2711 for (i = 0; i < mis->postcopy_channels; i++) {
2712 postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2713 }
2714
2715 error_report("Detected IO failure for postcopy. "
2716 "Migration paused.");
2717
2718 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2719 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2720 }
2721
2722 trace_postcopy_pause_incoming_continued();
2723
2724 return true;
2725 }
2726
2727 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2728 {
2729 uint8_t section_type;
2730 int ret = 0;
2731
2732 retry:
2733 while (true) {
2734 section_type = qemu_get_byte(f);
2735
2736 ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2737 if (ret) {
2738 break;
2739 }
2740
2741 trace_qemu_loadvm_state_section(section_type);
2742 switch (section_type) {
2743 case QEMU_VM_SECTION_START:
2744 case QEMU_VM_SECTION_FULL:
2745 ret = qemu_loadvm_section_start_full(f, mis);
2746 if (ret < 0) {
2747 goto out;
2748 }
2749 break;
2750 case QEMU_VM_SECTION_PART:
2751 case QEMU_VM_SECTION_END:
2752 ret = qemu_loadvm_section_part_end(f, mis);
2753 if (ret < 0) {
2754 goto out;
2755 }
2756 break;
2757 case QEMU_VM_COMMAND:
2758 ret = loadvm_process_command(f);
2759 trace_qemu_loadvm_state_section_command(ret);
2760 if ((ret < 0) || (ret == LOADVM_QUIT)) {
2761 goto out;
2762 }
2763 break;
2764 case QEMU_VM_EOF:
2765 /* This is the end of migration */
2766 goto out;
2767 default:
2768 error_report("Unknown savevm section type %d", section_type);
2769 ret = -EINVAL;
2770 goto out;
2771 }
2772 }
2773
2774 out:
2775 if (ret < 0) {
2776 qemu_file_set_error(f, ret);
2777
2778 /* Cancel bitmaps incoming regardless of recovery */
2779 dirty_bitmap_mig_cancel_incoming();
2780
2781 /*
2782 * If we are during an active postcopy, then we pause instead
2783 * of bail out to at least keep the VM's dirty data. Note
2784 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2785 * during which we're still receiving device states and we
2786 * still haven't yet started the VM on destination.
2787 *
2788 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2789 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2790 * recovering.
2791 */
2792 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2793 migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2794 /* Reset f to point to the newly created channel */
2795 f = mis->from_src_file;
2796 goto retry;
2797 }
2798 }
2799 return ret;
2800 }
2801
2802 int qemu_loadvm_state(QEMUFile *f)
2803 {
2804 MigrationIncomingState *mis = migration_incoming_get_current();
2805 Error *local_err = NULL;
2806 int ret;
2807
2808 if (qemu_savevm_state_blocked(&local_err)) {
2809 error_report_err(local_err);
2810 return -EINVAL;
2811 }
2812
2813 ret = qemu_loadvm_state_header(f);
2814 if (ret) {
2815 return ret;
2816 }
2817
2818 if (qemu_loadvm_state_setup(f) != 0) {
2819 return -EINVAL;
2820 }
2821
2822 if (migrate_switchover_ack()) {
2823 qemu_loadvm_state_switchover_ack_needed(mis);
2824 }
2825
2826 cpu_synchronize_all_pre_loadvm();
2827
2828 ret = qemu_loadvm_state_main(f, mis);
2829 qemu_event_set(&mis->main_thread_load_event);
2830
2831 trace_qemu_loadvm_state_post_main(ret);
2832
2833 if (mis->have_listen_thread) {
2834 /* Listen thread still going, can't clean up yet */
2835 return ret;
2836 }
2837
2838 if (ret == 0) {
2839 ret = qemu_file_get_error(f);
2840 }
2841
2842 /*
2843 * Try to read in the VMDESC section as well, so that dumping tools that
2844 * intercept our migration stream have the chance to see it.
2845 */
2846
2847 /* We've got to be careful; if we don't read the data and just shut the fd
2848 * then the sender can error if we close while it's still sending.
2849 * We also mustn't read data that isn't there; some transports (RDMA)
2850 * will stall waiting for that data when the source has already closed.
2851 */
2852 if (ret == 0 && should_send_vmdesc()) {
2853 uint8_t *buf;
2854 uint32_t size;
2855 uint8_t section_type = qemu_get_byte(f);
2856
2857 if (section_type != QEMU_VM_VMDESCRIPTION) {
2858 error_report("Expected vmdescription section, but got %d",
2859 section_type);
2860 /*
2861 * It doesn't seem worth failing at this point since
2862 * we apparently have an otherwise valid VM state
2863 */
2864 } else {
2865 buf = g_malloc(0x1000);
2866 size = qemu_get_be32(f);
2867
2868 while (size > 0) {
2869 uint32_t read_chunk = MIN(size, 0x1000);
2870 qemu_get_buffer(f, buf, read_chunk);
2871 size -= read_chunk;
2872 }
2873 g_free(buf);
2874 }
2875 }
2876
2877 qemu_loadvm_state_cleanup();
2878 cpu_synchronize_all_post_init();
2879
2880 return ret;
2881 }
2882
2883 int qemu_load_device_state(QEMUFile *f)
2884 {
2885 MigrationIncomingState *mis = migration_incoming_get_current();
2886 int ret;
2887
2888 /* Load QEMU_VM_SECTION_FULL section */
2889 ret = qemu_loadvm_state_main(f, mis);
2890 if (ret < 0) {
2891 error_report("Failed to load device state: %d", ret);
2892 return ret;
2893 }
2894
2895 cpu_synchronize_all_post_init();
2896 return 0;
2897 }
2898
2899 int qemu_loadvm_approve_switchover(void)
2900 {
2901 MigrationIncomingState *mis = migration_incoming_get_current();
2902
2903 if (!mis->switchover_ack_pending_num) {
2904 return -EINVAL;
2905 }
2906
2907 mis->switchover_ack_pending_num--;
2908 trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
2909
2910 if (mis->switchover_ack_pending_num) {
2911 return 0;
2912 }
2913
2914 return migrate_send_rp_switchover_ack(mis);
2915 }
2916
2917 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
2918 bool has_devices, strList *devices, Error **errp)
2919 {
2920 BlockDriverState *bs;
2921 QEMUSnapshotInfo sn1, *sn = &sn1;
2922 int ret = -1, ret2;
2923 QEMUFile *f;
2924 int saved_vm_running;
2925 uint64_t vm_state_size;
2926 g_autoptr(GDateTime) now = g_date_time_new_now_local();
2927 AioContext *aio_context;
2928
2929 GLOBAL_STATE_CODE();
2930
2931 if (migration_is_blocked(errp)) {
2932 return false;
2933 }
2934
2935 if (!replay_can_snapshot()) {
2936 error_setg(errp, "Record/replay does not allow making snapshot "
2937 "right now. Try once more later.");
2938 return false;
2939 }
2940
2941 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
2942 return false;
2943 }
2944
2945 /* Delete old snapshots of the same name */
2946 if (name) {
2947 if (overwrite) {
2948 if (bdrv_all_delete_snapshot(name, has_devices,
2949 devices, errp) < 0) {
2950 return false;
2951 }
2952 } else {
2953 ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
2954 if (ret2 < 0) {
2955 return false;
2956 }
2957 if (ret2 == 1) {
2958 error_setg(errp,
2959 "Snapshot '%s' already exists in one or more devices",
2960 name);
2961 return false;
2962 }
2963 }
2964 }
2965
2966 bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
2967 if (bs == NULL) {
2968 return false;
2969 }
2970 aio_context = bdrv_get_aio_context(bs);
2971
2972 saved_vm_running = runstate_is_running();
2973
2974 global_state_store();
2975 vm_stop(RUN_STATE_SAVE_VM);
2976
2977 bdrv_drain_all_begin();
2978
2979 aio_context_acquire(aio_context);
2980
2981 memset(sn, 0, sizeof(*sn));
2982
2983 /* fill auxiliary fields */
2984 sn->date_sec = g_date_time_to_unix(now);
2985 sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
2986 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2987 if (replay_mode != REPLAY_MODE_NONE) {
2988 sn->icount = replay_get_current_icount();
2989 } else {
2990 sn->icount = -1ULL;
2991 }
2992
2993 if (name) {
2994 pstrcpy(sn->name, sizeof(sn->name), name);
2995 } else {
2996 g_autofree char *autoname = g_date_time_format(now, "vm-%Y%m%d%H%M%S");
2997 pstrcpy(sn->name, sizeof(sn->name), autoname);
2998 }
2999
3000 /* save the VM state */
3001 f = qemu_fopen_bdrv(bs, 1);
3002 if (!f) {
3003 error_setg(errp, "Could not open VM state file");
3004 goto the_end;
3005 }
3006 ret = qemu_savevm_state(f, errp);
3007 vm_state_size = qemu_file_transferred_noflush(f);
3008 ret2 = qemu_fclose(f);
3009 if (ret < 0) {
3010 goto the_end;
3011 }
3012 if (ret2 < 0) {
3013 ret = ret2;
3014 goto the_end;
3015 }
3016
3017 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
3018 * for itself. BDRV_POLL_WHILE() does not support nested locking because
3019 * it only releases the lock once. Therefore synchronous I/O will deadlock
3020 * unless we release the AioContext before bdrv_all_create_snapshot().
3021 */
3022 aio_context_release(aio_context);
3023 aio_context = NULL;
3024
3025 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3026 has_devices, devices, errp);
3027 if (ret < 0) {
3028 bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3029 goto the_end;
3030 }
3031
3032 ret = 0;
3033
3034 the_end:
3035 if (aio_context) {
3036 aio_context_release(aio_context);
3037 }
3038
3039 bdrv_drain_all_end();
3040
3041 if (saved_vm_running) {
3042 vm_start();
3043 }
3044 return ret == 0;
3045 }
3046
3047 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3048 Error **errp)
3049 {
3050 QEMUFile *f;
3051 QIOChannelFile *ioc;
3052 int saved_vm_running;
3053 int ret;
3054
3055 if (!has_live) {
3056 /* live default to true so old version of Xen tool stack can have a
3057 * successful live migration */
3058 live = true;
3059 }
3060
3061 saved_vm_running = runstate_is_running();
3062 vm_stop(RUN_STATE_SAVE_VM);
3063 global_state_store_running();
3064
3065 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3066 0660, errp);
3067 if (!ioc) {
3068 goto the_end;
3069 }
3070 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3071 f = qemu_file_new_output(QIO_CHANNEL(ioc));
3072 object_unref(OBJECT(ioc));
3073 ret = qemu_save_device_state(f);
3074 if (ret < 0 || qemu_fclose(f) < 0) {
3075 error_setg(errp, QERR_IO_ERROR);
3076 } else {
3077 /* libxl calls the QMP command "stop" before calling
3078 * "xen-save-devices-state" and in case of migration failure, libxl
3079 * would call "cont".
3080 * So call bdrv_inactivate_all (release locks) here to let the other
3081 * side of the migration take control of the images.
3082 */
3083 if (live && !saved_vm_running) {
3084 ret = bdrv_inactivate_all();
3085 if (ret) {
3086 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
3087 __func__, ret);
3088 }
3089 }
3090 }
3091
3092 the_end:
3093 if (saved_vm_running) {
3094 vm_start();
3095 }
3096 }
3097
3098 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3099 {
3100 QEMUFile *f;
3101 QIOChannelFile *ioc;
3102 int ret;
3103
3104 /* Guest must be paused before loading the device state; the RAM state
3105 * will already have been loaded by xc
3106 */
3107 if (runstate_is_running()) {
3108 error_setg(errp, "Cannot update device state while vm is running");
3109 return;
3110 }
3111 vm_stop(RUN_STATE_RESTORE_VM);
3112
3113 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3114 if (!ioc) {
3115 return;
3116 }
3117 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3118 f = qemu_file_new_input(QIO_CHANNEL(ioc));
3119 object_unref(OBJECT(ioc));
3120
3121 ret = qemu_loadvm_state(f);
3122 qemu_fclose(f);
3123 if (ret < 0) {
3124 error_setg(errp, QERR_IO_ERROR);
3125 }
3126 migration_incoming_state_destroy();
3127 }
3128
3129 bool load_snapshot(const char *name, const char *vmstate,
3130 bool has_devices, strList *devices, Error **errp)
3131 {
3132 BlockDriverState *bs_vm_state;
3133 QEMUSnapshotInfo sn;
3134 QEMUFile *f;
3135 int ret;
3136 AioContext *aio_context;
3137 MigrationIncomingState *mis = migration_incoming_get_current();
3138
3139 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3140 return false;
3141 }
3142 ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3143 if (ret < 0) {
3144 return false;
3145 }
3146 if (ret == 0) {
3147 error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3148 name);
3149 return false;
3150 }
3151
3152 bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3153 if (!bs_vm_state) {
3154 return false;
3155 }
3156 aio_context = bdrv_get_aio_context(bs_vm_state);
3157
3158 /* Don't even try to load empty VM states */
3159 aio_context_acquire(aio_context);
3160 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3161 aio_context_release(aio_context);
3162 if (ret < 0) {
3163 return false;
3164 } else if (sn.vm_state_size == 0) {
3165 error_setg(errp, "This is a disk-only snapshot. Revert to it "
3166 " offline using qemu-img");
3167 return false;
3168 }
3169
3170 /*
3171 * Flush the record/replay queue. Now the VM state is going
3172 * to change. Therefore we don't need to preserve its consistency
3173 */
3174 replay_flush_events();
3175
3176 /* Flush all IO requests so they don't interfere with the new state. */
3177 bdrv_drain_all_begin();
3178
3179 ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3180 if (ret < 0) {
3181 goto err_drain;
3182 }
3183
3184 /* restore the VM state */
3185 f = qemu_fopen_bdrv(bs_vm_state, 0);
3186 if (!f) {
3187 error_setg(errp, "Could not open VM state file");
3188 goto err_drain;
3189 }
3190
3191 qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3192 mis->from_src_file = f;
3193
3194 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3195 ret = -EINVAL;
3196 goto err_drain;
3197 }
3198 aio_context_acquire(aio_context);
3199 ret = qemu_loadvm_state(f);
3200 migration_incoming_state_destroy();
3201 aio_context_release(aio_context);
3202
3203 bdrv_drain_all_end();
3204
3205 if (ret < 0) {
3206 error_setg(errp, "Error %d while loading VM state", ret);
3207 return false;
3208 }
3209
3210 return true;
3211
3212 err_drain:
3213 bdrv_drain_all_end();
3214 return false;
3215 }
3216
3217 bool delete_snapshot(const char *name, bool has_devices,
3218 strList *devices, Error **errp)
3219 {
3220 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3221 return false;
3222 }
3223
3224 if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3225 return false;
3226 }
3227
3228 return true;
3229 }
3230
3231 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3232 {
3233 qemu_ram_set_idstr(mr->ram_block,
3234 memory_region_name(mr), dev);
3235 qemu_ram_set_migratable(mr->ram_block);
3236 }
3237
3238 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3239 {
3240 qemu_ram_unset_idstr(mr->ram_block);
3241 qemu_ram_unset_migratable(mr->ram_block);
3242 }
3243
3244 void vmstate_register_ram_global(MemoryRegion *mr)
3245 {
3246 vmstate_register_ram(mr, NULL);
3247 }
3248
3249 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3250 {
3251 /* check needed if --only-migratable is specified */
3252 if (!only_migratable) {
3253 return true;
3254 }
3255
3256 return !(vmsd && vmsd->unmigratable);
3257 }
3258
3259 typedef struct SnapshotJob {
3260 Job common;
3261 char *tag;
3262 char *vmstate;
3263 strList *devices;
3264 Coroutine *co;
3265 Error **errp;
3266 bool ret;
3267 } SnapshotJob;
3268
3269 static void qmp_snapshot_job_free(SnapshotJob *s)
3270 {
3271 g_free(s->tag);
3272 g_free(s->vmstate);
3273 qapi_free_strList(s->devices);
3274 }
3275
3276
3277 static void snapshot_load_job_bh(void *opaque)
3278 {
3279 Job *job = opaque;
3280 SnapshotJob *s = container_of(job, SnapshotJob, common);
3281 int orig_vm_running;
3282
3283 job_progress_set_remaining(&s->common, 1);
3284
3285 orig_vm_running = runstate_is_running();
3286 vm_stop(RUN_STATE_RESTORE_VM);
3287
3288 s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3289 if (s->ret && orig_vm_running) {
3290 vm_start();
3291 }
3292
3293 job_progress_update(&s->common, 1);
3294
3295 qmp_snapshot_job_free(s);
3296 aio_co_wake(s->co);
3297 }
3298
3299 static void snapshot_save_job_bh(void *opaque)
3300 {
3301 Job *job = opaque;
3302 SnapshotJob *s = container_of(job, SnapshotJob, common);
3303
3304 job_progress_set_remaining(&s->common, 1);
3305 s->ret = save_snapshot(s->tag, false, s->vmstate,
3306 true, s->devices, s->errp);
3307 job_progress_update(&s->common, 1);
3308
3309 qmp_snapshot_job_free(s);
3310 aio_co_wake(s->co);
3311 }
3312
3313 static void snapshot_delete_job_bh(void *opaque)
3314 {
3315 Job *job = opaque;
3316 SnapshotJob *s = container_of(job, SnapshotJob, common);
3317
3318 job_progress_set_remaining(&s->common, 1);
3319 s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3320 job_progress_update(&s->common, 1);
3321
3322 qmp_snapshot_job_free(s);
3323 aio_co_wake(s->co);
3324 }
3325
3326 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3327 {
3328 SnapshotJob *s = container_of(job, SnapshotJob, common);
3329 s->errp = errp;
3330 s->co = qemu_coroutine_self();
3331 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3332 snapshot_save_job_bh, job);
3333 qemu_coroutine_yield();
3334 return s->ret ? 0 : -1;
3335 }
3336
3337 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3338 {
3339 SnapshotJob *s = container_of(job, SnapshotJob, common);
3340 s->errp = errp;
3341 s->co = qemu_coroutine_self();
3342 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3343 snapshot_load_job_bh, job);
3344 qemu_coroutine_yield();
3345 return s->ret ? 0 : -1;
3346 }
3347
3348 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3349 {
3350 SnapshotJob *s = container_of(job, SnapshotJob, common);
3351 s->errp = errp;
3352 s->co = qemu_coroutine_self();
3353 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3354 snapshot_delete_job_bh, job);
3355 qemu_coroutine_yield();
3356 return s->ret ? 0 : -1;
3357 }
3358
3359
3360 static const JobDriver snapshot_load_job_driver = {
3361 .instance_size = sizeof(SnapshotJob),
3362 .job_type = JOB_TYPE_SNAPSHOT_LOAD,
3363 .run = snapshot_load_job_run,
3364 };
3365
3366 static const JobDriver snapshot_save_job_driver = {
3367 .instance_size = sizeof(SnapshotJob),
3368 .job_type = JOB_TYPE_SNAPSHOT_SAVE,
3369 .run = snapshot_save_job_run,
3370 };
3371
3372 static const JobDriver snapshot_delete_job_driver = {
3373 .instance_size = sizeof(SnapshotJob),
3374 .job_type = JOB_TYPE_SNAPSHOT_DELETE,
3375 .run = snapshot_delete_job_run,
3376 };
3377
3378
3379 void qmp_snapshot_save(const char *job_id,
3380 const char *tag,
3381 const char *vmstate,
3382 strList *devices,
3383 Error **errp)
3384 {
3385 SnapshotJob *s;
3386
3387 s = job_create(job_id, &snapshot_save_job_driver, NULL,
3388 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3389 NULL, NULL, errp);
3390 if (!s) {
3391 return;
3392 }
3393
3394 s->tag = g_strdup(tag);
3395 s->vmstate = g_strdup(vmstate);
3396 s->devices = QAPI_CLONE(strList, devices);
3397
3398 job_start(&s->common);
3399 }
3400
3401 void qmp_snapshot_load(const char *job_id,
3402 const char *tag,
3403 const char *vmstate,
3404 strList *devices,
3405 Error **errp)
3406 {
3407 SnapshotJob *s;
3408
3409 s = job_create(job_id, &snapshot_load_job_driver, NULL,
3410 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3411 NULL, NULL, errp);
3412 if (!s) {
3413 return;
3414 }
3415
3416 s->tag = g_strdup(tag);
3417 s->vmstate = g_strdup(vmstate);
3418 s->devices = QAPI_CLONE(strList, devices);
3419
3420 job_start(&s->common);
3421 }
3422
3423 void qmp_snapshot_delete(const char *job_id,
3424 const char *tag,
3425 strList *devices,
3426 Error **errp)
3427 {
3428 SnapshotJob *s;
3429
3430 s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3431 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3432 NULL, NULL, errp);
3433 if (!s) {
3434 return;
3435 }
3436
3437 s->tag = g_strdup(tag);
3438 s->devices = QAPI_CLONE(strList, devices);
3439
3440 job_start(&s->common);
3441 }