]> git.proxmox.com Git - mirror_qemu.git/blame - migration/savevm.c
migration: Move self_announce_delay() to misc.h
[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"
511d2b14 31#include "hw/hw.h"
7685ee6a 32#include "hw/qdev.h"
88c16567 33#include "hw/xen/xen.h"
1422e32d 34#include "net/net.h"
9c17d615 35#include "sysemu/sysemu.h"
1de7afc9 36#include "qemu/timer.h"
caf71f86 37#include "migration/migration.h"
5e22479a 38#include "migration/snapshot.h"
f8d806c9 39#include "migration/misc.h"
7b1e1a22 40#include "ram.h"
40014d81 41#include "qemu-file-channel.h"
08a0aee1 42#include "qemu-file.h"
20a519a0 43#include "savevm.h"
be07b0ac 44#include "postcopy-ram.h"
cc7a8ea7 45#include "qapi/qmp/qerror.h"
d49b6836 46#include "qemu/error-report.h"
1de7afc9 47#include "qemu/queue.h"
9c17d615 48#include "sysemu/cpus.h"
022c62cb 49#include "exec/memory.h"
51180423 50#include "exec/target_page.h"
a7ae8355 51#include "qmp-commands.h"
517a13c9 52#include "trace.h"
093e3c42 53#include "qemu/bitops.h"
28085f7b 54#include "qemu/iov.h"
de08c606 55#include "block/snapshot.h"
f348b6d1 56#include "qemu/cutils.h"
61b67d47 57#include "io/channel-buffer.h"
8925839f 58#include "io/channel-file.h"
a672b469 59
18995b98 60#ifndef ETH_P_RARP
f8778a77 61#define ETH_P_RARP 0x8035
18995b98
N
62#endif
63#define ARP_HTYPE_ETH 0x0001
64#define ARP_PTYPE_IP 0x0800
65#define ARP_OP_REQUEST_REV 0x3
66
093e3c42
DDAG
67const unsigned int postcopy_ram_discard_version = 0;
68
37fb569c
DDAG
69static bool skip_section_footers;
70
20a519a0
JQ
71/* Subcommands for QEMU_VM_COMMAND */
72enum qemu_vm_cmd {
73 MIG_CMD_INVALID = 0, /* Must be 0 */
74 MIG_CMD_OPEN_RETURN_PATH, /* Tell the dest to open the Return path */
75 MIG_CMD_PING, /* Request a PONG on the RP */
76
77 MIG_CMD_POSTCOPY_ADVISE, /* Prior to any page transfers, just
78 warn we might want to do PC */
79 MIG_CMD_POSTCOPY_LISTEN, /* Start listening for incoming
80 pages as it's running. */
81 MIG_CMD_POSTCOPY_RUN, /* Start execution */
82
83 MIG_CMD_POSTCOPY_RAM_DISCARD, /* A list of pages to discard that
84 were previously sent during
85 precopy but are dirty. */
86 MIG_CMD_PACKAGED, /* Send a wrapped stream within this stream */
87 MIG_CMD_MAX
88};
89
90#define MAX_VM_CMD_PACKAGED_SIZE (1ul << 24)
c76ca188
DDAG
91static struct mig_cmd_args {
92 ssize_t len; /* -1 = variable */
93 const char *name;
94} mig_cmd_args[] = {
95 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
2e37701e
DDAG
96 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
97 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
093e3c42
DDAG
98 [MIG_CMD_POSTCOPY_ADVISE] = { .len = 16, .name = "POSTCOPY_ADVISE" },
99 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
100 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
101 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
102 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
11cf1d98 103 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
c76ca188
DDAG
104 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
105};
106
18995b98 107static int announce_self_create(uint8_t *buf,
5cecf414 108 uint8_t *mac_addr)
a672b469 109{
18995b98
N
110 /* Ethernet header. */
111 memset(buf, 0xff, 6); /* destination MAC addr */
112 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
113 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
114
115 /* RARP header. */
116 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
117 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
118 *(buf + 18) = 6; /* hardware addr length (ethernet) */
119 *(buf + 19) = 4; /* protocol addr length (IPv4) */
120 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
121 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
122 memset(buf + 28, 0x00, 4); /* source protocol addr */
123 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
124 memset(buf + 38, 0x00, 4); /* target protocol addr */
125
126 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
127 memset(buf + 42, 0x00, 18);
128
129 return 60; /* len (FCS will be added by hardware) */
a672b469
AL
130}
131
f401ca22 132static void qemu_announce_self_iter(NICState *nic, void *opaque)
a672b469 133{
18995b98 134 uint8_t buf[60];
f401ca22
MM
135 int len;
136
9013dca5 137 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic->conf->macaddr));
f401ca22
MM
138 len = announce_self_create(buf, nic->conf->macaddr.a);
139
b356f76d 140 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
f401ca22
MM
141}
142
143
144static void qemu_announce_self_once(void *opaque)
145{
ed8b330b
GN
146 static int count = SELF_ANNOUNCE_ROUNDS;
147 QEMUTimer *timer = *(QEMUTimer **)opaque;
a672b469 148
f401ca22
MM
149 qemu_foreach_nic(qemu_announce_self_iter, NULL);
150
18995b98
N
151 if (--count) {
152 /* delay 50ms, 150ms, 250ms, ... */
bc72ad67 153 timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
508e1180 154 self_announce_delay(count));
ed8b330b 155 } else {
5cecf414
EH
156 timer_del(timer);
157 timer_free(timer);
ed8b330b
GN
158 }
159}
160
161void qemu_announce_self(void)
162{
5cecf414
EH
163 static QEMUTimer *timer;
164 timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
165 qemu_announce_self_once(&timer);
a672b469
AL
166}
167
168/***********************************************************/
169/* savevm/loadvm support */
170
05fcc848
KW
171static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
172 int64_t pos)
173{
174 int ret;
175 QEMUIOVector qiov;
176
177 qemu_iovec_init_external(&qiov, iov, iovcnt);
178 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
179 if (ret < 0) {
180 return ret;
181 }
182
183 return qiov.size;
184}
185
a202a4c0
DDAG
186static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
187 size_t size)
a672b469 188{
45566e9c 189 return bdrv_load_vmstate(opaque, buf, pos, size);
a672b469
AL
190}
191
192static int bdrv_fclose(void *opaque)
193{
ad492c92 194 return bdrv_flush(opaque);
a672b469
AL
195}
196
9229bf3c
PB
197static const QEMUFileOps bdrv_read_ops = {
198 .get_buffer = block_get_buffer,
199 .close = bdrv_fclose
200};
201
202static const QEMUFileOps bdrv_write_ops = {
05fcc848
KW
203 .writev_buffer = block_writev_buffer,
204 .close = bdrv_fclose
9229bf3c
PB
205};
206
45566e9c 207static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
a672b469 208{
38ff78d3 209 if (is_writable) {
9229bf3c 210 return qemu_fopen_ops(bs, &bdrv_write_ops);
38ff78d3 211 }
9229bf3c 212 return qemu_fopen_ops(bs, &bdrv_read_ops);
a672b469
AL
213}
214
2ff68d07 215
bb1a6d8c
EH
216/* QEMUFile timer support.
217 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
218 */
2ff68d07 219
40daca54 220void timer_put(QEMUFile *f, QEMUTimer *ts)
2ff68d07
PB
221{
222 uint64_t expire_time;
223
e93379b0 224 expire_time = timer_expire_time_ns(ts);
2ff68d07
PB
225 qemu_put_be64(f, expire_time);
226}
227
40daca54 228void timer_get(QEMUFile *f, QEMUTimer *ts)
2ff68d07
PB
229{
230 uint64_t expire_time;
231
232 expire_time = qemu_get_be64(f);
233 if (expire_time != -1) {
bc72ad67 234 timer_mod_ns(ts, expire_time);
2ff68d07 235 } else {
bc72ad67 236 timer_del(ts);
2ff68d07
PB
237 }
238}
239
240
bb1a6d8c
EH
241/* VMState timer support.
242 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
243 */
dde0463b 244
2c21ee76 245static int get_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field)
dde0463b
JQ
246{
247 QEMUTimer *v = pv;
40daca54 248 timer_get(f, v);
dde0463b
JQ
249 return 0;
250}
251
2c21ee76
JD
252static int put_timer(QEMUFile *f, void *pv, size_t size, VMStateField *field,
253 QJSON *vmdesc)
dde0463b 254{
84e2e3eb 255 QEMUTimer *v = pv;
40daca54 256 timer_put(f, v);
2c21ee76
JD
257
258 return 0;
dde0463b
JQ
259}
260
261const VMStateInfo vmstate_info_timer = {
262 .name = "timer",
263 .get = get_timer,
264 .put = put_timer,
265};
266
08e99e29 267
7685ee6a
AW
268typedef struct CompatEntry {
269 char idstr[256];
270 int instance_id;
271} CompatEntry;
272
a672b469 273typedef struct SaveStateEntry {
72cf2d4f 274 QTAILQ_ENTRY(SaveStateEntry) entry;
a672b469
AL
275 char idstr[256];
276 int instance_id;
4d2ffa08 277 int alias_id;
a672b469 278 int version_id;
0f42f657
JQ
279 /* version id read from the stream */
280 int load_version_id;
a672b469 281 int section_id;
0f42f657
JQ
282 /* section id read from the stream */
283 int load_section_id;
22ea40f4 284 SaveVMHandlers *ops;
9ed7d6ae 285 const VMStateDescription *vmsd;
a672b469 286 void *opaque;
7685ee6a 287 CompatEntry *compat;
a7ae8355 288 int is_ram;
a672b469
AL
289} SaveStateEntry;
290
0163a2e0
JQ
291typedef struct SaveState {
292 QTAILQ_HEAD(, SaveStateEntry) handlers;
293 int global_section_id;
61964c23
JQ
294 bool skip_configuration;
295 uint32_t len;
296 const char *name;
59811a32 297 uint32_t target_page_bits;
0163a2e0
JQ
298} SaveState;
299
300static SaveState savevm_state = {
301 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
302 .global_section_id = 0,
61964c23
JQ
303 .skip_configuration = false,
304};
305
306void savevm_skip_configuration(void)
307{
308 savevm_state.skip_configuration = true;
309}
310
311
312static void configuration_pre_save(void *opaque)
313{
314 SaveState *state = opaque;
315 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
316
317 state->len = strlen(current_name);
318 state->name = current_name;
46d702b1 319 state->target_page_bits = qemu_target_page_bits();
59811a32
PM
320}
321
322static int configuration_pre_load(void *opaque)
323{
324 SaveState *state = opaque;
325
326 /* If there is no target-page-bits subsection it means the source
327 * predates the variable-target-page-bits support and is using the
328 * minimum possible value for this CPU.
329 */
46d702b1 330 state->target_page_bits = qemu_target_page_bits_min();
59811a32 331 return 0;
61964c23
JQ
332}
333
334static int configuration_post_load(void *opaque, int version_id)
335{
336 SaveState *state = opaque;
337 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
338
339 if (strncmp(state->name, current_name, state->len) != 0) {
15d61692
GK
340 error_report("Machine type received is '%.*s' and local is '%s'",
341 (int) state->len, state->name, current_name);
61964c23
JQ
342 return -EINVAL;
343 }
59811a32 344
46d702b1 345 if (state->target_page_bits != qemu_target_page_bits()) {
59811a32 346 error_report("Received TARGET_PAGE_BITS is %d but local is %d",
46d702b1 347 state->target_page_bits, qemu_target_page_bits());
59811a32
PM
348 return -EINVAL;
349 }
350
61964c23
JQ
351 return 0;
352}
353
59811a32
PM
354/* The target-page-bits subsection is present only if the
355 * target page size is not the same as the default (ie the
356 * minimum page size for a variable-page-size guest CPU).
357 * If it is present then it contains the actual target page
358 * bits for the machine, and migration will fail if the
359 * two ends don't agree about it.
360 */
361static bool vmstate_target_page_bits_needed(void *opaque)
362{
46d702b1
JQ
363 return qemu_target_page_bits()
364 > qemu_target_page_bits_min();
59811a32
PM
365}
366
367static const VMStateDescription vmstate_target_page_bits = {
368 .name = "configuration/target-page-bits",
369 .version_id = 1,
370 .minimum_version_id = 1,
371 .needed = vmstate_target_page_bits_needed,
372 .fields = (VMStateField[]) {
373 VMSTATE_UINT32(target_page_bits, SaveState),
374 VMSTATE_END_OF_LIST()
375 }
376};
377
61964c23
JQ
378static const VMStateDescription vmstate_configuration = {
379 .name = "configuration",
380 .version_id = 1,
59811a32 381 .pre_load = configuration_pre_load,
61964c23
JQ
382 .post_load = configuration_post_load,
383 .pre_save = configuration_pre_save,
384 .fields = (VMStateField[]) {
385 VMSTATE_UINT32(len, SaveState),
59046ec2 386 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
61964c23
JQ
387 VMSTATE_END_OF_LIST()
388 },
59811a32
PM
389 .subsections = (const VMStateDescription*[]) {
390 &vmstate_target_page_bits,
391 NULL
392 }
0163a2e0 393};
a672b469 394
abfd9ce3
AS
395static void dump_vmstate_vmsd(FILE *out_file,
396 const VMStateDescription *vmsd, int indent,
397 bool is_subsection);
398
399static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
400 int indent)
401{
402 fprintf(out_file, "%*s{\n", indent, "");
403 indent += 2;
404 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
405 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
406 field->version_id);
407 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
408 field->field_exists ? "true" : "false");
409 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
410 if (field->vmsd != NULL) {
411 fprintf(out_file, ",\n");
412 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
413 }
414 fprintf(out_file, "\n%*s}", indent - 2, "");
415}
416
417static void dump_vmstate_vmss(FILE *out_file,
5cd8cada 418 const VMStateDescription **subsection,
abfd9ce3
AS
419 int indent)
420{
5cd8cada
JQ
421 if (*subsection != NULL) {
422 dump_vmstate_vmsd(out_file, *subsection, indent, true);
abfd9ce3
AS
423 }
424}
425
426static void dump_vmstate_vmsd(FILE *out_file,
427 const VMStateDescription *vmsd, int indent,
428 bool is_subsection)
429{
430 if (is_subsection) {
431 fprintf(out_file, "%*s{\n", indent, "");
432 } else {
433 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
434 }
435 indent += 2;
436 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
437 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
438 vmsd->version_id);
439 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
440 vmsd->minimum_version_id);
441 if (vmsd->fields != NULL) {
442 const VMStateField *field = vmsd->fields;
443 bool first;
444
445 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
446 first = true;
447 while (field->name != NULL) {
448 if (field->flags & VMS_MUST_EXIST) {
449 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
450 field++;
451 continue;
452 }
453 if (!first) {
454 fprintf(out_file, ",\n");
455 }
456 dump_vmstate_vmsf(out_file, field, indent + 2);
457 field++;
458 first = false;
459 }
460 fprintf(out_file, "\n%*s]", indent, "");
461 }
462 if (vmsd->subsections != NULL) {
5cd8cada 463 const VMStateDescription **subsection = vmsd->subsections;
abfd9ce3
AS
464 bool first;
465
466 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
467 first = true;
5cd8cada 468 while (*subsection != NULL) {
abfd9ce3
AS
469 if (!first) {
470 fprintf(out_file, ",\n");
471 }
472 dump_vmstate_vmss(out_file, subsection, indent + 2);
473 subsection++;
474 first = false;
475 }
476 fprintf(out_file, "\n%*s]", indent, "");
477 }
478 fprintf(out_file, "\n%*s}", indent - 2, "");
479}
480
481static void dump_machine_type(FILE *out_file)
482{
483 MachineClass *mc;
484
485 mc = MACHINE_GET_CLASS(current_machine);
486
487 fprintf(out_file, " \"vmschkmachine\": {\n");
488 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
489 fprintf(out_file, " },\n");
490}
491
492void dump_vmstate_json_to_file(FILE *out_file)
493{
494 GSList *list, *elt;
495 bool first;
496
497 fprintf(out_file, "{\n");
498 dump_machine_type(out_file);
499
500 first = true;
501 list = object_class_get_list(TYPE_DEVICE, true);
502 for (elt = list; elt; elt = elt->next) {
503 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
504 TYPE_DEVICE);
505 const char *name;
506 int indent = 2;
507
508 if (!dc->vmsd) {
509 continue;
510 }
511
512 if (!first) {
513 fprintf(out_file, ",\n");
514 }
515 name = object_class_get_name(OBJECT_CLASS(dc));
516 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
517 indent += 2;
518 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
519 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
520 dc->vmsd->version_id);
521 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
522 dc->vmsd->minimum_version_id);
523
524 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
525
526 fprintf(out_file, "\n%*s}", indent - 2, "");
527 first = false;
528 }
529 fprintf(out_file, "\n}\n");
530 fclose(out_file);
531}
532
8718e999
JQ
533static int calculate_new_instance_id(const char *idstr)
534{
535 SaveStateEntry *se;
536 int instance_id = 0;
537
0163a2e0 538 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
8718e999
JQ
539 if (strcmp(idstr, se->idstr) == 0
540 && instance_id <= se->instance_id) {
541 instance_id = se->instance_id + 1;
542 }
543 }
544 return instance_id;
545}
546
7685ee6a
AW
547static int calculate_compat_instance_id(const char *idstr)
548{
549 SaveStateEntry *se;
550 int instance_id = 0;
551
0163a2e0 552 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
38ff78d3 553 if (!se->compat) {
7685ee6a 554 continue;
38ff78d3 555 }
7685ee6a
AW
556
557 if (strcmp(idstr, se->compat->idstr) == 0
558 && instance_id <= se->compat->instance_id) {
559 instance_id = se->compat->instance_id + 1;
560 }
561 }
562 return instance_id;
563}
564
f37bc036
PX
565static inline MigrationPriority save_state_priority(SaveStateEntry *se)
566{
567 if (se->vmsd) {
568 return se->vmsd->priority;
569 }
570 return MIG_PRI_DEFAULT;
571}
572
573static void savevm_state_handler_insert(SaveStateEntry *nse)
574{
575 MigrationPriority priority = save_state_priority(nse);
576 SaveStateEntry *se;
577
578 assert(priority <= MIG_PRI_MAX);
579
580 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
581 if (save_state_priority(se) < priority) {
582 break;
583 }
584 }
585
586 if (se) {
587 QTAILQ_INSERT_BEFORE(se, nse, entry);
588 } else {
589 QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
590 }
591}
592
a672b469
AL
593/* TODO: Individual devices generally have very little idea about the rest
594 of the system, so instance_id should be removed/replaced.
595 Meanwhile pass -1 as instance_id if you do not already have a clearly
596 distinguishing id for all instances of your device class. */
0be71e32
AW
597int register_savevm_live(DeviceState *dev,
598 const char *idstr,
a672b469
AL
599 int instance_id,
600 int version_id,
7908c78d 601 SaveVMHandlers *ops,
a672b469
AL
602 void *opaque)
603{
8718e999 604 SaveStateEntry *se;
a672b469 605
97f3ad35 606 se = g_new0(SaveStateEntry, 1);
a672b469 607 se->version_id = version_id;
0163a2e0 608 se->section_id = savevm_state.global_section_id++;
7908c78d 609 se->ops = ops;
a672b469 610 se->opaque = opaque;
9ed7d6ae 611 se->vmsd = NULL;
a7ae8355 612 /* if this is a live_savem then set is_ram */
16310a3c 613 if (ops->save_live_setup != NULL) {
a7ae8355
SS
614 se->is_ram = 1;
615 }
a672b469 616
09e5ab63
AL
617 if (dev) {
618 char *id = qdev_get_dev_path(dev);
7685ee6a 619 if (id) {
581f08ba
DDAG
620 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
621 sizeof(se->idstr)) {
622 error_report("Path too long for VMState (%s)", id);
623 g_free(id);
624 g_free(se);
625
626 return -1;
627 }
7267c094 628 g_free(id);
7685ee6a 629
97f3ad35 630 se->compat = g_new0(CompatEntry, 1);
7685ee6a
AW
631 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
632 se->compat->instance_id = instance_id == -1 ?
633 calculate_compat_instance_id(idstr) : instance_id;
634 instance_id = -1;
635 }
636 }
637 pstrcat(se->idstr, sizeof(se->idstr), idstr);
638
8718e999 639 if (instance_id == -1) {
7685ee6a 640 se->instance_id = calculate_new_instance_id(se->idstr);
8718e999
JQ
641 } else {
642 se->instance_id = instance_id;
a672b469 643 }
7685ee6a 644 assert(!se->compat || se->instance_id == 0);
f37bc036 645 savevm_state_handler_insert(se);
a672b469
AL
646 return 0;
647}
648
0be71e32 649void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
41bd13af 650{
8718e999 651 SaveStateEntry *se, *new_se;
7685ee6a
AW
652 char id[256] = "";
653
09e5ab63
AL
654 if (dev) {
655 char *path = qdev_get_dev_path(dev);
7685ee6a
AW
656 if (path) {
657 pstrcpy(id, sizeof(id), path);
658 pstrcat(id, sizeof(id), "/");
7267c094 659 g_free(path);
7685ee6a
AW
660 }
661 }
662 pstrcat(id, sizeof(id), idstr);
41bd13af 663
0163a2e0 664 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
7685ee6a 665 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
0163a2e0 666 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
ef1e1e07 667 g_free(se->compat);
7267c094 668 g_free(se);
41bd13af 669 }
41bd13af
AL
670 }
671}
672
0be71e32 673int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
4d2ffa08
JK
674 const VMStateDescription *vmsd,
675 void *opaque, int alias_id,
bc5c4f21
DDAG
676 int required_for_version,
677 Error **errp)
9ed7d6ae 678{
8718e999 679 SaveStateEntry *se;
9ed7d6ae 680
4d2ffa08
JK
681 /* If this triggers, alias support can be dropped for the vmsd. */
682 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
683
97f3ad35 684 se = g_new0(SaveStateEntry, 1);
9ed7d6ae 685 se->version_id = vmsd->version_id;
0163a2e0 686 se->section_id = savevm_state.global_section_id++;
9ed7d6ae
JQ
687 se->opaque = opaque;
688 se->vmsd = vmsd;
4d2ffa08 689 se->alias_id = alias_id;
9ed7d6ae 690
09e5ab63
AL
691 if (dev) {
692 char *id = qdev_get_dev_path(dev);
7685ee6a 693 if (id) {
581f08ba
DDAG
694 if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
695 sizeof(se->idstr)) {
696 error_setg(errp, "Path too long for VMState (%s)", id);
697 g_free(id);
698 g_free(se);
699
700 return -1;
701 }
128e4e10 702 g_free(id);
7685ee6a 703
97f3ad35 704 se->compat = g_new0(CompatEntry, 1);
7685ee6a
AW
705 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
706 se->compat->instance_id = instance_id == -1 ?
707 calculate_compat_instance_id(vmsd->name) : instance_id;
708 instance_id = -1;
709 }
710 }
711 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
712
8718e999 713 if (instance_id == -1) {
7685ee6a 714 se->instance_id = calculate_new_instance_id(se->idstr);
8718e999
JQ
715 } else {
716 se->instance_id = instance_id;
9ed7d6ae 717 }
7685ee6a 718 assert(!se->compat || se->instance_id == 0);
f37bc036 719 savevm_state_handler_insert(se);
9ed7d6ae
JQ
720 return 0;
721}
722
0be71e32
AW
723void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
724 void *opaque)
9ed7d6ae 725{
1eb7538b
JQ
726 SaveStateEntry *se, *new_se;
727
0163a2e0 728 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
1eb7538b 729 if (se->vmsd == vmsd && se->opaque == opaque) {
0163a2e0 730 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
ef1e1e07 731 g_free(se->compat);
7267c094 732 g_free(se);
1eb7538b
JQ
733 }
734 }
9ed7d6ae
JQ
735}
736
3a011c26 737static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
4082be4d 738{
9013dca5 739 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
9ed7d6ae 740 if (!se->vmsd) { /* Old style */
3a011c26 741 return se->ops->load_state(f, se->opaque, se->load_version_id);
9ed7d6ae 742 }
3a011c26 743 return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
4082be4d
JQ
744}
745
8118f095
AG
746static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
747{
748 int64_t old_offset, size;
749
750 old_offset = qemu_ftell_fast(f);
751 se->ops->save_state(f, se->opaque);
752 size = qemu_ftell_fast(f) - old_offset;
753
754 if (vmdesc) {
755 json_prop_int(vmdesc, "size", size);
756 json_start_array(vmdesc, "fields");
757 json_start_object(vmdesc, NULL);
758 json_prop_str(vmdesc, "name", "data");
759 json_prop_int(vmdesc, "size", size);
760 json_prop_str(vmdesc, "type", "buffer");
761 json_end_object(vmdesc);
762 json_end_array(vmdesc);
763 }
764}
765
766static void vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
4082be4d 767{
9013dca5 768 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
8118f095
AG
769 if (!se->vmsd) {
770 vmstate_save_old_style(f, se, vmdesc);
dc912121 771 return;
9ed7d6ae 772 }
8118f095 773 vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
4082be4d
JQ
774}
775
37fb569c
DDAG
776void savevm_skip_section_footers(void)
777{
778 skip_section_footers = true;
779}
780
ce39bfc9
DDAG
781/*
782 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
783 */
784static void save_section_header(QEMUFile *f, SaveStateEntry *se,
785 uint8_t section_type)
786{
787 qemu_put_byte(f, section_type);
788 qemu_put_be32(f, se->section_id);
789
790 if (section_type == QEMU_VM_SECTION_FULL ||
791 section_type == QEMU_VM_SECTION_START) {
792 /* ID string */
793 size_t len = strlen(se->idstr);
794 qemu_put_byte(f, len);
795 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
796
797 qemu_put_be32(f, se->instance_id);
798 qemu_put_be32(f, se->version_id);
799 }
800}
801
f68945d4
DDAG
802/*
803 * Write a footer onto device sections that catches cases misformatted device
804 * sections.
805 */
806static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
807{
808 if (!skip_section_footers) {
809 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
810 qemu_put_be32(f, se->section_id);
811 }
812}
813
c76ca188
DDAG
814/**
815 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
816 * command and associated data.
817 *
818 * @f: File to send command on
819 * @command: Command type to send
820 * @len: Length of associated data
821 * @data: Data associated with command.
822 */
20a519a0
JQ
823static void qemu_savevm_command_send(QEMUFile *f,
824 enum qemu_vm_cmd command,
825 uint16_t len,
826 uint8_t *data)
c76ca188
DDAG
827{
828 trace_savevm_command_send(command, len);
829 qemu_put_byte(f, QEMU_VM_COMMAND);
830 qemu_put_be16(f, (uint16_t)command);
831 qemu_put_be16(f, len);
832 qemu_put_buffer(f, data, len);
833 qemu_fflush(f);
834}
835
2e37701e
DDAG
836void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
837{
838 uint32_t buf;
839
840 trace_savevm_send_ping(value);
841 buf = cpu_to_be32(value);
842 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
843}
844
845void qemu_savevm_send_open_return_path(QEMUFile *f)
846{
847 trace_savevm_send_open_return_path();
848 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
849}
850
11cf1d98
DDAG
851/* We have a buffer of data to send; we don't want that all to be loaded
852 * by the command itself, so the command contains just the length of the
853 * extra buffer that we then send straight after it.
854 * TODO: Must be a better way to organise that
855 *
856 * Returns:
857 * 0 on success
858 * -ve on error
859 */
61b67d47 860int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
11cf1d98 861{
11cf1d98
DDAG
862 uint32_t tmp;
863
864 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
865 error_report("%s: Unreasonably large packaged state: %zu",
866 __func__, len);
867 return -1;
868 }
869
870 tmp = cpu_to_be32(len);
871
872 trace_qemu_savevm_send_packaged();
873 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
874
61b67d47 875 qemu_put_buffer(f, buf, len);
11cf1d98
DDAG
876
877 return 0;
878}
879
093e3c42
DDAG
880/* Send prior to any postcopy transfer */
881void qemu_savevm_send_postcopy_advise(QEMUFile *f)
882{
883 uint64_t tmp[2];
e8ca1db2 884 tmp[0] = cpu_to_be64(ram_pagesize_summary());
20afaed9 885 tmp[1] = cpu_to_be64(qemu_target_page_size());
093e3c42
DDAG
886
887 trace_qemu_savevm_send_postcopy_advise();
888 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 16, (uint8_t *)tmp);
889}
890
891/* Sent prior to starting the destination running in postcopy, discard pages
892 * that have already been sent but redirtied on the source.
893 * CMD_POSTCOPY_RAM_DISCARD consist of:
894 * byte version (0)
895 * byte Length of name field (not including 0)
896 * n x byte RAM block name
897 * byte 0 terminator (just for safety)
898 * n x Byte ranges within the named RAMBlock
899 * be64 Start of the range
900 * be64 Length
901 *
902 * name: RAMBlock name that these entries are part of
903 * len: Number of page entries
904 * start_list: 'len' addresses
905 * length_list: 'len' addresses
906 *
907 */
908void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
909 uint16_t len,
910 uint64_t *start_list,
911 uint64_t *length_list)
912{
913 uint8_t *buf;
914 uint16_t tmplen;
915 uint16_t t;
916 size_t name_len = strlen(name);
917
918 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
919 assert(name_len < 256);
920 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
921 buf[0] = postcopy_ram_discard_version;
922 buf[1] = name_len;
923 memcpy(buf + 2, name, name_len);
924 tmplen = 2 + name_len;
925 buf[tmplen++] = '\0';
926
927 for (t = 0; t < len; t++) {
4d885131 928 stq_be_p(buf + tmplen, start_list[t]);
093e3c42 929 tmplen += 8;
4d885131 930 stq_be_p(buf + tmplen, length_list[t]);
093e3c42
DDAG
931 tmplen += 8;
932 }
933 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
934 g_free(buf);
935}
936
937/* Get the destination into a state where it can receive postcopy data. */
938void qemu_savevm_send_postcopy_listen(QEMUFile *f)
939{
940 trace_savevm_send_postcopy_listen();
941 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
942}
943
944/* Kick the destination into running */
945void qemu_savevm_send_postcopy_run(QEMUFile *f)
946{
947 trace_savevm_send_postcopy_run();
948 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
949}
950
e1c37d0e 951bool qemu_savevm_state_blocked(Error **errp)
dc912121
AW
952{
953 SaveStateEntry *se;
954
0163a2e0 955 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
7d854c47 956 if (se->vmsd && se->vmsd->unmigratable) {
f231b88d
CR
957 error_setg(errp, "State blocked by non-migratable device '%s'",
958 se->idstr);
dc912121
AW
959 return true;
960 }
961 }
962 return false;
963}
964
902c053d
GK
965static bool enforce_config_section(void)
966{
967 MachineState *machine = MACHINE(qdev_get_machine());
968 return machine->enforce_config_section;
969}
970
f796baa1
DDAG
971void qemu_savevm_state_header(QEMUFile *f)
972{
973 trace_savevm_state_header();
974 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
975 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
172dfd4f 976
902c053d 977 if (!savevm_state.skip_configuration || enforce_config_section()) {
172dfd4f
DDAG
978 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
979 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
980 }
981
f796baa1
DDAG
982}
983
a0762d9e 984void qemu_savevm_state_begin(QEMUFile *f)
a672b469
AL
985{
986 SaveStateEntry *se;
39346385 987 int ret;
a672b469 988
9013dca5 989 trace_savevm_state_begin();
0163a2e0 990 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
d1315aac 991 if (!se->ops || !se->ops->save_live_setup) {
a672b469 992 continue;
22ea40f4 993 }
6bd68781
JQ
994 if (se->ops && se->ops->is_active) {
995 if (!se->ops->is_active(se->opaque)) {
996 continue;
997 }
998 }
ce39bfc9 999 save_section_header(f, se, QEMU_VM_SECTION_START);
a672b469 1000
d1315aac 1001 ret = se->ops->save_live_setup(f, se->opaque);
f68945d4 1002 save_section_footer(f, se);
2975725f 1003 if (ret < 0) {
47c8c17a
PB
1004 qemu_file_set_error(f, ret);
1005 break;
2975725f 1006 }
a672b469 1007 }
a672b469
AL
1008}
1009
39346385 1010/*
07f35073 1011 * this function has three return values:
39346385
JQ
1012 * negative: there was one error, and we have -errno.
1013 * 0 : We haven't finished, caller have to go again
1014 * 1 : We have finished, we can go to complete phase
1015 */
35ecd943 1016int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
a672b469
AL
1017{
1018 SaveStateEntry *se;
1019 int ret = 1;
1020
9013dca5 1021 trace_savevm_state_iterate();
0163a2e0 1022 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
16310a3c 1023 if (!se->ops || !se->ops->save_live_iterate) {
a672b469 1024 continue;
22ea40f4 1025 }
6bd68781
JQ
1026 if (se->ops && se->ops->is_active) {
1027 if (!se->ops->is_active(se->opaque)) {
1028 continue;
1029 }
1030 }
35ecd943
DDAG
1031 /*
1032 * In the postcopy phase, any device that doesn't know how to
1033 * do postcopy should have saved it's state in the _complete
1034 * call that's already run, it might get confused if we call
1035 * iterate afterwards.
1036 */
1037 if (postcopy && !se->ops->save_live_complete_postcopy) {
1038 continue;
1039 }
aac844ed
JQ
1040 if (qemu_file_rate_limit(f)) {
1041 return 0;
1042 }
464400f6 1043 trace_savevm_section_start(se->idstr, se->section_id);
ce39bfc9
DDAG
1044
1045 save_section_header(f, se, QEMU_VM_SECTION_PART);
a672b469 1046
16310a3c 1047 ret = se->ops->save_live_iterate(f, se->opaque);
a5df2a02 1048 trace_savevm_section_end(se->idstr, se->section_id, ret);
f68945d4 1049 save_section_footer(f, se);
517a13c9 1050
47c8c17a
PB
1051 if (ret < 0) {
1052 qemu_file_set_error(f, ret);
1053 }
2975725f 1054 if (ret <= 0) {
90697be8
JK
1055 /* Do not proceed to the next vmstate before this one reported
1056 completion of the current stage. This serializes the migration
1057 and reduces the probability that a faster changing state is
1058 synchronized over and over again. */
1059 break;
1060 }
a672b469 1061 }
39346385 1062 return ret;
a672b469
AL
1063}
1064
9850c604
AG
1065static bool should_send_vmdesc(void)
1066{
1067 MachineState *machine = MACHINE(qdev_get_machine());
5727309d 1068 bool in_postcopy = migration_in_postcopy();
8421b205 1069 return !machine->suppress_vmdesc && !in_postcopy;
9850c604
AG
1070}
1071
763c906b
DDAG
1072/*
1073 * Calls the save_live_complete_postcopy methods
1074 * causing the last few pages to be sent immediately and doing any associated
1075 * cleanup.
1076 * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1077 * all the other devices, but that happens at the point we switch to postcopy.
1078 */
1079void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1080{
1081 SaveStateEntry *se;
1082 int ret;
1083
1084 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1085 if (!se->ops || !se->ops->save_live_complete_postcopy) {
1086 continue;
1087 }
1088 if (se->ops && se->ops->is_active) {
1089 if (!se->ops->is_active(se->opaque)) {
1090 continue;
1091 }
1092 }
1093 trace_savevm_section_start(se->idstr, se->section_id);
1094 /* Section type */
1095 qemu_put_byte(f, QEMU_VM_SECTION_END);
1096 qemu_put_be32(f, se->section_id);
1097
1098 ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1099 trace_savevm_section_end(se->idstr, se->section_id, ret);
1100 save_section_footer(f, se);
1101 if (ret < 0) {
1102 qemu_file_set_error(f, ret);
1103 return;
1104 }
1105 }
1106
1107 qemu_put_byte(f, QEMU_VM_EOF);
1108 qemu_fflush(f);
1109}
1110
1c0d249d 1111void qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only)
a672b469 1112{
8118f095
AG
1113 QJSON *vmdesc;
1114 int vmdesc_len;
a672b469 1115 SaveStateEntry *se;
2975725f 1116 int ret;
5727309d 1117 bool in_postcopy = migration_in_postcopy();
a672b469 1118
a3e06c3d 1119 trace_savevm_state_complete_precopy();
9013dca5 1120
ea375f9a
JK
1121 cpu_synchronize_all_states();
1122
0163a2e0 1123 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
763c906b
DDAG
1124 if (!se->ops ||
1125 (in_postcopy && se->ops->save_live_complete_postcopy) ||
1c0d249d 1126 (in_postcopy && !iterable_only) ||
763c906b 1127 !se->ops->save_live_complete_precopy) {
a672b469 1128 continue;
22ea40f4 1129 }
1c0d249d 1130
6bd68781
JQ
1131 if (se->ops && se->ops->is_active) {
1132 if (!se->ops->is_active(se->opaque)) {
1133 continue;
1134 }
1135 }
464400f6 1136 trace_savevm_section_start(se->idstr, se->section_id);
ce39bfc9
DDAG
1137
1138 save_section_header(f, se, QEMU_VM_SECTION_END);
a672b469 1139
a3e06c3d 1140 ret = se->ops->save_live_complete_precopy(f, se->opaque);
a5df2a02 1141 trace_savevm_section_end(se->idstr, se->section_id, ret);
f68945d4 1142 save_section_footer(f, se);
2975725f 1143 if (ret < 0) {
47c8c17a
PB
1144 qemu_file_set_error(f, ret);
1145 return;
2975725f 1146 }
a672b469
AL
1147 }
1148
1c0d249d
DDAG
1149 if (iterable_only) {
1150 return;
1151 }
1152
8118f095 1153 vmdesc = qjson_new();
46d702b1 1154 json_prop_int(vmdesc, "page_size", qemu_target_page_size());
8118f095 1155 json_start_array(vmdesc, "devices");
0163a2e0 1156 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
a672b469 1157
22ea40f4 1158 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
5cecf414 1159 continue;
22ea40f4 1160 }
df896152
JQ
1161 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1162 trace_savevm_section_skip(se->idstr, se->section_id);
1163 continue;
1164 }
1165
464400f6 1166 trace_savevm_section_start(se->idstr, se->section_id);
8118f095
AG
1167
1168 json_start_object(vmdesc, NULL);
1169 json_prop_str(vmdesc, "name", se->idstr);
1170 json_prop_int(vmdesc, "instance_id", se->instance_id);
1171
ce39bfc9 1172 save_section_header(f, se, QEMU_VM_SECTION_FULL);
8118f095 1173 vmstate_save(f, se, vmdesc);
a5df2a02 1174 trace_savevm_section_end(se->idstr, se->section_id, 0);
f68945d4 1175 save_section_footer(f, se);
bdf46d64
WY
1176
1177 json_end_object(vmdesc);
a672b469
AL
1178 }
1179
763c906b
DDAG
1180 if (!in_postcopy) {
1181 /* Postcopy stream will still be going */
1182 qemu_put_byte(f, QEMU_VM_EOF);
1183 }
8118f095
AG
1184
1185 json_end_array(vmdesc);
1186 qjson_finish(vmdesc);
1187 vmdesc_len = strlen(qjson_get_str(vmdesc));
1188
9850c604
AG
1189 if (should_send_vmdesc()) {
1190 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1191 qemu_put_be32(f, vmdesc_len);
1192 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1193 }
b72fe9e6 1194 qjson_destroy(vmdesc);
8118f095 1195
edaae611 1196 qemu_fflush(f);
a672b469
AL
1197}
1198
c31b098f
DDAG
1199/* Give an estimate of the amount left to be transferred,
1200 * the result is split into the amount for units that can and
1201 * for units that can't do postcopy.
1202 */
faec066a 1203void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
c31b098f
DDAG
1204 uint64_t *res_non_postcopiable,
1205 uint64_t *res_postcopiable)
e4ed1541
JQ
1206{
1207 SaveStateEntry *se;
c31b098f
DDAG
1208
1209 *res_non_postcopiable = 0;
1210 *res_postcopiable = 0;
1211
e4ed1541 1212
0163a2e0 1213 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
e4ed1541
JQ
1214 if (!se->ops || !se->ops->save_live_pending) {
1215 continue;
1216 }
1217 if (se->ops && se->ops->is_active) {
1218 if (!se->ops->is_active(se->opaque)) {
1219 continue;
1220 }
1221 }
faec066a 1222 se->ops->save_live_pending(f, se->opaque, threshold_size,
c31b098f 1223 res_non_postcopiable, res_postcopiable);
e4ed1541 1224 }
e4ed1541
JQ
1225}
1226
ea7415fa 1227void qemu_savevm_state_cleanup(void)
4ec7fcc7
JK
1228{
1229 SaveStateEntry *se;
1230
ea7415fa 1231 trace_savevm_state_cleanup();
0163a2e0 1232 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
d1a8548c
LL
1233 if (se->ops && se->ops->cleanup) {
1234 se->ops->cleanup(se->opaque);
4ec7fcc7
JK
1235 }
1236 }
1237}
1238
5d80448c 1239static int qemu_savevm_state(QEMUFile *f, Error **errp)
a672b469 1240{
a672b469 1241 int ret;
a0762d9e 1242 MigrationState *ms = migrate_init();
6dcf6668 1243 MigrationStatus status;
89a02a9f 1244 ms->to_dst_file = f;
a672b469 1245
24f3902b 1246 if (migration_is_blocked(errp)) {
6dcf6668
DL
1247 ret = -EINVAL;
1248 goto done;
dc912121
AW
1249 }
1250
ce7c817c
JQ
1251 if (migrate_use_block()) {
1252 error_setg(errp, "Block migration and snapshots are incompatible");
1253 ret = -EINVAL;
1254 goto done;
1255 }
1256
9b095037 1257 qemu_mutex_unlock_iothread();
f796baa1 1258 qemu_savevm_state_header(f);
a0762d9e 1259 qemu_savevm_state_begin(f);
9b095037
PB
1260 qemu_mutex_lock_iothread();
1261
47c8c17a 1262 while (qemu_file_get_error(f) == 0) {
35ecd943 1263 if (qemu_savevm_state_iterate(f, false) > 0) {
47c8c17a
PB
1264 break;
1265 }
1266 }
a672b469 1267
47c8c17a 1268 ret = qemu_file_get_error(f);
39346385 1269 if (ret == 0) {
1c0d249d 1270 qemu_savevm_state_complete_precopy(f, false);
624b9cc2 1271 ret = qemu_file_get_error(f);
39346385 1272 }
15b3b8ea 1273 qemu_savevm_state_cleanup();
04943eba 1274 if (ret != 0) {
5d80448c 1275 error_setg_errno(errp, -ret, "Error while writing VM state");
04943eba 1276 }
6dcf6668
DL
1277
1278done:
1279 if (ret != 0) {
1280 status = MIGRATION_STATUS_FAILED;
1281 } else {
1282 status = MIGRATION_STATUS_COMPLETED;
1283 }
1284 migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
f9c8caa0
VSO
1285
1286 /* f is outer parameter, it should not stay in global migration state after
1287 * this function finished */
1288 ms->to_dst_file = NULL;
1289
a672b469
AL
1290 return ret;
1291}
1292
a7ae8355
SS
1293static int qemu_save_device_state(QEMUFile *f)
1294{
1295 SaveStateEntry *se;
1296
1297 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1298 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1299
1300 cpu_synchronize_all_states();
1301
0163a2e0 1302 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
a7ae8355
SS
1303 if (se->is_ram) {
1304 continue;
1305 }
22ea40f4 1306 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
a7ae8355
SS
1307 continue;
1308 }
df896152
JQ
1309 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1310 continue;
1311 }
a7ae8355 1312
ce39bfc9 1313 save_section_header(f, se, QEMU_VM_SECTION_FULL);
a7ae8355 1314
8118f095 1315 vmstate_save(f, se, NULL);
f68945d4
DDAG
1316
1317 save_section_footer(f, se);
a7ae8355
SS
1318 }
1319
1320 qemu_put_byte(f, QEMU_VM_EOF);
1321
1322 return qemu_file_get_error(f);
1323}
1324
a672b469
AL
1325static SaveStateEntry *find_se(const char *idstr, int instance_id)
1326{
1327 SaveStateEntry *se;
1328
0163a2e0 1329 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
a672b469 1330 if (!strcmp(se->idstr, idstr) &&
4d2ffa08
JK
1331 (instance_id == se->instance_id ||
1332 instance_id == se->alias_id))
a672b469 1333 return se;
7685ee6a
AW
1334 /* Migrating from an older version? */
1335 if (strstr(se->idstr, idstr) && se->compat) {
1336 if (!strcmp(se->compat->idstr, idstr) &&
1337 (instance_id == se->compat->instance_id ||
1338 instance_id == se->alias_id))
1339 return se;
1340 }
a672b469
AL
1341 }
1342 return NULL;
1343}
1344
7b89bf27
DDAG
1345enum LoadVMExitCodes {
1346 /* Allow a command to quit all layers of nested loadvm loops */
1347 LOADVM_QUIT = 1,
1348};
1349
1350static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
093e3c42
DDAG
1351
1352/* ------ incoming postcopy messages ------ */
1353/* 'advise' arrives before any transfers just to tell us that a postcopy
1354 * *might* happen - it might be skipped if precopy transferred everything
1355 * quickly.
1356 */
1357static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)
1358{
1359 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
e8ca1db2 1360 uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
093e3c42
DDAG
1361
1362 trace_loadvm_postcopy_handle_advise();
1363 if (ps != POSTCOPY_INCOMING_NONE) {
1364 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1365 return -1;
1366 }
1367
eb59db53 1368 if (!postcopy_ram_supported_by_host()) {
328d4d85 1369 postcopy_state_set(POSTCOPY_INCOMING_NONE);
eb59db53
DDAG
1370 return -1;
1371 }
1372
e8ca1db2
DDAG
1373 remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1374 local_pagesize_summary = ram_pagesize_summary();
1375
1376 if (remote_pagesize_summary != local_pagesize_summary) {
093e3c42 1377 /*
e8ca1db2
DDAG
1378 * This detects two potential causes of mismatch:
1379 * a) A mismatch in host page sizes
1380 * Some combinations of mismatch are probably possible but it gets
1381 * a bit more complicated. In particular we need to place whole
1382 * host pages on the dest at once, and we need to ensure that we
1383 * handle dirtying to make sure we never end up sending part of
1384 * a hostpage on it's own.
1385 * b) The use of different huge page sizes on source/destination
1386 * a more fine grain test is performed during RAM block migration
1387 * but this test here causes a nice early clear failure, and
1388 * also fails when passed to an older qemu that doesn't
1389 * do huge pages.
093e3c42 1390 */
e8ca1db2
DDAG
1391 error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1392 " d=%" PRIx64 ")",
1393 remote_pagesize_summary, local_pagesize_summary);
093e3c42
DDAG
1394 return -1;
1395 }
1396
1397 remote_tps = qemu_get_be64(mis->from_src_file);
20afaed9 1398 if (remote_tps != qemu_target_page_size()) {
093e3c42
DDAG
1399 /*
1400 * Again, some differences could be dealt with, but for now keep it
1401 * simple.
1402 */
20afaed9
JQ
1403 error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1404 (int)remote_tps, qemu_target_page_size());
093e3c42
DDAG
1405 return -1;
1406 }
1407
1caddf8a
DDAG
1408 if (ram_postcopy_incoming_init(mis)) {
1409 return -1;
1410 }
1411
1412 postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1413
093e3c42
DDAG
1414 return 0;
1415}
1416
1417/* After postcopy we will be told to throw some pages away since they're
1418 * dirty and will have to be demand fetched. Must happen before CPU is
1419 * started.
1420 * There can be 0..many of these messages, each encoding multiple pages.
1421 */
1422static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1423 uint16_t len)
1424{
1425 int tmp;
1426 char ramid[256];
1427 PostcopyState ps = postcopy_state_get();
1428
1429 trace_loadvm_postcopy_ram_handle_discard();
1430
1431 switch (ps) {
1432 case POSTCOPY_INCOMING_ADVISE:
1433 /* 1st discard */
f9527107 1434 tmp = postcopy_ram_prepare_discard(mis);
093e3c42
DDAG
1435 if (tmp) {
1436 return tmp;
1437 }
1438 break;
1439
1440 case POSTCOPY_INCOMING_DISCARD:
1441 /* Expected state */
1442 break;
1443
1444 default:
1445 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1446 ps);
1447 return -1;
1448 }
1449 /* We're expecting a
1450 * Version (0)
1451 * a RAM ID string (length byte, name, 0 term)
1452 * then at least 1 16 byte chunk
1453 */
1454 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1455 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1456 return -1;
1457 }
1458
1459 tmp = qemu_get_byte(mis->from_src_file);
1460 if (tmp != postcopy_ram_discard_version) {
1461 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1462 return -1;
1463 }
1464
1465 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1466 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1467 return -1;
1468 }
1469 tmp = qemu_get_byte(mis->from_src_file);
1470 if (tmp != 0) {
1471 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1472 return -1;
1473 }
1474
1475 len -= 3 + strlen(ramid);
1476 if (len % 16) {
1477 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1478 return -1;
1479 }
1480 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1481 while (len) {
093e3c42
DDAG
1482 uint64_t start_addr, block_length;
1483 start_addr = qemu_get_be64(mis->from_src_file);
1484 block_length = qemu_get_be64(mis->from_src_file);
1485
1486 len -= 16;
aaa2064c 1487 int ret = ram_discard_range(ramid, start_addr, block_length);
093e3c42
DDAG
1488 if (ret) {
1489 return ret;
1490 }
093e3c42
DDAG
1491 }
1492 trace_loadvm_postcopy_ram_handle_discard_end();
1493
1494 return 0;
1495}
1496
c76201ab
DDAG
1497/*
1498 * Triggered by a postcopy_listen command; this thread takes over reading
1499 * the input stream, leaving the main thread free to carry on loading the rest
1500 * of the device state (from RAM).
1501 * (TODO:This could do with being in a postcopy file - but there again it's
1502 * just another input loop, not that postcopy specific)
1503 */
1504static void *postcopy_ram_listen_thread(void *opaque)
1505{
1506 QEMUFile *f = opaque;
1507 MigrationIncomingState *mis = migration_incoming_get_current();
1508 int load_res;
1509
6ba996bb
DDAG
1510 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1511 MIGRATION_STATUS_POSTCOPY_ACTIVE);
c76201ab
DDAG
1512 qemu_sem_post(&mis->listen_thread_sem);
1513 trace_postcopy_ram_listen_thread_start();
1514
1515 /*
1516 * Because we're a thread and not a coroutine we can't yield
1517 * in qemu_file, and thus we must be blocking now.
1518 */
1519 qemu_file_set_blocking(f, true);
1520 load_res = qemu_loadvm_state_main(f, mis);
1521 /* And non-blocking again so we don't block in any cleanup */
1522 qemu_file_set_blocking(f, false);
1523
1524 trace_postcopy_ram_listen_thread_exit();
1525 if (load_res < 0) {
1526 error_report("%s: loadvm failed: %d", __func__, load_res);
1527 qemu_file_set_error(f, load_res);
6ba996bb
DDAG
1528 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1529 MIGRATION_STATUS_FAILED);
c76201ab
DDAG
1530 } else {
1531 /*
1532 * This looks good, but it's possible that the device loading in the
1533 * main thread hasn't finished yet, and so we might not be in 'RUN'
1534 * state yet; wait for the end of the main thread.
1535 */
1536 qemu_event_wait(&mis->main_thread_load_event);
1537 }
1538 postcopy_ram_incoming_cleanup(mis);
c76201ab
DDAG
1539
1540 if (load_res < 0) {
1541 /*
1542 * If something went wrong then we have a bad state so exit;
1543 * depending how far we got it might be possible at this point
1544 * to leave the guest running and fire MCEs for pages that never
1545 * arrived as a desperate recovery step.
1546 */
1547 exit(EXIT_FAILURE);
1548 }
1549
6ba996bb
DDAG
1550 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1551 MIGRATION_STATUS_COMPLETED);
1552 /*
1553 * If everything has worked fine, then the main thread has waited
1554 * for us to start, and we're the last use of the mis.
1555 * (If something broke then qemu will have to exit anyway since it's
1556 * got a bad migration state).
1557 */
1558 migration_incoming_state_destroy();
1559
1560
c76201ab
DDAG
1561 return NULL;
1562}
1563
093e3c42
DDAG
1564/* After this message we must be able to immediately receive postcopy data */
1565static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1566{
1567 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1568 trace_loadvm_postcopy_handle_listen();
1569 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1570 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1571 return -1;
1572 }
f9527107
DDAG
1573 if (ps == POSTCOPY_INCOMING_ADVISE) {
1574 /*
1575 * A rare case, we entered listen without having to do any discards,
1576 * so do the setup that's normally done at the time of the 1st discard.
1577 */
1578 postcopy_ram_prepare_discard(mis);
1579 }
093e3c42 1580
f0a227ad
DDAG
1581 /*
1582 * Sensitise RAM - can now generate requests for blocks that don't exist
1583 * However, at this point the CPU shouldn't be running, and the IO
1584 * shouldn't be doing anything yet so don't actually expect requests
1585 */
1586 if (postcopy_ram_enable_notify(mis)) {
1587 return -1;
1588 }
1589
c76201ab
DDAG
1590 if (mis->have_listen_thread) {
1591 error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1592 return -1;
1593 }
1594
1595 mis->have_listen_thread = true;
1596 /* Start up the listening thread and wait for it to signal ready */
1597 qemu_sem_init(&mis->listen_thread_sem, 0);
1598 qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1599 postcopy_ram_listen_thread, mis->from_src_file,
a587a3fe 1600 QEMU_THREAD_DETACHED);
c76201ab
DDAG
1601 qemu_sem_wait(&mis->listen_thread_sem);
1602 qemu_sem_destroy(&mis->listen_thread_sem);
1603
093e3c42
DDAG
1604 return 0;
1605}
1606
86469922
DL
1607
1608typedef struct {
1609 QEMUBH *bh;
1610} HandleRunBhData;
1611
ea6a55bc 1612static void loadvm_postcopy_handle_run_bh(void *opaque)
093e3c42 1613{
27c6825b 1614 Error *local_err = NULL;
86469922 1615 HandleRunBhData *data = opaque;
093e3c42 1616
27c6825b
DDAG
1617 /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1618 * in migration.c
1619 */
1620 cpu_synchronize_all_post_init();
1621
1622 qemu_announce_self();
1623
ace21a58
KW
1624 /* Make sure all file formats flush their mutable metadata.
1625 * If we get an error here, just don't restart the VM yet. */
27c6825b 1626 bdrv_invalidate_cache_all(&local_err);
0042fd36 1627 if (local_err) {
ace21a58 1628 error_report_err(local_err);
0042fd36
KW
1629 local_err = NULL;
1630 autostart = false;
1631 }
1632
27c6825b
DDAG
1633 trace_loadvm_postcopy_handle_run_cpu_sync();
1634 cpu_synchronize_all_post_init();
1635
1636 trace_loadvm_postcopy_handle_run_vmstart();
1637
093e3c42
DDAG
1638 if (autostart) {
1639 /* Hold onto your hats, starting the CPU */
1640 vm_start();
1641 } else {
1642 /* leave it paused and let management decide when to start the CPU */
1643 runstate_set(RUN_STATE_PAUSED);
1644 }
1645
86469922
DL
1646 qemu_bh_delete(data->bh);
1647 g_free(data);
ea6a55bc
DL
1648}
1649
1650/* After all discards we can start running and asking for pages */
1651static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1652{
1653 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
86469922 1654 HandleRunBhData *data;
ea6a55bc
DL
1655
1656 trace_loadvm_postcopy_handle_run();
1657 if (ps != POSTCOPY_INCOMING_LISTENING) {
1658 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1659 return -1;
1660 }
1661
86469922
DL
1662 data = g_new(HandleRunBhData, 1);
1663 data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1664 qemu_bh_schedule(data->bh);
ea6a55bc 1665
27c6825b
DDAG
1666 /* We need to finish reading the stream from the package
1667 * and also stop reading anything more from the stream that loaded the
1668 * package (since it's now being read by the listener thread).
1669 * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1670 */
1671 return LOADVM_QUIT;
093e3c42
DDAG
1672}
1673
c76ca188 1674/**
11cf1d98
DDAG
1675 * Immediately following this command is a blob of data containing an embedded
1676 * chunk of migration stream; read it and load it.
1677 *
1678 * @mis: Incoming state
1679 * @length: Length of packaged data to read
c76ca188 1680 *
11cf1d98
DDAG
1681 * Returns: Negative values on error
1682 *
1683 */
1684static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1685{
1686 int ret;
61b67d47
DB
1687 size_t length;
1688 QIOChannelBuffer *bioc;
11cf1d98
DDAG
1689
1690 length = qemu_get_be32(mis->from_src_file);
1691 trace_loadvm_handle_cmd_packaged(length);
1692
1693 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
61b67d47 1694 error_report("Unreasonably large packaged state: %zu", length);
11cf1d98
DDAG
1695 return -1;
1696 }
61b67d47
DB
1697
1698 bioc = qio_channel_buffer_new(length);
6f01f136 1699 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
61b67d47
DB
1700 ret = qemu_get_buffer(mis->from_src_file,
1701 bioc->data,
1702 length);
11cf1d98 1703 if (ret != length) {
61b67d47
DB
1704 object_unref(OBJECT(bioc));
1705 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
9af9e0fe 1706 ret, length);
11cf1d98
DDAG
1707 return (ret < 0) ? ret : -EAGAIN;
1708 }
61b67d47 1709 bioc->usage += length;
11cf1d98
DDAG
1710 trace_loadvm_handle_cmd_packaged_received(ret);
1711
61b67d47 1712 QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
11cf1d98
DDAG
1713
1714 ret = qemu_loadvm_state_main(packf, mis);
1715 trace_loadvm_handle_cmd_packaged_main(ret);
1716 qemu_fclose(packf);
61b67d47 1717 object_unref(OBJECT(bioc));
11cf1d98
DDAG
1718
1719 return ret;
1720}
1721
1722/*
1723 * Process an incoming 'QEMU_VM_COMMAND'
1724 * 0 just a normal return
1725 * LOADVM_QUIT All good, but exit the loop
1726 * <0 Error
c76ca188
DDAG
1727 */
1728static int loadvm_process_command(QEMUFile *f)
1729{
2e37701e 1730 MigrationIncomingState *mis = migration_incoming_get_current();
c76ca188
DDAG
1731 uint16_t cmd;
1732 uint16_t len;
2e37701e 1733 uint32_t tmp32;
c76ca188
DDAG
1734
1735 cmd = qemu_get_be16(f);
1736 len = qemu_get_be16(f);
1737
1738 trace_loadvm_process_command(cmd, len);
1739 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
1740 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
1741 return -EINVAL;
1742 }
1743
1744 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
1745 error_report("%s received with bad length - expecting %zu, got %d",
1746 mig_cmd_args[cmd].name,
1747 (size_t)mig_cmd_args[cmd].len, len);
1748 return -ERANGE;
1749 }
1750
1751 switch (cmd) {
2e37701e
DDAG
1752 case MIG_CMD_OPEN_RETURN_PATH:
1753 if (mis->to_src_file) {
1754 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1755 /* Not really a problem, so don't give up */
1756 return 0;
1757 }
1758 mis->to_src_file = qemu_file_get_return_path(f);
1759 if (!mis->to_src_file) {
1760 error_report("CMD_OPEN_RETURN_PATH failed");
1761 return -1;
1762 }
1763 break;
1764
1765 case MIG_CMD_PING:
1766 tmp32 = qemu_get_be32(f);
1767 trace_loadvm_process_command_ping(tmp32);
1768 if (!mis->to_src_file) {
1769 error_report("CMD_PING (0x%x) received with no return path",
1770 tmp32);
1771 return -1;
1772 }
6decec93 1773 migrate_send_rp_pong(mis, tmp32);
2e37701e 1774 break;
093e3c42 1775
11cf1d98
DDAG
1776 case MIG_CMD_PACKAGED:
1777 return loadvm_handle_cmd_packaged(mis);
1778
093e3c42
DDAG
1779 case MIG_CMD_POSTCOPY_ADVISE:
1780 return loadvm_postcopy_handle_advise(mis);
1781
1782 case MIG_CMD_POSTCOPY_LISTEN:
1783 return loadvm_postcopy_handle_listen(mis);
1784
1785 case MIG_CMD_POSTCOPY_RUN:
1786 return loadvm_postcopy_handle_run(mis);
1787
1788 case MIG_CMD_POSTCOPY_RAM_DISCARD:
1789 return loadvm_postcopy_ram_handle_discard(mis, len);
c76ca188
DDAG
1790 }
1791
1792 return 0;
1793}
1794
59f39a47
DDAG
1795/*
1796 * Read a footer off the wire and check that it matches the expected section
1797 *
1798 * Returns: true if the footer was good
1799 * false if there is a problem (and calls error_report to say why)
1800 */
0f42f657 1801static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
59f39a47
DDAG
1802{
1803 uint8_t read_mark;
1804 uint32_t read_section_id;
1805
1806 if (skip_section_footers) {
1807 /* No footer to check */
1808 return true;
1809 }
1810
1811 read_mark = qemu_get_byte(f);
1812
1813 if (read_mark != QEMU_VM_SECTION_FOOTER) {
0f42f657 1814 error_report("Missing section footer for %s", se->idstr);
59f39a47
DDAG
1815 return false;
1816 }
1817
1818 read_section_id = qemu_get_be32(f);
0f42f657 1819 if (read_section_id != se->load_section_id) {
59f39a47
DDAG
1820 error_report("Mismatched section id in footer for %s -"
1821 " read 0x%x expected 0x%x",
0f42f657 1822 se->idstr, read_section_id, se->load_section_id);
59f39a47
DDAG
1823 return false;
1824 }
1825
1826 /* All good */
1827 return true;
1828}
1829
fb3520a8
HZ
1830static int
1831qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
1832{
1833 uint32_t instance_id, version_id, section_id;
1834 SaveStateEntry *se;
fb3520a8
HZ
1835 char idstr[256];
1836 int ret;
1837
1838 /* Read section start */
1839 section_id = qemu_get_be32(f);
1840 if (!qemu_get_counted_string(f, idstr)) {
1841 error_report("Unable to read ID string for section %u",
1842 section_id);
1843 return -EINVAL;
1844 }
1845 instance_id = qemu_get_be32(f);
1846 version_id = qemu_get_be32(f);
1847
1848 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
1849 instance_id, version_id);
1850 /* Find savevm section */
1851 se = find_se(idstr, instance_id);
1852 if (se == NULL) {
1853 error_report("Unknown savevm section or instance '%s' %d",
1854 idstr, instance_id);
1855 return -EINVAL;
1856 }
1857
1858 /* Validate version */
1859 if (version_id > se->version_id) {
1860 error_report("savevm: unsupported version %d for '%s' v%d",
1861 version_id, idstr, se->version_id);
1862 return -EINVAL;
1863 }
0f42f657
JQ
1864 se->load_version_id = version_id;
1865 se->load_section_id = section_id;
fb3520a8 1866
88c16567
WC
1867 /* Validate if it is a device's state */
1868 if (xen_enabled() && se->is_ram) {
1869 error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
1870 return -EINVAL;
1871 }
1872
3a011c26 1873 ret = vmstate_load(f, se);
fb3520a8
HZ
1874 if (ret < 0) {
1875 error_report("error while loading state for instance 0x%x of"
1876 " device '%s'", instance_id, idstr);
1877 return ret;
1878 }
0f42f657 1879 if (!check_section_footer(f, se)) {
fb3520a8
HZ
1880 return -EINVAL;
1881 }
1882
1883 return 0;
1884}
1885
1886static int
1887qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
1888{
1889 uint32_t section_id;
0f42f657 1890 SaveStateEntry *se;
fb3520a8
HZ
1891 int ret;
1892
1893 section_id = qemu_get_be32(f);
1894
1895 trace_qemu_loadvm_state_section_partend(section_id);
0f42f657
JQ
1896 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1897 if (se->load_section_id == section_id) {
fb3520a8
HZ
1898 break;
1899 }
1900 }
0f42f657 1901 if (se == NULL) {
fb3520a8
HZ
1902 error_report("Unknown savevm section %d", section_id);
1903 return -EINVAL;
1904 }
1905
3a011c26 1906 ret = vmstate_load(f, se);
fb3520a8
HZ
1907 if (ret < 0) {
1908 error_report("error while loading state section id %d(%s)",
0f42f657 1909 section_id, se->idstr);
fb3520a8
HZ
1910 return ret;
1911 }
0f42f657 1912 if (!check_section_footer(f, se)) {
fb3520a8
HZ
1913 return -EINVAL;
1914 }
1915
1916 return 0;
1917}
1918
7b89bf27 1919static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
1a8f46f8 1920{
a672b469 1921 uint8_t section_type;
ccb783c3 1922 int ret = 0;
61964c23 1923
a672b469 1924 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
ccb783c3 1925 ret = 0;
a5df2a02 1926 trace_qemu_loadvm_state_section(section_type);
a672b469
AL
1927 switch (section_type) {
1928 case QEMU_VM_SECTION_START:
1929 case QEMU_VM_SECTION_FULL:
fb3520a8 1930 ret = qemu_loadvm_section_start_full(f, mis);
b5a22e4a 1931 if (ret < 0) {
ccb783c3 1932 goto out;
b5a22e4a 1933 }
a672b469
AL
1934 break;
1935 case QEMU_VM_SECTION_PART:
1936 case QEMU_VM_SECTION_END:
fb3520a8 1937 ret = qemu_loadvm_section_part_end(f, mis);
b5a22e4a 1938 if (ret < 0) {
ccb783c3 1939 goto out;
b5a22e4a 1940 }
a672b469 1941 break;
c76ca188
DDAG
1942 case QEMU_VM_COMMAND:
1943 ret = loadvm_process_command(f);
7b89bf27
DDAG
1944 trace_qemu_loadvm_state_section_command(ret);
1945 if ((ret < 0) || (ret & LOADVM_QUIT)) {
ccb783c3 1946 goto out;
c76ca188
DDAG
1947 }
1948 break;
a672b469 1949 default:
6a64b644 1950 error_report("Unknown savevm section type %d", section_type);
ccb783c3
DDAG
1951 ret = -EINVAL;
1952 goto out;
a672b469
AL
1953 }
1954 }
1955
ccb783c3
DDAG
1956out:
1957 if (ret < 0) {
1958 qemu_file_set_error(f, ret);
1959 }
1960 return ret;
7b89bf27
DDAG
1961}
1962
1963int qemu_loadvm_state(QEMUFile *f)
1964{
1965 MigrationIncomingState *mis = migration_incoming_get_current();
1966 Error *local_err = NULL;
1967 unsigned int v;
1968 int ret;
1969
1970 if (qemu_savevm_state_blocked(&local_err)) {
1971 error_report_err(local_err);
1972 return -EINVAL;
1973 }
1974
1975 v = qemu_get_be32(f);
1976 if (v != QEMU_VM_FILE_MAGIC) {
1977 error_report("Not a migration stream");
1978 return -EINVAL;
1979 }
1980
1981 v = qemu_get_be32(f);
1982 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
1983 error_report("SaveVM v2 format is obsolete and don't work anymore");
1984 return -ENOTSUP;
1985 }
1986 if (v != QEMU_VM_FILE_VERSION) {
1987 error_report("Unsupported migration stream version");
1988 return -ENOTSUP;
1989 }
1990
902c053d 1991 if (!savevm_state.skip_configuration || enforce_config_section()) {
7b89bf27
DDAG
1992 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
1993 error_report("Configuration section missing");
1994 return -EINVAL;
1995 }
1996 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
1997
1998 if (ret) {
1999 return ret;
2000 }
2001 }
2002
75e972da
DG
2003 cpu_synchronize_all_pre_loadvm();
2004
7b89bf27
DDAG
2005 ret = qemu_loadvm_state_main(f, mis);
2006 qemu_event_set(&mis->main_thread_load_event);
2007
2008 trace_qemu_loadvm_state_post_main(ret);
2009
c76201ab
DDAG
2010 if (mis->have_listen_thread) {
2011 /* Listen thread still going, can't clean up yet */
2012 return ret;
2013 }
2014
7b89bf27
DDAG
2015 if (ret == 0) {
2016 ret = qemu_file_get_error(f);
2017 }
1925cebc
AG
2018
2019 /*
2020 * Try to read in the VMDESC section as well, so that dumping tools that
2021 * intercept our migration stream have the chance to see it.
2022 */
1aca9a5f
DDAG
2023
2024 /* We've got to be careful; if we don't read the data and just shut the fd
2025 * then the sender can error if we close while it's still sending.
2026 * We also mustn't read data that isn't there; some transports (RDMA)
2027 * will stall waiting for that data when the source has already closed.
2028 */
7b89bf27 2029 if (ret == 0 && should_send_vmdesc()) {
1aca9a5f
DDAG
2030 uint8_t *buf;
2031 uint32_t size;
7b89bf27 2032 uint8_t section_type = qemu_get_byte(f);
1aca9a5f
DDAG
2033
2034 if (section_type != QEMU_VM_VMDESCRIPTION) {
2035 error_report("Expected vmdescription section, but got %d",
2036 section_type);
2037 /*
2038 * It doesn't seem worth failing at this point since
2039 * we apparently have an otherwise valid VM state
2040 */
2041 } else {
2042 buf = g_malloc(0x1000);
2043 size = qemu_get_be32(f);
2044
2045 while (size > 0) {
2046 uint32_t read_chunk = MIN(size, 0x1000);
2047 qemu_get_buffer(f, buf, read_chunk);
2048 size -= read_chunk;
2049 }
2050 g_free(buf);
1925cebc 2051 }
1925cebc
AG
2052 }
2053
ea375f9a
JK
2054 cpu_synchronize_all_post_init();
2055
a672b469
AL
2056 return ret;
2057}
2058
5e22479a 2059int save_snapshot(const char *name, Error **errp)
a672b469
AL
2060{
2061 BlockDriverState *bs, *bs1;
2062 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
ac8c19ba 2063 int ret = -1;
a672b469
AL
2064 QEMUFile *f;
2065 int saved_vm_running;
c2c9a466 2066 uint64_t vm_state_size;
68b891ec 2067 qemu_timeval tv;
7d631a11 2068 struct tm tm;
79b3c12a 2069 AioContext *aio_context;
a672b469 2070
e9ff957a 2071 if (!bdrv_all_can_snapshot(&bs)) {
927d6638
JQ
2072 error_setg(errp, "Device '%s' is writable but does not support "
2073 "snapshots", bdrv_get_device_name(bs));
ac8c19ba 2074 return ret;
feeee5ac
MDCF
2075 }
2076
0b461605 2077 /* Delete old snapshots of the same name */
ac8c19ba 2078 if (name) {
927d6638 2079 ret = bdrv_all_delete_snapshot(name, &bs1, errp);
ac8c19ba 2080 if (ret < 0) {
927d6638
JQ
2081 error_prepend(errp, "Error while deleting snapshot on device "
2082 "'%s': ", bdrv_get_device_name(bs1));
ac8c19ba
PD
2083 return ret;
2084 }
0b461605
DL
2085 }
2086
7cb14481
DL
2087 bs = bdrv_all_find_vmstate_bs();
2088 if (bs == NULL) {
927d6638 2089 error_setg(errp, "No block device can accept snapshots");
ac8c19ba 2090 return ret;
a672b469 2091 }
79b3c12a 2092 aio_context = bdrv_get_aio_context(bs);
a672b469 2093
1354869c 2094 saved_vm_running = runstate_is_running();
560d027b
JQ
2095
2096 ret = global_state_store();
2097 if (ret) {
927d6638 2098 error_setg(errp, "Error saving global state");
ac8c19ba 2099 return ret;
560d027b 2100 }
0461d5a6 2101 vm_stop(RUN_STATE_SAVE_VM);
a672b469 2102
79b3c12a
DL
2103 aio_context_acquire(aio_context);
2104
cb499fb2 2105 memset(sn, 0, sizeof(*sn));
a672b469
AL
2106
2107 /* fill auxiliary fields */
68b891ec 2108 qemu_gettimeofday(&tv);
a672b469
AL
2109 sn->date_sec = tv.tv_sec;
2110 sn->date_nsec = tv.tv_usec * 1000;
bc72ad67 2111 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
a672b469 2112
7d631a11
MDCF
2113 if (name) {
2114 ret = bdrv_snapshot_find(bs, old_sn, name);
2115 if (ret >= 0) {
2116 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2117 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2118 } else {
2119 pstrcpy(sn->name, sizeof(sn->name), name);
2120 }
2121 } else {
d7d9b528
BS
2122 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2123 localtime_r((const time_t *)&tv.tv_sec, &tm);
7d631a11 2124 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
7d631a11
MDCF
2125 }
2126
a672b469 2127 /* save the VM state */
45566e9c 2128 f = qemu_fopen_bdrv(bs, 1);
a672b469 2129 if (!f) {
927d6638 2130 error_setg(errp, "Could not open VM state file");
a672b469
AL
2131 goto the_end;
2132 }
927d6638 2133 ret = qemu_savevm_state(f, errp);
2d22b18f 2134 vm_state_size = qemu_ftell(f);
a672b469
AL
2135 qemu_fclose(f);
2136 if (ret < 0) {
a672b469
AL
2137 goto the_end;
2138 }
2139
a9085f9b
DL
2140 ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2141 if (ret < 0) {
927d6638
JQ
2142 error_setg(errp, "Error while creating snapshot on '%s'",
2143 bdrv_get_device_name(bs));
ac8c19ba 2144 goto the_end;
a672b469
AL
2145 }
2146
ac8c19ba
PD
2147 ret = 0;
2148
a672b469 2149 the_end:
79b3c12a 2150 aio_context_release(aio_context);
38ff78d3 2151 if (saved_vm_running) {
a672b469 2152 vm_start();
38ff78d3 2153 }
ac8c19ba
PD
2154 return ret;
2155}
2156
a7ae8355
SS
2157void qmp_xen_save_devices_state(const char *filename, Error **errp)
2158{
2159 QEMUFile *f;
8925839f 2160 QIOChannelFile *ioc;
a7ae8355
SS
2161 int saved_vm_running;
2162 int ret;
2163
2164 saved_vm_running = runstate_is_running();
2165 vm_stop(RUN_STATE_SAVE_VM);
c69adea4 2166 global_state_store_running();
a7ae8355 2167
8925839f
DB
2168 ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2169 if (!ioc) {
a7ae8355
SS
2170 goto the_end;
2171 }
6f01f136 2172 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
8925839f 2173 f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
a7ae8355
SS
2174 ret = qemu_save_device_state(f);
2175 qemu_fclose(f);
2176 if (ret < 0) {
c6bd8c70 2177 error_setg(errp, QERR_IO_ERROR);
a7ae8355
SS
2178 }
2179
2180 the_end:
38ff78d3 2181 if (saved_vm_running) {
a7ae8355 2182 vm_start();
38ff78d3 2183 }
a7ae8355
SS
2184}
2185
88c16567
WC
2186void qmp_xen_load_devices_state(const char *filename, Error **errp)
2187{
2188 QEMUFile *f;
2189 QIOChannelFile *ioc;
2190 int ret;
2191
2192 /* Guest must be paused before loading the device state; the RAM state
2193 * will already have been loaded by xc
2194 */
2195 if (runstate_is_running()) {
2196 error_setg(errp, "Cannot update device state while vm is running");
2197 return;
2198 }
2199 vm_stop(RUN_STATE_RESTORE_VM);
2200
2201 ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2202 if (!ioc) {
2203 return;
2204 }
6f01f136 2205 qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
88c16567
WC
2206 f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2207
88c16567
WC
2208 ret = qemu_loadvm_state(f);
2209 qemu_fclose(f);
2210 if (ret < 0) {
2211 error_setg(errp, QERR_IO_ERROR);
2212 }
2213 migration_incoming_state_destroy();
2214}
2215
5e22479a 2216int load_snapshot(const char *name, Error **errp)
a672b469 2217{
f0aa7a8b 2218 BlockDriverState *bs, *bs_vm_state;
2d22b18f 2219 QEMUSnapshotInfo sn;
a672b469 2220 QEMUFile *f;
751c6a17 2221 int ret;
79b3c12a 2222 AioContext *aio_context;
b4b076da 2223 MigrationIncomingState *mis = migration_incoming_get_current();
a672b469 2224
849f96e2 2225 if (!bdrv_all_can_snapshot(&bs)) {
927d6638
JQ
2226 error_setg(errp,
2227 "Device '%s' is writable but does not support snapshots",
2228 bdrv_get_device_name(bs));
849f96e2
DL
2229 return -ENOTSUP;
2230 }
723ccda1
DL
2231 ret = bdrv_all_find_snapshot(name, &bs);
2232 if (ret < 0) {
927d6638
JQ
2233 error_setg(errp,
2234 "Device '%s' does not have the requested snapshot '%s'",
2235 bdrv_get_device_name(bs), name);
723ccda1
DL
2236 return ret;
2237 }
849f96e2 2238
7cb14481 2239 bs_vm_state = bdrv_all_find_vmstate_bs();
f0aa7a8b 2240 if (!bs_vm_state) {
927d6638 2241 error_setg(errp, "No block device supports snapshots");
f0aa7a8b
MDCF
2242 return -ENOTSUP;
2243 }
79b3c12a 2244 aio_context = bdrv_get_aio_context(bs_vm_state);
f0aa7a8b
MDCF
2245
2246 /* Don't even try to load empty VM states */
79b3c12a 2247 aio_context_acquire(aio_context);
f0aa7a8b 2248 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
79b3c12a 2249 aio_context_release(aio_context);
f0aa7a8b
MDCF
2250 if (ret < 0) {
2251 return ret;
2252 } else if (sn.vm_state_size == 0) {
927d6638
JQ
2253 error_setg(errp, "This is a disk-only snapshot. Revert to it "
2254 " offline using qemu-img");
f0aa7a8b
MDCF
2255 return -EINVAL;
2256 }
2257
a672b469 2258 /* Flush all IO requests so they don't interfere with the new state. */
922453bc 2259 bdrv_drain_all();
a672b469 2260
4c1cdbaa
DL
2261 ret = bdrv_all_goto_snapshot(name, &bs);
2262 if (ret < 0) {
927d6638 2263 error_setg(errp, "Error %d while activating snapshot '%s' on '%s'",
4c1cdbaa
DL
2264 ret, name, bdrv_get_device_name(bs));
2265 return ret;
a672b469
AL
2266 }
2267
a672b469 2268 /* restore the VM state */
f0aa7a8b 2269 f = qemu_fopen_bdrv(bs_vm_state, 0);
a672b469 2270 if (!f) {
927d6638 2271 error_setg(errp, "Could not open VM state file");
05f2401e 2272 return -EINVAL;
a672b469 2273 }
f0aa7a8b 2274
aedbe192 2275 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
b4b076da 2276 mis->from_src_file = f;
f0aa7a8b 2277
79b3c12a
DL
2278 aio_context_acquire(aio_context);
2279 ret = qemu_loadvm_state(f);
79b3c12a
DL
2280 aio_context_release(aio_context);
2281
bca7856a 2282 migration_incoming_state_destroy();
a672b469 2283 if (ret < 0) {
927d6638 2284 error_setg(errp, "Error %d while loading VM state", ret);
05f2401e 2285 return ret;
a672b469 2286 }
f0aa7a8b 2287
05f2401e 2288 return 0;
7b630349
JQ
2289}
2290
c5705a77
AK
2291void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2292{
fa53a0e5 2293 qemu_ram_set_idstr(mr->ram_block,
c5705a77
AK
2294 memory_region_name(mr), dev);
2295}
2296
2297void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2298{
fa53a0e5 2299 qemu_ram_unset_idstr(mr->ram_block);
c5705a77
AK
2300}
2301
2302void vmstate_register_ram_global(MemoryRegion *mr)
2303{
2304 vmstate_register_ram(mr, NULL);
2305}
1bfe5f05
JQ
2306
2307bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2308{
2309 /* check needed if --only-migratable is specified */
2310 if (!only_migratable) {
2311 return true;
2312 }
2313
2314 return !(vmsd && vmsd->unmigratable);
2315}