]> git.proxmox.com Git - mirror_qemu.git/blob - migration/savevm.c
MIG_CMD_PACKAGED: Send a packaged chunk of migration stream
[mirror_qemu.git] / migration / savevm.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2009-2015 Red Hat Inc
6 *
7 * Authors:
8 * Juan Quintela <quintela@redhat.com>
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 */
28
29 #include "config-host.h"
30 #include "qemu-common.h"
31 #include "hw/boards.h"
32 #include "hw/hw.h"
33 #include "hw/qdev.h"
34 #include "net/net.h"
35 #include "monitor/monitor.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/timer.h"
38 #include "audio/audio.h"
39 #include "migration/migration.h"
40 #include "qapi/qmp/qerror.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "qemu/queue.h"
44 #include "sysemu/cpus.h"
45 #include "exec/memory.h"
46 #include "qmp-commands.h"
47 #include "trace.h"
48 #include "qemu/bitops.h"
49 #include "qemu/iov.h"
50 #include "block/snapshot.h"
51 #include "block/qapi.h"
52
53
54 #ifndef ETH_P_RARP
55 #define ETH_P_RARP 0x8035
56 #endif
57 #define ARP_HTYPE_ETH 0x0001
58 #define ARP_PTYPE_IP 0x0800
59 #define ARP_OP_REQUEST_REV 0x3
60
61 const unsigned int postcopy_ram_discard_version = 0;
62
63 static bool skip_section_footers;
64
65 static struct mig_cmd_args {
66 ssize_t len; /* -1 = variable */
67 const char *name;
68 } mig_cmd_args[] = {
69 [MIG_CMD_INVALID] = { .len = -1, .name = "INVALID" },
70 [MIG_CMD_OPEN_RETURN_PATH] = { .len = 0, .name = "OPEN_RETURN_PATH" },
71 [MIG_CMD_PING] = { .len = sizeof(uint32_t), .name = "PING" },
72 [MIG_CMD_POSTCOPY_ADVISE] = { .len = 16, .name = "POSTCOPY_ADVISE" },
73 [MIG_CMD_POSTCOPY_LISTEN] = { .len = 0, .name = "POSTCOPY_LISTEN" },
74 [MIG_CMD_POSTCOPY_RUN] = { .len = 0, .name = "POSTCOPY_RUN" },
75 [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
76 .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
77 [MIG_CMD_PACKAGED] = { .len = 4, .name = "PACKAGED" },
78 [MIG_CMD_MAX] = { .len = -1, .name = "MAX" },
79 };
80
81 static int announce_self_create(uint8_t *buf,
82 uint8_t *mac_addr)
83 {
84 /* Ethernet header. */
85 memset(buf, 0xff, 6); /* destination MAC addr */
86 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
87 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
88
89 /* RARP header. */
90 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
91 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
92 *(buf + 18) = 6; /* hardware addr length (ethernet) */
93 *(buf + 19) = 4; /* protocol addr length (IPv4) */
94 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
95 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
96 memset(buf + 28, 0x00, 4); /* source protocol addr */
97 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
98 memset(buf + 38, 0x00, 4); /* target protocol addr */
99
100 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
101 memset(buf + 42, 0x00, 18);
102
103 return 60; /* len (FCS will be added by hardware) */
104 }
105
106 static void qemu_announce_self_iter(NICState *nic, void *opaque)
107 {
108 uint8_t buf[60];
109 int len;
110
111 trace_qemu_announce_self_iter(qemu_ether_ntoa(&nic->conf->macaddr));
112 len = announce_self_create(buf, nic->conf->macaddr.a);
113
114 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
115 }
116
117
118 static void qemu_announce_self_once(void *opaque)
119 {
120 static int count = SELF_ANNOUNCE_ROUNDS;
121 QEMUTimer *timer = *(QEMUTimer **)opaque;
122
123 qemu_foreach_nic(qemu_announce_self_iter, NULL);
124
125 if (--count) {
126 /* delay 50ms, 150ms, 250ms, ... */
127 timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
128 self_announce_delay(count));
129 } else {
130 timer_del(timer);
131 timer_free(timer);
132 }
133 }
134
135 void qemu_announce_self(void)
136 {
137 static QEMUTimer *timer;
138 timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
139 qemu_announce_self_once(&timer);
140 }
141
142 /***********************************************************/
143 /* savevm/loadvm support */
144
145 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
146 int64_t pos)
147 {
148 int ret;
149 QEMUIOVector qiov;
150
151 qemu_iovec_init_external(&qiov, iov, iovcnt);
152 ret = bdrv_writev_vmstate(opaque, &qiov, pos);
153 if (ret < 0) {
154 return ret;
155 }
156
157 return qiov.size;
158 }
159
160 static ssize_t block_put_buffer(void *opaque, const uint8_t *buf,
161 int64_t pos, size_t size)
162 {
163 bdrv_save_vmstate(opaque, buf, pos, size);
164 return size;
165 }
166
167 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
168 size_t size)
169 {
170 return bdrv_load_vmstate(opaque, buf, pos, size);
171 }
172
173 static int bdrv_fclose(void *opaque)
174 {
175 return bdrv_flush(opaque);
176 }
177
178 static const QEMUFileOps bdrv_read_ops = {
179 .get_buffer = block_get_buffer,
180 .close = bdrv_fclose
181 };
182
183 static const QEMUFileOps bdrv_write_ops = {
184 .put_buffer = block_put_buffer,
185 .writev_buffer = block_writev_buffer,
186 .close = bdrv_fclose
187 };
188
189 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
190 {
191 if (is_writable) {
192 return qemu_fopen_ops(bs, &bdrv_write_ops);
193 }
194 return qemu_fopen_ops(bs, &bdrv_read_ops);
195 }
196
197
198 /* QEMUFile timer support.
199 * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
200 */
201
202 void timer_put(QEMUFile *f, QEMUTimer *ts)
203 {
204 uint64_t expire_time;
205
206 expire_time = timer_expire_time_ns(ts);
207 qemu_put_be64(f, expire_time);
208 }
209
210 void timer_get(QEMUFile *f, QEMUTimer *ts)
211 {
212 uint64_t expire_time;
213
214 expire_time = qemu_get_be64(f);
215 if (expire_time != -1) {
216 timer_mod_ns(ts, expire_time);
217 } else {
218 timer_del(ts);
219 }
220 }
221
222
223 /* VMState timer support.
224 * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
225 */
226
227 static int get_timer(QEMUFile *f, void *pv, size_t size)
228 {
229 QEMUTimer *v = pv;
230 timer_get(f, v);
231 return 0;
232 }
233
234 static void put_timer(QEMUFile *f, void *pv, size_t size)
235 {
236 QEMUTimer *v = pv;
237 timer_put(f, v);
238 }
239
240 const VMStateInfo vmstate_info_timer = {
241 .name = "timer",
242 .get = get_timer,
243 .put = put_timer,
244 };
245
246
247 typedef struct CompatEntry {
248 char idstr[256];
249 int instance_id;
250 } CompatEntry;
251
252 typedef struct SaveStateEntry {
253 QTAILQ_ENTRY(SaveStateEntry) entry;
254 char idstr[256];
255 int instance_id;
256 int alias_id;
257 int version_id;
258 int section_id;
259 SaveVMHandlers *ops;
260 const VMStateDescription *vmsd;
261 void *opaque;
262 CompatEntry *compat;
263 int is_ram;
264 } SaveStateEntry;
265
266 typedef struct SaveState {
267 QTAILQ_HEAD(, SaveStateEntry) handlers;
268 int global_section_id;
269 bool skip_configuration;
270 uint32_t len;
271 const char *name;
272 } SaveState;
273
274 static SaveState savevm_state = {
275 .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
276 .global_section_id = 0,
277 .skip_configuration = false,
278 };
279
280 void savevm_skip_configuration(void)
281 {
282 savevm_state.skip_configuration = true;
283 }
284
285
286 static void configuration_pre_save(void *opaque)
287 {
288 SaveState *state = opaque;
289 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
290
291 state->len = strlen(current_name);
292 state->name = current_name;
293 }
294
295 static int configuration_post_load(void *opaque, int version_id)
296 {
297 SaveState *state = opaque;
298 const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
299
300 if (strncmp(state->name, current_name, state->len) != 0) {
301 error_report("Machine type received is '%s' and local is '%s'",
302 state->name, current_name);
303 return -EINVAL;
304 }
305 return 0;
306 }
307
308 static const VMStateDescription vmstate_configuration = {
309 .name = "configuration",
310 .version_id = 1,
311 .post_load = configuration_post_load,
312 .pre_save = configuration_pre_save,
313 .fields = (VMStateField[]) {
314 VMSTATE_UINT32(len, SaveState),
315 VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, 0, len),
316 VMSTATE_END_OF_LIST()
317 },
318 };
319
320 static void dump_vmstate_vmsd(FILE *out_file,
321 const VMStateDescription *vmsd, int indent,
322 bool is_subsection);
323
324 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
325 int indent)
326 {
327 fprintf(out_file, "%*s{\n", indent, "");
328 indent += 2;
329 fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
330 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
331 field->version_id);
332 fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
333 field->field_exists ? "true" : "false");
334 fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
335 if (field->vmsd != NULL) {
336 fprintf(out_file, ",\n");
337 dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
338 }
339 fprintf(out_file, "\n%*s}", indent - 2, "");
340 }
341
342 static void dump_vmstate_vmss(FILE *out_file,
343 const VMStateDescription **subsection,
344 int indent)
345 {
346 if (*subsection != NULL) {
347 dump_vmstate_vmsd(out_file, *subsection, indent, true);
348 }
349 }
350
351 static void dump_vmstate_vmsd(FILE *out_file,
352 const VMStateDescription *vmsd, int indent,
353 bool is_subsection)
354 {
355 if (is_subsection) {
356 fprintf(out_file, "%*s{\n", indent, "");
357 } else {
358 fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
359 }
360 indent += 2;
361 fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
362 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
363 vmsd->version_id);
364 fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
365 vmsd->minimum_version_id);
366 if (vmsd->fields != NULL) {
367 const VMStateField *field = vmsd->fields;
368 bool first;
369
370 fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
371 first = true;
372 while (field->name != NULL) {
373 if (field->flags & VMS_MUST_EXIST) {
374 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
375 field++;
376 continue;
377 }
378 if (!first) {
379 fprintf(out_file, ",\n");
380 }
381 dump_vmstate_vmsf(out_file, field, indent + 2);
382 field++;
383 first = false;
384 }
385 fprintf(out_file, "\n%*s]", indent, "");
386 }
387 if (vmsd->subsections != NULL) {
388 const VMStateDescription **subsection = vmsd->subsections;
389 bool first;
390
391 fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
392 first = true;
393 while (*subsection != NULL) {
394 if (!first) {
395 fprintf(out_file, ",\n");
396 }
397 dump_vmstate_vmss(out_file, subsection, indent + 2);
398 subsection++;
399 first = false;
400 }
401 fprintf(out_file, "\n%*s]", indent, "");
402 }
403 fprintf(out_file, "\n%*s}", indent - 2, "");
404 }
405
406 static void dump_machine_type(FILE *out_file)
407 {
408 MachineClass *mc;
409
410 mc = MACHINE_GET_CLASS(current_machine);
411
412 fprintf(out_file, " \"vmschkmachine\": {\n");
413 fprintf(out_file, " \"Name\": \"%s\"\n", mc->name);
414 fprintf(out_file, " },\n");
415 }
416
417 void dump_vmstate_json_to_file(FILE *out_file)
418 {
419 GSList *list, *elt;
420 bool first;
421
422 fprintf(out_file, "{\n");
423 dump_machine_type(out_file);
424
425 first = true;
426 list = object_class_get_list(TYPE_DEVICE, true);
427 for (elt = list; elt; elt = elt->next) {
428 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
429 TYPE_DEVICE);
430 const char *name;
431 int indent = 2;
432
433 if (!dc->vmsd) {
434 continue;
435 }
436
437 if (!first) {
438 fprintf(out_file, ",\n");
439 }
440 name = object_class_get_name(OBJECT_CLASS(dc));
441 fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
442 indent += 2;
443 fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
444 fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
445 dc->vmsd->version_id);
446 fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
447 dc->vmsd->minimum_version_id);
448
449 dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
450
451 fprintf(out_file, "\n%*s}", indent - 2, "");
452 first = false;
453 }
454 fprintf(out_file, "\n}\n");
455 fclose(out_file);
456 }
457
458 static int calculate_new_instance_id(const char *idstr)
459 {
460 SaveStateEntry *se;
461 int instance_id = 0;
462
463 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
464 if (strcmp(idstr, se->idstr) == 0
465 && instance_id <= se->instance_id) {
466 instance_id = se->instance_id + 1;
467 }
468 }
469 return instance_id;
470 }
471
472 static int calculate_compat_instance_id(const char *idstr)
473 {
474 SaveStateEntry *se;
475 int instance_id = 0;
476
477 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
478 if (!se->compat) {
479 continue;
480 }
481
482 if (strcmp(idstr, se->compat->idstr) == 0
483 && instance_id <= se->compat->instance_id) {
484 instance_id = se->compat->instance_id + 1;
485 }
486 }
487 return instance_id;
488 }
489
490 /* TODO: Individual devices generally have very little idea about the rest
491 of the system, so instance_id should be removed/replaced.
492 Meanwhile pass -1 as instance_id if you do not already have a clearly
493 distinguishing id for all instances of your device class. */
494 int register_savevm_live(DeviceState *dev,
495 const char *idstr,
496 int instance_id,
497 int version_id,
498 SaveVMHandlers *ops,
499 void *opaque)
500 {
501 SaveStateEntry *se;
502
503 se = g_new0(SaveStateEntry, 1);
504 se->version_id = version_id;
505 se->section_id = savevm_state.global_section_id++;
506 se->ops = ops;
507 se->opaque = opaque;
508 se->vmsd = NULL;
509 /* if this is a live_savem then set is_ram */
510 if (ops->save_live_setup != NULL) {
511 se->is_ram = 1;
512 }
513
514 if (dev) {
515 char *id = qdev_get_dev_path(dev);
516 if (id) {
517 pstrcpy(se->idstr, sizeof(se->idstr), id);
518 pstrcat(se->idstr, sizeof(se->idstr), "/");
519 g_free(id);
520
521 se->compat = g_new0(CompatEntry, 1);
522 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
523 se->compat->instance_id = instance_id == -1 ?
524 calculate_compat_instance_id(idstr) : instance_id;
525 instance_id = -1;
526 }
527 }
528 pstrcat(se->idstr, sizeof(se->idstr), idstr);
529
530 if (instance_id == -1) {
531 se->instance_id = calculate_new_instance_id(se->idstr);
532 } else {
533 se->instance_id = instance_id;
534 }
535 assert(!se->compat || se->instance_id == 0);
536 /* add at the end of list */
537 QTAILQ_INSERT_TAIL(&savevm_state.handlers, se, entry);
538 return 0;
539 }
540
541 int register_savevm(DeviceState *dev,
542 const char *idstr,
543 int instance_id,
544 int version_id,
545 SaveStateHandler *save_state,
546 LoadStateHandler *load_state,
547 void *opaque)
548 {
549 SaveVMHandlers *ops = g_new0(SaveVMHandlers, 1);
550 ops->save_state = save_state;
551 ops->load_state = load_state;
552 return register_savevm_live(dev, idstr, instance_id, version_id,
553 ops, opaque);
554 }
555
556 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
557 {
558 SaveStateEntry *se, *new_se;
559 char id[256] = "";
560
561 if (dev) {
562 char *path = qdev_get_dev_path(dev);
563 if (path) {
564 pstrcpy(id, sizeof(id), path);
565 pstrcat(id, sizeof(id), "/");
566 g_free(path);
567 }
568 }
569 pstrcat(id, sizeof(id), idstr);
570
571 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
572 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
573 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
574 g_free(se->compat);
575 g_free(se->ops);
576 g_free(se);
577 }
578 }
579 }
580
581 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
582 const VMStateDescription *vmsd,
583 void *opaque, int alias_id,
584 int required_for_version)
585 {
586 SaveStateEntry *se;
587
588 /* If this triggers, alias support can be dropped for the vmsd. */
589 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
590
591 se = g_new0(SaveStateEntry, 1);
592 se->version_id = vmsd->version_id;
593 se->section_id = savevm_state.global_section_id++;
594 se->opaque = opaque;
595 se->vmsd = vmsd;
596 se->alias_id = alias_id;
597
598 if (dev) {
599 char *id = qdev_get_dev_path(dev);
600 if (id) {
601 pstrcpy(se->idstr, sizeof(se->idstr), id);
602 pstrcat(se->idstr, sizeof(se->idstr), "/");
603 g_free(id);
604
605 se->compat = g_new0(CompatEntry, 1);
606 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
607 se->compat->instance_id = instance_id == -1 ?
608 calculate_compat_instance_id(vmsd->name) : instance_id;
609 instance_id = -1;
610 }
611 }
612 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
613
614 if (instance_id == -1) {
615 se->instance_id = calculate_new_instance_id(se->idstr);
616 } else {
617 se->instance_id = instance_id;
618 }
619 assert(!se->compat || se->instance_id == 0);
620 /* add at the end of list */
621 QTAILQ_INSERT_TAIL(&savevm_state.handlers, se, entry);
622 return 0;
623 }
624
625 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
626 void *opaque)
627 {
628 SaveStateEntry *se, *new_se;
629
630 QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
631 if (se->vmsd == vmsd && se->opaque == opaque) {
632 QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
633 g_free(se->compat);
634 g_free(se);
635 }
636 }
637 }
638
639 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
640 {
641 trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
642 if (!se->vmsd) { /* Old style */
643 return se->ops->load_state(f, se->opaque, version_id);
644 }
645 return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
646 }
647
648 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
649 {
650 int64_t old_offset, size;
651
652 old_offset = qemu_ftell_fast(f);
653 se->ops->save_state(f, se->opaque);
654 size = qemu_ftell_fast(f) - old_offset;
655
656 if (vmdesc) {
657 json_prop_int(vmdesc, "size", size);
658 json_start_array(vmdesc, "fields");
659 json_start_object(vmdesc, NULL);
660 json_prop_str(vmdesc, "name", "data");
661 json_prop_int(vmdesc, "size", size);
662 json_prop_str(vmdesc, "type", "buffer");
663 json_end_object(vmdesc);
664 json_end_array(vmdesc);
665 }
666 }
667
668 static void vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
669 {
670 trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
671 if (!se->vmsd) {
672 vmstate_save_old_style(f, se, vmdesc);
673 return;
674 }
675 vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
676 }
677
678 void savevm_skip_section_footers(void)
679 {
680 skip_section_footers = true;
681 }
682
683 /*
684 * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
685 */
686 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
687 uint8_t section_type)
688 {
689 qemu_put_byte(f, section_type);
690 qemu_put_be32(f, se->section_id);
691
692 if (section_type == QEMU_VM_SECTION_FULL ||
693 section_type == QEMU_VM_SECTION_START) {
694 /* ID string */
695 size_t len = strlen(se->idstr);
696 qemu_put_byte(f, len);
697 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
698
699 qemu_put_be32(f, se->instance_id);
700 qemu_put_be32(f, se->version_id);
701 }
702 }
703
704 /*
705 * Write a footer onto device sections that catches cases misformatted device
706 * sections.
707 */
708 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
709 {
710 if (!skip_section_footers) {
711 qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
712 qemu_put_be32(f, se->section_id);
713 }
714 }
715
716 /**
717 * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
718 * command and associated data.
719 *
720 * @f: File to send command on
721 * @command: Command type to send
722 * @len: Length of associated data
723 * @data: Data associated with command.
724 */
725 void qemu_savevm_command_send(QEMUFile *f,
726 enum qemu_vm_cmd command,
727 uint16_t len,
728 uint8_t *data)
729 {
730 trace_savevm_command_send(command, len);
731 qemu_put_byte(f, QEMU_VM_COMMAND);
732 qemu_put_be16(f, (uint16_t)command);
733 qemu_put_be16(f, len);
734 qemu_put_buffer(f, data, len);
735 qemu_fflush(f);
736 }
737
738 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
739 {
740 uint32_t buf;
741
742 trace_savevm_send_ping(value);
743 buf = cpu_to_be32(value);
744 qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
745 }
746
747 void qemu_savevm_send_open_return_path(QEMUFile *f)
748 {
749 trace_savevm_send_open_return_path();
750 qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
751 }
752
753 /* We have a buffer of data to send; we don't want that all to be loaded
754 * by the command itself, so the command contains just the length of the
755 * extra buffer that we then send straight after it.
756 * TODO: Must be a better way to organise that
757 *
758 * Returns:
759 * 0 on success
760 * -ve on error
761 */
762 int qemu_savevm_send_packaged(QEMUFile *f, const QEMUSizedBuffer *qsb)
763 {
764 size_t cur_iov;
765 size_t len = qsb_get_length(qsb);
766 uint32_t tmp;
767
768 if (len > MAX_VM_CMD_PACKAGED_SIZE) {
769 error_report("%s: Unreasonably large packaged state: %zu",
770 __func__, len);
771 return -1;
772 }
773
774 tmp = cpu_to_be32(len);
775
776 trace_qemu_savevm_send_packaged();
777 qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
778
779 /* all the data follows (concatinating the iov's) */
780 for (cur_iov = 0; cur_iov < qsb->n_iov; cur_iov++) {
781 /* The iov entries are partially filled */
782 size_t towrite = MIN(qsb->iov[cur_iov].iov_len, len);
783 len -= towrite;
784
785 if (!towrite) {
786 break;
787 }
788
789 qemu_put_buffer(f, qsb->iov[cur_iov].iov_base, towrite);
790 }
791
792 return 0;
793 }
794
795 /* Send prior to any postcopy transfer */
796 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
797 {
798 uint64_t tmp[2];
799 tmp[0] = cpu_to_be64(getpagesize());
800 tmp[1] = cpu_to_be64(1ul << qemu_target_page_bits());
801
802 trace_qemu_savevm_send_postcopy_advise();
803 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 16, (uint8_t *)tmp);
804 }
805
806 /* Sent prior to starting the destination running in postcopy, discard pages
807 * that have already been sent but redirtied on the source.
808 * CMD_POSTCOPY_RAM_DISCARD consist of:
809 * byte version (0)
810 * byte Length of name field (not including 0)
811 * n x byte RAM block name
812 * byte 0 terminator (just for safety)
813 * n x Byte ranges within the named RAMBlock
814 * be64 Start of the range
815 * be64 Length
816 *
817 * name: RAMBlock name that these entries are part of
818 * len: Number of page entries
819 * start_list: 'len' addresses
820 * length_list: 'len' addresses
821 *
822 */
823 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
824 uint16_t len,
825 uint64_t *start_list,
826 uint64_t *length_list)
827 {
828 uint8_t *buf;
829 uint16_t tmplen;
830 uint16_t t;
831 size_t name_len = strlen(name);
832
833 trace_qemu_savevm_send_postcopy_ram_discard(name, len);
834 assert(name_len < 256);
835 buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
836 buf[0] = postcopy_ram_discard_version;
837 buf[1] = name_len;
838 memcpy(buf + 2, name, name_len);
839 tmplen = 2 + name_len;
840 buf[tmplen++] = '\0';
841
842 for (t = 0; t < len; t++) {
843 cpu_to_be64w((uint64_t *)(buf + tmplen), start_list[t]);
844 tmplen += 8;
845 cpu_to_be64w((uint64_t *)(buf + tmplen), length_list[t]);
846 tmplen += 8;
847 }
848 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
849 g_free(buf);
850 }
851
852 /* Get the destination into a state where it can receive postcopy data. */
853 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
854 {
855 trace_savevm_send_postcopy_listen();
856 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
857 }
858
859 /* Kick the destination into running */
860 void qemu_savevm_send_postcopy_run(QEMUFile *f)
861 {
862 trace_savevm_send_postcopy_run();
863 qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
864 }
865
866 bool qemu_savevm_state_blocked(Error **errp)
867 {
868 SaveStateEntry *se;
869
870 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
871 if (se->vmsd && se->vmsd->unmigratable) {
872 error_setg(errp, "State blocked by non-migratable device '%s'",
873 se->idstr);
874 return true;
875 }
876 }
877 return false;
878 }
879
880 void qemu_savevm_state_header(QEMUFile *f)
881 {
882 trace_savevm_state_header();
883 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
884 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
885
886 if (!savevm_state.skip_configuration) {
887 qemu_put_byte(f, QEMU_VM_CONFIGURATION);
888 vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
889 }
890
891 }
892
893 void qemu_savevm_state_begin(QEMUFile *f,
894 const MigrationParams *params)
895 {
896 SaveStateEntry *se;
897 int ret;
898
899 trace_savevm_state_begin();
900 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
901 if (!se->ops || !se->ops->set_params) {
902 continue;
903 }
904 se->ops->set_params(params, se->opaque);
905 }
906
907 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
908 if (!se->ops || !se->ops->save_live_setup) {
909 continue;
910 }
911 if (se->ops && se->ops->is_active) {
912 if (!se->ops->is_active(se->opaque)) {
913 continue;
914 }
915 }
916 save_section_header(f, se, QEMU_VM_SECTION_START);
917
918 ret = se->ops->save_live_setup(f, se->opaque);
919 save_section_footer(f, se);
920 if (ret < 0) {
921 qemu_file_set_error(f, ret);
922 break;
923 }
924 }
925 }
926
927 /*
928 * this function has three return values:
929 * negative: there was one error, and we have -errno.
930 * 0 : We haven't finished, caller have to go again
931 * 1 : We have finished, we can go to complete phase
932 */
933 int qemu_savevm_state_iterate(QEMUFile *f)
934 {
935 SaveStateEntry *se;
936 int ret = 1;
937
938 trace_savevm_state_iterate();
939 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
940 if (!se->ops || !se->ops->save_live_iterate) {
941 continue;
942 }
943 if (se->ops && se->ops->is_active) {
944 if (!se->ops->is_active(se->opaque)) {
945 continue;
946 }
947 }
948 if (qemu_file_rate_limit(f)) {
949 return 0;
950 }
951 trace_savevm_section_start(se->idstr, se->section_id);
952
953 save_section_header(f, se, QEMU_VM_SECTION_PART);
954
955 ret = se->ops->save_live_iterate(f, se->opaque);
956 trace_savevm_section_end(se->idstr, se->section_id, ret);
957 save_section_footer(f, se);
958
959 if (ret < 0) {
960 qemu_file_set_error(f, ret);
961 }
962 if (ret <= 0) {
963 /* Do not proceed to the next vmstate before this one reported
964 completion of the current stage. This serializes the migration
965 and reduces the probability that a faster changing state is
966 synchronized over and over again. */
967 break;
968 }
969 }
970 return ret;
971 }
972
973 static bool should_send_vmdesc(void)
974 {
975 MachineState *machine = MACHINE(qdev_get_machine());
976 return !machine->suppress_vmdesc;
977 }
978
979 void qemu_savevm_state_complete_precopy(QEMUFile *f)
980 {
981 QJSON *vmdesc;
982 int vmdesc_len;
983 SaveStateEntry *se;
984 int ret;
985
986 trace_savevm_state_complete_precopy();
987
988 cpu_synchronize_all_states();
989
990 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
991 if (!se->ops || !se->ops->save_live_complete_precopy) {
992 continue;
993 }
994 if (se->ops && se->ops->is_active) {
995 if (!se->ops->is_active(se->opaque)) {
996 continue;
997 }
998 }
999 trace_savevm_section_start(se->idstr, se->section_id);
1000
1001 save_section_header(f, se, QEMU_VM_SECTION_END);
1002
1003 ret = se->ops->save_live_complete_precopy(f, se->opaque);
1004 trace_savevm_section_end(se->idstr, se->section_id, ret);
1005 save_section_footer(f, se);
1006 if (ret < 0) {
1007 qemu_file_set_error(f, ret);
1008 return;
1009 }
1010 }
1011
1012 vmdesc = qjson_new();
1013 json_prop_int(vmdesc, "page_size", TARGET_PAGE_SIZE);
1014 json_start_array(vmdesc, "devices");
1015 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1016
1017 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1018 continue;
1019 }
1020 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1021 trace_savevm_section_skip(se->idstr, se->section_id);
1022 continue;
1023 }
1024
1025 trace_savevm_section_start(se->idstr, se->section_id);
1026
1027 json_start_object(vmdesc, NULL);
1028 json_prop_str(vmdesc, "name", se->idstr);
1029 json_prop_int(vmdesc, "instance_id", se->instance_id);
1030
1031 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1032
1033 vmstate_save(f, se, vmdesc);
1034
1035 json_end_object(vmdesc);
1036 trace_savevm_section_end(se->idstr, se->section_id, 0);
1037 save_section_footer(f, se);
1038 }
1039
1040 qemu_put_byte(f, QEMU_VM_EOF);
1041
1042 json_end_array(vmdesc);
1043 qjson_finish(vmdesc);
1044 vmdesc_len = strlen(qjson_get_str(vmdesc));
1045
1046 if (should_send_vmdesc()) {
1047 qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1048 qemu_put_be32(f, vmdesc_len);
1049 qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1050 }
1051 object_unref(OBJECT(vmdesc));
1052
1053 qemu_fflush(f);
1054 }
1055
1056 uint64_t qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size)
1057 {
1058 SaveStateEntry *se;
1059 uint64_t ret = 0;
1060
1061 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1062 if (!se->ops || !se->ops->save_live_pending) {
1063 continue;
1064 }
1065 if (se->ops && se->ops->is_active) {
1066 if (!se->ops->is_active(se->opaque)) {
1067 continue;
1068 }
1069 }
1070 ret += se->ops->save_live_pending(f, se->opaque, max_size);
1071 }
1072 return ret;
1073 }
1074
1075 void qemu_savevm_state_cleanup(void)
1076 {
1077 SaveStateEntry *se;
1078
1079 trace_savevm_state_cleanup();
1080 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1081 if (se->ops && se->ops->cleanup) {
1082 se->ops->cleanup(se->opaque);
1083 }
1084 }
1085 }
1086
1087 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1088 {
1089 int ret;
1090 MigrationParams params = {
1091 .blk = 0,
1092 .shared = 0
1093 };
1094 MigrationState *ms = migrate_init(&params);
1095 ms->file = f;
1096
1097 if (qemu_savevm_state_blocked(errp)) {
1098 return -EINVAL;
1099 }
1100
1101 qemu_mutex_unlock_iothread();
1102 qemu_savevm_state_header(f);
1103 qemu_savevm_state_begin(f, &params);
1104 qemu_mutex_lock_iothread();
1105
1106 while (qemu_file_get_error(f) == 0) {
1107 if (qemu_savevm_state_iterate(f) > 0) {
1108 break;
1109 }
1110 }
1111
1112 ret = qemu_file_get_error(f);
1113 if (ret == 0) {
1114 qemu_savevm_state_complete_precopy(f);
1115 ret = qemu_file_get_error(f);
1116 }
1117 if (ret != 0) {
1118 qemu_savevm_state_cleanup();
1119 error_setg_errno(errp, -ret, "Error while writing VM state");
1120 }
1121 return ret;
1122 }
1123
1124 static int qemu_save_device_state(QEMUFile *f)
1125 {
1126 SaveStateEntry *se;
1127
1128 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1129 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1130
1131 cpu_synchronize_all_states();
1132
1133 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1134 if (se->is_ram) {
1135 continue;
1136 }
1137 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1138 continue;
1139 }
1140 if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1141 continue;
1142 }
1143
1144 save_section_header(f, se, QEMU_VM_SECTION_FULL);
1145
1146 vmstate_save(f, se, NULL);
1147
1148 save_section_footer(f, se);
1149 }
1150
1151 qemu_put_byte(f, QEMU_VM_EOF);
1152
1153 return qemu_file_get_error(f);
1154 }
1155
1156 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1157 {
1158 SaveStateEntry *se;
1159
1160 QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1161 if (!strcmp(se->idstr, idstr) &&
1162 (instance_id == se->instance_id ||
1163 instance_id == se->alias_id))
1164 return se;
1165 /* Migrating from an older version? */
1166 if (strstr(se->idstr, idstr) && se->compat) {
1167 if (!strcmp(se->compat->idstr, idstr) &&
1168 (instance_id == se->compat->instance_id ||
1169 instance_id == se->alias_id))
1170 return se;
1171 }
1172 }
1173 return NULL;
1174 }
1175
1176 enum LoadVMExitCodes {
1177 /* Allow a command to quit all layers of nested loadvm loops */
1178 LOADVM_QUIT = 1,
1179 };
1180
1181 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis);
1182
1183 /* ------ incoming postcopy messages ------ */
1184 /* 'advise' arrives before any transfers just to tell us that a postcopy
1185 * *might* happen - it might be skipped if precopy transferred everything
1186 * quickly.
1187 */
1188 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)
1189 {
1190 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1191 uint64_t remote_hps, remote_tps;
1192
1193 trace_loadvm_postcopy_handle_advise();
1194 if (ps != POSTCOPY_INCOMING_NONE) {
1195 error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1196 return -1;
1197 }
1198
1199 remote_hps = qemu_get_be64(mis->from_src_file);
1200 if (remote_hps != getpagesize()) {
1201 /*
1202 * Some combinations of mismatch are probably possible but it gets
1203 * a bit more complicated. In particular we need to place whole
1204 * host pages on the dest at once, and we need to ensure that we
1205 * handle dirtying to make sure we never end up sending part of
1206 * a hostpage on it's own.
1207 */
1208 error_report("Postcopy needs matching host page sizes (s=%d d=%d)",
1209 (int)remote_hps, getpagesize());
1210 return -1;
1211 }
1212
1213 remote_tps = qemu_get_be64(mis->from_src_file);
1214 if (remote_tps != (1ul << qemu_target_page_bits())) {
1215 /*
1216 * Again, some differences could be dealt with, but for now keep it
1217 * simple.
1218 */
1219 error_report("Postcopy needs matching target page sizes (s=%d d=%d)",
1220 (int)remote_tps, 1 << qemu_target_page_bits());
1221 return -1;
1222 }
1223
1224 return 0;
1225 }
1226
1227 /* After postcopy we will be told to throw some pages away since they're
1228 * dirty and will have to be demand fetched. Must happen before CPU is
1229 * started.
1230 * There can be 0..many of these messages, each encoding multiple pages.
1231 */
1232 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1233 uint16_t len)
1234 {
1235 int tmp;
1236 char ramid[256];
1237 PostcopyState ps = postcopy_state_get();
1238
1239 trace_loadvm_postcopy_ram_handle_discard();
1240
1241 switch (ps) {
1242 case POSTCOPY_INCOMING_ADVISE:
1243 /* 1st discard */
1244 tmp = 0; /* TODO: later patch postcopy_ram_prepare_discard(mis); */
1245 if (tmp) {
1246 return tmp;
1247 }
1248 break;
1249
1250 case POSTCOPY_INCOMING_DISCARD:
1251 /* Expected state */
1252 break;
1253
1254 default:
1255 error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1256 ps);
1257 return -1;
1258 }
1259 /* We're expecting a
1260 * Version (0)
1261 * a RAM ID string (length byte, name, 0 term)
1262 * then at least 1 16 byte chunk
1263 */
1264 if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1265 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1266 return -1;
1267 }
1268
1269 tmp = qemu_get_byte(mis->from_src_file);
1270 if (tmp != postcopy_ram_discard_version) {
1271 error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1272 return -1;
1273 }
1274
1275 if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1276 error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1277 return -1;
1278 }
1279 tmp = qemu_get_byte(mis->from_src_file);
1280 if (tmp != 0) {
1281 error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1282 return -1;
1283 }
1284
1285 len -= 3 + strlen(ramid);
1286 if (len % 16) {
1287 error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1288 return -1;
1289 }
1290 trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1291 while (len) {
1292 /* TODO - ram_discard_range gets added in a later patch
1293 uint64_t start_addr, block_length;
1294 start_addr = qemu_get_be64(mis->from_src_file);
1295 block_length = qemu_get_be64(mis->from_src_file);
1296
1297 len -= 16;
1298 int ret = ram_discard_range(mis, ramid, start_addr,
1299 block_length);
1300 if (ret) {
1301 return ret;
1302 }
1303 */
1304 }
1305 trace_loadvm_postcopy_ram_handle_discard_end();
1306
1307 return 0;
1308 }
1309
1310 /* After this message we must be able to immediately receive postcopy data */
1311 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1312 {
1313 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1314 trace_loadvm_postcopy_handle_listen();
1315 if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1316 error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1317 return -1;
1318 }
1319
1320 /* TODO start up the postcopy listening thread */
1321 return 0;
1322 }
1323
1324 /* After all discards we can start running and asking for pages */
1325 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1326 {
1327 PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1328 trace_loadvm_postcopy_handle_run();
1329 if (ps != POSTCOPY_INCOMING_LISTENING) {
1330 error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1331 return -1;
1332 }
1333
1334 if (autostart) {
1335 /* Hold onto your hats, starting the CPU */
1336 vm_start();
1337 } else {
1338 /* leave it paused and let management decide when to start the CPU */
1339 runstate_set(RUN_STATE_PAUSED);
1340 }
1341
1342 return 0;
1343 }
1344
1345 /**
1346 * Immediately following this command is a blob of data containing an embedded
1347 * chunk of migration stream; read it and load it.
1348 *
1349 * @mis: Incoming state
1350 * @length: Length of packaged data to read
1351 *
1352 * Returns: Negative values on error
1353 *
1354 */
1355 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1356 {
1357 int ret;
1358 uint8_t *buffer;
1359 uint32_t length;
1360 QEMUSizedBuffer *qsb;
1361
1362 length = qemu_get_be32(mis->from_src_file);
1363 trace_loadvm_handle_cmd_packaged(length);
1364
1365 if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1366 error_report("Unreasonably large packaged state: %u", length);
1367 return -1;
1368 }
1369 buffer = g_malloc0(length);
1370 ret = qemu_get_buffer(mis->from_src_file, buffer, (int)length);
1371 if (ret != length) {
1372 g_free(buffer);
1373 error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%d\n",
1374 ret, length);
1375 return (ret < 0) ? ret : -EAGAIN;
1376 }
1377 trace_loadvm_handle_cmd_packaged_received(ret);
1378
1379 /* Setup a dummy QEMUFile that actually reads from the buffer */
1380 qsb = qsb_create(buffer, length);
1381 g_free(buffer); /* Because qsb_create copies */
1382 if (!qsb) {
1383 error_report("Unable to create qsb");
1384 }
1385 QEMUFile *packf = qemu_bufopen("r", qsb);
1386
1387 ret = qemu_loadvm_state_main(packf, mis);
1388 trace_loadvm_handle_cmd_packaged_main(ret);
1389 qemu_fclose(packf);
1390 qsb_free(qsb);
1391
1392 return ret;
1393 }
1394
1395 /*
1396 * Process an incoming 'QEMU_VM_COMMAND'
1397 * 0 just a normal return
1398 * LOADVM_QUIT All good, but exit the loop
1399 * <0 Error
1400 */
1401 static int loadvm_process_command(QEMUFile *f)
1402 {
1403 MigrationIncomingState *mis = migration_incoming_get_current();
1404 uint16_t cmd;
1405 uint16_t len;
1406 uint32_t tmp32;
1407
1408 cmd = qemu_get_be16(f);
1409 len = qemu_get_be16(f);
1410
1411 trace_loadvm_process_command(cmd, len);
1412 if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
1413 error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
1414 return -EINVAL;
1415 }
1416
1417 if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
1418 error_report("%s received with bad length - expecting %zu, got %d",
1419 mig_cmd_args[cmd].name,
1420 (size_t)mig_cmd_args[cmd].len, len);
1421 return -ERANGE;
1422 }
1423
1424 switch (cmd) {
1425 case MIG_CMD_OPEN_RETURN_PATH:
1426 if (mis->to_src_file) {
1427 error_report("CMD_OPEN_RETURN_PATH called when RP already open");
1428 /* Not really a problem, so don't give up */
1429 return 0;
1430 }
1431 mis->to_src_file = qemu_file_get_return_path(f);
1432 if (!mis->to_src_file) {
1433 error_report("CMD_OPEN_RETURN_PATH failed");
1434 return -1;
1435 }
1436 break;
1437
1438 case MIG_CMD_PING:
1439 tmp32 = qemu_get_be32(f);
1440 trace_loadvm_process_command_ping(tmp32);
1441 if (!mis->to_src_file) {
1442 error_report("CMD_PING (0x%x) received with no return path",
1443 tmp32);
1444 return -1;
1445 }
1446 migrate_send_rp_pong(mis, tmp32);
1447 break;
1448
1449 case MIG_CMD_PACKAGED:
1450 return loadvm_handle_cmd_packaged(mis);
1451
1452 case MIG_CMD_POSTCOPY_ADVISE:
1453 return loadvm_postcopy_handle_advise(mis);
1454
1455 case MIG_CMD_POSTCOPY_LISTEN:
1456 return loadvm_postcopy_handle_listen(mis);
1457
1458 case MIG_CMD_POSTCOPY_RUN:
1459 return loadvm_postcopy_handle_run(mis);
1460
1461 case MIG_CMD_POSTCOPY_RAM_DISCARD:
1462 return loadvm_postcopy_ram_handle_discard(mis, len);
1463 }
1464
1465 return 0;
1466 }
1467
1468 struct LoadStateEntry {
1469 QLIST_ENTRY(LoadStateEntry) entry;
1470 SaveStateEntry *se;
1471 int section_id;
1472 int version_id;
1473 };
1474
1475 /*
1476 * Read a footer off the wire and check that it matches the expected section
1477 *
1478 * Returns: true if the footer was good
1479 * false if there is a problem (and calls error_report to say why)
1480 */
1481 static bool check_section_footer(QEMUFile *f, LoadStateEntry *le)
1482 {
1483 uint8_t read_mark;
1484 uint32_t read_section_id;
1485
1486 if (skip_section_footers) {
1487 /* No footer to check */
1488 return true;
1489 }
1490
1491 read_mark = qemu_get_byte(f);
1492
1493 if (read_mark != QEMU_VM_SECTION_FOOTER) {
1494 error_report("Missing section footer for %s", le->se->idstr);
1495 return false;
1496 }
1497
1498 read_section_id = qemu_get_be32(f);
1499 if (read_section_id != le->section_id) {
1500 error_report("Mismatched section id in footer for %s -"
1501 " read 0x%x expected 0x%x",
1502 le->se->idstr, read_section_id, le->section_id);
1503 return false;
1504 }
1505
1506 /* All good */
1507 return true;
1508 }
1509
1510 void loadvm_free_handlers(MigrationIncomingState *mis)
1511 {
1512 LoadStateEntry *le, *new_le;
1513
1514 QLIST_FOREACH_SAFE(le, &mis->loadvm_handlers, entry, new_le) {
1515 QLIST_REMOVE(le, entry);
1516 g_free(le);
1517 }
1518 }
1519
1520 static int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
1521 {
1522 uint8_t section_type;
1523 int ret;
1524
1525 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
1526 uint32_t instance_id, version_id, section_id;
1527 SaveStateEntry *se;
1528 LoadStateEntry *le;
1529 char idstr[256];
1530
1531 trace_qemu_loadvm_state_section(section_type);
1532 switch (section_type) {
1533 case QEMU_VM_SECTION_START:
1534 case QEMU_VM_SECTION_FULL:
1535 /* Read section start */
1536 section_id = qemu_get_be32(f);
1537 if (!qemu_get_counted_string(f, idstr)) {
1538 error_report("Unable to read ID string for section %u",
1539 section_id);
1540 return -EINVAL;
1541 }
1542 instance_id = qemu_get_be32(f);
1543 version_id = qemu_get_be32(f);
1544
1545 trace_qemu_loadvm_state_section_startfull(section_id, idstr,
1546 instance_id, version_id);
1547 /* Find savevm section */
1548 se = find_se(idstr, instance_id);
1549 if (se == NULL) {
1550 error_report("Unknown savevm section or instance '%s' %d",
1551 idstr, instance_id);
1552 return -EINVAL;
1553 }
1554
1555 /* Validate version */
1556 if (version_id > se->version_id) {
1557 error_report("savevm: unsupported version %d for '%s' v%d",
1558 version_id, idstr, se->version_id);
1559 return -EINVAL;
1560 }
1561
1562 /* Add entry */
1563 le = g_malloc0(sizeof(*le));
1564
1565 le->se = se;
1566 le->section_id = section_id;
1567 le->version_id = version_id;
1568 QLIST_INSERT_HEAD(&mis->loadvm_handlers, le, entry);
1569
1570 ret = vmstate_load(f, le->se, le->version_id);
1571 if (ret < 0) {
1572 error_report("error while loading state for instance 0x%x of"
1573 " device '%s'", instance_id, idstr);
1574 return ret;
1575 }
1576 if (!check_section_footer(f, le)) {
1577 return -EINVAL;
1578 }
1579 break;
1580 case QEMU_VM_SECTION_PART:
1581 case QEMU_VM_SECTION_END:
1582 section_id = qemu_get_be32(f);
1583
1584 trace_qemu_loadvm_state_section_partend(section_id);
1585 QLIST_FOREACH(le, &mis->loadvm_handlers, entry) {
1586 if (le->section_id == section_id) {
1587 break;
1588 }
1589 }
1590 if (le == NULL) {
1591 error_report("Unknown savevm section %d", section_id);
1592 return -EINVAL;
1593 }
1594
1595 ret = vmstate_load(f, le->se, le->version_id);
1596 if (ret < 0) {
1597 error_report("error while loading state section id %d(%s)",
1598 section_id, le->se->idstr);
1599 return ret;
1600 }
1601 if (!check_section_footer(f, le)) {
1602 return -EINVAL;
1603 }
1604 break;
1605 case QEMU_VM_COMMAND:
1606 ret = loadvm_process_command(f);
1607 trace_qemu_loadvm_state_section_command(ret);
1608 if ((ret < 0) || (ret & LOADVM_QUIT)) {
1609 return ret;
1610 }
1611 break;
1612 default:
1613 error_report("Unknown savevm section type %d", section_type);
1614 return -EINVAL;
1615 }
1616 }
1617
1618 return 0;
1619 }
1620
1621 int qemu_loadvm_state(QEMUFile *f)
1622 {
1623 MigrationIncomingState *mis = migration_incoming_get_current();
1624 Error *local_err = NULL;
1625 unsigned int v;
1626 int ret;
1627
1628 if (qemu_savevm_state_blocked(&local_err)) {
1629 error_report_err(local_err);
1630 return -EINVAL;
1631 }
1632
1633 v = qemu_get_be32(f);
1634 if (v != QEMU_VM_FILE_MAGIC) {
1635 error_report("Not a migration stream");
1636 return -EINVAL;
1637 }
1638
1639 v = qemu_get_be32(f);
1640 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
1641 error_report("SaveVM v2 format is obsolete and don't work anymore");
1642 return -ENOTSUP;
1643 }
1644 if (v != QEMU_VM_FILE_VERSION) {
1645 error_report("Unsupported migration stream version");
1646 return -ENOTSUP;
1647 }
1648
1649 if (!savevm_state.skip_configuration) {
1650 if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
1651 error_report("Configuration section missing");
1652 return -EINVAL;
1653 }
1654 ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
1655
1656 if (ret) {
1657 return ret;
1658 }
1659 }
1660
1661 ret = qemu_loadvm_state_main(f, mis);
1662 qemu_event_set(&mis->main_thread_load_event);
1663
1664 trace_qemu_loadvm_state_post_main(ret);
1665
1666 if (ret == 0) {
1667 ret = qemu_file_get_error(f);
1668 }
1669
1670 /*
1671 * Try to read in the VMDESC section as well, so that dumping tools that
1672 * intercept our migration stream have the chance to see it.
1673 */
1674
1675 /* We've got to be careful; if we don't read the data and just shut the fd
1676 * then the sender can error if we close while it's still sending.
1677 * We also mustn't read data that isn't there; some transports (RDMA)
1678 * will stall waiting for that data when the source has already closed.
1679 */
1680 if (ret == 0 && should_send_vmdesc()) {
1681 uint8_t *buf;
1682 uint32_t size;
1683 uint8_t section_type = qemu_get_byte(f);
1684
1685 if (section_type != QEMU_VM_VMDESCRIPTION) {
1686 error_report("Expected vmdescription section, but got %d",
1687 section_type);
1688 /*
1689 * It doesn't seem worth failing at this point since
1690 * we apparently have an otherwise valid VM state
1691 */
1692 } else {
1693 buf = g_malloc(0x1000);
1694 size = qemu_get_be32(f);
1695
1696 while (size > 0) {
1697 uint32_t read_chunk = MIN(size, 0x1000);
1698 qemu_get_buffer(f, buf, read_chunk);
1699 size -= read_chunk;
1700 }
1701 g_free(buf);
1702 }
1703 }
1704
1705 cpu_synchronize_all_post_init();
1706
1707 return ret;
1708 }
1709
1710 static BlockDriverState *find_vmstate_bs(void)
1711 {
1712 BlockDriverState *bs = NULL;
1713 while ((bs = bdrv_next(bs))) {
1714 if (bdrv_can_snapshot(bs)) {
1715 return bs;
1716 }
1717 }
1718 return NULL;
1719 }
1720
1721 /*
1722 * Deletes snapshots of a given name in all opened images.
1723 */
1724 static int del_existing_snapshots(Monitor *mon, const char *name)
1725 {
1726 BlockDriverState *bs;
1727 QEMUSnapshotInfo sn1, *snapshot = &sn1;
1728 Error *err = NULL;
1729
1730 bs = NULL;
1731 while ((bs = bdrv_next(bs))) {
1732 if (bdrv_can_snapshot(bs) &&
1733 bdrv_snapshot_find(bs, snapshot, name) >= 0) {
1734 bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
1735 if (err) {
1736 monitor_printf(mon,
1737 "Error while deleting snapshot on device '%s':"
1738 " %s\n",
1739 bdrv_get_device_name(bs),
1740 error_get_pretty(err));
1741 error_free(err);
1742 return -1;
1743 }
1744 }
1745 }
1746
1747 return 0;
1748 }
1749
1750 void hmp_savevm(Monitor *mon, const QDict *qdict)
1751 {
1752 BlockDriverState *bs, *bs1;
1753 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
1754 int ret;
1755 QEMUFile *f;
1756 int saved_vm_running;
1757 uint64_t vm_state_size;
1758 qemu_timeval tv;
1759 struct tm tm;
1760 const char *name = qdict_get_try_str(qdict, "name");
1761 Error *local_err = NULL;
1762
1763 /* Verify if there is a device that doesn't support snapshots and is writable */
1764 bs = NULL;
1765 while ((bs = bdrv_next(bs))) {
1766
1767 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
1768 continue;
1769 }
1770
1771 if (!bdrv_can_snapshot(bs)) {
1772 monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
1773 bdrv_get_device_name(bs));
1774 return;
1775 }
1776 }
1777
1778 bs = find_vmstate_bs();
1779 if (!bs) {
1780 monitor_printf(mon, "No block device can accept snapshots\n");
1781 return;
1782 }
1783
1784 saved_vm_running = runstate_is_running();
1785
1786 ret = global_state_store();
1787 if (ret) {
1788 monitor_printf(mon, "Error saving global state\n");
1789 return;
1790 }
1791 vm_stop(RUN_STATE_SAVE_VM);
1792
1793 memset(sn, 0, sizeof(*sn));
1794
1795 /* fill auxiliary fields */
1796 qemu_gettimeofday(&tv);
1797 sn->date_sec = tv.tv_sec;
1798 sn->date_nsec = tv.tv_usec * 1000;
1799 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1800
1801 if (name) {
1802 ret = bdrv_snapshot_find(bs, old_sn, name);
1803 if (ret >= 0) {
1804 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
1805 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
1806 } else {
1807 pstrcpy(sn->name, sizeof(sn->name), name);
1808 }
1809 } else {
1810 /* cast below needed for OpenBSD where tv_sec is still 'long' */
1811 localtime_r((const time_t *)&tv.tv_sec, &tm);
1812 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
1813 }
1814
1815 /* Delete old snapshots of the same name */
1816 if (name && del_existing_snapshots(mon, name) < 0) {
1817 goto the_end;
1818 }
1819
1820 /* save the VM state */
1821 f = qemu_fopen_bdrv(bs, 1);
1822 if (!f) {
1823 monitor_printf(mon, "Could not open VM state file\n");
1824 goto the_end;
1825 }
1826 ret = qemu_savevm_state(f, &local_err);
1827 vm_state_size = qemu_ftell(f);
1828 qemu_fclose(f);
1829 if (ret < 0) {
1830 monitor_printf(mon, "%s\n", error_get_pretty(local_err));
1831 error_free(local_err);
1832 goto the_end;
1833 }
1834
1835 /* create the snapshots */
1836
1837 bs1 = NULL;
1838 while ((bs1 = bdrv_next(bs1))) {
1839 if (bdrv_can_snapshot(bs1)) {
1840 /* Write VM state size only to the image that contains the state */
1841 sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
1842 ret = bdrv_snapshot_create(bs1, sn);
1843 if (ret < 0) {
1844 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
1845 bdrv_get_device_name(bs1));
1846 }
1847 }
1848 }
1849
1850 the_end:
1851 if (saved_vm_running) {
1852 vm_start();
1853 }
1854 }
1855
1856 void qmp_xen_save_devices_state(const char *filename, Error **errp)
1857 {
1858 QEMUFile *f;
1859 int saved_vm_running;
1860 int ret;
1861
1862 saved_vm_running = runstate_is_running();
1863 vm_stop(RUN_STATE_SAVE_VM);
1864 global_state_store_running();
1865
1866 f = qemu_fopen(filename, "wb");
1867 if (!f) {
1868 error_setg_file_open(errp, errno, filename);
1869 goto the_end;
1870 }
1871 ret = qemu_save_device_state(f);
1872 qemu_fclose(f);
1873 if (ret < 0) {
1874 error_setg(errp, QERR_IO_ERROR);
1875 }
1876
1877 the_end:
1878 if (saved_vm_running) {
1879 vm_start();
1880 }
1881 }
1882
1883 int load_vmstate(const char *name)
1884 {
1885 BlockDriverState *bs, *bs_vm_state;
1886 QEMUSnapshotInfo sn;
1887 QEMUFile *f;
1888 int ret;
1889
1890 bs_vm_state = find_vmstate_bs();
1891 if (!bs_vm_state) {
1892 error_report("No block device supports snapshots");
1893 return -ENOTSUP;
1894 }
1895
1896 /* Don't even try to load empty VM states */
1897 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
1898 if (ret < 0) {
1899 return ret;
1900 } else if (sn.vm_state_size == 0) {
1901 error_report("This is a disk-only snapshot. Revert to it offline "
1902 "using qemu-img.");
1903 return -EINVAL;
1904 }
1905
1906 /* Verify if there is any device that doesn't support snapshots and is
1907 writable and check if the requested snapshot is available too. */
1908 bs = NULL;
1909 while ((bs = bdrv_next(bs))) {
1910
1911 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
1912 continue;
1913 }
1914
1915 if (!bdrv_can_snapshot(bs)) {
1916 error_report("Device '%s' is writable but does not support snapshots.",
1917 bdrv_get_device_name(bs));
1918 return -ENOTSUP;
1919 }
1920
1921 ret = bdrv_snapshot_find(bs, &sn, name);
1922 if (ret < 0) {
1923 error_report("Device '%s' does not have the requested snapshot '%s'",
1924 bdrv_get_device_name(bs), name);
1925 return ret;
1926 }
1927 }
1928
1929 /* Flush all IO requests so they don't interfere with the new state. */
1930 bdrv_drain_all();
1931
1932 bs = NULL;
1933 while ((bs = bdrv_next(bs))) {
1934 if (bdrv_can_snapshot(bs)) {
1935 ret = bdrv_snapshot_goto(bs, name);
1936 if (ret < 0) {
1937 error_report("Error %d while activating snapshot '%s' on '%s'",
1938 ret, name, bdrv_get_device_name(bs));
1939 return ret;
1940 }
1941 }
1942 }
1943
1944 /* restore the VM state */
1945 f = qemu_fopen_bdrv(bs_vm_state, 0);
1946 if (!f) {
1947 error_report("Could not open VM state file");
1948 return -EINVAL;
1949 }
1950
1951 qemu_system_reset(VMRESET_SILENT);
1952 migration_incoming_state_new(f);
1953 ret = qemu_loadvm_state(f);
1954
1955 qemu_fclose(f);
1956 migration_incoming_state_destroy();
1957 if (ret < 0) {
1958 error_report("Error %d while loading VM state", ret);
1959 return ret;
1960 }
1961
1962 return 0;
1963 }
1964
1965 void hmp_delvm(Monitor *mon, const QDict *qdict)
1966 {
1967 BlockDriverState *bs;
1968 Error *err;
1969 const char *name = qdict_get_str(qdict, "name");
1970
1971 if (!find_vmstate_bs()) {
1972 monitor_printf(mon, "No block device supports snapshots\n");
1973 return;
1974 }
1975
1976 bs = NULL;
1977 while ((bs = bdrv_next(bs))) {
1978 if (bdrv_can_snapshot(bs)) {
1979 err = NULL;
1980 bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
1981 if (err) {
1982 monitor_printf(mon,
1983 "Error while deleting snapshot on device '%s':"
1984 " %s\n",
1985 bdrv_get_device_name(bs),
1986 error_get_pretty(err));
1987 error_free(err);
1988 }
1989 }
1990 }
1991 }
1992
1993 void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
1994 {
1995 BlockDriverState *bs, *bs1;
1996 QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
1997 int nb_sns, i, ret, available;
1998 int total;
1999 int *available_snapshots;
2000
2001 bs = find_vmstate_bs();
2002 if (!bs) {
2003 monitor_printf(mon, "No available block device supports snapshots\n");
2004 return;
2005 }
2006
2007 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2008 if (nb_sns < 0) {
2009 monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
2010 return;
2011 }
2012
2013 if (nb_sns == 0) {
2014 monitor_printf(mon, "There is no snapshot available.\n");
2015 return;
2016 }
2017
2018 available_snapshots = g_new0(int, nb_sns);
2019 total = 0;
2020 for (i = 0; i < nb_sns; i++) {
2021 sn = &sn_tab[i];
2022 available = 1;
2023 bs1 = NULL;
2024
2025 while ((bs1 = bdrv_next(bs1))) {
2026 if (bdrv_can_snapshot(bs1) && bs1 != bs) {
2027 ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
2028 if (ret < 0) {
2029 available = 0;
2030 break;
2031 }
2032 }
2033 }
2034
2035 if (available) {
2036 available_snapshots[total] = i;
2037 total++;
2038 }
2039 }
2040
2041 if (total > 0) {
2042 bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);
2043 monitor_printf(mon, "\n");
2044 for (i = 0; i < total; i++) {
2045 sn = &sn_tab[available_snapshots[i]];
2046 bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);
2047 monitor_printf(mon, "\n");
2048 }
2049 } else {
2050 monitor_printf(mon, "There is no suitable snapshot available\n");
2051 }
2052
2053 g_free(sn_tab);
2054 g_free(available_snapshots);
2055
2056 }
2057
2058 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2059 {
2060 qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
2061 memory_region_name(mr), dev);
2062 }
2063
2064 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2065 {
2066 qemu_ram_unset_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK);
2067 }
2068
2069 void vmstate_register_ram_global(MemoryRegion *mr)
2070 {
2071 vmstate_register_ram(mr, NULL);
2072 }