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