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