]> git.proxmox.com Git - mirror_qemu.git/blame - migration/savevm.c
block/copy-before-write: implement cbw-timeout option
[mirror_qemu.git] / migration / savevm.c
CommitLineData
a672b469
AL
1/*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
76cc7b58
JQ
5 * Copyright (c) 2009-2015 Red Hat Inc
6 *
7 * Authors:
8 * Juan Quintela <quintela@redhat.com>
a672b469
AL
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 */
a672b469 28
1393a485 29#include "qemu/osdep.h"
abfd9ce3 30#include "hw/boards.h"
1422e32d 31#include "net/net.h"
6666c96a 32#include "migration.h"
5e22479a 33#include "migration/snapshot.h"
d6454270 34#include "migration/vmstate.h"
f8d806c9 35#include "migration/misc.h"
f2a8f0a6 36#include "migration/register.h"
84a899de 37#include "migration/global_state.h"
67bdabe2 38#include "migration/channel-block.h"
7b1e1a22 39#include "ram.h"
08a0aee1 40#include "qemu-file.h"
20a519a0 41#include "savevm.h"
be07b0ac 42#include "postcopy-ram.h"
e688df6b 43#include "qapi/error.h"
112ed241 44#include "qapi/qapi-commands-migration.h"
3ddba9a9 45#include "qapi/qmp/json-writer.h"
f1a9fcdd
DB
46#include "qapi/clone-visitor.h"
47#include "qapi/qapi-builtin-visit.h"
cc7a8ea7 48#include "qapi/qmp/qerror.h"
d49b6836 49#include "qemu/error-report.h"
9c17d615 50#include "sysemu/cpus.h"
022c62cb 51#include "exec/memory.h"
51180423 52#include "exec/target_page.h"
517a13c9 53#include "trace.h"
28085f7b 54#include "qemu/iov.h"
db725815 55#include "qemu/main-loop.h"
de08c606 56#include "block/snapshot.h"
f348b6d1 57#include "qemu/cutils.h"
61b67d47 58#include "io/channel-buffer.h"
8925839f 59#include "io/channel-file.h"
377b21cc 60#include "sysemu/replay.h"
54d31236 61#include "sysemu/runstate.h"
46517dd4 62#include "sysemu/sysemu.h"
da278d58 63#include "sysemu/xen.h"
aad555c2 64#include "migration/colo.h"
6cafc8e4 65#include "qemu/bitmap.h"
7659505c 66#include "net/announce.h"
b5eea99e 67#include "qemu/yank.h"
39675fff 68#include "yank_functions.h"
18995b98 69
49324e93 70const unsigned int postcopy_ram_discard_version;
093e3c42 71
20a519a0
JQ
72/* Subcommands for QEMU_VM_COMMAND */
73enum qemu_vm_cmd {
74 MIG_CMD_INVALID = 0, /* Must be 0 */
75 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
76 MIG_CMD_PING, /* Request a PONG on the RP */
77
78 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
79 warn we might want to do PC */
80 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
81 pages as it's running. */
82 MIG_CMD_POSTCOPY_RUN, /* Start execution */
83
84 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
85 were previously sent during
86 precopy but are dirty. */
87 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
aad555c2 88 MIG_CMD_ENABLE_COLO, /* Enable COLO */
858b6d62 89 MIG_CMD_POSTCOPY_RESUME, /* resume postcopy on dest */
f25d4225 90 MIG_CMD_RECV_BITMAP, /* Request for recved bitmap on dst */
20a519a0
JQ
91 MIG_CMD_MAX
92};
93
ee555cdf 94#define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
c76ca188
DDAG
95static struct mig_cmd_args {
96 ssize_t len; /* -1 = variable */
97 const char *name;
98} mig_cmd_args[] = {
99 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
2e37701e
DDAG
100 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
101 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
58110f0a 102 [MIG_CMD_POSTCOPY_ADVISE] = { .len = -1, .name = "POSTCOPY_ADVISE" },
093e3c42
DDAG
103 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
104 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
105 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
106 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
3f5875ec 107 [MIG_CMD_POSTCOPY_RESUME] = { .len = 0, .name = "POSTCOPY_RESUME" },
11cf1d98 108 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
f25d4225 109 [MIG_CMD_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
c76ca188
DDAG
110 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
111};
112
58110f0a
VSO
113/* Note for MIG_CMD_POSTCOPY_ADVISE:
114 * The format of arguments is depending on postcopy mode:
115 * - postcopy RAM only
116 * uint64_t host page size
117 * uint64_t taget page size
118 *
119 * - postcopy RAM and postcopy dirty bitmaps
120 * format is the same as for postcopy RAM only
121 *
122 * - postcopy dirty bitmaps only
123 * Nothing. Command length field is 0.
124 *
125 * Be careful: adding a new postcopy entity with some other parameters should
126 * not break format self-description ability. Good way is to introduce some
127 * generic extendable format with an exception for two old entities.
128 */
129
a672b469
AL
130/***********************************************************/
131/* savevm/loadvm support */
132
45566e9c 133static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
a672b469 134{
38ff78d3 135 if (is_writable) {
77ef2dc1 136 return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
67bdabe2 137 } else {
77ef2dc1 138 return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
38ff78d3 139 }
a672b469
AL
140}
141
2ff68d07 142
bb1a6d8c
EH
143/* QEMUFile timer support.
144 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
145 */
2ff68d07 146
40daca54 147void timer_put(QEMUFile *f, QEMUTimer *ts)
2ff68d07
PB
148{
149 uint64_t expire_time;
150
e93379b0 151 expire_time = timer_expire_time_ns(ts);
2ff68d07
PB
152 qemu_put_be64(f, expire_time);
153}
154
40daca54 155void timer_get(QEMUFile *f, QEMUTimer *ts)
2ff68d07
PB
156{
157 uint64_t expire_time;
158
159 expire_time = qemu_get_be64(f);
160 if (expire_time != -1) {
bc72ad67 161 timer_mod_ns(ts, expire_time);
2ff68d07 162 } else {
bc72ad67 163 timer_del(ts);
2ff68d07
PB
164 }
165}
166
167
bb1a6d8c
EH
168/* VMState timer support.
169 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
170 */
dde0463b 171
03fee66f
MAL
172static int get_timer(QEMUFile *f, void *pv, size_t size,
173 const VMStateField *field)
dde0463b
JQ
174{
175 QEMUTimer *v = pv;
40daca54 176 timer_get(f, v);
dde0463b
JQ
177 return 0;
178}
179
03fee66f 180static int put_timer(QEMUFile *f, void *pv, size_t size,
3ddba9a9 181 const VMStateField *field, JSONWriter *vmdesc)
dde0463b 182{
84e2e3eb 183 QEMUTimer *v = pv;
40daca54 184 timer_put(f, v);
2c21ee76
JD
185
186 return 0;
dde0463b
JQ
187}
188
189const VMStateInfo vmstate_info_timer = {
190 .name = "timer",
191 .get = get_timer,
192 .put = put_timer,
193};
194
08e99e29 195
7685ee6a
AW
196typedef struct CompatEntry {
197 char idstr[256];
198 int instance_id;
199} CompatEntry;
200
a672b469 201typedef struct SaveStateEntry {
72cf2d4f 202 QTAILQ_ENTRY(SaveStateEntry) entry;
a672b469 203 char idstr[256];
93062e23 204 uint32_t instance_id;
4d2ffa08 205 int alias_id;
a672b469 206 int version_id;
0f42f657
JQ
207 /* version id read from the stream */
208 int load_version_id;
a672b469 209 int section_id;
0f42f657
JQ
210 /* section id read from the stream */
211 int load_section_id;
de22ded0 212 const SaveVMHandlers *ops;
9ed7d6ae 213 const VMStateDescription *vmsd;
a672b469 214 void *opaque;
7685ee6a 215 CompatEntry *compat;
a7ae8355 216 int is_ram;
a672b469
AL
217} SaveStateEntry;
218
0163a2e0
JQ
219typedef struct SaveState {
220 QTAILQ_HEAD(, SaveStateEntry) handlers;
174723ff 221 SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
0163a2e0 222 int global_section_id;
61964c23
JQ
223 uint32_t len;
224 const char *name;
59811a32 225 uint32_t target_page_bits;
6cafc8e4
YK
226 uint32_t caps_count;
227 MigrationCapability *capabilities;
b9d68df6 228 QemuUUID uuid;
0163a2e0
JQ
229} SaveState;
230
231static SaveState savevm_state = {
232 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
174723ff 233 .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
0163a2e0 234 .global_section_id = 0,
61964c23
JQ
235};
236
6cafc8e4
YK
237static bool should_validate_capability(int capability)
238{
239 assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
240 /* Validate only new capabilities to keep compatibility. */
241 switch (capability) {
242 case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
243 return true;
244 default:
245 return false;
246 }
247}
248
249static uint32_t get_validatable_capabilities_count(void)
250{
251 MigrationState *s = migrate_get_current();
252 uint32_t result = 0;
253 int i;
254 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
255 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
256 result++;
257 }
258 }
259 return result;
260}
261
44b1ff31 262static int configuration_pre_save(void *opaque)
61964c23
JQ
263{
264 SaveState *state = opaque;
265 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
6cafc8e4
YK
266 MigrationState *s = migrate_get_current();
267 int i, j;
61964c23
JQ
268
269 state->len = strlen(current_name);
270 state->name = current_name;
46d702b1 271 state->target_page_bits = qemu_target_page_bits();
44b1ff31 272
6cafc8e4
YK
273 state->caps_count = get_validatable_capabilities_count();
274 state->capabilities = g_renew(MigrationCapability, state->capabilities,
275 state->caps_count);
276 for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
277 if (should_validate_capability(i) && s->enabled_capabilities[i]) {
278 state->capabilities[j++] = i;
279 }
280 }
b9d68df6 281 state->uuid = qemu_uuid;
6cafc8e4 282
44b1ff31 283 return 0;
59811a32
PM
284}
285
39f633d4
JG
286static int configuration_post_save(void *opaque)
287{
288 SaveState *state = opaque;
289
290 g_free(state->capabilities);
291 state->capabilities = NULL;
292 state->caps_count = 0;
293 return 0;
294}
295
59811a32
PM
296static int configuration_pre_load(void *opaque)
297{
298 SaveState *state = opaque;
299
300 /* If there is no target-page-bits subsection it means the source
301 * predates the variable-target-page-bits support and is using the
302 * minimum possible value for this CPU.
303 */
46d702b1 304 state->target_page_bits = qemu_target_page_bits_min();
59811a32 305 return 0;
61964c23
JQ
306}
307
6cafc8e4
YK
308static bool configuration_validate_capabilities(SaveState *state)
309{
310 bool ret = true;
311 MigrationState *s = migrate_get_current();
312 unsigned long *source_caps_bm;
313 int i;
314
315 source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
316 for (i = 0; i < state->caps_count; i++) {
317 MigrationCapability capability = state->capabilities[i];
318 set_bit(capability, source_caps_bm);
319 }
320
321 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
322 bool source_state, target_state;
323 if (!should_validate_capability(i)) {
324 continue;
325 }
326 source_state = test_bit(i, source_caps_bm);
327 target_state = s->enabled_capabilities[i];
328 if (source_state != target_state) {
329 error_report("Capability %s is %s, but received capability is %s",
330 MigrationCapability_str(i),
331 target_state ? "on" : "off",
332 source_state ? "on" : "off");
333 ret = false;
334 /* Don't break here to report all failed capabilities */
335 }
336 }
337
338 g_free(source_caps_bm);
339 return ret;
340}
341
61964c23
JQ
342static int configuration_post_load(void *opaque, int version_id)
343{
344 SaveState *state = opaque;
345 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
39f633d4 346 int ret = 0;
61964c23
JQ
347
348 if (strncmp(state->name, current_name, state->len) != 0) {
15d61692
GK
349 error_report("Machine type received is '%.*s' and local is '%s'",
350 (int) state->len, state->name, current_name);
39f633d4
JG
351 ret = -EINVAL;
352 goto out;
61964c23 353 }
59811a32 354
46d702b1 355 if (state->target_page_bits != qemu_target_page_bits()) {
59811a32 356 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
46d702b1 357 state->target_page_bits, qemu_target_page_bits());
39f633d4
JG
358 ret = -EINVAL;
359 goto out;
59811a32
PM
360 }
361
6cafc8e4 362 if (!configuration_validate_capabilities(state)) {
39f633d4
JG
363 ret = -EINVAL;
364 goto out;
6cafc8e4
YK
365 }
366
39f633d4
JG
367out:
368 g_free((void *)state->name);
369 state->name = NULL;
370 state->len = 0;
371 g_free(state->capabilities);
372 state->capabilities = NULL;
373 state->caps_count = 0;
374
375 return ret;
61964c23
JQ
376}
377
6cafc8e4
YK
378static int get_capability(QEMUFile *f, void *pv, size_t size,
379 const VMStateField *field)
380{
381 MigrationCapability *capability = pv;
382 char capability_str[UINT8_MAX + 1];
383 uint8_t len;
384 int i;
385
386 len = qemu_get_byte(f);
387 qemu_get_buffer(f, (uint8_t *)capability_str, len);
388 capability_str[len] = '\0';
389 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
390 if (!strcmp(MigrationCapability_str(i), capability_str)) {
391 *capability = i;
392 return 0;
393 }
394 }
395 error_report("Received unknown capability %s", capability_str);
396 return -EINVAL;
397}
398
399static int put_capability(QEMUFile *f, void *pv, size_t size,
3ddba9a9 400 const VMStateField *field, JSONWriter *vmdesc)
6cafc8e4
YK
401{
402 MigrationCapability *capability = pv;
403 const char *capability_str = MigrationCapability_str(*capability);
404 size_t len = strlen(capability_str);
405 assert(len <= UINT8_MAX);
406
407 qemu_put_byte(f, len);
408 qemu_put_buffer(f, (uint8_t *)capability_str, len);
409 return 0;
410}
411
412static const VMStateInfo vmstate_info_capability = {
413 .name = "capability",
414 .get = get_capability,
415 .put = put_capability,
416};
417
59811a32
PM
418/* The target-page-bits subsection is present only if the
419 * target page size is not the same as the default (ie the
420 * minimum page size for a variable-page-size guest CPU).
421 * If it is present then it contains the actual target page
422 * bits for the machine, and migration will fail if the
423 * two ends don't agree about it.
424 */
425static bool vmstate_target_page_bits_needed(void *opaque)
426{
46d702b1
JQ
427 return qemu_target_page_bits()
428 > qemu_target_page_bits_min();
59811a32
PM
429}
430
431static const VMStateDescription vmstate_target_page_bits = {
432 .name = "configuration/target-page-bits",
433 .version_id = 1,
434 .minimum_version_id = 1,
435 .needed = vmstate_target_page_bits_needed,
436 .fields = (VMStateField[]) {
437 VMSTATE_UINT32(target_page_bits, SaveState),
438 VMSTATE_END_OF_LIST()
439 }
440};
441
6cafc8e4
YK
442static bool vmstate_capabilites_needed(void *opaque)
443{
444 return get_validatable_capabilities_count() > 0;
445}
446
447static const VMStateDescription vmstate_capabilites = {
448 .name = "configuration/capabilities",
449 .version_id = 1,
450 .minimum_version_id = 1,
451 .needed = vmstate_capabilites_needed,
452 .fields = (VMStateField[]) {
453 VMSTATE_UINT32_V(caps_count, SaveState, 1),
454 VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
455 vmstate_info_capability,
456 MigrationCapability),
457 VMSTATE_END_OF_LIST()
458 }
459};
460
b9d68df6
YK
461static bool vmstate_uuid_needed(void *opaque)
462{
463 return qemu_uuid_set && migrate_validate_uuid();
464}
465
466static int vmstate_uuid_post_load(void *opaque, int version_id)
467{
468 SaveState *state = opaque;
469 char uuid_src[UUID_FMT_LEN + 1];
470 char uuid_dst[UUID_FMT_LEN + 1];
471
472 if (!qemu_uuid_set) {
473 /*
474 * It's warning because user might not know UUID in some cases,
475 * e.g. load an old snapshot
476 */
477 qemu_uuid_unparse(&state->uuid, uuid_src);
478 warn_report("UUID is received %s, but local uuid isn't set",
479 uuid_src);
480 return 0;
481 }
482 if (!qemu_uuid_is_equal(&state->uuid, &qemu_uuid)) {
483 qemu_uuid_unparse(&state->uuid, uuid_src);
484 qemu_uuid_unparse(&qemu_uuid, uuid_dst);
485 error_report("UUID received is %s and local is %s", uuid_src, uuid_dst);
486 return -EINVAL;
487 }
488 return 0;
489}
490
491static const VMStateDescription vmstate_uuid = {
492 .name = "configuration/uuid",
493 .version_id = 1,
494 .minimum_version_id = 1,
495 .needed = vmstate_uuid_needed,
496 .post_load = vmstate_uuid_post_load,
497 .fields = (VMStateField[]) {
498 VMSTATE_UINT8_ARRAY_V(uuid.data, SaveState, sizeof(QemuUUID), 1),
499 VMSTATE_END_OF_LIST()
500 }
501};
502
61964c23
JQ
503static const VMStateDescription vmstate_configuration = {
504 .name = "configuration",
505 .version_id = 1,
59811a32 506 .pre_load = configuration_pre_load,
61964c23
JQ
507 .post_load = configuration_post_load,
508 .pre_save = configuration_pre_save,
39f633d4 509 .post_save = configuration_post_save,
61964c23
JQ
510 .fields = (VMStateField[]) {
511 VMSTATE_UINT32(len, SaveState),
59046ec2 512 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
61964c23
JQ
513 VMSTATE_END_OF_LIST()
514 },
395cb450 515 .subsections = (const VMStateDescription *[]) {
59811a32 516 &vmstate_target_page_bits,
6cafc8e4 517 &vmstate_capabilites,
b9d68df6 518 &vmstate_uuid,
59811a32
PM
519 NULL
520 }
0163a2e0 521};
a672b469 522
abfd9ce3
AS
523static void dump_vmstate_vmsd(FILE *out_file,
524 const VMStateDescription *vmsd, int indent,
525 bool is_subsection);
526
527static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
528 int indent)
529{
530 fprintf(out_file, "%*s{\n", indent, "");
531 indent += 2;
532 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
533 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
534 field->version_id);
535 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
536 field->field_exists ? "true" : "false");
537 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
538 if (field->vmsd != NULL) {
539 fprintf(out_file, ",\n");
540 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
541 }
542 fprintf(out_file, "\n%*s}", indent - 2, "");
543}
544
545static void dump_vmstate_vmss(FILE *out_file,
5cd8cada 546 const VMStateDescription **subsection,
abfd9ce3
AS
547 int indent)
548{
5cd8cada
JQ
549 if (*subsection != NULL) {
550 dump_vmstate_vmsd(out_file, *subsection, indent, true);
abfd9ce3
AS
551 }
552}
553
554static void dump_vmstate_vmsd(FILE *out_file,
555 const VMStateDescription *vmsd, int indent,
556 bool is_subsection)
557{
558 if (is_subsection) {
559 fprintf(out_file, "%*s{\n", indent, "");
560 } else {
561 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
562 }
563 indent += 2;
564 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
565 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
566 vmsd->version_id);
567 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
568 vmsd->minimum_version_id);
569 if (vmsd->fields != NULL) {
570 const VMStateField *field = vmsd->fields;
571 bool first;
572
573 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
574 first = true;
575 while (field->name != NULL) {
576 if (field->flags & VMS_MUST_EXIST) {
577 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
578 field++;
579 continue;
580 }
581 if (!first) {
582 fprintf(out_file, ",\n");
583 }
584 dump_vmstate_vmsf(out_file, field, indent + 2);
585 field++;
586 first = false;
587 }
588 fprintf(out_file, "\n%*s]", indent, "");
589 }
590 if (vmsd->subsections != NULL) {
5cd8cada 591 const VMStateDescription **subsection = vmsd->subsections;
abfd9ce3
AS
592 bool first;
593
594 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
595 first = true;
5cd8cada 596 while (*subsection != NULL) {
abfd9ce3
AS
597 if (!first) {
598 fprintf(out_file, ",\n");
599 }
600 dump_vmstate_vmss(out_file, subsection, indent + 2);
601 subsection++;
602 first = false;
603 }
604 fprintf(out_file, "\n%*s]", indent, "");
605 }
606 fprintf(out_file, "\n%*s}", indent - 2, "");
607}
608
609static void dump_machine_type(FILE *out_file)
610{
611 MachineClass *mc;
612
613 mc = MACHINE_GET_CLASS(current_machine);
614
615 fprintf(out_file, " \"vmschkmachine\": {\n");
616 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
617 fprintf(out_file, " },\n");
618}
619
620void dump_vmstate_json_to_file(FILE *out_file)
621{
622 GSList *list, *elt;
623 bool first;
624
625 fprintf(out_file, "{\n");
626 dump_machine_type(out_file);
627
628 first = true;
629 list = object_class_get_list(TYPE_DEVICE, true);
630 for (elt = list; elt; elt = elt->next) {
631 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
632 TYPE_DEVICE);
633 const char *name;
634 int indent = 2;
635
636 if (!dc->vmsd) {
637 continue;
638 }
639
640 if (!first) {
641 fprintf(out_file, ",\n");
642 }
643 name = object_class_get_name(OBJECT_CLASS(dc));
644 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
645 indent += 2;
646 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
647 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
648 dc->vmsd->version_id);
649 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
650 dc->vmsd->minimum_version_id);
651
652 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
653
654 fprintf(out_file, "\n%*s}", indent - 2, "");
655 first = false;
656 }
657 fprintf(out_file, "\n}\n");
658 fclose(out_file);
26daeba4 659 g_slist_free(list);
abfd9ce3
AS
660}
661
93062e23 662static uint32_t calculate_new_instance_id(const char *idstr)
8718e999
JQ
663{
664 SaveStateEntry *se;
93062e23 665 uint32_t instance_id = 0;
8718e999 666
0163a2e0 667 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
8718e999
JQ
668 if (strcmp(idstr, se->idstr) == 0
669 && instance_id <= se->instance_id) {
670 instance_id = se->instance_id + 1;
671 }
672 }
93062e23
PX
673 /* Make sure we never loop over without being noticed */
674 assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
8718e999
JQ
675 return instance_id;
676}
677
7685ee6a
AW
678static int calculate_compat_instance_id(const char *idstr)
679{
680 SaveStateEntry *se;
681 int instance_id = 0;
682
0163a2e0 683 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
38ff78d3 684 if (!se->compat) {
7685ee6a 685 continue;
38ff78d3 686 }
7685ee6a
AW
687
688 if (strcmp(idstr, se->compat->idstr) == 0
689 && instance_id <= se->compat->instance_id) {
690 instance_id = se->compat->instance_id + 1;
691 }
692 }
693 return instance_id;
694}
695
f37bc036
PX
696static inline MigrationPriority save_state_priority(SaveStateEntry *se)
697{
698 if (se->vmsd) {
699 return se->vmsd->priority;
700 }
701 return MIG_PRI_DEFAULT;
702}
703
704static void savevm_state_handler_insert(SaveStateEntry *nse)
705{
706 MigrationPriority priority = save_state_priority(nse);
707 SaveStateEntry *se;
174723ff 708 int i;
f37bc036
PX
709
710 assert(priority <= MIG_PRI_MAX);
711
174723ff
SC
712 for (i = priority - 1; i >= 0; i--) {
713 se = savevm_state.handler_pri_head[i];
714 if (se != NULL) {
715 assert(save_state_priority(se) < priority);
f37bc036
PX
716 break;
717 }
718 }
719
174723ff 720 if (i >= 0) {
f37bc036
PX
721 QTAILQ_INSERT_BEFORE(se, nse, entry);
722 } else {
723 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
724 }
174723ff
SC
725
726 if (savevm_state.handler_pri_head[priority] == NULL) {
727 savevm_state.handler_pri_head[priority] = nse;
728 }
f37bc036
PX
729}
730
bd5de61e
SC
731static void savevm_state_handler_remove(SaveStateEntry *se)
732{
174723ff
SC
733 SaveStateEntry *next;
734 MigrationPriority priority = save_state_priority(se);
735
736 if (se == savevm_state.handler_pri_head[priority]) {
737 next = QTAILQ_NEXT(se, entry);
738 if (next != NULL && save_state_priority(next) == priority) {
739 savevm_state.handler_pri_head[priority] = next;
740 } else {
741 savevm_state.handler_pri_head[priority] = NULL;
742 }
743 }
bd5de61e
SC
744 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
745}
746
a672b469
AL
747/* TODO: Individual devices generally have very little idea about the rest
748 of the system, so instance_id should be removed/replaced.
749 Meanwhile pass -1 as instance_id if you do not already have a clearly
750 distinguishing id for all instances of your device class. */
ce62df53 751int register_savevm_live(const char *idstr,
93062e23 752 uint32_t instance_id,
a672b469 753 int version_id,
de22ded0 754 const SaveVMHandlers *ops,
a672b469
AL
755 void *opaque)
756{
8718e999 757 SaveStateEntry *se;
a672b469 758
97f3ad35 759 se = g_new0(SaveStateEntry, 1);
a672b469 760 se->version_id = version_id;
0163a2e0 761 se->section_id = savevm_state.global_section_id++;
7908c78d 762 se->ops = ops;
a672b469 763 se->opaque = opaque;
9ed7d6ae 764 se->vmsd = NULL;
a7ae8355 765 /* if this is a live_savem then set is_ram */
9907e842 766 if (ops->save_setup != NULL) {
a7ae8355
SS
767 se->is_ram = 1;
768 }
a672b469 769
7685ee6a
AW
770 pstrcat(se->idstr, sizeof(se->idstr), idstr);
771
1df2c9a2 772 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
7685ee6a 773 se->instance_id = calculate_new_instance_id(se->idstr);
8718e999
JQ
774 } else {
775 se->instance_id = instance_id;
a672b469 776 }
7685ee6a 777 assert(!se->compat || se->instance_id == 0);
f37bc036 778 savevm_state_handler_insert(se);
a672b469
AL
779 return 0;
780}
781
3cad405b 782void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
41bd13af 783{
8718e999 784 SaveStateEntry *se, *new_se;
7685ee6a
AW
785 char id[256] = "";
786
3cad405b
MAL
787 if (obj) {
788 char *oid = vmstate_if_get_id(obj);
789 if (oid) {
790 pstrcpy(id, sizeof(id), oid);
7685ee6a 791 pstrcat(id, sizeof(id), "/");
3cad405b 792 g_free(oid);
7685ee6a
AW
793 }
794 }
795 pstrcat(id, sizeof(id), idstr);
41bd13af 796
0163a2e0 797 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
7685ee6a 798 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
bd5de61e 799 savevm_state_handler_remove(se);
ef1e1e07 800 g_free(se->compat);
7267c094 801 g_free(se);
41bd13af 802 }
41bd13af
AL
803 }
804}
805
93062e23 806int vmstate_register_with_alias_id(VMStateIf *obj, uint32_t instance_id,
4d2ffa08
JK
807 const VMStateDescription *vmsd,
808 void *opaque, int alias_id,
bc5c4f21
DDAG
809 int required_for_version,
810 Error **errp)
9ed7d6ae 811{
8718e999 812 SaveStateEntry *se;
9ed7d6ae 813
4d2ffa08
JK
814 /* If this triggers, alias support can be dropped for the vmsd. */
815 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
816
97f3ad35 817 se = g_new0(SaveStateEntry, 1);
9ed7d6ae 818 se->version_id = vmsd->version_id;
0163a2e0 819 se->section_id = savevm_state.global_section_id++;
9ed7d6ae
JQ
820 se->opaque = opaque;
821 se->vmsd = vmsd;
4d2ffa08 822 se->alias_id = alias_id;
9ed7d6ae 823
3cad405b
MAL
824 if (obj) {
825 char *id = vmstate_if_get_id(obj);
7685ee6a 826 if (id) {
581f08ba
DDAG
827 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
828 sizeof(se->idstr)) {
829 error_setg(errp, "Path too long for VMState (%s)", id);
830 g_free(id);
831 g_free(se);
832
833 return -1;
834 }
128e4e10 835 g_free(id);
7685ee6a 836
97f3ad35 837 se->compat = g_new0(CompatEntry, 1);
7685ee6a 838 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
1df2c9a2 839 se->compat->instance_id = instance_id == VMSTATE_INSTANCE_ID_ANY ?
7685ee6a 840 calculate_compat_instance_id(vmsd->name) : instance_id;
1df2c9a2 841 instance_id = VMSTATE_INSTANCE_ID_ANY;
7685ee6a
AW
842 }
843 }
844 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
845
1df2c9a2 846 if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
7685ee6a 847 se->instance_id = calculate_new_instance_id(se->idstr);
8718e999
JQ
848 } else {
849 se->instance_id = instance_id;
9ed7d6ae 850 }
7685ee6a 851 assert(!se->compat || se->instance_id == 0);
f37bc036 852 savevm_state_handler_insert(se);
9ed7d6ae
JQ
853 return 0;
854}
855
3cad405b 856void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
0be71e32 857 void *opaque)
9ed7d6ae 858{
1eb7538b
JQ
859 SaveStateEntry *se, *new_se;
860
0163a2e0 861 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
1eb7538b 862 if (se->vmsd == vmsd && se->opaque == opaque) {
bd5de61e 863 savevm_state_handler_remove(se);
ef1e1e07 864 g_free(se->compat);
7267c094 865 g_free(se);
1eb7538b
JQ
866 }
867 }
9ed7d6ae
JQ
868}
869
3a011c26 870static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
4082be4d 871{
9013dca5 872 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
9ed7d6ae 873 if (!se->vmsd) { /* Old style */
3a011c26 874 return se->ops->load_state(f, se->opaque, se->load_version_id);
9ed7d6ae 875 }
3a011c26 876 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
4082be4d
JQ
877}
878
3ddba9a9
MA
879static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
880 JSONWriter *vmdesc)
8118f095
AG
881{
882 int64_t old_offset, size;
883
fbfa6404 884 old_offset = qemu_file_total_transferred_fast(f);
8118f095 885 se->ops->save_state(f, se->opaque);
fbfa6404 886 size = qemu_file_total_transferred_fast(f) - old_offset;
8118f095
AG
887
888 if (vmdesc) {
3ddba9a9
MA
889 json_writer_int64(vmdesc, "size", size);
890 json_writer_start_array(vmdesc, "fields");
891 json_writer_start_object(vmdesc, NULL);
892 json_writer_str(vmdesc, "name", "data");
893 json_writer_int64(vmdesc, "size", size);
894 json_writer_str(vmdesc, "type", "buffer");
895 json_writer_end_object(vmdesc);
896 json_writer_end_array(vmdesc);
8118f095
AG
897 }
898}
899
3ddba9a9
MA
900static int vmstate_save(QEMUFile *f, SaveStateEntry *se,
901 JSONWriter *vmdesc)
4082be4d 902{
9013dca5 903 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
8118f095
AG
904 if (!se->vmsd) {
905 vmstate_save_old_style(f, se, vmdesc);
687433f6 906 return 0;
9ed7d6ae 907 }
687433f6 908 return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
4082be4d
JQ
909}
910
ce39bfc9
DDAG
911/*
912 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
913 */
914static void save_section_header(QEMUFile *f, SaveStateEntry *se,
915 uint8_t section_type)
916{
917 qemu_put_byte(f, section_type);
918 qemu_put_be32(f, se->section_id);
919
920 if (section_type == QEMU_VM_SECTION_FULL ||
921 section_type == QEMU_VM_SECTION_START) {
922 /* ID string */
923 size_t len = strlen(se->idstr);
924 qemu_put_byte(f, len);
925 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
926
927 qemu_put_be32(f, se->instance_id);
928 qemu_put_be32(f, se->version_id);
929 }
930}
931
f68945d4
DDAG
932/*
933 * Write a footer onto device sections that catches cases misformatted device
934 * sections.
935 */
936static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
937{
15c38503 938 if (migrate_get_current()->send_section_footer) {
f68945d4
DDAG
939 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
940 qemu_put_be32(f, se->section_id);
941 }
942}
943
c76ca188
DDAG
944/**
945 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
946 * command and associated data.
947 *
948 * @f: File to send command on
949 * @command: Command type to send
950 * @len: Length of associated data
951 * @data: Data associated with command.
952 */
20a519a0
JQ
953static void qemu_savevm_command_send(QEMUFile *f,
954 enum qemu_vm_cmd command,
955 uint16_t len,
956 uint8_t *data)
c76ca188
DDAG
957{
958 trace_savevm_command_send(command, len);
959 qemu_put_byte(f, QEMU_VM_COMMAND);
960 qemu_put_be16(f, (uint16_t)command);
961 qemu_put_be16(f, len);
962 qemu_put_buffer(f, data, len);
963 qemu_fflush(f);
964}
965
aad555c2
ZC
966void qemu_savevm_send_colo_enable(QEMUFile *f)
967{
968 trace_savevm_send_colo_enable();
969 qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
970}
971
2e37701e
DDAG
972void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
973{
974 uint32_t buf;
975
976 trace_savevm_send_ping(value);
977 buf = cpu_to_be32(value);
978 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
979}
980
981void qemu_savevm_send_open_return_path(QEMUFile *f)
982{
983 trace_savevm_send_open_return_path();
984 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
985}
986
11cf1d98
DDAG
987/* We have a buffer of data to send; we don't want that all to be loaded
988 * by the command itself, so the command contains just the length of the
989 * extra buffer that we then send straight after it.
990 * TODO: Must be a better way to organise that
991 *
992 * Returns:
993 * 0 on success
994 * -ve on error
995 */
61b67d47 996int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
11cf1d98 997{
11cf1d98
DDAG
998 uint32_t tmp;
999
1000 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1001 error_report("%s: Unreasonably large packaged state: %zu",
1002 __func__, len);
1003 return -1;
1004 }
1005
1006 tmp = cpu_to_be32(len);
1007
1008 trace_qemu_savevm_send_packaged();
1009 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1010
61b67d47 1011 qemu_put_buffer(f, buf, len);
11cf1d98
DDAG
1012
1013 return 0;
1014}
1015
093e3c42
DDAG
1016/* Send prior to any postcopy transfer */
1017void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1018{
58110f0a
VSO
1019 if (migrate_postcopy_ram()) {
1020 uint64_t tmp[2];
1021 tmp[0] = cpu_to_be64(ram_pagesize_summary());
1022 tmp[1] = cpu_to_be64(qemu_target_page_size());
1023
1024 trace_qemu_savevm_send_postcopy_advise();
1025 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1026 16, (uint8_t *)tmp);
1027 } else {
1028 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1029 }
093e3c42
DDAG
1030}
1031
1032/* Sent prior to starting the destination running in postcopy, discard pages
1033 * that have already been sent but redirtied on the source.
1034 * CMD_POSTCOPY_RAM_DISCARD consist of:
1035 * byte version (0)
1036 * byte Length of name field (not including 0)
1037 * n x byte RAM block name
1038 * byte 0 terminator (just for safety)
1039 * n x Byte ranges within the named RAMBlock
1040 * be64 Start of the range
1041 * be64 Length
1042 *
1043 * name: RAMBlock name that these entries are part of
1044 * len: Number of page entries
1045 * start_list: 'len' addresses
1046 * length_list: 'len' addresses
1047 *
1048 */
1049void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1050 uint16_t len,
1051 uint64_t *start_list,
1052 uint64_t *length_list)
1053{
1054 uint8_t *buf;
1055 uint16_t tmplen;
1056 uint16_t t;
1057 size_t name_len = strlen(name);
1058
1059 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1060 assert(name_len < 256);
1061 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1062 buf[0] = postcopy_ram_discard_version;
1063 buf[1] = name_len;
1064 memcpy(buf + 2, name, name_len);
1065 tmplen = 2 + name_len;
1066 buf[tmplen++] = '\0';
1067
1068 for (t = 0; t < len; t++) {
4d885131 1069 stq_be_p(buf + tmplen, start_list[t]);
093e3c42 1070 tmplen += 8;
4d885131 1071 stq_be_p(buf + tmplen, length_list[t]);
093e3c42
DDAG
1072 tmplen += 8;
1073 }
1074 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1075 g_free(buf);
1076}
1077
1078/* Get the destination into a state where it can receive postcopy data. */
1079void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1080{
1081 trace_savevm_send_postcopy_listen();
1082 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1083}
1084
1085/* Kick the destination into running */
1086void qemu_savevm_send_postcopy_run(QEMUFile *f)
1087{
1088 trace_savevm_send_postcopy_run();
1089 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1090}
1091
3f5875ec
PX
1092void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1093{
1094 trace_savevm_send_postcopy_resume();
1095 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1096}
1097
f25d4225
PX
1098void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1099{
1100 size_t len;
1101 char buf[256];
1102
1103 trace_savevm_send_recv_bitmap(block_name);
1104
1105 buf[0] = len = strlen(block_name);
1106 memcpy(buf + 1, block_name, len);
1107
1108 qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1109}
1110
e1c37d0e 1111bool qemu_savevm_state_blocked(Error **errp)
dc912121
AW
1112{
1113 SaveStateEntry *se;
1114
0163a2e0 1115 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
7d854c47 1116 if (se->vmsd && se->vmsd->unmigratable) {
f231b88d
CR
1117 error_setg(errp, "State blocked by non-migratable device '%s'",
1118 se->idstr);
dc912121
AW
1119 return true;
1120 }
1121 }
1122 return false;
1123}
1124
3af8554b
DDAG
1125void qemu_savevm_non_migratable_list(strList **reasons)
1126{
1127 SaveStateEntry *se;
1128
1129 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1130 if (se->vmsd && se->vmsd->unmigratable) {
1131 QAPI_LIST_PREPEND(*reasons,
1132 g_strdup_printf("non-migratable device: %s",
1133 se->idstr));
1134 }
1135 }
1136}
1137
f796baa1
DDAG
1138void qemu_savevm_state_header(QEMUFile *f)
1139{
1140 trace_savevm_state_header();
1141 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1142 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
172dfd4f 1143
4ffdb337 1144 if (migrate_get_current()->send_configuration) {
172dfd4f
DDAG
1145 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1146 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1147 }
f796baa1
DDAG
1148}
1149
d05de9e3 1150bool qemu_savevm_state_guest_unplug_pending(void)
c7e0acd5
JF
1151{
1152 SaveStateEntry *se;
c7e0acd5
JF
1153
1154 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
284f42a5
JF
1155 if (se->vmsd && se->vmsd->dev_unplug_pending &&
1156 se->vmsd->dev_unplug_pending(se->opaque)) {
d05de9e3 1157 return true;
c7e0acd5
JF
1158 }
1159 }
1160
d05de9e3 1161 return false;
c7e0acd5
JF
1162}
1163
9907e842 1164void qemu_savevm_state_setup(QEMUFile *f)
a672b469
AL
1165{
1166 SaveStateEntry *se;
bd227060 1167 Error *local_err = NULL;
39346385 1168 int ret;
a672b469 1169
9907e842 1170 trace_savevm_state_setup();
0163a2e0 1171 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
9907e842 1172 if (!se->ops || !se->ops->save_setup) {
a672b469 1173 continue;
22ea40f4 1174 }
cea3b4c0 1175 if (se->ops->is_active) {
6bd68781
JQ
1176 if (!se->ops->is_active(se->opaque)) {
1177 continue;
1178 }
1179 }
ce39bfc9 1180 save_section_header(f, se, QEMU_VM_SECTION_START);
a672b469 1181
9907e842 1182 ret = se->ops->save_setup(f, se->opaque);
f68945d4 1183 save_section_footer(f, se);
2975725f 1184 if (ret < 0) {
47c8c17a
PB
1185 qemu_file_set_error(f, ret);
1186 break;
2975725f 1187 }
a672b469 1188 }
bd227060
WW
1189
1190 if (precopy_notify(PRECOPY_NOTIFY_SETUP, &local_err)) {
1191 error_report_err(local_err);
1192 }
a672b469
AL
1193}
1194
d1b8eadb
PX
1195int qemu_savevm_state_resume_prepare(MigrationState *s)
1196{
1197 SaveStateEntry *se;
1198 int ret;
1199
1200 trace_savevm_state_resume_prepare();
1201
1202 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1203 if (!se->ops || !se->ops->resume_prepare) {
1204 continue;
1205 }
cea3b4c0 1206 if (se->ops->is_active) {
d1b8eadb
PX
1207 if (!se->ops->is_active(se->opaque)) {
1208 continue;
1209 }
1210 }
1211 ret = se->ops->resume_prepare(s, se->opaque);
1212 if (ret < 0) {
1213 return ret;
1214 }
1215 }
1216
1217 return 0;
1218}
1219
39346385 1220/*
07f35073 1221 * this function has three return values:
39346385
JQ
1222 * negative: there was one error, and we have -errno.
1223 * 0 : We haven't finished, caller have to go again
1224 * 1 : We have finished, we can go to complete phase
1225 */
35ecd943 1226int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
a672b469
AL
1227{
1228 SaveStateEntry *se;
1229 int ret = 1;
1230
9013dca5 1231 trace_savevm_state_iterate();
0163a2e0 1232 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
16310a3c 1233 if (!se->ops || !se->ops->save_live_iterate) {
a672b469 1234 continue;
22ea40f4 1235 }
a94cd7b8
WY
1236 if (se->ops->is_active &&
1237 !se->ops->is_active(se->opaque)) {
1238 continue;
6bd68781 1239 }
a94cd7b8
WY
1240 if (se->ops->is_active_iterate &&
1241 !se->ops->is_active_iterate(se->opaque)) {
1242 continue;
c865d848 1243 }
35ecd943
DDAG
1244 /*
1245 * In the postcopy phase, any device that doesn't know how to
1246 * do postcopy should have saved it's state in the _complete
1247 * call that's already run, it might get confused if we call
1248 * iterate afterwards.
1249 */
c6467627
VSO
1250 if (postcopy &&
1251 !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
35ecd943
DDAG
1252 continue;
1253 }
aac844ed
JQ
1254 if (qemu_file_rate_limit(f)) {
1255 return 0;
1256 }
464400f6 1257 trace_savevm_section_start(se->idstr, se->section_id);
ce39bfc9
DDAG
1258
1259 save_section_header(f, se, QEMU_VM_SECTION_PART);
a672b469 1260
16310a3c 1261 ret = se->ops->save_live_iterate(f, se->opaque);
a5df2a02 1262 trace_savevm_section_end(se->idstr, se->section_id, ret);
f68945d4 1263 save_section_footer(f, se);
517a13c9 1264
47c8c17a 1265 if (ret < 0) {
92002658
DE
1266 error_report("failed to save SaveStateEntry with id(name): "
1267 "%d(%s): %d",
1268 se->section_id, se->idstr, ret);
47c8c17a
PB
1269 qemu_file_set_error(f, ret);
1270 }
2975725f 1271 if (ret <= 0) {
90697be8
JK
1272 /* Do not proceed to the next vmstate before this one reported
1273 completion of the current stage. This serializes the migration
1274 and reduces the probability that a faster changing state is
1275 synchronized over and over again. */
1276 break;
1277 }
a672b469 1278 }
39346385 1279 return ret;
a672b469
AL
1280}
1281
9850c604
AG
1282static bool should_send_vmdesc(void)
1283{
1284 MachineState *machine = MACHINE(qdev_get_machine());
5727309d 1285 bool in_postcopy = migration_in_postcopy();
8421b205 1286 return !machine->suppress_vmdesc && !in_postcopy;
9850c604
AG
1287}
1288
763c906b
DDAG
1289/*
1290 * Calls the save_live_complete_postcopy methods
1291 * causing the last few pages to be sent immediately and doing any associated
1292 * cleanup.
1293 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1294 * all the other devices, but that happens at the point we switch to postcopy.
1295 */
1296void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1297{
1298 SaveStateEntry *se;
1299 int ret;
1300
1301 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1302 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1303 continue;
1304 }
cea3b4c0 1305 if (se->ops->is_active) {
763c906b
DDAG
1306 if (!se->ops->is_active(se->opaque)) {
1307 continue;
1308 }
1309 }
1310 trace_savevm_section_start(se->idstr, se->section_id);
1311 /* Section type */
1312 qemu_put_byte(f, QEMU_VM_SECTION_END);
1313 qemu_put_be32(f, se->section_id);
1314
1315 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1316 trace_savevm_section_end(se->idstr, se->section_id, ret);
1317 save_section_footer(f, se);
1318 if (ret < 0) {
1319 qemu_file_set_error(f, ret);
1320 return;
1321 }
1322 }
1323
1324 qemu_put_byte(f, QEMU_VM_EOF);
1325 qemu_fflush(f);
1326}
1327
622a80c9 1328static
e326767b 1329int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
a672b469
AL
1330{
1331 SaveStateEntry *se;
2975725f 1332 int ret;
ea375f9a 1333
0163a2e0 1334 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
763c906b 1335 if (!se->ops ||
c6467627
VSO
1336 (in_postcopy && se->ops->has_postcopy &&
1337 se->ops->has_postcopy(se->opaque)) ||
763c906b 1338 !se->ops->save_live_complete_precopy) {
a672b469 1339 continue;
22ea40f4 1340 }
1c0d249d 1341
cea3b4c0 1342 if (se->ops->is_active) {
6bd68781
JQ
1343 if (!se->ops->is_active(se->opaque)) {
1344 continue;
1345 }
1346 }
464400f6 1347 trace_savevm_section_start(se->idstr, se->section_id);
ce39bfc9
DDAG
1348
1349 save_section_header(f, se, QEMU_VM_SECTION_END);
a672b469 1350
a3e06c3d 1351 ret = se->ops->save_live_complete_precopy(f, se->opaque);
a5df2a02 1352 trace_savevm_section_end(se->idstr, se->section_id, ret);
f68945d4 1353 save_section_footer(f, se);
2975725f 1354 if (ret < 0) {
47c8c17a 1355 qemu_file_set_error(f, ret);
a1fbe750 1356 return -1;
2975725f 1357 }
a672b469
AL
1358 }
1359
622a80c9
WY
1360 return 0;
1361}
1362
622a80c9
WY
1363int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1364 bool in_postcopy,
1365 bool inactivate_disks)
1366{
3ddba9a9 1367 g_autoptr(JSONWriter) vmdesc = NULL;
622a80c9
WY
1368 int vmdesc_len;
1369 SaveStateEntry *se;
1370 int ret;
1c0d249d 1371
3ddba9a9
MA
1372 vmdesc = json_writer_new(false);
1373 json_writer_start_object(vmdesc, NULL);
1374 json_writer_int64(vmdesc, "page_size", qemu_target_page_size());
1375 json_writer_start_array(vmdesc, "devices");
0163a2e0 1376 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
a672b469 1377
22ea40f4 1378 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
5cecf414 1379 continue;
22ea40f4 1380 }
df896152
JQ
1381 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1382 trace_savevm_section_skip(se->idstr, se->section_id);
1383 continue;
1384 }
1385
464400f6 1386 trace_savevm_section_start(se->idstr, se->section_id);
8118f095 1387
3ddba9a9
MA
1388 json_writer_start_object(vmdesc, NULL);
1389 json_writer_str(vmdesc, "name", se->idstr);
1390 json_writer_int64(vmdesc, "instance_id", se->instance_id);
8118f095 1391
ce39bfc9 1392 save_section_header(f, se, QEMU_VM_SECTION_FULL);
687433f6
DDAG
1393 ret = vmstate_save(f, se, vmdesc);
1394 if (ret) {
1395 qemu_file_set_error(f, ret);
1396 return ret;
1397 }
a5df2a02 1398 trace_savevm_section_end(se->idstr, se->section_id, 0);
f68945d4 1399 save_section_footer(f, se);
bdf46d64 1400
3ddba9a9 1401 json_writer_end_object(vmdesc);
a672b469
AL
1402 }
1403
a1fbe750
FZ
1404 if (inactivate_disks) {
1405 /* Inactivate before sending QEMU_VM_EOF so that the
3b717194 1406 * bdrv_activate_all() on the other end won't fail. */
a1fbe750
FZ
1407 ret = bdrv_inactivate_all();
1408 if (ret) {
c232bf58
DDAG
1409 error_report("%s: bdrv_inactivate_all() failed (%d)",
1410 __func__, ret);
a1fbe750
FZ
1411 qemu_file_set_error(f, ret);
1412 return ret;
1413 }
1414 }
763c906b
DDAG
1415 if (!in_postcopy) {
1416 /* Postcopy stream will still be going */
1417 qemu_put_byte(f, QEMU_VM_EOF);
1418 }
8118f095 1419
3ddba9a9
MA
1420 json_writer_end_array(vmdesc);
1421 json_writer_end_object(vmdesc);
1422 vmdesc_len = strlen(json_writer_get(vmdesc));
8118f095 1423
9850c604
AG
1424 if (should_send_vmdesc()) {
1425 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1426 qemu_put_be32(f, vmdesc_len);
3ddba9a9 1427 qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
9850c604 1428 }
8118f095 1429
622a80c9
WY
1430 return 0;
1431}
1432
1433int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1434 bool inactivate_disks)
1435{
1436 int ret;
1437 Error *local_err = NULL;
1438 bool in_postcopy = migration_in_postcopy();
1439
1440 if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1441 error_report_err(local_err);
1442 }
1443
1444 trace_savevm_state_complete_precopy();
1445
1446 cpu_synchronize_all_states();
1447
e326767b
WY
1448 if (!in_postcopy || iterable_only) {
1449 ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1450 if (ret) {
1451 return ret;
1452 }
622a80c9
WY
1453 }
1454
1455 if (iterable_only) {
1456 goto flush;
1457 }
1458
1459 ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1460 inactivate_disks);
1461 if (ret) {
1462 return ret;
1463 }
1464
4e455d51 1465flush:
edaae611 1466 qemu_fflush(f);
a1fbe750 1467 return 0;
a672b469
AL
1468}
1469
c31b098f
DDAG
1470/* Give an estimate of the amount left to be transferred,
1471 * the result is split into the amount for units that can and
1472 * for units that can't do postcopy.
1473 */
faec066a 1474void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
47995026
VSO
1475 uint64_t *res_precopy_only,
1476 uint64_t *res_compatible,
1477 uint64_t *res_postcopy_only)
e4ed1541
JQ
1478{
1479 SaveStateEntry *se;
c31b098f 1480
47995026
VSO
1481 *res_precopy_only = 0;
1482 *res_compatible = 0;
1483 *res_postcopy_only = 0;
c31b098f 1484
e4ed1541 1485
0163a2e0 1486 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
e4ed1541
JQ
1487 if (!se->ops || !se->ops->save_live_pending) {
1488 continue;
1489 }
cea3b4c0 1490 if (se->ops->is_active) {
e4ed1541
JQ
1491 if (!se->ops->is_active(se->opaque)) {
1492 continue;
1493 }
1494 }
faec066a 1495 se->ops->save_live_pending(f, se->opaque, threshold_size,
47995026
VSO
1496 res_precopy_only, res_compatible,
1497 res_postcopy_only);
e4ed1541 1498 }
e4ed1541
JQ
1499}
1500
ea7415fa 1501void qemu_savevm_state_cleanup(void)
4ec7fcc7
JK
1502{
1503 SaveStateEntry *se;
bd227060
WW
1504 Error *local_err = NULL;
1505
1506 if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1507 error_report_err(local_err);
1508 }
4ec7fcc7 1509
ea7415fa 1510 trace_savevm_state_cleanup();
0163a2e0 1511 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
70f794fc
JQ
1512 if (se->ops && se->ops->save_cleanup) {
1513 se->ops->save_cleanup(se->opaque);
4ec7fcc7
JK
1514 }
1515 }
1516}
1517
5d80448c 1518static int qemu_savevm_state(QEMUFile *f, Error **errp)
a672b469 1519{
a672b469 1520 int ret;
3e0c8050 1521 MigrationState *ms = migrate_get_current();
6dcf6668 1522 MigrationStatus status;
3e0c8050 1523
392d87e2 1524 if (migration_is_running(ms->state)) {
3d63da16
JL
1525 error_setg(errp, QERR_MIGRATION_ACTIVE);
1526 return -EINVAL;
1527 }
a672b469 1528
ce7c817c
JQ
1529 if (migrate_use_block()) {
1530 error_setg(errp, "Block migration and snapshots are incompatible");
3d63da16 1531 return -EINVAL;
ce7c817c
JQ
1532 }
1533
3d63da16 1534 migrate_init(ms);
87f3bd87 1535 memset(&ram_counters, 0, sizeof(ram_counters));
02abee3d 1536 memset(&compression_counters, 0, sizeof(compression_counters));
3d63da16
JL
1537 ms->to_dst_file = f;
1538
9b095037 1539 qemu_mutex_unlock_iothread();
f796baa1 1540 qemu_savevm_state_header(f);
9907e842 1541 qemu_savevm_state_setup(f);
9b095037
PB
1542 qemu_mutex_lock_iothread();
1543
47c8c17a 1544 while (qemu_file_get_error(f) == 0) {
35ecd943 1545 if (qemu_savevm_state_iterate(f, false) > 0) {
47c8c17a
PB
1546 break;
1547 }
1548 }
a672b469 1549
47c8c17a 1550 ret = qemu_file_get_error(f);
39346385 1551 if (ret == 0) {
a1fbe750 1552 qemu_savevm_state_complete_precopy(f, false, false);
624b9cc2 1553 ret = qemu_file_get_error(f);
39346385 1554 }
15b3b8ea 1555 qemu_savevm_state_cleanup();
04943eba 1556 if (ret != 0) {
5d80448c 1557 error_setg_errno(errp, -ret, "Error while writing VM state");
04943eba 1558 }
6dcf6668 1559
6dcf6668
DL
1560 if (ret != 0) {
1561 status = MIGRATION_STATUS_FAILED;
1562 } else {
1563 status = MIGRATION_STATUS_COMPLETED;
1564 }
1565 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
f9c8caa0
VSO
1566
1567 /* f is outer parameter, it should not stay in global migration state after
1568 * this function finished */
1569 ms->to_dst_file = NULL;
1570
a672b469
AL
1571 return ret;
1572}
1573
3f6df99d 1574void qemu_savevm_live_state(QEMUFile *f)
a7ae8355 1575{
3f6df99d
ZC
1576 /* save QEMU_VM_SECTION_END section */
1577 qemu_savevm_state_complete_precopy(f, true, false);
1578 qemu_put_byte(f, QEMU_VM_EOF);
1579}
a7ae8355 1580
3f6df99d
ZC
1581int qemu_save_device_state(QEMUFile *f)
1582{
1583 SaveStateEntry *se;
a7ae8355 1584
3f6df99d
ZC
1585 if (!migration_in_colo_state()) {
1586 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1587 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1588 }
a7ae8355
SS
1589 cpu_synchronize_all_states();
1590
0163a2e0 1591 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
687433f6
DDAG
1592 int ret;
1593
a7ae8355
SS
1594 if (se->is_ram) {
1595 continue;
1596 }
22ea40f4 1597 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
a7ae8355
SS
1598 continue;
1599 }
df896152
JQ
1600 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1601 continue;
1602 }
a7ae8355 1603
ce39bfc9 1604 save_section_header(f, se, QEMU_VM_SECTION_FULL);
a7ae8355 1605
687433f6
DDAG
1606 ret = vmstate_save(f, se, NULL);
1607 if (ret) {
1608 return ret;
1609 }
f68945d4
DDAG
1610
1611 save_section_footer(f, se);
a7ae8355
SS
1612 }
1613
1614 qemu_put_byte(f, QEMU_VM_EOF);
1615
1616 return qemu_file_get_error(f);
1617}
1618
93062e23 1619static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
a672b469
AL
1620{
1621 SaveStateEntry *se;
1622
0163a2e0 1623 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
a672b469 1624 if (!strcmp(se->idstr, idstr) &&
4d2ffa08
JK
1625 (instance_id == se->instance_id ||
1626 instance_id == se->alias_id))
a672b469 1627 return se;
7685ee6a
AW
1628 /* Migrating from an older version? */
1629 if (strstr(se->idstr, idstr) && se->compat) {
1630 if (!strcmp(se->compat->idstr, idstr) &&
1631 (instance_id == se->compat->instance_id ||
1632 instance_id == se->alias_id))
1633 return se;
1634 }
a672b469
AL
1635 }
1636 return NULL;
1637}
1638
7b89bf27
DDAG
1639enum LoadVMExitCodes {
1640 /* Allow a command to quit all layers of nested loadvm loops */
1641 LOADVM_QUIT = 1,
1642};
1643
093e3c42
DDAG
1644/* ------ incoming postcopy messages ------ */
1645/* 'advise' arrives before any transfers just to tell us that a postcopy
1646 * *might* happen - it might be skipped if precopy transferred everything
1647 * quickly.
1648 */
875fcd01
GK
1649static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1650 uint16_t len)
093e3c42
DDAG
1651{
1652 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
e8ca1db2 1653 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
144fa06b 1654 size_t page_size = qemu_target_page_size();
d3dff7a5 1655 Error *local_err = NULL;
093e3c42
DDAG
1656
1657 trace_loadvm_postcopy_handle_advise();
1658 if (ps != POSTCOPY_INCOMING_NONE) {
1659 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1660 return -1;
1661 }
1662
875fcd01
GK
1663 switch (len) {
1664 case 0:
1665 if (migrate_postcopy_ram()) {
1666 error_report("RAM postcopy is enabled but have 0 byte advise");
1667 return -EINVAL;
1668 }
58110f0a 1669 return 0;
875fcd01
GK
1670 case 8 + 8:
1671 if (!migrate_postcopy_ram()) {
1672 error_report("RAM postcopy is disabled but have 16 byte advise");
1673 return -EINVAL;
1674 }
1675 break;
1676 default:
1677 error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1678 return -EINVAL;
58110f0a
VSO
1679 }
1680
d7651f15 1681 if (!postcopy_ram_supported_by_host(mis)) {
328d4d85 1682 postcopy_state_set(POSTCOPY_INCOMING_NONE);
eb59db53
DDAG
1683 return -1;
1684 }
1685
e8ca1db2
DDAG
1686 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1687 local_pagesize_summary = ram_pagesize_summary();
1688
1689 if (remote_pagesize_summary != local_pagesize_summary) {
093e3c42 1690 /*
e8ca1db2
DDAG
1691 * This detects two potential causes of mismatch:
1692 * a) A mismatch in host page sizes
1693 * Some combinations of mismatch are probably possible but it gets
1694 * a bit more complicated. In particular we need to place whole
1695 * host pages on the dest at once, and we need to ensure that we
1696 * handle dirtying to make sure we never end up sending part of
1697 * a hostpage on it's own.
1698 * b) The use of different huge page sizes on source/destination
1699 * a more fine grain test is performed during RAM block migration
1700 * but this test here causes a nice early clear failure, and
1701 * also fails when passed to an older qemu that doesn't
1702 * do huge pages.
093e3c42 1703 */
e8ca1db2
DDAG
1704 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1705 " d=%" PRIx64 ")",
1706 remote_pagesize_summary, local_pagesize_summary);
093e3c42
DDAG
1707 return -1;
1708 }
1709
1710 remote_tps = qemu_get_be64(mis->from_src_file);
144fa06b 1711 if (remote_tps != page_size) {
093e3c42
DDAG
1712 /*
1713 * Again, some differences could be dealt with, but for now keep it
1714 * simple.
1715 */
20afaed9 1716 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
144fa06b 1717 (int)remote_tps, page_size);
093e3c42
DDAG
1718 return -1;
1719 }
1720
d3dff7a5
DDAG
1721 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1722 error_report_err(local_err);
1723 return -1;
1724 }
1725
1caddf8a
DDAG
1726 if (ram_postcopy_incoming_init(mis)) {
1727 return -1;
1728 }
1729
093e3c42
DDAG
1730 return 0;
1731}
1732
1733/* After postcopy we will be told to throw some pages away since they're
1734 * dirty and will have to be demand fetched. Must happen before CPU is
1735 * started.
1736 * There can be 0..many of these messages, each encoding multiple pages.
1737 */
1738static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1739 uint16_t len)
1740{
1741 int tmp;
1742 char ramid[256];
1743 PostcopyState ps = postcopy_state_get();
1744
1745 trace_loadvm_postcopy_ram_handle_discard();
1746
1747 switch (ps) {
1748 case POSTCOPY_INCOMING_ADVISE:
1749 /* 1st discard */
f9527107 1750 tmp = postcopy_ram_prepare_discard(mis);
093e3c42
DDAG
1751 if (tmp) {
1752 return tmp;
1753 }
1754 break;
1755
1756 case POSTCOPY_INCOMING_DISCARD:
1757 /* Expected state */
1758 break;
1759
1760 default:
1761 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1762 ps);
1763 return -1;
1764 }
1765 /* We're expecting a
1766 * Version (0)
1767 * a RAM ID string (length byte, name, 0 term)
1768 * then at least 1 16 byte chunk
1769 */
1770 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1771 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1772 return -1;
1773 }
1774
1775 tmp = qemu_get_byte(mis->from_src_file);
1776 if (tmp != postcopy_ram_discard_version) {
1777 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1778 return -1;
1779 }
1780
1781 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1782 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1783 return -1;
1784 }
1785 tmp = qemu_get_byte(mis->from_src_file);
1786 if (tmp != 0) {
1787 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1788 return -1;
1789 }
1790
1791 len -= 3 + strlen(ramid);
1792 if (len % 16) {
1793 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1794 return -1;
1795 }
1796 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1797 while (len) {
093e3c42
DDAG
1798 uint64_t start_addr, block_length;
1799 start_addr = qemu_get_be64(mis->from_src_file);
1800 block_length = qemu_get_be64(mis->from_src_file);
1801
1802 len -= 16;
aaa2064c 1803 int ret = ram_discard_range(ramid, start_addr, block_length);
093e3c42
DDAG
1804 if (ret) {
1805 return ret;
1806 }
093e3c42
DDAG
1807 }
1808 trace_loadvm_postcopy_ram_handle_discard_end();
1809
1810 return 0;
1811}
1812
c76201ab
DDAG
1813/*
1814 * Triggered by a postcopy_listen command; this thread takes over reading
1815 * the input stream, leaving the main thread free to carry on loading the rest
1816 * of the device state (from RAM).
1817 * (TODO:This could do with being in a postcopy file - but there again it's
1818 * just another input loop, not that postcopy specific)
1819 */
1820static void *postcopy_ram_listen_thread(void *opaque)
1821{
c76201ab 1822 MigrationIncomingState *mis = migration_incoming_get_current();
b411b844 1823 QEMUFile *f = mis->from_src_file;
c76201ab 1824 int load_res;
ee647225
VSO
1825 MigrationState *migr = migrate_get_current();
1826
1827 object_ref(OBJECT(migr));
c76201ab 1828
6ba996bb
DDAG
1829 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1830 MIGRATION_STATUS_POSTCOPY_ACTIVE);
095c12a4 1831 qemu_sem_post(&mis->thread_sync_sem);
c76201ab
DDAG
1832 trace_postcopy_ram_listen_thread_start();
1833
74637e6f 1834 rcu_register_thread();
c76201ab
DDAG
1835 /*
1836 * Because we're a thread and not a coroutine we can't yield
1837 * in qemu_file, and thus we must be blocking now.
1838 */
1839 qemu_file_set_blocking(f, true);
1840 load_res = qemu_loadvm_state_main(f, mis);
b411b844
PX
1841
1842 /*
1843 * This is tricky, but, mis->from_src_file can change after it
1844 * returns, when postcopy recovery happened. In the future, we may
1845 * want a wrapper for the QEMUFile handle.
1846 */
1847 f = mis->from_src_file;
1848
c76201ab
DDAG
1849 /* And non-blocking again so we don't block in any cleanup */
1850 qemu_file_set_blocking(f, false);
1851
1852 trace_postcopy_ram_listen_thread_exit();
1853 if (load_res < 0) {
c76201ab 1854 qemu_file_set_error(f, load_res);
ee647225
VSO
1855 dirty_bitmap_mig_cancel_incoming();
1856 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
1857 !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1858 {
1859 error_report("%s: loadvm failed during postcopy: %d. All states "
1860 "are migrated except dirty bitmaps. Some dirty "
1861 "bitmaps may be lost, and present migrated dirty "
1862 "bitmaps are correctly migrated and valid.",
1863 __func__, load_res);
1864 load_res = 0; /* prevent further exit() */
1865 } else {
1866 error_report("%s: loadvm failed: %d", __func__, load_res);
1867 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1868 MIGRATION_STATUS_FAILED);
1869 }
1870 }
1871 if (load_res >= 0) {
c76201ab
DDAG
1872 /*
1873 * This looks good, but it's possible that the device loading in the
1874 * main thread hasn't finished yet, and so we might not be in 'RUN'
1875 * state yet; wait for the end of the main thread.
1876 */
1877 qemu_event_wait(&mis->main_thread_load_event);
1878 }
1879 postcopy_ram_incoming_cleanup(mis);
c76201ab
DDAG
1880
1881 if (load_res < 0) {
1882 /*
1883 * If something went wrong then we have a bad state so exit;
1884 * depending how far we got it might be possible at this point
1885 * to leave the guest running and fire MCEs for pages that never
1886 * arrived as a desperate recovery step.
1887 */
74637e6f 1888 rcu_unregister_thread();
c76201ab
DDAG
1889 exit(EXIT_FAILURE);
1890 }
1891
6ba996bb
DDAG
1892 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1893 MIGRATION_STATUS_COMPLETED);
1894 /*
1895 * If everything has worked fine, then the main thread has waited
1896 * for us to start, and we're the last use of the mis.
1897 * (If something broke then qemu will have to exit anyway since it's
1898 * got a bad migration state).
1899 */
1900 migration_incoming_state_destroy();
acb5ea86 1901 qemu_loadvm_state_cleanup();
6ba996bb 1902
74637e6f 1903 rcu_unregister_thread();
9cf4bb87 1904 mis->have_listen_thread = false;
2d49bacd
WY
1905 postcopy_state_set(POSTCOPY_INCOMING_END);
1906
ee647225
VSO
1907 object_unref(OBJECT(migr));
1908
c76201ab
DDAG
1909 return NULL;
1910}
1911
093e3c42
DDAG
1912/* After this message we must be able to immediately receive postcopy data */
1913static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1914{
1915 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
6864a7b5
DDAG
1916 Error *local_err = NULL;
1917
c84f976e
PX
1918 trace_loadvm_postcopy_handle_listen("enter");
1919
093e3c42
DDAG
1920 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1921 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1922 return -1;
1923 }
f9527107
DDAG
1924 if (ps == POSTCOPY_INCOMING_ADVISE) {
1925 /*
1926 * A rare case, we entered listen without having to do any discards,
1927 * so do the setup that's normally done at the time of the 1st discard.
1928 */
58110f0a
VSO
1929 if (migrate_postcopy_ram()) {
1930 postcopy_ram_prepare_discard(mis);
1931 }
f9527107 1932 }
093e3c42 1933
c84f976e
PX
1934 trace_loadvm_postcopy_handle_listen("after discard");
1935
f0a227ad
DDAG
1936 /*
1937 * Sensitise RAM - can now generate requests for blocks that don't exist
1938 * However, at this point the CPU shouldn't be running, and the IO
1939 * shouldn't be doing anything yet so don't actually expect requests
1940 */
58110f0a 1941 if (migrate_postcopy_ram()) {
2a7eb148 1942 if (postcopy_ram_incoming_setup(mis)) {
91b02dc7 1943 postcopy_ram_incoming_cleanup(mis);
58110f0a
VSO
1944 return -1;
1945 }
f0a227ad
DDAG
1946 }
1947
c84f976e
PX
1948 trace_loadvm_postcopy_handle_listen("after uffd");
1949
6864a7b5
DDAG
1950 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1951 error_report_err(local_err);
1952 return -1;
1953 }
1954
c76201ab 1955 mis->have_listen_thread = true;
095c12a4
PX
1956 postcopy_thread_create(mis, &mis->listen_thread, "postcopy/listen",
1957 postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
c84f976e
PX
1958 trace_loadvm_postcopy_handle_listen("return");
1959
093e3c42
DDAG
1960 return 0;
1961}
1962
ea6a55bc 1963static void loadvm_postcopy_handle_run_bh(void *opaque)
093e3c42 1964{
27c6825b 1965 Error *local_err = NULL;
1ce54262 1966 MigrationIncomingState *mis = opaque;
093e3c42 1967
b9a040b9
PX
1968 trace_loadvm_postcopy_handle_run_bh("enter");
1969
27c6825b
DDAG
1970 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1971 * in migration.c
1972 */
1973 cpu_synchronize_all_post_init();
1974
b9a040b9
PX
1975 trace_loadvm_postcopy_handle_run_bh("after cpu sync");
1976
7659505c 1977 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
27c6825b 1978
b9a040b9
PX
1979 trace_loadvm_postcopy_handle_run_bh("after announce");
1980
3b717194 1981 /* Make sure all file formats throw away their mutable metadata.
ace21a58 1982 * If we get an error here, just don't restart the VM yet. */
3b717194 1983 bdrv_activate_all(&local_err);
0042fd36 1984 if (local_err) {
ace21a58 1985 error_report_err(local_err);
0042fd36
KW
1986 local_err = NULL;
1987 autostart = false;
1988 }
1989
b9a040b9 1990 trace_loadvm_postcopy_handle_run_bh("after invalidate cache");
27c6825b 1991
b35ebdf0
VSO
1992 dirty_bitmap_mig_before_vm_start();
1993
093e3c42
DDAG
1994 if (autostart) {
1995 /* Hold onto your hats, starting the CPU */
1996 vm_start();
1997 } else {
1998 /* leave it paused and let management decide when to start the CPU */
1999 runstate_set(RUN_STATE_PAUSED);
2000 }
2001
1ce54262 2002 qemu_bh_delete(mis->bh);
b9a040b9
PX
2003
2004 trace_loadvm_postcopy_handle_run_bh("return");
ea6a55bc
DL
2005}
2006
2007/* After all discards we can start running and asking for pages */
2008static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2009{
0197d890 2010 PostcopyState ps = postcopy_state_get();
ea6a55bc
DL
2011
2012 trace_loadvm_postcopy_handle_run();
2013 if (ps != POSTCOPY_INCOMING_LISTENING) {
2014 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2015 return -1;
2016 }
2017
0197d890 2018 postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1ce54262
WY
2019 mis->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, mis);
2020 qemu_bh_schedule(mis->bh);
ea6a55bc 2021
27c6825b
DDAG
2022 /* We need to finish reading the stream from the package
2023 * and also stop reading anything more from the stream that loaded the
2024 * package (since it's now being read by the listener thread).
2025 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2026 */
2027 return LOADVM_QUIT;
093e3c42
DDAG
2028}
2029
0c26781c
PX
2030/* We must be with page_request_mutex held */
2031static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2032 gpointer data)
2033{
2034 MigrationIncomingState *mis = data;
2035 void *host_addr = (void *) key;
2036 ram_addr_t rb_offset;
2037 RAMBlock *rb;
2038 int ret;
2039
2040 rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2041 if (!rb) {
2042 /*
2043 * This should _never_ happen. However be nice for a migrating VM to
2044 * not crash/assert. Post an error (note: intended to not use *_once
2045 * because we do want to see all the illegal addresses; and this can
2046 * never be triggered by the guest so we're safe) and move on next.
2047 */
2048 error_report("%s: illegal host addr %p", __func__, host_addr);
2049 /* Try the next entry */
2050 return FALSE;
2051 }
2052
2053 ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2054 if (ret) {
2055 /* Please refer to above comment. */
2056 error_report("%s: send rp message failed for addr %p",
2057 __func__, host_addr);
2058 return FALSE;
2059 }
2060
2061 trace_postcopy_page_req_sync(host_addr);
2062
2063 return FALSE;
2064}
2065
2066static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2067{
2068 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2069 g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2070 }
2071}
2072
3f5875ec
PX
2073static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2074{
2075 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2076 error_report("%s: illegal resume received", __func__);
2077 /* Don't fail the load, only for this. */
2078 return 0;
2079 }
2080
cc5ab872
PX
2081 /*
2082 * Reset the last_rb before we resend any page req to source again, since
2083 * the source should have it reset already.
2084 */
2085 mis->last_rb = NULL;
2086
3f5875ec
PX
2087 /*
2088 * This means source VM is ready to resume the postcopy migration.
3f5875ec
PX
2089 */
2090 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2091 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3f5875ec
PX
2092
2093 trace_loadvm_postcopy_handle_resume();
2094
13955b89
PX
2095 /* Tell source that "we are ready" */
2096 migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
3f5875ec 2097
0c26781c
PX
2098 /*
2099 * After a postcopy recovery, the source should have lost the postcopy
2100 * queue, or potentially the requested pages could have been lost during
2101 * the network down phase. Let's re-sync with the source VM by re-sending
2102 * all the pending pages that we eagerly need, so these threads won't get
2103 * blocked too long due to the recovery.
2104 *
2105 * Without this procedure, the faulted destination VM threads (waiting for
2106 * page requests right before the postcopy is interrupted) can keep hanging
2107 * until the pages are sent by the source during the background copying of
2108 * pages, or another thread faulted on the same address accidentally.
2109 */
2110 migrate_send_rp_req_pages_pending(mis);
2111
5e773431
PX
2112 /*
2113 * It's time to switch state and release the fault thread to continue
2114 * service page faults. Note that this should be explicitly after the
2115 * above call to migrate_send_rp_req_pages_pending(). In short:
2116 * migrate_send_rp_message_req_pages() is not thread safe, yet.
2117 */
2118 qemu_sem_post(&mis->postcopy_pause_sem_fault);
2119
3f5875ec
PX
2120 return 0;
2121}
2122
c76ca188 2123/**
11cf1d98
DDAG
2124 * Immediately following this command is a blob of data containing an embedded
2125 * chunk of migration stream; read it and load it.
2126 *
2127 * @mis: Incoming state
2128 * @length: Length of packaged data to read
c76ca188 2129 *
11cf1d98
DDAG
2130 * Returns: Negative values on error
2131 *
2132 */
2133static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2134{
2135 int ret;
61b67d47
DB
2136 size_t length;
2137 QIOChannelBuffer *bioc;
11cf1d98
DDAG
2138
2139 length = qemu_get_be32(mis->from_src_file);
2140 trace_loadvm_handle_cmd_packaged(length);
2141
2142 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
61b67d47 2143 error_report("Unreasonably large packaged state: %zu", length);
11cf1d98
DDAG
2144 return -1;
2145 }
61b67d47
DB
2146
2147 bioc = qio_channel_buffer_new(length);
6f01f136 2148 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
61b67d47
DB
2149 ret = qemu_get_buffer(mis->from_src_file,
2150 bioc->data,
2151 length);
11cf1d98 2152 if (ret != length) {
61b67d47
DB
2153 object_unref(OBJECT(bioc));
2154 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
9af9e0fe 2155 ret, length);
11cf1d98
DDAG
2156 return (ret < 0) ? ret : -EAGAIN;
2157 }
61b67d47 2158 bioc->usage += length;
11cf1d98
DDAG
2159 trace_loadvm_handle_cmd_packaged_received(ret);
2160
77ef2dc1 2161 QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
11cf1d98
DDAG
2162
2163 ret = qemu_loadvm_state_main(packf, mis);
2164 trace_loadvm_handle_cmd_packaged_main(ret);
2165 qemu_fclose(packf);
61b67d47 2166 object_unref(OBJECT(bioc));
11cf1d98
DDAG
2167
2168 return ret;
2169}
2170
f25d4225
PX
2171/*
2172 * Handle request that source requests for recved_bitmap on
2173 * destination. Payload format:
2174 *
2175 * len (1 byte) + ramblock_name (<255 bytes)
2176 */
2177static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2178 uint16_t len)
2179{
2180 QEMUFile *file = mis->from_src_file;
2181 RAMBlock *rb;
2182 char block_name[256];
2183 size_t cnt;
2184
2185 cnt = qemu_get_counted_string(file, block_name);
2186 if (!cnt) {
2187 error_report("%s: failed to read block name", __func__);
2188 return -EINVAL;
2189 }
2190
2191 /* Validate before using the data */
2192 if (qemu_file_get_error(file)) {
2193 return qemu_file_get_error(file);
2194 }
2195
2196 if (len != cnt + 1) {
2197 error_report("%s: invalid payload length (%d)", __func__, len);
2198 return -EINVAL;
2199 }
2200
2201 rb = qemu_ram_block_by_name(block_name);
2202 if (!rb) {
2203 error_report("%s: block '%s' not found", __func__, block_name);
2204 return -EINVAL;
2205 }
2206
a335debb 2207 migrate_send_rp_recv_bitmap(mis, block_name);
f25d4225
PX
2208
2209 trace_loadvm_handle_recv_bitmap(block_name);
2210
2211 return 0;
2212}
2213
aad555c2
ZC
2214static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2215{
18b1d3c9
DH
2216 int ret = migration_incoming_enable_colo();
2217
2218 if (!ret) {
2219 ret = colo_init_ram_cache();
2220 if (ret) {
2221 migration_incoming_disable_colo();
2222 }
2223 }
2224 return ret;
aad555c2
ZC
2225}
2226
11cf1d98
DDAG
2227/*
2228 * Process an incoming 'QEMU_VM_COMMAND'
2229 * 0 just a normal return
2230 * LOADVM_QUIT All good, but exit the loop
2231 * <0 Error
c76ca188
DDAG
2232 */
2233static int loadvm_process_command(QEMUFile *f)
2234{
2e37701e 2235 MigrationIncomingState *mis = migration_incoming_get_current();
c76ca188
DDAG
2236 uint16_t cmd;
2237 uint16_t len;
2e37701e 2238 uint32_t tmp32;
c76ca188
DDAG
2239
2240 cmd = qemu_get_be16(f);
2241 len = qemu_get_be16(f);
2242
7a9ddfbf
PX
2243 /* Check validity before continue processing of cmds */
2244 if (qemu_file_get_error(f)) {
2245 return qemu_file_get_error(f);
2246 }
2247
c76ca188
DDAG
2248 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2249 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2250 return -EINVAL;
2251 }
2252
a7060ba3
PX
2253 trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2254
c76ca188
DDAG
2255 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2256 error_report("%s received with bad length - expecting %zu, got %d",
2257 mig_cmd_args[cmd].name,
2258 (size_t)mig_cmd_args[cmd].len, len);
2259 return -ERANGE;
2260 }
2261
2262 switch (cmd) {
2e37701e
DDAG
2263 case MIG_CMD_OPEN_RETURN_PATH:
2264 if (mis->to_src_file) {
2265 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2266 /* Not really a problem, so don't give up */
2267 return 0;
2268 }
2269 mis->to_src_file = qemu_file_get_return_path(f);
2270 if (!mis->to_src_file) {
2271 error_report("CMD_OPEN_RETURN_PATH failed");
2272 return -1;
2273 }
2274 break;
2275
2276 case MIG_CMD_PING:
2277 tmp32 = qemu_get_be32(f);
2278 trace_loadvm_process_command_ping(tmp32);
2279 if (!mis->to_src_file) {
2280 error_report("CMD_PING (0x%x) received with no return path",
2281 tmp32);
2282 return -1;
2283 }
6decec93 2284 migrate_send_rp_pong(mis, tmp32);
2e37701e 2285 break;
093e3c42 2286
11cf1d98
DDAG
2287 case MIG_CMD_PACKAGED:
2288 return loadvm_handle_cmd_packaged(mis);
2289
093e3c42 2290 case MIG_CMD_POSTCOPY_ADVISE:
875fcd01 2291 return loadvm_postcopy_handle_advise(mis, len);
093e3c42
DDAG
2292
2293 case MIG_CMD_POSTCOPY_LISTEN:
2294 return loadvm_postcopy_handle_listen(mis);
2295
2296 case MIG_CMD_POSTCOPY_RUN:
2297 return loadvm_postcopy_handle_run(mis);
2298
2299 case MIG_CMD_POSTCOPY_RAM_DISCARD:
2300 return loadvm_postcopy_ram_handle_discard(mis, len);
f25d4225 2301
3f5875ec
PX
2302 case MIG_CMD_POSTCOPY_RESUME:
2303 return loadvm_postcopy_handle_resume(mis);
2304
f25d4225
PX
2305 case MIG_CMD_RECV_BITMAP:
2306 return loadvm_handle_recv_bitmap(mis, len);
aad555c2
ZC
2307
2308 case MIG_CMD_ENABLE_COLO:
2309 return loadvm_process_enable_colo(mis);
c76ca188
DDAG
2310 }
2311
2312 return 0;
2313}
2314
59f39a47
DDAG
2315/*
2316 * Read a footer off the wire and check that it matches the expected section
2317 *
2318 * Returns: true if the footer was good
2319 * false if there is a problem (and calls error_report to say why)
2320 */
0f42f657 2321static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
59f39a47 2322{
7a9ddfbf 2323 int ret;
59f39a47
DDAG
2324 uint8_t read_mark;
2325 uint32_t read_section_id;
2326
15c38503 2327 if (!migrate_get_current()->send_section_footer) {
59f39a47
DDAG
2328 /* No footer to check */
2329 return true;
2330 }
2331
2332 read_mark = qemu_get_byte(f);
2333
7a9ddfbf
PX
2334 ret = qemu_file_get_error(f);
2335 if (ret) {
2336 error_report("%s: Read section footer failed: %d",
2337 __func__, ret);
2338 return false;
2339 }
2340
59f39a47 2341 if (read_mark != QEMU_VM_SECTION_FOOTER) {
0f42f657 2342 error_report("Missing section footer for %s", se->idstr);
59f39a47
DDAG
2343 return false;
2344 }
2345
2346 read_section_id = qemu_get_be32(f);
0f42f657 2347 if (read_section_id != se->load_section_id) {
59f39a47
DDAG
2348 error_report("Mismatched section id in footer for %s -"
2349 " read 0x%x expected 0x%x",
0f42f657 2350 se->idstr, read_section_id, se->load_section_id);
59f39a47
DDAG
2351 return false;
2352 }
2353
2354 /* All good */
2355 return true;
2356}
2357
fb3520a8
HZ
2358static int
2359qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2360{
2361 uint32_t instance_id, version_id, section_id;
2362 SaveStateEntry *se;
fb3520a8
HZ
2363 char idstr[256];
2364 int ret;
2365
2366 /* Read section start */
2367 section_id = qemu_get_be32(f);
2368 if (!qemu_get_counted_string(f, idstr)) {
2369 error_report("Unable to read ID string for section %u",
2370 section_id);
2371 return -EINVAL;
2372 }
2373 instance_id = qemu_get_be32(f);
2374 version_id = qemu_get_be32(f);
2375
7a9ddfbf
PX
2376 ret = qemu_file_get_error(f);
2377 if (ret) {
2378 error_report("%s: Failed to read instance/version ID: %d",
2379 __func__, ret);
2380 return ret;
2381 }
2382
fb3520a8
HZ
2383 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2384 instance_id, version_id);
2385 /* Find savevm section */
2386 se = find_se(idstr, instance_id);
2387 if (se == NULL) {
93062e23 2388 error_report("Unknown savevm section or instance '%s' %"PRIu32". "
827beacb
JRZ
2389 "Make sure that your current VM setup matches your "
2390 "saved VM setup, including any hotplugged devices",
fb3520a8
HZ
2391 idstr, instance_id);
2392 return -EINVAL;
2393 }
2394
2395 /* Validate version */
2396 if (version_id > se->version_id) {
2397 error_report("savevm: unsupported version %d for '%s' v%d",
2398 version_id, idstr, se->version_id);
2399 return -EINVAL;
2400 }
0f42f657
JQ
2401 se->load_version_id = version_id;
2402 se->load_section_id = section_id;
fb3520a8 2403
88c16567
WC
2404 /* Validate if it is a device's state */
2405 if (xen_enabled() && se->is_ram) {
2406 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2407 return -EINVAL;
2408 }
2409
3a011c26 2410 ret = vmstate_load(f, se);
fb3520a8 2411 if (ret < 0) {
93062e23 2412 error_report("error while loading state for instance 0x%"PRIx32" of"
fb3520a8
HZ
2413 " device '%s'", instance_id, idstr);
2414 return ret;
2415 }
0f42f657 2416 if (!check_section_footer(f, se)) {
fb3520a8
HZ
2417 return -EINVAL;
2418 }
2419
2420 return 0;
2421}
2422
2423static int
2424qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2425{
2426 uint32_t section_id;
0f42f657 2427 SaveStateEntry *se;
fb3520a8
HZ
2428 int ret;
2429
2430 section_id = qemu_get_be32(f);
2431
7a9ddfbf
PX
2432 ret = qemu_file_get_error(f);
2433 if (ret) {
2434 error_report("%s: Failed to read section ID: %d",
2435 __func__, ret);
2436 return ret;
2437 }
2438
fb3520a8 2439 trace_qemu_loadvm_state_section_partend(section_id);
0f42f657
JQ
2440 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2441 if (se->load_section_id == section_id) {
fb3520a8
HZ
2442 break;
2443 }
2444 }
0f42f657 2445 if (se == NULL) {
fb3520a8
HZ
2446 error_report("Unknown savevm section %d", section_id);
2447 return -EINVAL;
2448 }
2449
3a011c26 2450 ret = vmstate_load(f, se);
fb3520a8
HZ
2451 if (ret < 0) {
2452 error_report("error while loading state section id %d(%s)",
0f42f657 2453 section_id, se->idstr);
fb3520a8
HZ
2454 return ret;
2455 }
0f42f657 2456 if (!check_section_footer(f, se)) {
fb3520a8
HZ
2457 return -EINVAL;
2458 }
2459
2460 return 0;
2461}
2462
16015d32
WY
2463static int qemu_loadvm_state_header(QEMUFile *f)
2464{
2465 unsigned int v;
2466 int ret;
2467
2468 v = qemu_get_be32(f);
2469 if (v != QEMU_VM_FILE_MAGIC) {
2470 error_report("Not a migration stream");
2471 return -EINVAL;
2472 }
2473
2474 v = qemu_get_be32(f);
2475 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2476 error_report("SaveVM v2 format is obsolete and don't work anymore");
2477 return -ENOTSUP;
2478 }
2479 if (v != QEMU_VM_FILE_VERSION) {
2480 error_report("Unsupported migration stream version");
2481 return -ENOTSUP;
2482 }
2483
2484 if (migrate_get_current()->send_configuration) {
2485 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2486 error_report("Configuration section missing");
2487 qemu_loadvm_state_cleanup();
2488 return -EINVAL;
2489 }
2490 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2491
2492 if (ret) {
2493 qemu_loadvm_state_cleanup();
2494 return ret;
2495 }
2496 }
2497 return 0;
2498}
2499
acb5ea86
JQ
2500static int qemu_loadvm_state_setup(QEMUFile *f)
2501{
2502 SaveStateEntry *se;
2503 int ret;
2504
2505 trace_loadvm_state_setup();
2506 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2507 if (!se->ops || !se->ops->load_setup) {
2508 continue;
2509 }
cea3b4c0 2510 if (se->ops->is_active) {
acb5ea86
JQ
2511 if (!se->ops->is_active(se->opaque)) {
2512 continue;
2513 }
2514 }
2515
2516 ret = se->ops->load_setup(f, se->opaque);
2517 if (ret < 0) {
2518 qemu_file_set_error(f, ret);
2519 error_report("Load state of device %s failed", se->idstr);
2520 return ret;
2521 }
2522 }
2523 return 0;
2524}
2525
2526void qemu_loadvm_state_cleanup(void)
2527{
2528 SaveStateEntry *se;
2529
2530 trace_loadvm_state_cleanup();
2531 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2532 if (se->ops && se->ops->load_cleanup) {
2533 se->ops->load_cleanup(se->opaque);
2534 }
2535 }
2536}
2537
b411b844
PX
2538/* Return true if we should continue the migration, or false. */
2539static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2540{
77dadc3f
PX
2541 int i;
2542
2543 /*
2544 * If network is interrupted, any temp page we received will be useless
2545 * because we didn't mark them as "received" in receivedmap. After a
2546 * proper recovery later (which will sync src dirty bitmap with receivedmap
2547 * on dest) these cached small pages will be resent again.
2548 */
2549 for (i = 0; i < mis->postcopy_channels; i++) {
2550 postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2551 }
2552
b411b844
PX
2553 trace_postcopy_pause_incoming();
2554
ee647225
VSO
2555 assert(migrate_postcopy_ram());
2556
39675fff
PX
2557 /*
2558 * Unregister yank with either from/to src would work, since ioc behind it
2559 * is the same
2560 */
2561 migration_ioc_unregister_yank_from_file(mis->from_src_file);
2562
b411b844
PX
2563 assert(mis->from_src_file);
2564 qemu_file_shutdown(mis->from_src_file);
2565 qemu_fclose(mis->from_src_file);
2566 mis->from_src_file = NULL;
2567
2568 assert(mis->to_src_file);
2569 qemu_file_shutdown(mis->to_src_file);
2570 qemu_mutex_lock(&mis->rp_mutex);
2571 qemu_fclose(mis->to_src_file);
2572 mis->to_src_file = NULL;
2573 qemu_mutex_unlock(&mis->rp_mutex);
2574
eed1cc78
PX
2575 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2576 MIGRATION_STATUS_POSTCOPY_PAUSED);
2577
3a7804c3
PX
2578 /* Notify the fault thread for the invalidated file handle */
2579 postcopy_fault_thread_notify(mis);
2580
b411b844
PX
2581 error_report("Detected IO failure for postcopy. "
2582 "Migration paused.");
2583
2584 while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2585 qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2586 }
2587
2588 trace_postcopy_pause_incoming_continued();
2589
2590 return true;
2591}
2592
3f6df99d 2593int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
1a8f46f8 2594{
a672b469 2595 uint8_t section_type;
ccb783c3 2596 int ret = 0;
61964c23 2597
b411b844 2598retry:
7a9ddfbf
PX
2599 while (true) {
2600 section_type = qemu_get_byte(f);
2601
2602 if (qemu_file_get_error(f)) {
2603 ret = qemu_file_get_error(f);
2604 break;
2605 }
2606
a5df2a02 2607 trace_qemu_loadvm_state_section(section_type);
a672b469
AL
2608 switch (section_type) {
2609 case QEMU_VM_SECTION_START:
2610 case QEMU_VM_SECTION_FULL:
fb3520a8 2611 ret = qemu_loadvm_section_start_full(f, mis);
b5a22e4a 2612 if (ret < 0) {
ccb783c3 2613 goto out;
b5a22e4a 2614 }
a672b469
AL
2615 break;
2616 case QEMU_VM_SECTION_PART:
2617 case QEMU_VM_SECTION_END:
fb3520a8 2618 ret = qemu_loadvm_section_part_end(f, mis);
b5a22e4a 2619 if (ret < 0) {
ccb783c3 2620 goto out;
b5a22e4a 2621 }
a672b469 2622 break;
c76ca188
DDAG
2623 case QEMU_VM_COMMAND:
2624 ret = loadvm_process_command(f);
7b89bf27 2625 trace_qemu_loadvm_state_section_command(ret);
4695ce3f 2626 if ((ret < 0) || (ret == LOADVM_QUIT)) {
ccb783c3 2627 goto out;
c76ca188
DDAG
2628 }
2629 break;
7a9ddfbf
PX
2630 case QEMU_VM_EOF:
2631 /* This is the end of migration */
2632 goto out;
a672b469 2633 default:
6a64b644 2634 error_report("Unknown savevm section type %d", section_type);
ccb783c3
DDAG
2635 ret = -EINVAL;
2636 goto out;
a672b469
AL
2637 }
2638 }
2639
ccb783c3
DDAG
2640out:
2641 if (ret < 0) {
2642 qemu_file_set_error(f, ret);
b411b844 2643
ee647225
VSO
2644 /* Cancel bitmaps incoming regardless of recovery */
2645 dirty_bitmap_mig_cancel_incoming();
2646
b411b844 2647 /*
fd037a65
PX
2648 * If we are during an active postcopy, then we pause instead
2649 * of bail out to at least keep the VM's dirty data. Note
2650 * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2651 * during which we're still receiving device states and we
2652 * still haven't yet started the VM on destination.
ee647225
VSO
2653 *
2654 * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2655 * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2656 * recovering.
b411b844
PX
2657 */
2658 if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
ee647225 2659 migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
b411b844
PX
2660 /* Reset f to point to the newly created channel */
2661 f = mis->from_src_file;
2662 goto retry;
2663 }
ccb783c3
DDAG
2664 }
2665 return ret;
7b89bf27
DDAG
2666}
2667
2668int qemu_loadvm_state(QEMUFile *f)
2669{
2670 MigrationIncomingState *mis = migration_incoming_get_current();
2671 Error *local_err = NULL;
7b89bf27
DDAG
2672 int ret;
2673
2674 if (qemu_savevm_state_blocked(&local_err)) {
2675 error_report_err(local_err);
2676 return -EINVAL;
2677 }
2678
16015d32
WY
2679 ret = qemu_loadvm_state_header(f);
2680 if (ret) {
2681 return ret;
7b89bf27
DDAG
2682 }
2683
9e14b849
WY
2684 if (qemu_loadvm_state_setup(f) != 0) {
2685 return -EINVAL;
2686 }
2687
75e972da
DG
2688 cpu_synchronize_all_pre_loadvm();
2689
7b89bf27
DDAG
2690 ret = qemu_loadvm_state_main(f, mis);
2691 qemu_event_set(&mis->main_thread_load_event);
2692
2693 trace_qemu_loadvm_state_post_main(ret);
2694
c76201ab
DDAG
2695 if (mis->have_listen_thread) {
2696 /* Listen thread still going, can't clean up yet */
2697 return ret;
2698 }
2699
7b89bf27
DDAG
2700 if (ret == 0) {
2701 ret = qemu_file_get_error(f);
2702 }
1925cebc
AG
2703
2704 /*
2705 * Try to read in the VMDESC section as well, so that dumping tools that
2706 * intercept our migration stream have the chance to see it.
2707 */
1aca9a5f
DDAG
2708
2709 /* We've got to be careful; if we don't read the data and just shut the fd
2710 * then the sender can error if we close while it's still sending.
2711 * We also mustn't read data that isn't there; some transports (RDMA)
2712 * will stall waiting for that data when the source has already closed.
2713 */
7b89bf27 2714 if (ret == 0 && should_send_vmdesc()) {
1aca9a5f
DDAG
2715 uint8_t *buf;
2716 uint32_t size;
7b89bf27 2717 uint8_t section_type = qemu_get_byte(f);
1aca9a5f
DDAG
2718
2719 if (section_type != QEMU_VM_VMDESCRIPTION) {
2720 error_report("Expected vmdescription section, but got %d",
2721 section_type);
2722 /*
2723 * It doesn't seem worth failing at this point since
2724 * we apparently have an otherwise valid VM state
2725 */
2726 } else {
2727 buf = g_malloc(0x1000);
2728 size = qemu_get_be32(f);
2729
2730 while (size > 0) {
2731 uint32_t read_chunk = MIN(size, 0x1000);
2732 qemu_get_buffer(f, buf, read_chunk);
2733 size -= read_chunk;
2734 }
2735 g_free(buf);
1925cebc 2736 }
1925cebc
AG
2737 }
2738
acb5ea86 2739 qemu_loadvm_state_cleanup();
ea375f9a
JK
2740 cpu_synchronize_all_post_init();
2741
a672b469
AL
2742 return ret;
2743}
2744
3f6df99d
ZC
2745int qemu_load_device_state(QEMUFile *f)
2746{
2747 MigrationIncomingState *mis = migration_incoming_get_current();
2748 int ret;
2749
2750 /* Load QEMU_VM_SECTION_FULL section */
2751 ret = qemu_loadvm_state_main(f, mis);
2752 if (ret < 0) {
2753 error_report("Failed to load device state: %d", ret);
2754 return ret;
2755 }
2756
2757 cpu_synchronize_all_post_init();
2758 return 0;
2759}
2760
f1a9fcdd
DB
2761bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
2762 bool has_devices, strList *devices, Error **errp)
a672b469 2763{
e26f98e2 2764 BlockDriverState *bs;
80ef0586 2765 QEMUSnapshotInfo sn1, *sn = &sn1;
66270a47 2766 int ret = -1, ret2;
a672b469
AL
2767 QEMUFile *f;
2768 int saved_vm_running;
c2c9a466 2769 uint64_t vm_state_size;
85cd1cc6 2770 g_autoptr(GDateTime) now = g_date_time_new_now_local();
79b3c12a 2771 AioContext *aio_context;
a672b469 2772
6b573efe
EGE
2773 GLOBAL_STATE_CODE();
2774
5aaac467 2775 if (migration_is_blocked(errp)) {
7ea14df2 2776 return false;
5aaac467
PB
2777 }
2778
377b21cc 2779 if (!replay_can_snapshot()) {
4dd32b3d
MA
2780 error_setg(errp, "Record/replay does not allow making snapshot "
2781 "right now. Try once more later.");
7ea14df2 2782 return false;
377b21cc
PD
2783 }
2784
f1a9fcdd 2785 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
7ea14df2 2786 return false;
feeee5ac
MDCF
2787 }
2788
0b461605 2789 /* Delete old snapshots of the same name */
ac8c19ba 2790 if (name) {
f781f841 2791 if (overwrite) {
f1a9fcdd
DB
2792 if (bdrv_all_delete_snapshot(name, has_devices,
2793 devices, errp) < 0) {
f781f841
DB
2794 return false;
2795 }
2796 } else {
f1a9fcdd 2797 ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
f781f841
DB
2798 if (ret2 < 0) {
2799 return false;
2800 }
2801 if (ret2 == 1) {
2802 error_setg(errp,
2803 "Snapshot '%s' already exists in one or more devices",
2804 name);
2805 return false;
2806 }
ac8c19ba 2807 }
0b461605
DL
2808 }
2809
f1a9fcdd 2810 bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
7cb14481 2811 if (bs == NULL) {
7ea14df2 2812 return false;
a672b469 2813 }
79b3c12a 2814 aio_context = bdrv_get_aio_context(bs);
a672b469 2815
1354869c 2816 saved_vm_running = runstate_is_running();
560d027b
JQ
2817
2818 ret = global_state_store();
2819 if (ret) {
927d6638 2820 error_setg(errp, "Error saving global state");
7ea14df2 2821 return false;
560d027b 2822 }
0461d5a6 2823 vm_stop(RUN_STATE_SAVE_VM);
a672b469 2824
8649f2f9
SH
2825 bdrv_drain_all_begin();
2826
79b3c12a
DL
2827 aio_context_acquire(aio_context);
2828
cb499fb2 2829 memset(sn, 0, sizeof(*sn));
a672b469
AL
2830
2831 /* fill auxiliary fields */
85cd1cc6
DB
2832 sn->date_sec = g_date_time_to_unix(now);
2833 sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
bc72ad67 2834 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
b39847a5
PD
2835 if (replay_mode != REPLAY_MODE_NONE) {
2836 sn->icount = replay_get_current_icount();
2837 } else {
2838 sn->icount = -1ULL;
2839 }
a672b469 2840
7d631a11 2841 if (name) {
80ef0586 2842 pstrcpy(sn->name, sizeof(sn->name), name);
7d631a11 2843 } else {
85cd1cc6
DB
2844 g_autofree char *autoname = g_date_time_format(now, "vm-%Y%m%d%H%M%S");
2845 pstrcpy(sn->name, sizeof(sn->name), autoname);
7d631a11
MDCF
2846 }
2847
a672b469 2848 /* save the VM state */
45566e9c 2849 f = qemu_fopen_bdrv(bs, 1);
a672b469 2850 if (!f) {
927d6638 2851 error_setg(errp, "Could not open VM state file");
a672b469
AL
2852 goto the_end;
2853 }
927d6638 2854 ret = qemu_savevm_state(f, errp);
fbfa6404 2855 vm_state_size = qemu_file_total_transferred(f);
66270a47 2856 ret2 = qemu_fclose(f);
a672b469 2857 if (ret < 0) {
a672b469
AL
2858 goto the_end;
2859 }
66270a47
DL
2860 if (ret2 < 0) {
2861 ret = ret2;
2862 goto the_end;
2863 }
a672b469 2864
17e2a4a4
SH
2865 /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2866 * for itself. BDRV_POLL_WHILE() does not support nested locking because
2867 * it only releases the lock once. Therefore synchronous I/O will deadlock
2868 * unless we release the AioContext before bdrv_all_create_snapshot().
2869 */
2870 aio_context_release(aio_context);
2871 aio_context = NULL;
2872
f1a9fcdd
DB
2873 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
2874 has_devices, devices, errp);
a9085f9b 2875 if (ret < 0) {
f1a9fcdd 2876 bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
ac8c19ba 2877 goto the_end;
a672b469
AL
2878 }
2879
ac8c19ba
PD
2880 ret = 0;
2881
a672b469 2882 the_end:
17e2a4a4
SH
2883 if (aio_context) {
2884 aio_context_release(aio_context);
2885 }
8649f2f9
SH
2886
2887 bdrv_drain_all_end();
2888
38ff78d3 2889 if (saved_vm_running) {
a672b469 2890 vm_start();
38ff78d3 2891 }
7ea14df2 2892 return ret == 0;
ac8c19ba
PD
2893}
2894
5d6c599f
AP
2895void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2896 Error **errp)
a7ae8355
SS
2897{
2898 QEMUFile *f;
8925839f 2899 QIOChannelFile *ioc;
a7ae8355
SS
2900 int saved_vm_running;
2901 int ret;
2902
5d6c599f
AP
2903 if (!has_live) {
2904 /* live default to true so old version of Xen tool stack can have a
3a4452d8 2905 * successful live migration */
5d6c599f
AP
2906 live = true;
2907 }
2908
a7ae8355
SS
2909 saved_vm_running = runstate_is_running();
2910 vm_stop(RUN_STATE_SAVE_VM);
c69adea4 2911 global_state_store_running();
a7ae8355 2912
b4deb9bf
DM
2913 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
2914 0660, errp);
8925839f 2915 if (!ioc) {
a7ae8355
SS
2916 goto the_end;
2917 }
6f01f136 2918 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
77ef2dc1 2919 f = qemu_file_new_output(QIO_CHANNEL(ioc));
032b79f7 2920 object_unref(OBJECT(ioc));
a7ae8355 2921 ret = qemu_save_device_state(f);
96994fd1 2922 if (ret < 0 || qemu_fclose(f) < 0) {
c6bd8c70 2923 error_setg(errp, QERR_IO_ERROR);
5d6c599f
AP
2924 } else {
2925 /* libxl calls the QMP command "stop" before calling
2926 * "xen-save-devices-state" and in case of migration failure, libxl
2927 * would call "cont".
2928 * So call bdrv_inactivate_all (release locks) here to let the other
3a4452d8 2929 * side of the migration take control of the images.
5d6c599f
AP
2930 */
2931 if (live && !saved_vm_running) {
2932 ret = bdrv_inactivate_all();
2933 if (ret) {
2934 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2935 __func__, ret);
2936 }
2937 }
a7ae8355
SS
2938 }
2939
2940 the_end:
38ff78d3 2941 if (saved_vm_running) {
a7ae8355 2942 vm_start();
38ff78d3 2943 }
a7ae8355
SS
2944}
2945
88c16567
WC
2946void qmp_xen_load_devices_state(const char *filename, Error **errp)
2947{
2948 QEMUFile *f;
2949 QIOChannelFile *ioc;
2950 int ret;
2951
2952 /* Guest must be paused before loading the device state; the RAM state
2953 * will already have been loaded by xc
2954 */
2955 if (runstate_is_running()) {
2956 error_setg(errp, "Cannot update device state while vm is running");
2957 return;
2958 }
2959 vm_stop(RUN_STATE_RESTORE_VM);
2960
2961 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2962 if (!ioc) {
2963 return;
2964 }
6f01f136 2965 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
77ef2dc1 2966 f = qemu_file_new_input(QIO_CHANNEL(ioc));
032b79f7 2967 object_unref(OBJECT(ioc));
88c16567 2968
88c16567
WC
2969 ret = qemu_loadvm_state(f);
2970 qemu_fclose(f);
2971 if (ret < 0) {
2972 error_setg(errp, QERR_IO_ERROR);
2973 }
2974 migration_incoming_state_destroy();
2975}
2976
f1a9fcdd
DB
2977bool load_snapshot(const char *name, const char *vmstate,
2978 bool has_devices, strList *devices, Error **errp)
a672b469 2979{
e26f98e2 2980 BlockDriverState *bs_vm_state;
2d22b18f 2981 QEMUSnapshotInfo sn;
a672b469 2982 QEMUFile *f;
751c6a17 2983 int ret;
79b3c12a 2984 AioContext *aio_context;
b4b076da 2985 MigrationIncomingState *mis = migration_incoming_get_current();
a672b469 2986
f1a9fcdd 2987 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
f61fe11a 2988 return false;
849f96e2 2989 }
f1a9fcdd 2990 ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
723ccda1 2991 if (ret < 0) {
f61fe11a 2992 return false;
723ccda1 2993 }
3d3e9b1f
DB
2994 if (ret == 0) {
2995 error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
2996 name);
2997 return false;
2998 }
849f96e2 2999
f1a9fcdd 3000 bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
f0aa7a8b 3001 if (!bs_vm_state) {
f61fe11a 3002 return false;
f0aa7a8b 3003 }
79b3c12a 3004 aio_context = bdrv_get_aio_context(bs_vm_state);
f0aa7a8b
MDCF
3005
3006 /* Don't even try to load empty VM states */
79b3c12a 3007 aio_context_acquire(aio_context);
f0aa7a8b 3008 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
79b3c12a 3009 aio_context_release(aio_context);
f0aa7a8b 3010 if (ret < 0) {
f61fe11a 3011 return false;
f0aa7a8b 3012 } else if (sn.vm_state_size == 0) {
927d6638
JQ
3013 error_setg(errp, "This is a disk-only snapshot. Revert to it "
3014 " offline using qemu-img");
f61fe11a 3015 return false;
f0aa7a8b
MDCF
3016 }
3017
f9a9fb65
PD
3018 /*
3019 * Flush the record/replay queue. Now the VM state is going
3020 * to change. Therefore we don't need to preserve its consistency
3021 */
3022 replay_flush_events();
3023
a672b469 3024 /* Flush all IO requests so they don't interfere with the new state. */
8649f2f9 3025 bdrv_drain_all_begin();
a672b469 3026
f1a9fcdd 3027 ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
4c1cdbaa 3028 if (ret < 0) {
8649f2f9 3029 goto err_drain;
a672b469
AL
3030 }
3031
a672b469 3032 /* restore the VM state */
f0aa7a8b 3033 f = qemu_fopen_bdrv(bs_vm_state, 0);
a672b469 3034 if (!f) {
927d6638 3035 error_setg(errp, "Could not open VM state file");
8649f2f9 3036 goto err_drain;
a672b469 3037 }
f0aa7a8b 3038
aedbe192 3039 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
b4b076da 3040 mis->from_src_file = f;
f0aa7a8b 3041
b5eea99e
LS
3042 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3043 ret = -EINVAL;
3044 goto err_drain;
3045 }
79b3c12a
DL
3046 aio_context_acquire(aio_context);
3047 ret = qemu_loadvm_state(f);
1575829d 3048 migration_incoming_state_destroy();
79b3c12a
DL
3049 aio_context_release(aio_context);
3050
8649f2f9
SH
3051 bdrv_drain_all_end();
3052
a672b469 3053 if (ret < 0) {
927d6638 3054 error_setg(errp, "Error %d while loading VM state", ret);
f61fe11a 3055 return false;
a672b469 3056 }
f0aa7a8b 3057
f61fe11a 3058 return true;
8649f2f9
SH
3059
3060err_drain:
3061 bdrv_drain_all_end();
f61fe11a 3062 return false;
7b630349
JQ
3063}
3064
bef7e9e2
DB
3065bool delete_snapshot(const char *name, bool has_devices,
3066 strList *devices, Error **errp)
3067{
3068 if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3069 return false;
3070 }
3071
3072 if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3073 return false;
3074 }
3075
3076 return true;
3077}
3078
c5705a77
AK
3079void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3080{
fa53a0e5 3081 qemu_ram_set_idstr(mr->ram_block,
c5705a77 3082 memory_region_name(mr), dev);
b895de50 3083 qemu_ram_set_migratable(mr->ram_block);
c5705a77
AK
3084}
3085
3086void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3087{
fa53a0e5 3088 qemu_ram_unset_idstr(mr->ram_block);
b895de50 3089 qemu_ram_unset_migratable(mr->ram_block);
c5705a77
AK
3090}
3091
3092void vmstate_register_ram_global(MemoryRegion *mr)
3093{
3094 vmstate_register_ram(mr, NULL);
3095}
1bfe5f05
JQ
3096
3097bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3098{
3099 /* check needed if --only-migratable is specified */
811f8652 3100 if (!only_migratable) {
1bfe5f05
JQ
3101 return true;
3102 }
3103
3104 return !(vmsd && vmsd->unmigratable);
3105}
0f0d83a4
DB
3106
3107typedef struct SnapshotJob {
3108 Job common;
3109 char *tag;
3110 char *vmstate;
3111 strList *devices;
3112 Coroutine *co;
3113 Error **errp;
3114 bool ret;
3115} SnapshotJob;
3116
3117static void qmp_snapshot_job_free(SnapshotJob *s)
3118{
3119 g_free(s->tag);
3120 g_free(s->vmstate);
3121 qapi_free_strList(s->devices);
3122}
3123
3124
3125static void snapshot_load_job_bh(void *opaque)
3126{
3127 Job *job = opaque;
3128 SnapshotJob *s = container_of(job, SnapshotJob, common);
3129 int orig_vm_running;
3130
3131 job_progress_set_remaining(&s->common, 1);
3132
3133 orig_vm_running = runstate_is_running();
3134 vm_stop(RUN_STATE_RESTORE_VM);
3135
3136 s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3137 if (s->ret && orig_vm_running) {
3138 vm_start();
3139 }
3140
3141 job_progress_update(&s->common, 1);
3142
3143 qmp_snapshot_job_free(s);
3144 aio_co_wake(s->co);
3145}
3146
3147static void snapshot_save_job_bh(void *opaque)
3148{
3149 Job *job = opaque;
3150 SnapshotJob *s = container_of(job, SnapshotJob, common);
3151
3152 job_progress_set_remaining(&s->common, 1);
3153 s->ret = save_snapshot(s->tag, false, s->vmstate,
3154 true, s->devices, s->errp);
3155 job_progress_update(&s->common, 1);
3156
3157 qmp_snapshot_job_free(s);
3158 aio_co_wake(s->co);
3159}
3160
3161static void snapshot_delete_job_bh(void *opaque)
3162{
3163 Job *job = opaque;
3164 SnapshotJob *s = container_of(job, SnapshotJob, common);
3165
3166 job_progress_set_remaining(&s->common, 1);
3167 s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3168 job_progress_update(&s->common, 1);
3169
3170 qmp_snapshot_job_free(s);
3171 aio_co_wake(s->co);
3172}
3173
3174static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3175{
3176 SnapshotJob *s = container_of(job, SnapshotJob, common);
3177 s->errp = errp;
3178 s->co = qemu_coroutine_self();
3179 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3180 snapshot_save_job_bh, job);
3181 qemu_coroutine_yield();
3182 return s->ret ? 0 : -1;
3183}
3184
3185static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3186{
3187 SnapshotJob *s = container_of(job, SnapshotJob, common);
3188 s->errp = errp;
3189 s->co = qemu_coroutine_self();
3190 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3191 snapshot_load_job_bh, job);
3192 qemu_coroutine_yield();
3193 return s->ret ? 0 : -1;
3194}
3195
3196static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3197{
3198 SnapshotJob *s = container_of(job, SnapshotJob, common);
3199 s->errp = errp;
3200 s->co = qemu_coroutine_self();
3201 aio_bh_schedule_oneshot(qemu_get_aio_context(),
3202 snapshot_delete_job_bh, job);
3203 qemu_coroutine_yield();
3204 return s->ret ? 0 : -1;
3205}
3206
3207
3208static const JobDriver snapshot_load_job_driver = {
3209 .instance_size = sizeof(SnapshotJob),
3210 .job_type = JOB_TYPE_SNAPSHOT_LOAD,
3211 .run = snapshot_load_job_run,
3212};
3213
3214static const JobDriver snapshot_save_job_driver = {
3215 .instance_size = sizeof(SnapshotJob),
3216 .job_type = JOB_TYPE_SNAPSHOT_SAVE,
3217 .run = snapshot_save_job_run,
3218};
3219
3220static const JobDriver snapshot_delete_job_driver = {
3221 .instance_size = sizeof(SnapshotJob),
3222 .job_type = JOB_TYPE_SNAPSHOT_DELETE,
3223 .run = snapshot_delete_job_run,
3224};
3225
3226
3227void qmp_snapshot_save(const char *job_id,
3228 const char *tag,
3229 const char *vmstate,
3230 strList *devices,
3231 Error **errp)
3232{
3233 SnapshotJob *s;
3234
3235 s = job_create(job_id, &snapshot_save_job_driver, NULL,
3236 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3237 NULL, NULL, errp);
3238 if (!s) {
3239 return;
3240 }
3241
3242 s->tag = g_strdup(tag);
3243 s->vmstate = g_strdup(vmstate);
3244 s->devices = QAPI_CLONE(strList, devices);
3245
3246 job_start(&s->common);
3247}
3248
3249void qmp_snapshot_load(const char *job_id,
3250 const char *tag,
3251 const char *vmstate,
3252 strList *devices,
3253 Error **errp)
3254{
3255 SnapshotJob *s;
3256
3257 s = job_create(job_id, &snapshot_load_job_driver, NULL,
3258 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3259 NULL, NULL, errp);
3260 if (!s) {
3261 return;
3262 }
3263
3264 s->tag = g_strdup(tag);
3265 s->vmstate = g_strdup(vmstate);
3266 s->devices = QAPI_CLONE(strList, devices);
3267
3268 job_start(&s->common);
3269}
3270
3271void qmp_snapshot_delete(const char *job_id,
3272 const char *tag,
3273 strList *devices,
3274 Error **errp)
3275{
3276 SnapshotJob *s;
3277
3278 s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3279 qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3280 NULL, NULL, errp);
3281 if (!s) {
3282 return;
3283 }
3284
3285 s->tag = g_strdup(tag);
3286 s->devices = QAPI_CLONE(strList, devices);
3287
3288 job_start(&s->common);
3289}