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