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