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