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