xref: /openbmc/qemu/migration/savevm.c (revision e50a24ea)
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 "net/net.h"
32 #include "migration.h"
33 #include "migration/snapshot.h"
34 #include "migration-stats.h"
35 #include "migration/vmstate.h"
36 #include "migration/misc.h"
37 #include "migration/register.h"
38 #include "migration/global_state.h"
39 #include "migration/channel-block.h"
40 #include "ram.h"
41 #include "qemu-file.h"
42 #include "savevm.h"
43 #include "postcopy-ram.h"
44 #include "qapi/error.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/clone-visitor.h"
47 #include "qapi/qapi-builtin-visit.h"
48 #include "qemu/error-report.h"
49 #include "sysemu/cpus.h"
50 #include "exec/memory.h"
51 #include "exec/target_page.h"
52 #include "trace.h"
53 #include "qemu/iov.h"
54 #include "qemu/job.h"
55 #include "qemu/main-loop.h"
56 #include "block/snapshot.h"
57 #include "qemu/cutils.h"
58 #include "io/channel-buffer.h"
59 #include "io/channel-file.h"
60 #include "sysemu/replay.h"
61 #include "sysemu/runstate.h"
62 #include "sysemu/sysemu.h"
63 #include "sysemu/xen.h"
64 #include "migration/colo.h"
65 #include "qemu/bitmap.h"
66 #include "net/announce.h"
67 #include "qemu/yank.h"
68 #include "yank_functions.h"
69 #include "sysemu/qtest.h"
70 #include "options.h"
71 
72 const unsigned int postcopy_ram_discard_version;
73 
74 /* Subcommands for QEMU_VM_COMMAND */
75 enum qemu_vm_cmd {
76     MIG_CMD_INVALID = 0,   /* Must be 0 */
77     MIG_CMD_OPEN_RETURN_PATH,  /* Tell the dest to open the Return path */
78     MIG_CMD_PING,              /* Request a PONG on the RP */
79 
80     MIG_CMD_POSTCOPY_ADVISE,       /* Prior to any page transfers, just
81                                       warn we might want to do PC */
82     MIG_CMD_POSTCOPY_LISTEN,       /* Start listening for incoming
83                                       pages as it's running. */
84     MIG_CMD_POSTCOPY_RUN,          /* Start execution */
85 
86     MIG_CMD_POSTCOPY_RAM_DISCARD,  /* A list of pages to discard that
87                                       were previously sent during
88                                       precopy but are dirty. */
89     MIG_CMD_PACKAGED,          /* Send a wrapped stream within this stream */
90     MIG_CMD_ENABLE_COLO,       /* Enable COLO */
91     MIG_CMD_POSTCOPY_RESUME,   /* resume postcopy on dest */
92     MIG_CMD_RECV_BITMAP,       /* Request for recved bitmap on dst */
93     MIG_CMD_MAX
94 };
95 
96 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
97 static struct mig_cmd_args {
98     ssize_t     len; /* -1 = variable */
99     const char *name;
100 } mig_cmd_args[] = {
101     [MIG_CMD_INVALID]          = { .len = -1, .name = "INVALID" },
102     [MIG_CMD_OPEN_RETURN_PATH] = { .len =  0, .name = "OPEN_RETURN_PATH" },
103     [MIG_CMD_PING]             = { .len = sizeof(uint32_t), .name = "PING" },
104     [MIG_CMD_POSTCOPY_ADVISE]  = { .len = -1, .name = "POSTCOPY_ADVISE" },
105     [MIG_CMD_POSTCOPY_LISTEN]  = { .len =  0, .name = "POSTCOPY_LISTEN" },
106     [MIG_CMD_POSTCOPY_RUN]     = { .len =  0, .name = "POSTCOPY_RUN" },
107     [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
108                                    .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
109     [MIG_CMD_POSTCOPY_RESUME]  = { .len =  0, .name = "POSTCOPY_RESUME" },
110     [MIG_CMD_PACKAGED]         = { .len =  4, .name = "PACKAGED" },
111     [MIG_CMD_RECV_BITMAP]      = { .len = -1, .name = "RECV_BITMAP" },
112     [MIG_CMD_MAX]              = { .len = -1, .name = "MAX" },
113 };
114 
115 /* Note for MIG_CMD_POSTCOPY_ADVISE:
116  * The format of arguments is depending on postcopy mode:
117  * - postcopy RAM only
118  *   uint64_t host page size
119  *   uint64_t target page size
120  *
121  * - postcopy RAM and postcopy dirty bitmaps
122  *   format is the same as for postcopy RAM only
123  *
124  * - postcopy dirty bitmaps only
125  *   Nothing. Command length field is 0.
126  *
127  * Be careful: adding a new postcopy entity with some other parameters should
128  * not break format self-description ability. Good way is to introduce some
129  * generic extendable format with an exception for two old entities.
130  */
131 
132 /***********************************************************/
133 /* savevm/loadvm support */
134 
135 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
136 {
137     if (is_writable) {
138         return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
139     } else {
140         return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
141     }
142 }
143 
144 
145 /* QEMUFile timer support.
146  * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
147  */
148 
149 void timer_put(QEMUFile *f, QEMUTimer *ts)
150 {
151     uint64_t expire_time;
152 
153     expire_time = timer_expire_time_ns(ts);
154     qemu_put_be64(f, expire_time);
155 }
156 
157 void timer_get(QEMUFile *f, QEMUTimer *ts)
158 {
159     uint64_t expire_time;
160 
161     expire_time = qemu_get_be64(f);
162     if (expire_time != -1) {
163         timer_mod_ns(ts, expire_time);
164     } else {
165         timer_del(ts);
166     }
167 }
168 
169 
170 /* VMState timer support.
171  * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
172  */
173 
174 static int get_timer(QEMUFile *f, void *pv, size_t size,
175                      const VMStateField *field)
176 {
177     QEMUTimer *v = pv;
178     timer_get(f, v);
179     return 0;
180 }
181 
182 static int put_timer(QEMUFile *f, void *pv, size_t size,
183                      const VMStateField *field, JSONWriter *vmdesc)
184 {
185     QEMUTimer *v = pv;
186     timer_put(f, v);
187 
188     return 0;
189 }
190 
191 const VMStateInfo vmstate_info_timer = {
192     .name = "timer",
193     .get  = get_timer,
194     .put  = put_timer,
195 };
196 
197 
198 typedef struct CompatEntry {
199     char idstr[256];
200     int instance_id;
201 } CompatEntry;
202 
203 typedef struct SaveStateEntry {
204     QTAILQ_ENTRY(SaveStateEntry) entry;
205     char idstr[256];
206     uint32_t instance_id;
207     int alias_id;
208     int version_id;
209     /* version id read from the stream */
210     int load_version_id;
211     int section_id;
212     /* section id read from the stream */
213     int load_section_id;
214     const SaveVMHandlers *ops;
215     const VMStateDescription *vmsd;
216     void *opaque;
217     CompatEntry *compat;
218     int is_ram;
219 } SaveStateEntry;
220 
221 typedef struct SaveState {
222     QTAILQ_HEAD(, SaveStateEntry) handlers;
223     SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
224     int global_section_id;
225     uint32_t len;
226     const char *name;
227     uint32_t target_page_bits;
228     uint32_t caps_count;
229     MigrationCapability *capabilities;
230     QemuUUID uuid;
231 } SaveState;
232 
233 static SaveState savevm_state = {
234     .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
235     .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
236     .global_section_id = 0,
237 };
238 
239 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id);
240 
241 static bool should_validate_capability(int capability)
242 {
243     assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
244     /* Validate only new capabilities to keep compatibility. */
245     switch (capability) {
246     case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
247     case MIGRATION_CAPABILITY_MAPPED_RAM:
248         return true;
249     default:
250         return false;
251     }
252 }
253 
254 static uint32_t get_validatable_capabilities_count(void)
255 {
256     MigrationState *s = migrate_get_current();
257     uint32_t result = 0;
258     int i;
259     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
260         if (should_validate_capability(i) && s->capabilities[i]) {
261             result++;
262         }
263     }
264     return result;
265 }
266 
267 static int configuration_pre_save(void *opaque)
268 {
269     SaveState *state = opaque;
270     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
271     MigrationState *s = migrate_get_current();
272     int i, j;
273 
274     state->len = strlen(current_name);
275     state->name = current_name;
276     state->target_page_bits = qemu_target_page_bits();
277 
278     state->caps_count = get_validatable_capabilities_count();
279     state->capabilities = g_renew(MigrationCapability, state->capabilities,
280                                   state->caps_count);
281     for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
282         if (should_validate_capability(i) && s->capabilities[i]) {
283             state->capabilities[j++] = i;
284         }
285     }
286     state->uuid = qemu_uuid;
287 
288     return 0;
289 }
290 
291 static int configuration_post_save(void *opaque)
292 {
293     SaveState *state = opaque;
294 
295     g_free(state->capabilities);
296     state->capabilities = NULL;
297     state->caps_count = 0;
298     return 0;
299 }
300 
301 static int configuration_pre_load(void *opaque)
302 {
303     SaveState *state = opaque;
304 
305     /* If there is no target-page-bits subsection it means the source
306      * predates the variable-target-page-bits support and is using the
307      * minimum possible value for this CPU.
308      */
309     state->target_page_bits = qemu_target_page_bits_min();
310     return 0;
311 }
312 
313 static bool configuration_validate_capabilities(SaveState *state)
314 {
315     bool ret = true;
316     MigrationState *s = migrate_get_current();
317     unsigned long *source_caps_bm;
318     int i;
319 
320     source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
321     for (i = 0; i < state->caps_count; i++) {
322         MigrationCapability capability = state->capabilities[i];
323         set_bit(capability, source_caps_bm);
324     }
325 
326     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
327         bool source_state, target_state;
328         if (!should_validate_capability(i)) {
329             continue;
330         }
331         source_state = test_bit(i, source_caps_bm);
332         target_state = s->capabilities[i];
333         if (source_state != target_state) {
334             error_report("Capability %s is %s, but received capability is %s",
335                          MigrationCapability_str(i),
336                          target_state ? "on" : "off",
337                          source_state ? "on" : "off");
338             ret = false;
339             /* Don't break here to report all failed capabilities */
340         }
341     }
342 
343     g_free(source_caps_bm);
344     return ret;
345 }
346 
347 static int configuration_post_load(void *opaque, int version_id)
348 {
349     SaveState *state = opaque;
350     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
351     int ret = 0;
352 
353     if (strncmp(state->name, current_name, state->len) != 0) {
354         error_report("Machine type received is '%.*s' and local is '%s'",
355                      (int) state->len, state->name, current_name);
356         ret = -EINVAL;
357         goto out;
358     }
359 
360     if (state->target_page_bits != qemu_target_page_bits()) {
361         error_report("Received TARGET_PAGE_BITS is %d but local is %d",
362                      state->target_page_bits, qemu_target_page_bits());
363         ret = -EINVAL;
364         goto out;
365     }
366 
367     if (!configuration_validate_capabilities(state)) {
368         ret = -EINVAL;
369         goto out;
370     }
371 
372 out:
373     g_free((void *)state->name);
374     state->name = NULL;
375     state->len = 0;
376     g_free(state->capabilities);
377     state->capabilities = NULL;
378     state->caps_count = 0;
379 
380     return ret;
381 }
382 
383 static int get_capability(QEMUFile *f, void *pv, size_t size,
384                           const VMStateField *field)
385 {
386     MigrationCapability *capability = pv;
387     char capability_str[UINT8_MAX + 1];
388     uint8_t len;
389     int i;
390 
391     len = qemu_get_byte(f);
392     qemu_get_buffer(f, (uint8_t *)capability_str, len);
393     capability_str[len] = '\0';
394     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
395         if (!strcmp(MigrationCapability_str(i), capability_str)) {
396             *capability = i;
397             return 0;
398         }
399     }
400     error_report("Received unknown capability %s", capability_str);
401     return -EINVAL;
402 }
403 
404 static int put_capability(QEMUFile *f, void *pv, size_t size,
405                           const VMStateField *field, JSONWriter *vmdesc)
406 {
407     MigrationCapability *capability = pv;
408     const char *capability_str = MigrationCapability_str(*capability);
409     size_t len = strlen(capability_str);
410     assert(len <= UINT8_MAX);
411 
412     qemu_put_byte(f, len);
413     qemu_put_buffer(f, (uint8_t *)capability_str, len);
414     return 0;
415 }
416 
417 static const VMStateInfo vmstate_info_capability = {
418     .name = "capability",
419     .get  = get_capability,
420     .put  = put_capability,
421 };
422 
423 /* The target-page-bits subsection is present only if the
424  * target page size is not the same as the default (ie the
425  * minimum page size for a variable-page-size guest CPU).
426  * If it is present then it contains the actual target page
427  * bits for the machine, and migration will fail if the
428  * two ends don't agree about it.
429  */
430 static bool vmstate_target_page_bits_needed(void *opaque)
431 {
432     return qemu_target_page_bits()
433         > qemu_target_page_bits_min();
434 }
435 
436 static const VMStateDescription vmstate_target_page_bits = {
437     .name = "configuration/target-page-bits",
438     .version_id = 1,
439     .minimum_version_id = 1,
440     .needed = vmstate_target_page_bits_needed,
441     .fields = (const VMStateField[]) {
442         VMSTATE_UINT32(target_page_bits, SaveState),
443         VMSTATE_END_OF_LIST()
444     }
445 };
446 
447 static bool vmstate_capabilites_needed(void *opaque)
448 {
449     return get_validatable_capabilities_count() > 0;
450 }
451 
452 static const VMStateDescription vmstate_capabilites = {
453     .name = "configuration/capabilities",
454     .version_id = 1,
455     .minimum_version_id = 1,
456     .needed = vmstate_capabilites_needed,
457     .fields = (const VMStateField[]) {
458         VMSTATE_UINT32_V(caps_count, SaveState, 1),
459         VMSTATE_VARRAY_UINT32_ALLOC(capabilities, SaveState, caps_count, 1,
460                                     vmstate_info_capability,
461                                     MigrationCapability),
462         VMSTATE_END_OF_LIST()
463     }
464 };
465 
466 static bool vmstate_uuid_needed(void *opaque)
467 {
468     return qemu_uuid_set && migrate_validate_uuid();
469 }
470 
471 static int vmstate_uuid_post_load(void *opaque, int version_id)
472 {
473     SaveState *state = opaque;
474     char uuid_src[UUID_STR_LEN];
475     char uuid_dst[UUID_STR_LEN];
476 
477     if (!qemu_uuid_set) {
478         /*
479          * It's warning because user might not know UUID in some cases,
480          * e.g. load an old snapshot
481          */
482         qemu_uuid_unparse(&state->uuid, uuid_src);
483         warn_report("UUID is received %s, but local uuid isn't set",
484                      uuid_src);
485         return 0;
486     }
487     if (!qemu_uuid_is_equal(&state->uuid, &qemu_uuid)) {
488         qemu_uuid_unparse(&state->uuid, uuid_src);
489         qemu_uuid_unparse(&qemu_uuid, uuid_dst);
490         error_report("UUID received is %s and local is %s", uuid_src, uuid_dst);
491         return -EINVAL;
492     }
493     return 0;
494 }
495 
496 static const VMStateDescription vmstate_uuid = {
497     .name = "configuration/uuid",
498     .version_id = 1,
499     .minimum_version_id = 1,
500     .needed = vmstate_uuid_needed,
501     .post_load = vmstate_uuid_post_load,
502     .fields = (const VMStateField[]) {
503         VMSTATE_UINT8_ARRAY_V(uuid.data, SaveState, sizeof(QemuUUID), 1),
504         VMSTATE_END_OF_LIST()
505     }
506 };
507 
508 static const VMStateDescription vmstate_configuration = {
509     .name = "configuration",
510     .version_id = 1,
511     .pre_load = configuration_pre_load,
512     .post_load = configuration_post_load,
513     .pre_save = configuration_pre_save,
514     .post_save = configuration_post_save,
515     .fields = (const VMStateField[]) {
516         VMSTATE_UINT32(len, SaveState),
517         VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
518         VMSTATE_END_OF_LIST()
519     },
520     .subsections = (const VMStateDescription * const []) {
521         &vmstate_target_page_bits,
522         &vmstate_capabilites,
523         &vmstate_uuid,
524         NULL
525     }
526 };
527 
528 static void dump_vmstate_vmsd(FILE *out_file,
529                               const VMStateDescription *vmsd, int indent,
530                               bool is_subsection);
531 
532 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
533                               int indent)
534 {
535     fprintf(out_file, "%*s{\n", indent, "");
536     indent += 2;
537     fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
538     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
539             field->version_id);
540     fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
541             field->field_exists ? "true" : "false");
542     if (field->flags & VMS_ARRAY) {
543         fprintf(out_file, "%*s\"num\": %d,\n", indent, "", field->num);
544     }
545     fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
546     if (field->vmsd != NULL) {
547         fprintf(out_file, ",\n");
548         dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
549     }
550     fprintf(out_file, "\n%*s}", indent - 2, "");
551 }
552 
553 static void dump_vmstate_vmss(FILE *out_file,
554                               const VMStateDescription *subsection,
555                               int indent)
556 {
557     if (subsection != NULL) {
558         dump_vmstate_vmsd(out_file, subsection, indent, true);
559     }
560 }
561 
562 static void dump_vmstate_vmsd(FILE *out_file,
563                               const VMStateDescription *vmsd, int indent,
564                               bool is_subsection)
565 {
566     if (is_subsection) {
567         fprintf(out_file, "%*s{\n", indent, "");
568     } else {
569         fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
570     }
571     indent += 2;
572     fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
573     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
574             vmsd->version_id);
575     fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
576             vmsd->minimum_version_id);
577     if (vmsd->fields != NULL) {
578         const VMStateField *field = vmsd->fields;
579         bool first;
580 
581         fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
582         first = true;
583         while (field->name != NULL) {
584             if (field->flags & VMS_MUST_EXIST) {
585                 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
586                 field++;
587                 continue;
588             }
589             if (!first) {
590                 fprintf(out_file, ",\n");
591             }
592             dump_vmstate_vmsf(out_file, field, indent + 2);
593             field++;
594             first = false;
595         }
596         assert(field->flags == VMS_END);
597         fprintf(out_file, "\n%*s]", indent, "");
598     }
599     if (vmsd->subsections != NULL) {
600         const VMStateDescription * const *subsection = vmsd->subsections;
601         bool first;
602 
603         fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
604         first = true;
605         while (*subsection != NULL) {
606             if (!first) {
607                 fprintf(out_file, ",\n");
608             }
609             dump_vmstate_vmss(out_file, *subsection, indent + 2);
610             subsection++;
611             first = false;
612         }
613         fprintf(out_file, "\n%*s]", indent, "");
614     }
615     fprintf(out_file, "\n%*s}", indent - 2, "");
616 }
617 
618 static void dump_machine_type(FILE *out_file)
619 {
620     MachineClass *mc;
621 
622     mc = MACHINE_GET_CLASS(current_machine);
623 
624     fprintf(out_file, "  \"vmschkmachine\": {\n");
625     fprintf(out_file, "    \"Name\": \"%s\"\n", mc->name);
626     fprintf(out_file, "  },\n");
627 }
628 
629 void dump_vmstate_json_to_file(FILE *out_file)
630 {
631     GSList *list, *elt;
632     bool first;
633 
634     fprintf(out_file, "{\n");
635     dump_machine_type(out_file);
636 
637     first = true;
638     list = object_class_get_list(TYPE_DEVICE, true);
639     for (elt = list; elt; elt = elt->next) {
640         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
641                                              TYPE_DEVICE);
642         const char *name;
643         int indent = 2;
644 
645         if (!dc->vmsd) {
646             continue;
647         }
648 
649         if (!first) {
650             fprintf(out_file, ",\n");
651         }
652         name = object_class_get_name(OBJECT_CLASS(dc));
653         fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
654         indent += 2;
655         fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
656         fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
657                 dc->vmsd->version_id);
658         fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
659                 dc->vmsd->minimum_version_id);
660 
661         dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
662 
663         fprintf(out_file, "\n%*s}", indent - 2, "");
664         first = false;
665     }
666     fprintf(out_file, "\n}\n");
667     fclose(out_file);
668     g_slist_free(list);
669 }
670 
671 static uint32_t calculate_new_instance_id(const char *idstr)
672 {
673     SaveStateEntry *se;
674     uint32_t instance_id = 0;
675 
676     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
677         if (strcmp(idstr, se->idstr) == 0
678             && instance_id <= se->instance_id) {
679             instance_id = se->instance_id + 1;
680         }
681     }
682     /* Make sure we never loop over without being noticed */
683     assert(instance_id != VMSTATE_INSTANCE_ID_ANY);
684     return instance_id;
685 }
686 
687 static int calculate_compat_instance_id(const char *idstr)
688 {
689     SaveStateEntry *se;
690     int instance_id = 0;
691 
692     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
693         if (!se->compat) {
694             continue;
695         }
696 
697         if (strcmp(idstr, se->compat->idstr) == 0
698             && instance_id <= se->compat->instance_id) {
699             instance_id = se->compat->instance_id + 1;
700         }
701     }
702     return instance_id;
703 }
704 
705 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
706 {
707     if (se->vmsd) {
708         return se->vmsd->priority;
709     }
710     return MIG_PRI_DEFAULT;
711 }
712 
713 static void savevm_state_handler_insert(SaveStateEntry *nse)
714 {
715     MigrationPriority priority = save_state_priority(nse);
716     SaveStateEntry *se;
717     int i;
718 
719     assert(priority <= MIG_PRI_MAX);
720 
721     /*
722      * This should never happen otherwise migration will probably fail
723      * silently somewhere because we can be wrongly applying one
724      * object properties upon another one.  Bail out ASAP.
725      */
726     if (find_se(nse->idstr, nse->instance_id)) {
727         error_report("%s: Detected duplicate SaveStateEntry: "
728                      "id=%s, instance_id=0x%"PRIx32, __func__,
729                      nse->idstr, nse->instance_id);
730         exit(EXIT_FAILURE);
731     }
732 
733     for (i = priority - 1; i >= 0; i--) {
734         se = savevm_state.handler_pri_head[i];
735         if (se != NULL) {
736             assert(save_state_priority(se) < priority);
737             break;
738         }
739     }
740 
741     if (i >= 0) {
742         QTAILQ_INSERT_BEFORE(se, nse, entry);
743     } else {
744         QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
745     }
746 
747     if (savevm_state.handler_pri_head[priority] == NULL) {
748         savevm_state.handler_pri_head[priority] = nse;
749     }
750 }
751 
752 static void savevm_state_handler_remove(SaveStateEntry *se)
753 {
754     SaveStateEntry *next;
755     MigrationPriority priority = save_state_priority(se);
756 
757     if (se == savevm_state.handler_pri_head[priority]) {
758         next = QTAILQ_NEXT(se, entry);
759         if (next != NULL && save_state_priority(next) == priority) {
760             savevm_state.handler_pri_head[priority] = next;
761         } else {
762             savevm_state.handler_pri_head[priority] = NULL;
763         }
764     }
765     QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
766 }
767 
768 /* TODO: Individual devices generally have very little idea about the rest
769    of the system, so instance_id should be removed/replaced.
770    Meanwhile pass -1 as instance_id if you do not already have a clearly
771    distinguishing id for all instances of your device class. */
772 int register_savevm_live(const char *idstr,
773                          uint32_t instance_id,
774                          int version_id,
775                          const SaveVMHandlers *ops,
776                          void *opaque)
777 {
778     SaveStateEntry *se;
779 
780     se = g_new0(SaveStateEntry, 1);
781     se->version_id = version_id;
782     se->section_id = savevm_state.global_section_id++;
783     se->ops = ops;
784     se->opaque = opaque;
785     se->vmsd = NULL;
786     /* if this is a live_savem then set is_ram */
787     if (ops->save_setup != NULL) {
788         se->is_ram = 1;
789     }
790 
791     pstrcat(se->idstr, sizeof(se->idstr), idstr);
792 
793     if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
794         se->instance_id = calculate_new_instance_id(se->idstr);
795     } else {
796         se->instance_id = instance_id;
797     }
798     assert(!se->compat || se->instance_id == 0);
799     savevm_state_handler_insert(se);
800     return 0;
801 }
802 
803 void unregister_savevm(VMStateIf *obj, const char *idstr, void *opaque)
804 {
805     SaveStateEntry *se, *new_se;
806     char id[256] = "";
807 
808     if (obj) {
809         char *oid = vmstate_if_get_id(obj);
810         if (oid) {
811             pstrcpy(id, sizeof(id), oid);
812             pstrcat(id, sizeof(id), "/");
813             g_free(oid);
814         }
815     }
816     pstrcat(id, sizeof(id), idstr);
817 
818     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
819         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
820             savevm_state_handler_remove(se);
821             g_free(se->compat);
822             g_free(se);
823         }
824     }
825 }
826 
827 /*
828  * Perform some basic checks on vmsd's at registration
829  * time.
830  */
831 static void vmstate_check(const VMStateDescription *vmsd)
832 {
833     const VMStateField *field = vmsd->fields;
834     const VMStateDescription * const *subsection = vmsd->subsections;
835 
836     if (field) {
837         while (field->name) {
838             if (field->flags & (VMS_STRUCT | VMS_VSTRUCT)) {
839                 /* Recurse to sub structures */
840                 vmstate_check(field->vmsd);
841             }
842             /* Carry on */
843             field++;
844         }
845         /* Check for the end of field list canary */
846         if (field->flags != VMS_END) {
847             error_report("VMSTATE not ending with VMS_END: %s", vmsd->name);
848             g_assert_not_reached();
849         }
850     }
851 
852     while (subsection && *subsection) {
853         /*
854          * The name of a subsection should start with the name of the
855          * current object.
856          */
857         assert(!strncmp(vmsd->name, (*subsection)->name, strlen(vmsd->name)));
858         vmstate_check(*subsection);
859         subsection++;
860     }
861 }
862 
863 
864 int vmstate_register_with_alias_id(VMStateIf *obj, uint32_t instance_id,
865                                    const VMStateDescription *vmsd,
866                                    void *opaque, int alias_id,
867                                    int required_for_version,
868                                    Error **errp)
869 {
870     SaveStateEntry *se;
871 
872     /* If this triggers, alias support can be dropped for the vmsd. */
873     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
874 
875     se = g_new0(SaveStateEntry, 1);
876     se->version_id = vmsd->version_id;
877     se->section_id = savevm_state.global_section_id++;
878     se->opaque = opaque;
879     se->vmsd = vmsd;
880     se->alias_id = alias_id;
881 
882     if (obj) {
883         char *id = vmstate_if_get_id(obj);
884         if (id) {
885             if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
886                 sizeof(se->idstr)) {
887                 error_setg(errp, "Path too long for VMState (%s)", id);
888                 g_free(id);
889                 g_free(se);
890 
891                 return -1;
892             }
893             g_free(id);
894 
895             se->compat = g_new0(CompatEntry, 1);
896             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
897             se->compat->instance_id = instance_id == VMSTATE_INSTANCE_ID_ANY ?
898                          calculate_compat_instance_id(vmsd->name) : instance_id;
899             instance_id = VMSTATE_INSTANCE_ID_ANY;
900         }
901     }
902     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
903 
904     if (instance_id == VMSTATE_INSTANCE_ID_ANY) {
905         se->instance_id = calculate_new_instance_id(se->idstr);
906     } else {
907         se->instance_id = instance_id;
908     }
909 
910     /* Perform a recursive sanity check during the test runs */
911     if (qtest_enabled()) {
912         vmstate_check(vmsd);
913     }
914     assert(!se->compat || se->instance_id == 0);
915     savevm_state_handler_insert(se);
916     return 0;
917 }
918 
919 void vmstate_unregister(VMStateIf *obj, const VMStateDescription *vmsd,
920                         void *opaque)
921 {
922     SaveStateEntry *se, *new_se;
923 
924     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
925         if (se->vmsd == vmsd && se->opaque == opaque) {
926             savevm_state_handler_remove(se);
927             g_free(se->compat);
928             g_free(se);
929         }
930     }
931 }
932 
933 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
934 {
935     trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
936     if (!se->vmsd) {         /* Old style */
937         return se->ops->load_state(f, se->opaque, se->load_version_id);
938     }
939     return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
940 }
941 
942 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se,
943                                    JSONWriter *vmdesc)
944 {
945     uint64_t old_offset = qemu_file_transferred(f);
946     se->ops->save_state(f, se->opaque);
947     uint64_t size = qemu_file_transferred(f) - old_offset;
948 
949     if (vmdesc) {
950         json_writer_int64(vmdesc, "size", size);
951         json_writer_start_array(vmdesc, "fields");
952         json_writer_start_object(vmdesc, NULL);
953         json_writer_str(vmdesc, "name", "data");
954         json_writer_int64(vmdesc, "size", size);
955         json_writer_str(vmdesc, "type", "buffer");
956         json_writer_end_object(vmdesc);
957         json_writer_end_array(vmdesc);
958     }
959 }
960 
961 /*
962  * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
963  */
964 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
965                                 uint8_t section_type)
966 {
967     qemu_put_byte(f, section_type);
968     qemu_put_be32(f, se->section_id);
969 
970     if (section_type == QEMU_VM_SECTION_FULL ||
971         section_type == QEMU_VM_SECTION_START) {
972         /* ID string */
973         size_t len = strlen(se->idstr);
974         qemu_put_byte(f, len);
975         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
976 
977         qemu_put_be32(f, se->instance_id);
978         qemu_put_be32(f, se->version_id);
979     }
980 }
981 
982 /*
983  * Write a footer onto device sections that catches cases misformatted device
984  * sections.
985  */
986 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
987 {
988     if (migrate_get_current()->send_section_footer) {
989         qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
990         qemu_put_be32(f, se->section_id);
991     }
992 }
993 
994 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, JSONWriter *vmdesc,
995                         Error **errp)
996 {
997     int ret;
998 
999     if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1000         return 0;
1001     }
1002     if (se->vmsd && !vmstate_section_needed(se->vmsd, se->opaque)) {
1003         trace_savevm_section_skip(se->idstr, se->section_id);
1004         return 0;
1005     }
1006 
1007     trace_savevm_section_start(se->idstr, se->section_id);
1008     save_section_header(f, se, QEMU_VM_SECTION_FULL);
1009     if (vmdesc) {
1010         json_writer_start_object(vmdesc, NULL);
1011         json_writer_str(vmdesc, "name", se->idstr);
1012         json_writer_int64(vmdesc, "instance_id", se->instance_id);
1013     }
1014 
1015     trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
1016     if (!se->vmsd) {
1017         vmstate_save_old_style(f, se, vmdesc);
1018     } else {
1019         ret = vmstate_save_state_with_err(f, se->vmsd, se->opaque, vmdesc,
1020                                           errp);
1021         if (ret) {
1022             return ret;
1023         }
1024     }
1025 
1026     trace_savevm_section_end(se->idstr, se->section_id, 0);
1027     save_section_footer(f, se);
1028     if (vmdesc) {
1029         json_writer_end_object(vmdesc);
1030     }
1031     return 0;
1032 }
1033 /**
1034  * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
1035  *                           command and associated data.
1036  *
1037  * @f: File to send command on
1038  * @command: Command type to send
1039  * @len: Length of associated data
1040  * @data: Data associated with command.
1041  */
1042 static void qemu_savevm_command_send(QEMUFile *f,
1043                                      enum qemu_vm_cmd command,
1044                                      uint16_t len,
1045                                      uint8_t *data)
1046 {
1047     trace_savevm_command_send(command, len);
1048     qemu_put_byte(f, QEMU_VM_COMMAND);
1049     qemu_put_be16(f, (uint16_t)command);
1050     qemu_put_be16(f, len);
1051     qemu_put_buffer(f, data, len);
1052     qemu_fflush(f);
1053 }
1054 
1055 void qemu_savevm_send_colo_enable(QEMUFile *f)
1056 {
1057     trace_savevm_send_colo_enable();
1058     qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
1059 }
1060 
1061 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
1062 {
1063     uint32_t buf;
1064 
1065     trace_savevm_send_ping(value);
1066     buf = cpu_to_be32(value);
1067     qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
1068 }
1069 
1070 void qemu_savevm_send_open_return_path(QEMUFile *f)
1071 {
1072     trace_savevm_send_open_return_path();
1073     qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
1074 }
1075 
1076 /* We have a buffer of data to send; we don't want that all to be loaded
1077  * by the command itself, so the command contains just the length of the
1078  * extra buffer that we then send straight after it.
1079  * TODO: Must be a better way to organise that
1080  *
1081  * Returns:
1082  *    0 on success
1083  *    -ve on error
1084  */
1085 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
1086 {
1087     uint32_t tmp;
1088     MigrationState *ms = migrate_get_current();
1089     Error *local_err = NULL;
1090 
1091     if (len > MAX_VM_CMD_PACKAGED_SIZE) {
1092         error_setg(&local_err, "%s: Unreasonably large packaged state: %zu",
1093                      __func__, len);
1094         migrate_set_error(ms, local_err);
1095         error_report_err(local_err);
1096         return -1;
1097     }
1098 
1099     tmp = cpu_to_be32(len);
1100 
1101     trace_qemu_savevm_send_packaged();
1102     qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
1103 
1104     qemu_put_buffer(f, buf, len);
1105 
1106     return 0;
1107 }
1108 
1109 /* Send prior to any postcopy transfer */
1110 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
1111 {
1112     if (migrate_postcopy_ram()) {
1113         uint64_t tmp[2];
1114         tmp[0] = cpu_to_be64(ram_pagesize_summary());
1115         tmp[1] = cpu_to_be64(qemu_target_page_size());
1116 
1117         trace_qemu_savevm_send_postcopy_advise();
1118         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
1119                                  16, (uint8_t *)tmp);
1120     } else {
1121         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
1122     }
1123 }
1124 
1125 /* Sent prior to starting the destination running in postcopy, discard pages
1126  * that have already been sent but redirtied on the source.
1127  * CMD_POSTCOPY_RAM_DISCARD consist of:
1128  *      byte   version (0)
1129  *      byte   Length of name field (not including 0)
1130  *  n x byte   RAM block name
1131  *      byte   0 terminator (just for safety)
1132  *  n x        Byte ranges within the named RAMBlock
1133  *      be64   Start of the range
1134  *      be64   Length
1135  *
1136  *  name:  RAMBlock name that these entries are part of
1137  *  len: Number of page entries
1138  *  start_list: 'len' addresses
1139  *  length_list: 'len' addresses
1140  *
1141  */
1142 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1143                                            uint16_t len,
1144                                            uint64_t *start_list,
1145                                            uint64_t *length_list)
1146 {
1147     uint8_t *buf;
1148     uint16_t tmplen;
1149     uint16_t t;
1150     size_t name_len = strlen(name);
1151 
1152     trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1153     assert(name_len < 256);
1154     buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1155     buf[0] = postcopy_ram_discard_version;
1156     buf[1] = name_len;
1157     memcpy(buf + 2, name, name_len);
1158     tmplen = 2 + name_len;
1159     buf[tmplen++] = '\0';
1160 
1161     for (t = 0; t < len; t++) {
1162         stq_be_p(buf + tmplen, start_list[t]);
1163         tmplen += 8;
1164         stq_be_p(buf + tmplen, length_list[t]);
1165         tmplen += 8;
1166     }
1167     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1168     g_free(buf);
1169 }
1170 
1171 /* Get the destination into a state where it can receive postcopy data. */
1172 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1173 {
1174     trace_savevm_send_postcopy_listen();
1175     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1176 }
1177 
1178 /* Kick the destination into running */
1179 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1180 {
1181     trace_savevm_send_postcopy_run();
1182     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1183 }
1184 
1185 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1186 {
1187     trace_savevm_send_postcopy_resume();
1188     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1189 }
1190 
1191 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1192 {
1193     size_t len;
1194     char buf[256];
1195 
1196     trace_savevm_send_recv_bitmap(block_name);
1197 
1198     buf[0] = len = strlen(block_name);
1199     memcpy(buf + 1, block_name, len);
1200 
1201     qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1202 }
1203 
1204 bool qemu_savevm_state_blocked(Error **errp)
1205 {
1206     SaveStateEntry *se;
1207 
1208     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1209         if (se->vmsd && se->vmsd->unmigratable) {
1210             error_setg(errp, "State blocked by non-migratable device '%s'",
1211                        se->idstr);
1212             return true;
1213         }
1214     }
1215     return false;
1216 }
1217 
1218 void qemu_savevm_non_migratable_list(strList **reasons)
1219 {
1220     SaveStateEntry *se;
1221 
1222     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1223         if (se->vmsd && se->vmsd->unmigratable) {
1224             QAPI_LIST_PREPEND(*reasons,
1225                               g_strdup_printf("non-migratable device: %s",
1226                                               se->idstr));
1227         }
1228     }
1229 }
1230 
1231 void qemu_savevm_state_header(QEMUFile *f)
1232 {
1233     MigrationState *s = migrate_get_current();
1234 
1235     s->vmdesc = json_writer_new(false);
1236 
1237     trace_savevm_state_header();
1238     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1239     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1240 
1241     if (s->send_configuration) {
1242         qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1243 
1244         /*
1245          * This starts the main json object and is paired with the
1246          * json_writer_end_object in
1247          * qemu_savevm_state_complete_precopy_non_iterable
1248          */
1249         json_writer_start_object(s->vmdesc, NULL);
1250 
1251         json_writer_start_object(s->vmdesc, "configuration");
1252         vmstate_save_state(f, &vmstate_configuration, &savevm_state, s->vmdesc);
1253         json_writer_end_object(s->vmdesc);
1254     }
1255 }
1256 
1257 bool qemu_savevm_state_guest_unplug_pending(void)
1258 {
1259     SaveStateEntry *se;
1260 
1261     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1262         if (se->vmsd && se->vmsd->dev_unplug_pending &&
1263             se->vmsd->dev_unplug_pending(se->opaque)) {
1264             return true;
1265         }
1266     }
1267 
1268     return false;
1269 }
1270 
1271 int qemu_savevm_state_prepare(Error **errp)
1272 {
1273     SaveStateEntry *se;
1274     int ret;
1275 
1276     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1277         if (!se->ops || !se->ops->save_prepare) {
1278             continue;
1279         }
1280         if (se->ops->is_active) {
1281             if (!se->ops->is_active(se->opaque)) {
1282                 continue;
1283             }
1284         }
1285 
1286         ret = se->ops->save_prepare(se->opaque, errp);
1287         if (ret < 0) {
1288             return ret;
1289         }
1290     }
1291 
1292     return 0;
1293 }
1294 
1295 int qemu_savevm_state_setup(QEMUFile *f, Error **errp)
1296 {
1297     ERRP_GUARD();
1298     MigrationState *ms = migrate_get_current();
1299     SaveStateEntry *se;
1300     int ret = 0;
1301 
1302     json_writer_int64(ms->vmdesc, "page_size", qemu_target_page_size());
1303     json_writer_start_array(ms->vmdesc, "devices");
1304 
1305     trace_savevm_state_setup();
1306     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1307         if (se->vmsd && se->vmsd->early_setup) {
1308             ret = vmstate_save(f, se, ms->vmdesc, errp);
1309             if (ret) {
1310                 migrate_set_error(ms, *errp);
1311                 qemu_file_set_error(f, ret);
1312                 break;
1313             }
1314             continue;
1315         }
1316 
1317         if (!se->ops || !se->ops->save_setup) {
1318             continue;
1319         }
1320         if (se->ops->is_active) {
1321             if (!se->ops->is_active(se->opaque)) {
1322                 continue;
1323             }
1324         }
1325         save_section_header(f, se, QEMU_VM_SECTION_START);
1326 
1327         ret = se->ops->save_setup(f, se->opaque, errp);
1328         save_section_footer(f, se);
1329         if (ret < 0) {
1330             qemu_file_set_error(f, ret);
1331             break;
1332         }
1333     }
1334 
1335     if (ret) {
1336         return ret;
1337     }
1338 
1339     /* TODO: Should we check that errp is set in case of failure ? */
1340     return precopy_notify(PRECOPY_NOTIFY_SETUP, errp);
1341 }
1342 
1343 int qemu_savevm_state_resume_prepare(MigrationState *s)
1344 {
1345     SaveStateEntry *se;
1346     int ret;
1347 
1348     trace_savevm_state_resume_prepare();
1349 
1350     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1351         if (!se->ops || !se->ops->resume_prepare) {
1352             continue;
1353         }
1354         if (se->ops->is_active) {
1355             if (!se->ops->is_active(se->opaque)) {
1356                 continue;
1357             }
1358         }
1359         ret = se->ops->resume_prepare(s, se->opaque);
1360         if (ret < 0) {
1361             return ret;
1362         }
1363     }
1364 
1365     return 0;
1366 }
1367 
1368 /*
1369  * this function has three return values:
1370  *   negative: there was one error, and we have -errno.
1371  *   0 : We haven't finished, caller have to go again
1372  *   1 : We have finished, we can go to complete phase
1373  */
1374 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1375 {
1376     SaveStateEntry *se;
1377     bool all_finished = true;
1378     int ret;
1379 
1380     trace_savevm_state_iterate();
1381     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1382         if (!se->ops || !se->ops->save_live_iterate) {
1383             continue;
1384         }
1385         if (se->ops->is_active &&
1386             !se->ops->is_active(se->opaque)) {
1387             continue;
1388         }
1389         if (se->ops->is_active_iterate &&
1390             !se->ops->is_active_iterate(se->opaque)) {
1391             continue;
1392         }
1393         /*
1394          * In the postcopy phase, any device that doesn't know how to
1395          * do postcopy should have saved it's state in the _complete
1396          * call that's already run, it might get confused if we call
1397          * iterate afterwards.
1398          */
1399         if (postcopy &&
1400             !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1401             continue;
1402         }
1403         if (migration_rate_exceeded(f)) {
1404             return 0;
1405         }
1406         trace_savevm_section_start(se->idstr, se->section_id);
1407 
1408         save_section_header(f, se, QEMU_VM_SECTION_PART);
1409 
1410         ret = se->ops->save_live_iterate(f, se->opaque);
1411         trace_savevm_section_end(se->idstr, se->section_id, ret);
1412         save_section_footer(f, se);
1413 
1414         if (ret < 0) {
1415             error_report("failed to save SaveStateEntry with id(name): "
1416                          "%d(%s): %d",
1417                          se->section_id, se->idstr, ret);
1418             qemu_file_set_error(f, ret);
1419             return ret;
1420         } else if (!ret) {
1421             all_finished = false;
1422         }
1423     }
1424     return all_finished;
1425 }
1426 
1427 static bool should_send_vmdesc(void)
1428 {
1429     MachineState *machine = MACHINE(qdev_get_machine());
1430     bool in_postcopy = migration_in_postcopy();
1431     return !machine->suppress_vmdesc && !in_postcopy;
1432 }
1433 
1434 /*
1435  * Calls the save_live_complete_postcopy methods
1436  * causing the last few pages to be sent immediately and doing any associated
1437  * cleanup.
1438  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1439  * all the other devices, but that happens at the point we switch to postcopy.
1440  */
1441 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1442 {
1443     SaveStateEntry *se;
1444     int ret;
1445 
1446     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1447         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1448             continue;
1449         }
1450         if (se->ops->is_active) {
1451             if (!se->ops->is_active(se->opaque)) {
1452                 continue;
1453             }
1454         }
1455         trace_savevm_section_start(se->idstr, se->section_id);
1456         /* Section type */
1457         qemu_put_byte(f, QEMU_VM_SECTION_END);
1458         qemu_put_be32(f, se->section_id);
1459 
1460         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1461         trace_savevm_section_end(se->idstr, se->section_id, ret);
1462         save_section_footer(f, se);
1463         if (ret < 0) {
1464             qemu_file_set_error(f, ret);
1465             return;
1466         }
1467     }
1468 
1469     qemu_put_byte(f, QEMU_VM_EOF);
1470     qemu_fflush(f);
1471 }
1472 
1473 static
1474 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1475 {
1476     int64_t start_ts_each, end_ts_each;
1477     SaveStateEntry *se;
1478     int ret;
1479 
1480     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1481         if (!se->ops ||
1482             (in_postcopy && se->ops->has_postcopy &&
1483              se->ops->has_postcopy(se->opaque)) ||
1484             !se->ops->save_live_complete_precopy) {
1485             continue;
1486         }
1487 
1488         if (se->ops->is_active) {
1489             if (!se->ops->is_active(se->opaque)) {
1490                 continue;
1491             }
1492         }
1493 
1494         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1495         trace_savevm_section_start(se->idstr, se->section_id);
1496 
1497         save_section_header(f, se, QEMU_VM_SECTION_END);
1498 
1499         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1500         trace_savevm_section_end(se->idstr, se->section_id, ret);
1501         save_section_footer(f, se);
1502         if (ret < 0) {
1503             qemu_file_set_error(f, ret);
1504             return -1;
1505         }
1506         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1507         trace_vmstate_downtime_save("iterable", se->idstr, se->instance_id,
1508                                     end_ts_each - start_ts_each);
1509     }
1510 
1511     trace_vmstate_downtime_checkpoint("src-iterable-saved");
1512 
1513     return 0;
1514 }
1515 
1516 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1517                                                     bool in_postcopy,
1518                                                     bool inactivate_disks)
1519 {
1520     MigrationState *ms = migrate_get_current();
1521     int64_t start_ts_each, end_ts_each;
1522     JSONWriter *vmdesc = ms->vmdesc;
1523     int vmdesc_len;
1524     SaveStateEntry *se;
1525     Error *local_err = NULL;
1526     int ret;
1527 
1528     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1529         if (se->vmsd && se->vmsd->early_setup) {
1530             /* Already saved during qemu_savevm_state_setup(). */
1531             continue;
1532         }
1533 
1534         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1535 
1536         ret = vmstate_save(f, se, vmdesc, &local_err);
1537         if (ret) {
1538             migrate_set_error(ms, local_err);
1539             error_report_err(local_err);
1540             qemu_file_set_error(f, ret);
1541             return ret;
1542         }
1543 
1544         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1545         trace_vmstate_downtime_save("non-iterable", se->idstr, se->instance_id,
1546                                     end_ts_each - start_ts_each);
1547     }
1548 
1549     if (inactivate_disks) {
1550         /* Inactivate before sending QEMU_VM_EOF so that the
1551          * bdrv_activate_all() on the other end won't fail. */
1552         ret = bdrv_inactivate_all();
1553         if (ret) {
1554             error_setg(&local_err, "%s: bdrv_inactivate_all() failed (%d)",
1555                        __func__, ret);
1556             migrate_set_error(ms, local_err);
1557             error_report_err(local_err);
1558             qemu_file_set_error(f, ret);
1559             return ret;
1560         }
1561     }
1562     if (!in_postcopy) {
1563         /* Postcopy stream will still be going */
1564         qemu_put_byte(f, QEMU_VM_EOF);
1565     }
1566 
1567     json_writer_end_array(vmdesc);
1568     json_writer_end_object(vmdesc);
1569     vmdesc_len = strlen(json_writer_get(vmdesc));
1570 
1571     if (should_send_vmdesc()) {
1572         qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1573         qemu_put_be32(f, vmdesc_len);
1574         qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1575     }
1576 
1577     /* Free it now to detect any inconsistencies. */
1578     json_writer_free(vmdesc);
1579     ms->vmdesc = NULL;
1580 
1581     trace_vmstate_downtime_checkpoint("src-non-iterable-saved");
1582 
1583     return 0;
1584 }
1585 
1586 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1587                                        bool inactivate_disks)
1588 {
1589     int ret;
1590     Error *local_err = NULL;
1591     bool in_postcopy = migration_in_postcopy();
1592 
1593     if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
1594         error_report_err(local_err);
1595     }
1596 
1597     trace_savevm_state_complete_precopy();
1598 
1599     cpu_synchronize_all_states();
1600 
1601     if (!in_postcopy || iterable_only) {
1602         ret = qemu_savevm_state_complete_precopy_iterable(f, in_postcopy);
1603         if (ret) {
1604             return ret;
1605         }
1606     }
1607 
1608     if (iterable_only) {
1609         goto flush;
1610     }
1611 
1612     ret = qemu_savevm_state_complete_precopy_non_iterable(f, in_postcopy,
1613                                                           inactivate_disks);
1614     if (ret) {
1615         return ret;
1616     }
1617 
1618 flush:
1619     return qemu_fflush(f);
1620 }
1621 
1622 /* Give an estimate of the amount left to be transferred,
1623  * the result is split into the amount for units that can and
1624  * for units that can't do postcopy.
1625  */
1626 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1627                                         uint64_t *can_postcopy)
1628 {
1629     SaveStateEntry *se;
1630 
1631     *must_precopy = 0;
1632     *can_postcopy = 0;
1633 
1634     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1635         if (!se->ops || !se->ops->state_pending_estimate) {
1636             continue;
1637         }
1638         if (se->ops->is_active) {
1639             if (!se->ops->is_active(se->opaque)) {
1640                 continue;
1641             }
1642         }
1643         se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1644     }
1645 }
1646 
1647 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1648                                      uint64_t *can_postcopy)
1649 {
1650     SaveStateEntry *se;
1651 
1652     *must_precopy = 0;
1653     *can_postcopy = 0;
1654 
1655     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1656         if (!se->ops || !se->ops->state_pending_exact) {
1657             continue;
1658         }
1659         if (se->ops->is_active) {
1660             if (!se->ops->is_active(se->opaque)) {
1661                 continue;
1662             }
1663         }
1664         se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1665     }
1666 }
1667 
1668 void qemu_savevm_state_cleanup(void)
1669 {
1670     SaveStateEntry *se;
1671     Error *local_err = NULL;
1672 
1673     if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1674         error_report_err(local_err);
1675     }
1676 
1677     trace_savevm_state_cleanup();
1678     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1679         if (se->ops && se->ops->save_cleanup) {
1680             se->ops->save_cleanup(se->opaque);
1681         }
1682     }
1683 }
1684 
1685 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1686 {
1687     int ret;
1688     MigrationState *ms = migrate_get_current();
1689     MigrationStatus status;
1690 
1691     if (migration_is_running()) {
1692         error_setg(errp, "There's a migration process in progress");
1693         return -EINVAL;
1694     }
1695 
1696     ret = migrate_init(ms, errp);
1697     if (ret) {
1698         return ret;
1699     }
1700     ms->to_dst_file = f;
1701 
1702     qemu_savevm_state_header(f);
1703     ret = qemu_savevm_state_setup(f, errp);
1704     if (ret) {
1705         goto cleanup;
1706     }
1707 
1708     while (qemu_file_get_error(f) == 0) {
1709         if (qemu_savevm_state_iterate(f, false) > 0) {
1710             break;
1711         }
1712     }
1713 
1714     ret = qemu_file_get_error(f);
1715     if (ret == 0) {
1716         qemu_savevm_state_complete_precopy(f, false, false);
1717         ret = qemu_file_get_error(f);
1718     }
1719     if (ret != 0) {
1720         error_setg_errno(errp, -ret, "Error while writing VM state");
1721     }
1722 cleanup:
1723     qemu_savevm_state_cleanup();
1724 
1725     if (ret != 0) {
1726         status = MIGRATION_STATUS_FAILED;
1727     } else {
1728         status = MIGRATION_STATUS_COMPLETED;
1729     }
1730     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1731 
1732     /* f is outer parameter, it should not stay in global migration state after
1733      * this function finished */
1734     ms->to_dst_file = NULL;
1735 
1736     return ret;
1737 }
1738 
1739 void qemu_savevm_live_state(QEMUFile *f)
1740 {
1741     /* save QEMU_VM_SECTION_END section */
1742     qemu_savevm_state_complete_precopy(f, true, false);
1743     qemu_put_byte(f, QEMU_VM_EOF);
1744 }
1745 
1746 int qemu_save_device_state(QEMUFile *f)
1747 {
1748     MigrationState *ms = migrate_get_current();
1749     Error *local_err = NULL;
1750     SaveStateEntry *se;
1751 
1752     if (!migration_in_colo_state()) {
1753         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1754         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1755     }
1756     cpu_synchronize_all_states();
1757 
1758     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1759         int ret;
1760 
1761         if (se->is_ram) {
1762             continue;
1763         }
1764         ret = vmstate_save(f, se, NULL, &local_err);
1765         if (ret) {
1766             migrate_set_error(ms, local_err);
1767             error_report_err(local_err);
1768             return ret;
1769         }
1770     }
1771 
1772     qemu_put_byte(f, QEMU_VM_EOF);
1773 
1774     return qemu_file_get_error(f);
1775 }
1776 
1777 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1778 {
1779     SaveStateEntry *se;
1780 
1781     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1782         if (!strcmp(se->idstr, idstr) &&
1783             (instance_id == se->instance_id ||
1784              instance_id == se->alias_id))
1785             return se;
1786         /* Migrating from an older version? */
1787         if (strstr(se->idstr, idstr) && se->compat) {
1788             if (!strcmp(se->compat->idstr, idstr) &&
1789                 (instance_id == se->compat->instance_id ||
1790                  instance_id == se->alias_id))
1791                 return se;
1792         }
1793     }
1794     return NULL;
1795 }
1796 
1797 enum LoadVMExitCodes {
1798     /* Allow a command to quit all layers of nested loadvm loops */
1799     LOADVM_QUIT     =  1,
1800 };
1801 
1802 /* ------ incoming postcopy messages ------ */
1803 /* 'advise' arrives before any transfers just to tell us that a postcopy
1804  * *might* happen - it might be skipped if precopy transferred everything
1805  * quickly.
1806  */
1807 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1808                                          uint16_t len)
1809 {
1810     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1811     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1812     size_t page_size = qemu_target_page_size();
1813     Error *local_err = NULL;
1814 
1815     trace_loadvm_postcopy_handle_advise();
1816     if (ps != POSTCOPY_INCOMING_NONE) {
1817         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1818         return -1;
1819     }
1820 
1821     switch (len) {
1822     case 0:
1823         if (migrate_postcopy_ram()) {
1824             error_report("RAM postcopy is enabled but have 0 byte advise");
1825             return -EINVAL;
1826         }
1827         return 0;
1828     case 8 + 8:
1829         if (!migrate_postcopy_ram()) {
1830             error_report("RAM postcopy is disabled but have 16 byte advise");
1831             return -EINVAL;
1832         }
1833         break;
1834     default:
1835         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1836         return -EINVAL;
1837     }
1838 
1839     if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1840         error_report_err(local_err);
1841         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1842         return -1;
1843     }
1844 
1845     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1846     local_pagesize_summary = ram_pagesize_summary();
1847 
1848     if (remote_pagesize_summary != local_pagesize_summary)  {
1849         /*
1850          * This detects two potential causes of mismatch:
1851          *   a) A mismatch in host page sizes
1852          *      Some combinations of mismatch are probably possible but it gets
1853          *      a bit more complicated.  In particular we need to place whole
1854          *      host pages on the dest at once, and we need to ensure that we
1855          *      handle dirtying to make sure we never end up sending part of
1856          *      a hostpage on it's own.
1857          *   b) The use of different huge page sizes on source/destination
1858          *      a more fine grain test is performed during RAM block migration
1859          *      but this test here causes a nice early clear failure, and
1860          *      also fails when passed to an older qemu that doesn't
1861          *      do huge pages.
1862          */
1863         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1864                                                              " d=%" PRIx64 ")",
1865                      remote_pagesize_summary, local_pagesize_summary);
1866         return -1;
1867     }
1868 
1869     remote_tps = qemu_get_be64(mis->from_src_file);
1870     if (remote_tps != page_size) {
1871         /*
1872          * Again, some differences could be dealt with, but for now keep it
1873          * simple.
1874          */
1875         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1876                      (int)remote_tps, page_size);
1877         return -1;
1878     }
1879 
1880     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1881         error_report_err(local_err);
1882         return -1;
1883     }
1884 
1885     if (ram_postcopy_incoming_init(mis)) {
1886         return -1;
1887     }
1888 
1889     return 0;
1890 }
1891 
1892 /* After postcopy we will be told to throw some pages away since they're
1893  * dirty and will have to be demand fetched.  Must happen before CPU is
1894  * started.
1895  * There can be 0..many of these messages, each encoding multiple pages.
1896  */
1897 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1898                                               uint16_t len)
1899 {
1900     int tmp;
1901     char ramid[256];
1902     PostcopyState ps = postcopy_state_get();
1903 
1904     trace_loadvm_postcopy_ram_handle_discard();
1905 
1906     switch (ps) {
1907     case POSTCOPY_INCOMING_ADVISE:
1908         /* 1st discard */
1909         tmp = postcopy_ram_prepare_discard(mis);
1910         if (tmp) {
1911             return tmp;
1912         }
1913         break;
1914 
1915     case POSTCOPY_INCOMING_DISCARD:
1916         /* Expected state */
1917         break;
1918 
1919     default:
1920         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1921                      ps);
1922         return -1;
1923     }
1924     /* We're expecting a
1925      *    Version (0)
1926      *    a RAM ID string (length byte, name, 0 term)
1927      *    then at least 1 16 byte chunk
1928     */
1929     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1930         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1931         return -1;
1932     }
1933 
1934     tmp = qemu_get_byte(mis->from_src_file);
1935     if (tmp != postcopy_ram_discard_version) {
1936         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1937         return -1;
1938     }
1939 
1940     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1941         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1942         return -1;
1943     }
1944     tmp = qemu_get_byte(mis->from_src_file);
1945     if (tmp != 0) {
1946         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1947         return -1;
1948     }
1949 
1950     len -= 3 + strlen(ramid);
1951     if (len % 16) {
1952         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1953         return -1;
1954     }
1955     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1956     while (len) {
1957         uint64_t start_addr, block_length;
1958         start_addr = qemu_get_be64(mis->from_src_file);
1959         block_length = qemu_get_be64(mis->from_src_file);
1960 
1961         len -= 16;
1962         int ret = ram_discard_range(ramid, start_addr, block_length);
1963         if (ret) {
1964             return ret;
1965         }
1966     }
1967     trace_loadvm_postcopy_ram_handle_discard_end();
1968 
1969     return 0;
1970 }
1971 
1972 /*
1973  * Triggered by a postcopy_listen command; this thread takes over reading
1974  * the input stream, leaving the main thread free to carry on loading the rest
1975  * of the device state (from RAM).
1976  * (TODO:This could do with being in a postcopy file - but there again it's
1977  * just another input loop, not that postcopy specific)
1978  */
1979 static void *postcopy_ram_listen_thread(void *opaque)
1980 {
1981     MigrationIncomingState *mis = migration_incoming_get_current();
1982     QEMUFile *f = mis->from_src_file;
1983     int load_res;
1984     MigrationState *migr = migrate_get_current();
1985 
1986     object_ref(OBJECT(migr));
1987 
1988     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1989                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
1990     qemu_sem_post(&mis->thread_sync_sem);
1991     trace_postcopy_ram_listen_thread_start();
1992 
1993     rcu_register_thread();
1994     /*
1995      * Because we're a thread and not a coroutine we can't yield
1996      * in qemu_file, and thus we must be blocking now.
1997      */
1998     qemu_file_set_blocking(f, true);
1999     load_res = qemu_loadvm_state_main(f, mis);
2000 
2001     /*
2002      * This is tricky, but, mis->from_src_file can change after it
2003      * returns, when postcopy recovery happened. In the future, we may
2004      * want a wrapper for the QEMUFile handle.
2005      */
2006     f = mis->from_src_file;
2007 
2008     /* And non-blocking again so we don't block in any cleanup */
2009     qemu_file_set_blocking(f, false);
2010 
2011     trace_postcopy_ram_listen_thread_exit();
2012     if (load_res < 0) {
2013         qemu_file_set_error(f, load_res);
2014         dirty_bitmap_mig_cancel_incoming();
2015         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2016             !migrate_postcopy_ram() && migrate_dirty_bitmaps())
2017         {
2018             error_report("%s: loadvm failed during postcopy: %d. All states "
2019                          "are migrated except dirty bitmaps. Some dirty "
2020                          "bitmaps may be lost, and present migrated dirty "
2021                          "bitmaps are correctly migrated and valid.",
2022                          __func__, load_res);
2023             load_res = 0; /* prevent further exit() */
2024         } else {
2025             error_report("%s: loadvm failed: %d", __func__, load_res);
2026             migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2027                                            MIGRATION_STATUS_FAILED);
2028         }
2029     }
2030     if (load_res >= 0) {
2031         /*
2032          * This looks good, but it's possible that the device loading in the
2033          * main thread hasn't finished yet, and so we might not be in 'RUN'
2034          * state yet; wait for the end of the main thread.
2035          */
2036         qemu_event_wait(&mis->main_thread_load_event);
2037     }
2038     postcopy_ram_incoming_cleanup(mis);
2039 
2040     if (load_res < 0) {
2041         /*
2042          * If something went wrong then we have a bad state so exit;
2043          * depending how far we got it might be possible at this point
2044          * to leave the guest running and fire MCEs for pages that never
2045          * arrived as a desperate recovery step.
2046          */
2047         rcu_unregister_thread();
2048         exit(EXIT_FAILURE);
2049     }
2050 
2051     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2052                                    MIGRATION_STATUS_COMPLETED);
2053     /*
2054      * If everything has worked fine, then the main thread has waited
2055      * for us to start, and we're the last use of the mis.
2056      * (If something broke then qemu will have to exit anyway since it's
2057      * got a bad migration state).
2058      */
2059     migration_incoming_state_destroy();
2060     qemu_loadvm_state_cleanup();
2061 
2062     rcu_unregister_thread();
2063     mis->have_listen_thread = false;
2064     postcopy_state_set(POSTCOPY_INCOMING_END);
2065 
2066     object_unref(OBJECT(migr));
2067 
2068     return NULL;
2069 }
2070 
2071 /* After this message we must be able to immediately receive postcopy data */
2072 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2073 {
2074     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2075     Error *local_err = NULL;
2076 
2077     trace_loadvm_postcopy_handle_listen("enter");
2078 
2079     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2080         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2081         return -1;
2082     }
2083     if (ps == POSTCOPY_INCOMING_ADVISE) {
2084         /*
2085          * A rare case, we entered listen without having to do any discards,
2086          * so do the setup that's normally done at the time of the 1st discard.
2087          */
2088         if (migrate_postcopy_ram()) {
2089             postcopy_ram_prepare_discard(mis);
2090         }
2091     }
2092 
2093     trace_loadvm_postcopy_handle_listen("after discard");
2094 
2095     /*
2096      * Sensitise RAM - can now generate requests for blocks that don't exist
2097      * However, at this point the CPU shouldn't be running, and the IO
2098      * shouldn't be doing anything yet so don't actually expect requests
2099      */
2100     if (migrate_postcopy_ram()) {
2101         if (postcopy_ram_incoming_setup(mis)) {
2102             postcopy_ram_incoming_cleanup(mis);
2103             return -1;
2104         }
2105     }
2106 
2107     trace_loadvm_postcopy_handle_listen("after uffd");
2108 
2109     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2110         error_report_err(local_err);
2111         return -1;
2112     }
2113 
2114     mis->have_listen_thread = true;
2115     postcopy_thread_create(mis, &mis->listen_thread,
2116                            MIGRATION_THREAD_DST_LISTEN,
2117                            postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2118     trace_loadvm_postcopy_handle_listen("return");
2119 
2120     return 0;
2121 }
2122 
2123 static void loadvm_postcopy_handle_run_bh(void *opaque)
2124 {
2125     Error *local_err = NULL;
2126     MigrationIncomingState *mis = opaque;
2127 
2128     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-enter");
2129 
2130     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2131      * in migration.c
2132      */
2133     cpu_synchronize_all_post_init();
2134 
2135     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cpu-synced");
2136 
2137     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2138 
2139     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-announced");
2140 
2141     /* Make sure all file formats throw away their mutable metadata.
2142      * If we get an error here, just don't restart the VM yet. */
2143     bdrv_activate_all(&local_err);
2144     if (local_err) {
2145         error_report_err(local_err);
2146         local_err = NULL;
2147         autostart = false;
2148     }
2149 
2150     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cache-invalidated");
2151 
2152     dirty_bitmap_mig_before_vm_start();
2153 
2154     if (autostart) {
2155         /* Hold onto your hats, starting the CPU */
2156         vm_start();
2157     } else {
2158         /* leave it paused and let management decide when to start the CPU */
2159         runstate_set(RUN_STATE_PAUSED);
2160     }
2161 
2162     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-vm-started");
2163 }
2164 
2165 /* After all discards we can start running and asking for pages */
2166 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2167 {
2168     PostcopyState ps = postcopy_state_get();
2169 
2170     trace_loadvm_postcopy_handle_run();
2171     if (ps != POSTCOPY_INCOMING_LISTENING) {
2172         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2173         return -1;
2174     }
2175 
2176     postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2177     migration_bh_schedule(loadvm_postcopy_handle_run_bh, mis);
2178 
2179     /* We need to finish reading the stream from the package
2180      * and also stop reading anything more from the stream that loaded the
2181      * package (since it's now being read by the listener thread).
2182      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2183      */
2184     return LOADVM_QUIT;
2185 }
2186 
2187 /* We must be with page_request_mutex held */
2188 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2189                                        gpointer data)
2190 {
2191     MigrationIncomingState *mis = data;
2192     void *host_addr = (void *) key;
2193     ram_addr_t rb_offset;
2194     RAMBlock *rb;
2195     int ret;
2196 
2197     rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2198     if (!rb) {
2199         /*
2200          * This should _never_ happen.  However be nice for a migrating VM to
2201          * not crash/assert.  Post an error (note: intended to not use *_once
2202          * because we do want to see all the illegal addresses; and this can
2203          * never be triggered by the guest so we're safe) and move on next.
2204          */
2205         error_report("%s: illegal host addr %p", __func__, host_addr);
2206         /* Try the next entry */
2207         return FALSE;
2208     }
2209 
2210     ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2211     if (ret) {
2212         /* Please refer to above comment. */
2213         error_report("%s: send rp message failed for addr %p",
2214                      __func__, host_addr);
2215         return FALSE;
2216     }
2217 
2218     trace_postcopy_page_req_sync(host_addr);
2219 
2220     return FALSE;
2221 }
2222 
2223 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2224 {
2225     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2226         g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2227     }
2228 }
2229 
2230 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2231 {
2232     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2233         error_report("%s: illegal resume received", __func__);
2234         /* Don't fail the load, only for this. */
2235         return 0;
2236     }
2237 
2238     /*
2239      * Reset the last_rb before we resend any page req to source again, since
2240      * the source should have it reset already.
2241      */
2242     mis->last_rb = NULL;
2243 
2244     /*
2245      * This means source VM is ready to resume the postcopy migration.
2246      */
2247     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2248                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2249 
2250     trace_loadvm_postcopy_handle_resume();
2251 
2252     /* Tell source that "we are ready" */
2253     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2254 
2255     /*
2256      * After a postcopy recovery, the source should have lost the postcopy
2257      * queue, or potentially the requested pages could have been lost during
2258      * the network down phase.  Let's re-sync with the source VM by re-sending
2259      * all the pending pages that we eagerly need, so these threads won't get
2260      * blocked too long due to the recovery.
2261      *
2262      * Without this procedure, the faulted destination VM threads (waiting for
2263      * page requests right before the postcopy is interrupted) can keep hanging
2264      * until the pages are sent by the source during the background copying of
2265      * pages, or another thread faulted on the same address accidentally.
2266      */
2267     migrate_send_rp_req_pages_pending(mis);
2268 
2269     /*
2270      * It's time to switch state and release the fault thread to continue
2271      * service page faults.  Note that this should be explicitly after the
2272      * above call to migrate_send_rp_req_pages_pending().  In short:
2273      * migrate_send_rp_message_req_pages() is not thread safe, yet.
2274      */
2275     qemu_sem_post(&mis->postcopy_pause_sem_fault);
2276 
2277     if (migrate_postcopy_preempt()) {
2278         /*
2279          * The preempt channel will be created in async manner, now let's
2280          * wait for it and make sure it's created.
2281          */
2282         qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2283         assert(mis->postcopy_qemufile_dst);
2284         /* Kick the fast ram load thread too */
2285         qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2286     }
2287 
2288     return 0;
2289 }
2290 
2291 /**
2292  * Immediately following this command is a blob of data containing an embedded
2293  * chunk of migration stream; read it and load it.
2294  *
2295  * @mis: Incoming state
2296  * @length: Length of packaged data to read
2297  *
2298  * Returns: Negative values on error
2299  *
2300  */
2301 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2302 {
2303     int ret;
2304     size_t length;
2305     QIOChannelBuffer *bioc;
2306 
2307     length = qemu_get_be32(mis->from_src_file);
2308     trace_loadvm_handle_cmd_packaged(length);
2309 
2310     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2311         error_report("Unreasonably large packaged state: %zu", length);
2312         return -1;
2313     }
2314 
2315     bioc = qio_channel_buffer_new(length);
2316     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2317     ret = qemu_get_buffer(mis->from_src_file,
2318                           bioc->data,
2319                           length);
2320     if (ret != length) {
2321         object_unref(OBJECT(bioc));
2322         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2323                      ret, length);
2324         return (ret < 0) ? ret : -EAGAIN;
2325     }
2326     bioc->usage += length;
2327     trace_loadvm_handle_cmd_packaged_received(ret);
2328 
2329     QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2330 
2331     /*
2332      * Before loading the guest states, ensure that the preempt channel has
2333      * been ready to use, as some of the states (e.g. via virtio_load) might
2334      * trigger page faults that will be handled through the preempt channel.
2335      * So yield to the main thread in the case that the channel create event
2336      * hasn't been dispatched.
2337      *
2338      * TODO: if we can move migration loadvm out of main thread, then we
2339      * won't block main thread from polling the accept() fds.  We can drop
2340      * this as a whole when that is done.
2341      */
2342     do {
2343         if (!migrate_postcopy_preempt() || !qemu_in_coroutine() ||
2344             mis->postcopy_qemufile_dst) {
2345             break;
2346         }
2347 
2348         aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
2349         qemu_coroutine_yield();
2350     } while (1);
2351 
2352     ret = qemu_loadvm_state_main(packf, mis);
2353     trace_loadvm_handle_cmd_packaged_main(ret);
2354     qemu_fclose(packf);
2355     object_unref(OBJECT(bioc));
2356 
2357     return ret;
2358 }
2359 
2360 /*
2361  * Handle request that source requests for recved_bitmap on
2362  * destination. Payload format:
2363  *
2364  * len (1 byte) + ramblock_name (<255 bytes)
2365  */
2366 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2367                                      uint16_t len)
2368 {
2369     QEMUFile *file = mis->from_src_file;
2370     RAMBlock *rb;
2371     char block_name[256];
2372     size_t cnt;
2373 
2374     cnt = qemu_get_counted_string(file, block_name);
2375     if (!cnt) {
2376         error_report("%s: failed to read block name", __func__);
2377         return -EINVAL;
2378     }
2379 
2380     /* Validate before using the data */
2381     if (qemu_file_get_error(file)) {
2382         return qemu_file_get_error(file);
2383     }
2384 
2385     if (len != cnt + 1) {
2386         error_report("%s: invalid payload length (%d)", __func__, len);
2387         return -EINVAL;
2388     }
2389 
2390     rb = qemu_ram_block_by_name(block_name);
2391     if (!rb) {
2392         error_report("%s: block '%s' not found", __func__, block_name);
2393         return -EINVAL;
2394     }
2395 
2396     migrate_send_rp_recv_bitmap(mis, block_name);
2397 
2398     trace_loadvm_handle_recv_bitmap(block_name);
2399 
2400     return 0;
2401 }
2402 
2403 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2404 {
2405     int ret = migration_incoming_enable_colo();
2406 
2407     if (!ret) {
2408         ret = colo_init_ram_cache();
2409         if (ret) {
2410             migration_incoming_disable_colo();
2411         }
2412     }
2413     return ret;
2414 }
2415 
2416 /*
2417  * Process an incoming 'QEMU_VM_COMMAND'
2418  * 0           just a normal return
2419  * LOADVM_QUIT All good, but exit the loop
2420  * <0          Error
2421  */
2422 static int loadvm_process_command(QEMUFile *f)
2423 {
2424     MigrationIncomingState *mis = migration_incoming_get_current();
2425     uint16_t cmd;
2426     uint16_t len;
2427     uint32_t tmp32;
2428 
2429     cmd = qemu_get_be16(f);
2430     len = qemu_get_be16(f);
2431 
2432     /* Check validity before continue processing of cmds */
2433     if (qemu_file_get_error(f)) {
2434         return qemu_file_get_error(f);
2435     }
2436 
2437     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2438         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2439         return -EINVAL;
2440     }
2441 
2442     trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2443 
2444     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2445         error_report("%s received with bad length - expecting %zu, got %d",
2446                      mig_cmd_args[cmd].name,
2447                      (size_t)mig_cmd_args[cmd].len, len);
2448         return -ERANGE;
2449     }
2450 
2451     switch (cmd) {
2452     case MIG_CMD_OPEN_RETURN_PATH:
2453         if (mis->to_src_file) {
2454             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2455             /* Not really a problem, so don't give up */
2456             return 0;
2457         }
2458         mis->to_src_file = qemu_file_get_return_path(f);
2459         if (!mis->to_src_file) {
2460             error_report("CMD_OPEN_RETURN_PATH failed");
2461             return -1;
2462         }
2463 
2464         /*
2465          * Switchover ack is enabled but no device uses it, so send an ACK to
2466          * source that it's OK to switchover. Do it here, after return path has
2467          * been created.
2468          */
2469         if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2470             int ret = migrate_send_rp_switchover_ack(mis);
2471             if (ret) {
2472                 error_report(
2473                     "Could not send switchover ack RP MSG, err %d (%s)", ret,
2474                     strerror(-ret));
2475                 return ret;
2476             }
2477         }
2478         break;
2479 
2480     case MIG_CMD_PING:
2481         tmp32 = qemu_get_be32(f);
2482         trace_loadvm_process_command_ping(tmp32);
2483         if (!mis->to_src_file) {
2484             error_report("CMD_PING (0x%x) received with no return path",
2485                          tmp32);
2486             return -1;
2487         }
2488         migrate_send_rp_pong(mis, tmp32);
2489         break;
2490 
2491     case MIG_CMD_PACKAGED:
2492         return loadvm_handle_cmd_packaged(mis);
2493 
2494     case MIG_CMD_POSTCOPY_ADVISE:
2495         return loadvm_postcopy_handle_advise(mis, len);
2496 
2497     case MIG_CMD_POSTCOPY_LISTEN:
2498         return loadvm_postcopy_handle_listen(mis);
2499 
2500     case MIG_CMD_POSTCOPY_RUN:
2501         return loadvm_postcopy_handle_run(mis);
2502 
2503     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2504         return loadvm_postcopy_ram_handle_discard(mis, len);
2505 
2506     case MIG_CMD_POSTCOPY_RESUME:
2507         return loadvm_postcopy_handle_resume(mis);
2508 
2509     case MIG_CMD_RECV_BITMAP:
2510         return loadvm_handle_recv_bitmap(mis, len);
2511 
2512     case MIG_CMD_ENABLE_COLO:
2513         return loadvm_process_enable_colo(mis);
2514     }
2515 
2516     return 0;
2517 }
2518 
2519 /*
2520  * Read a footer off the wire and check that it matches the expected section
2521  *
2522  * Returns: true if the footer was good
2523  *          false if there is a problem (and calls error_report to say why)
2524  */
2525 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2526 {
2527     int ret;
2528     uint8_t read_mark;
2529     uint32_t read_section_id;
2530 
2531     if (!migrate_get_current()->send_section_footer) {
2532         /* No footer to check */
2533         return true;
2534     }
2535 
2536     read_mark = qemu_get_byte(f);
2537 
2538     ret = qemu_file_get_error(f);
2539     if (ret) {
2540         error_report("%s: Read section footer failed: %d",
2541                      __func__, ret);
2542         return false;
2543     }
2544 
2545     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2546         error_report("Missing section footer for %s", se->idstr);
2547         return false;
2548     }
2549 
2550     read_section_id = qemu_get_be32(f);
2551     if (read_section_id != se->load_section_id) {
2552         error_report("Mismatched section id in footer for %s -"
2553                      " read 0x%x expected 0x%x",
2554                      se->idstr, read_section_id, se->load_section_id);
2555         return false;
2556     }
2557 
2558     /* All good */
2559     return true;
2560 }
2561 
2562 static int
2563 qemu_loadvm_section_start_full(QEMUFile *f, uint8_t type)
2564 {
2565     bool trace_downtime = (type == QEMU_VM_SECTION_FULL);
2566     uint32_t instance_id, version_id, section_id;
2567     int64_t start_ts, end_ts;
2568     SaveStateEntry *se;
2569     char idstr[256];
2570     int ret;
2571 
2572     /* Read section start */
2573     section_id = qemu_get_be32(f);
2574     if (!qemu_get_counted_string(f, idstr)) {
2575         error_report("Unable to read ID string for section %u",
2576                      section_id);
2577         return -EINVAL;
2578     }
2579     instance_id = qemu_get_be32(f);
2580     version_id = qemu_get_be32(f);
2581 
2582     ret = qemu_file_get_error(f);
2583     if (ret) {
2584         error_report("%s: Failed to read instance/version ID: %d",
2585                      __func__, ret);
2586         return ret;
2587     }
2588 
2589     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2590             instance_id, version_id);
2591     /* Find savevm section */
2592     se = find_se(idstr, instance_id);
2593     if (se == NULL) {
2594         error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2595                      "Make sure that your current VM setup matches your "
2596                      "saved VM setup, including any hotplugged devices",
2597                      idstr, instance_id);
2598         return -EINVAL;
2599     }
2600 
2601     /* Validate version */
2602     if (version_id > se->version_id) {
2603         error_report("savevm: unsupported version %d for '%s' v%d",
2604                      version_id, idstr, se->version_id);
2605         return -EINVAL;
2606     }
2607     se->load_version_id = version_id;
2608     se->load_section_id = section_id;
2609 
2610     /* Validate if it is a device's state */
2611     if (xen_enabled() && se->is_ram) {
2612         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2613         return -EINVAL;
2614     }
2615 
2616     if (trace_downtime) {
2617         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2618     }
2619 
2620     ret = vmstate_load(f, se);
2621     if (ret < 0) {
2622         error_report("error while loading state for instance 0x%"PRIx32" of"
2623                      " device '%s'", instance_id, idstr);
2624         return ret;
2625     }
2626 
2627     if (trace_downtime) {
2628         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2629         trace_vmstate_downtime_load("non-iterable", se->idstr,
2630                                     se->instance_id, end_ts - start_ts);
2631     }
2632 
2633     if (!check_section_footer(f, se)) {
2634         return -EINVAL;
2635     }
2636 
2637     return 0;
2638 }
2639 
2640 static int
2641 qemu_loadvm_section_part_end(QEMUFile *f, uint8_t type)
2642 {
2643     bool trace_downtime = (type == QEMU_VM_SECTION_END);
2644     int64_t start_ts, end_ts;
2645     uint32_t section_id;
2646     SaveStateEntry *se;
2647     int ret;
2648 
2649     section_id = qemu_get_be32(f);
2650 
2651     ret = qemu_file_get_error(f);
2652     if (ret) {
2653         error_report("%s: Failed to read section ID: %d",
2654                      __func__, ret);
2655         return ret;
2656     }
2657 
2658     trace_qemu_loadvm_state_section_partend(section_id);
2659     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2660         if (se->load_section_id == section_id) {
2661             break;
2662         }
2663     }
2664     if (se == NULL) {
2665         error_report("Unknown savevm section %d", section_id);
2666         return -EINVAL;
2667     }
2668 
2669     if (trace_downtime) {
2670         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2671     }
2672 
2673     ret = vmstate_load(f, se);
2674     if (ret < 0) {
2675         error_report("error while loading state section id %d(%s)",
2676                      section_id, se->idstr);
2677         return ret;
2678     }
2679 
2680     if (trace_downtime) {
2681         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2682         trace_vmstate_downtime_load("iterable", se->idstr,
2683                                     se->instance_id, end_ts - start_ts);
2684     }
2685 
2686     if (!check_section_footer(f, se)) {
2687         return -EINVAL;
2688     }
2689 
2690     return 0;
2691 }
2692 
2693 static int qemu_loadvm_state_header(QEMUFile *f)
2694 {
2695     unsigned int v;
2696     int ret;
2697 
2698     v = qemu_get_be32(f);
2699     if (v != QEMU_VM_FILE_MAGIC) {
2700         error_report("Not a migration stream");
2701         return -EINVAL;
2702     }
2703 
2704     v = qemu_get_be32(f);
2705     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2706         error_report("SaveVM v2 format is obsolete and don't work anymore");
2707         return -ENOTSUP;
2708     }
2709     if (v != QEMU_VM_FILE_VERSION) {
2710         error_report("Unsupported migration stream version");
2711         return -ENOTSUP;
2712     }
2713 
2714     if (migrate_get_current()->send_configuration) {
2715         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2716             error_report("Configuration section missing");
2717             return -EINVAL;
2718         }
2719         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2720 
2721         if (ret) {
2722             return ret;
2723         }
2724     }
2725     return 0;
2726 }
2727 
2728 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2729 {
2730     SaveStateEntry *se;
2731 
2732     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2733         if (!se->ops || !se->ops->switchover_ack_needed) {
2734             continue;
2735         }
2736 
2737         if (se->ops->switchover_ack_needed(se->opaque)) {
2738             mis->switchover_ack_pending_num++;
2739         }
2740     }
2741 
2742     trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2743 }
2744 
2745 static int qemu_loadvm_state_setup(QEMUFile *f, Error **errp)
2746 {
2747     ERRP_GUARD();
2748     SaveStateEntry *se;
2749     int ret;
2750 
2751     trace_loadvm_state_setup();
2752     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2753         if (!se->ops || !se->ops->load_setup) {
2754             continue;
2755         }
2756         if (se->ops->is_active) {
2757             if (!se->ops->is_active(se->opaque)) {
2758                 continue;
2759             }
2760         }
2761 
2762         ret = se->ops->load_setup(f, se->opaque, errp);
2763         if (ret < 0) {
2764             error_prepend(errp, "Load state of device %s failed: ",
2765                           se->idstr);
2766             qemu_file_set_error(f, ret);
2767             return ret;
2768         }
2769     }
2770     return 0;
2771 }
2772 
2773 void qemu_loadvm_state_cleanup(void)
2774 {
2775     SaveStateEntry *se;
2776 
2777     trace_loadvm_state_cleanup();
2778     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2779         if (se->ops && se->ops->load_cleanup) {
2780             se->ops->load_cleanup(se->opaque);
2781         }
2782     }
2783 }
2784 
2785 /* Return true if we should continue the migration, or false. */
2786 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2787 {
2788     int i;
2789 
2790     trace_postcopy_pause_incoming();
2791 
2792     assert(migrate_postcopy_ram());
2793 
2794     /*
2795      * Unregister yank with either from/to src would work, since ioc behind it
2796      * is the same
2797      */
2798     migration_ioc_unregister_yank_from_file(mis->from_src_file);
2799 
2800     assert(mis->from_src_file);
2801     qemu_file_shutdown(mis->from_src_file);
2802     qemu_fclose(mis->from_src_file);
2803     mis->from_src_file = NULL;
2804 
2805     assert(mis->to_src_file);
2806     qemu_file_shutdown(mis->to_src_file);
2807     qemu_mutex_lock(&mis->rp_mutex);
2808     qemu_fclose(mis->to_src_file);
2809     mis->to_src_file = NULL;
2810     qemu_mutex_unlock(&mis->rp_mutex);
2811 
2812     /*
2813      * NOTE: this must happen before reset the PostcopyTmpPages below,
2814      * otherwise it's racy to reset those fields when the fast load thread
2815      * can be accessing it in parallel.
2816      */
2817     if (mis->postcopy_qemufile_dst) {
2818         qemu_file_shutdown(mis->postcopy_qemufile_dst);
2819         /* Take the mutex to make sure the fast ram load thread halted */
2820         qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2821         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2822         qemu_fclose(mis->postcopy_qemufile_dst);
2823         mis->postcopy_qemufile_dst = NULL;
2824         qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2825     }
2826 
2827     /* Current state can be either ACTIVE or RECOVER */
2828     migrate_set_state(&mis->state, mis->state,
2829                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2830 
2831     /* Notify the fault thread for the invalidated file handle */
2832     postcopy_fault_thread_notify(mis);
2833 
2834     /*
2835      * If network is interrupted, any temp page we received will be useless
2836      * because we didn't mark them as "received" in receivedmap.  After a
2837      * proper recovery later (which will sync src dirty bitmap with receivedmap
2838      * on dest) these cached small pages will be resent again.
2839      */
2840     for (i = 0; i < mis->postcopy_channels; i++) {
2841         postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2842     }
2843 
2844     error_report("Detected IO failure for postcopy. "
2845                  "Migration paused.");
2846 
2847     do {
2848         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2849     } while (postcopy_is_paused(mis->state));
2850 
2851     trace_postcopy_pause_incoming_continued();
2852 
2853     return true;
2854 }
2855 
2856 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2857 {
2858     uint8_t section_type;
2859     int ret = 0;
2860 
2861 retry:
2862     while (true) {
2863         section_type = qemu_get_byte(f);
2864 
2865         ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2866         if (ret) {
2867             break;
2868         }
2869 
2870         trace_qemu_loadvm_state_section(section_type);
2871         switch (section_type) {
2872         case QEMU_VM_SECTION_START:
2873         case QEMU_VM_SECTION_FULL:
2874             ret = qemu_loadvm_section_start_full(f, section_type);
2875             if (ret < 0) {
2876                 goto out;
2877             }
2878             break;
2879         case QEMU_VM_SECTION_PART:
2880         case QEMU_VM_SECTION_END:
2881             ret = qemu_loadvm_section_part_end(f, section_type);
2882             if (ret < 0) {
2883                 goto out;
2884             }
2885             break;
2886         case QEMU_VM_COMMAND:
2887             ret = loadvm_process_command(f);
2888             trace_qemu_loadvm_state_section_command(ret);
2889             if ((ret < 0) || (ret == LOADVM_QUIT)) {
2890                 goto out;
2891             }
2892             break;
2893         case QEMU_VM_EOF:
2894             /* This is the end of migration */
2895             goto out;
2896         default:
2897             error_report("Unknown savevm section type %d", section_type);
2898             ret = -EINVAL;
2899             goto out;
2900         }
2901     }
2902 
2903 out:
2904     if (ret < 0) {
2905         qemu_file_set_error(f, ret);
2906 
2907         /* Cancel bitmaps incoming regardless of recovery */
2908         dirty_bitmap_mig_cancel_incoming();
2909 
2910         /*
2911          * If we are during an active postcopy, then we pause instead
2912          * of bail out to at least keep the VM's dirty data.  Note
2913          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2914          * during which we're still receiving device states and we
2915          * still haven't yet started the VM on destination.
2916          *
2917          * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2918          * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2919          * recovering.
2920          */
2921         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2922             migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2923             /* Reset f to point to the newly created channel */
2924             f = mis->from_src_file;
2925             goto retry;
2926         }
2927     }
2928     return ret;
2929 }
2930 
2931 int qemu_loadvm_state(QEMUFile *f)
2932 {
2933     MigrationIncomingState *mis = migration_incoming_get_current();
2934     Error *local_err = NULL;
2935     int ret;
2936 
2937     if (qemu_savevm_state_blocked(&local_err)) {
2938         error_report_err(local_err);
2939         return -EINVAL;
2940     }
2941 
2942     ret = qemu_loadvm_state_header(f);
2943     if (ret) {
2944         return ret;
2945     }
2946 
2947     if (qemu_loadvm_state_setup(f, &local_err) != 0) {
2948         error_report_err(local_err);
2949         return -EINVAL;
2950     }
2951 
2952     if (migrate_switchover_ack()) {
2953         qemu_loadvm_state_switchover_ack_needed(mis);
2954     }
2955 
2956     cpu_synchronize_all_pre_loadvm();
2957 
2958     ret = qemu_loadvm_state_main(f, mis);
2959     qemu_event_set(&mis->main_thread_load_event);
2960 
2961     trace_qemu_loadvm_state_post_main(ret);
2962 
2963     if (mis->have_listen_thread) {
2964         /*
2965          * Postcopy listen thread still going, don't synchronize the
2966          * cpus yet.
2967          */
2968         return ret;
2969     }
2970 
2971     if (ret == 0) {
2972         ret = qemu_file_get_error(f);
2973     }
2974 
2975     /*
2976      * Try to read in the VMDESC section as well, so that dumping tools that
2977      * intercept our migration stream have the chance to see it.
2978      */
2979 
2980     /* We've got to be careful; if we don't read the data and just shut the fd
2981      * then the sender can error if we close while it's still sending.
2982      * We also mustn't read data that isn't there; some transports (RDMA)
2983      * will stall waiting for that data when the source has already closed.
2984      */
2985     if (ret == 0 && should_send_vmdesc()) {
2986         uint8_t *buf;
2987         uint32_t size;
2988         uint8_t  section_type = qemu_get_byte(f);
2989 
2990         if (section_type != QEMU_VM_VMDESCRIPTION) {
2991             error_report("Expected vmdescription section, but got %d",
2992                          section_type);
2993             /*
2994              * It doesn't seem worth failing at this point since
2995              * we apparently have an otherwise valid VM state
2996              */
2997         } else {
2998             buf = g_malloc(0x1000);
2999             size = qemu_get_be32(f);
3000 
3001             while (size > 0) {
3002                 uint32_t read_chunk = MIN(size, 0x1000);
3003                 qemu_get_buffer(f, buf, read_chunk);
3004                 size -= read_chunk;
3005             }
3006             g_free(buf);
3007         }
3008     }
3009 
3010     cpu_synchronize_all_post_init();
3011 
3012     return ret;
3013 }
3014 
3015 int qemu_load_device_state(QEMUFile *f)
3016 {
3017     MigrationIncomingState *mis = migration_incoming_get_current();
3018     int ret;
3019 
3020     /* Load QEMU_VM_SECTION_FULL section */
3021     ret = qemu_loadvm_state_main(f, mis);
3022     if (ret < 0) {
3023         error_report("Failed to load device state: %d", ret);
3024         return ret;
3025     }
3026 
3027     cpu_synchronize_all_post_init();
3028     return 0;
3029 }
3030 
3031 int qemu_loadvm_approve_switchover(void)
3032 {
3033     MigrationIncomingState *mis = migration_incoming_get_current();
3034 
3035     if (!mis->switchover_ack_pending_num) {
3036         return -EINVAL;
3037     }
3038 
3039     mis->switchover_ack_pending_num--;
3040     trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
3041 
3042     if (mis->switchover_ack_pending_num) {
3043         return 0;
3044     }
3045 
3046     return migrate_send_rp_switchover_ack(mis);
3047 }
3048 
3049 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
3050                   bool has_devices, strList *devices, Error **errp)
3051 {
3052     BlockDriverState *bs;
3053     QEMUSnapshotInfo sn1, *sn = &sn1;
3054     int ret = -1, ret2;
3055     QEMUFile *f;
3056     RunState saved_state = runstate_get();
3057     uint64_t vm_state_size;
3058     g_autoptr(GDateTime) now = g_date_time_new_now_local();
3059 
3060     GLOBAL_STATE_CODE();
3061 
3062     if (migration_is_blocked(errp)) {
3063         return false;
3064     }
3065 
3066     if (!replay_can_snapshot()) {
3067         error_setg(errp, "Record/replay does not allow making snapshot "
3068                    "right now. Try once more later.");
3069         return false;
3070     }
3071 
3072     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3073         return false;
3074     }
3075 
3076     /* Delete old snapshots of the same name */
3077     if (name) {
3078         if (overwrite) {
3079             if (bdrv_all_delete_snapshot(name, has_devices,
3080                                          devices, errp) < 0) {
3081                 return false;
3082             }
3083         } else {
3084             ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3085             if (ret2 < 0) {
3086                 return false;
3087             }
3088             if (ret2 == 1) {
3089                 error_setg(errp,
3090                            "Snapshot '%s' already exists in one or more devices",
3091                            name);
3092                 return false;
3093             }
3094         }
3095     }
3096 
3097     bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3098     if (bs == NULL) {
3099         return false;
3100     }
3101 
3102     global_state_store();
3103     vm_stop(RUN_STATE_SAVE_VM);
3104 
3105     bdrv_drain_all_begin();
3106 
3107     memset(sn, 0, sizeof(*sn));
3108 
3109     /* fill auxiliary fields */
3110     sn->date_sec = g_date_time_to_unix(now);
3111     sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3112     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3113     if (replay_mode != REPLAY_MODE_NONE) {
3114         sn->icount = replay_get_current_icount();
3115     } else {
3116         sn->icount = -1ULL;
3117     }
3118 
3119     if (name) {
3120         pstrcpy(sn->name, sizeof(sn->name), name);
3121     } else {
3122         g_autofree char *autoname = g_date_time_format(now,  "vm-%Y%m%d%H%M%S");
3123         pstrcpy(sn->name, sizeof(sn->name), autoname);
3124     }
3125 
3126     /* save the VM state */
3127     f = qemu_fopen_bdrv(bs, 1);
3128     if (!f) {
3129         error_setg(errp, "Could not open VM state file");
3130         goto the_end;
3131     }
3132     ret = qemu_savevm_state(f, errp);
3133     vm_state_size = qemu_file_transferred(f);
3134     ret2 = qemu_fclose(f);
3135     if (ret < 0) {
3136         goto the_end;
3137     }
3138     if (ret2 < 0) {
3139         ret = ret2;
3140         goto the_end;
3141     }
3142 
3143     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3144                                    has_devices, devices, errp);
3145     if (ret < 0) {
3146         bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3147         goto the_end;
3148     }
3149 
3150     ret = 0;
3151 
3152  the_end:
3153     bdrv_drain_all_end();
3154 
3155     vm_resume(saved_state);
3156     return ret == 0;
3157 }
3158 
3159 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3160                                 Error **errp)
3161 {
3162     QEMUFile *f;
3163     QIOChannelFile *ioc;
3164     int saved_vm_running;
3165     int ret;
3166 
3167     if (!has_live) {
3168         /* live default to true so old version of Xen tool stack can have a
3169          * successful live migration */
3170         live = true;
3171     }
3172 
3173     saved_vm_running = runstate_is_running();
3174     vm_stop(RUN_STATE_SAVE_VM);
3175     global_state_store_running();
3176 
3177     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3178                                     0660, errp);
3179     if (!ioc) {
3180         goto the_end;
3181     }
3182     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3183     f = qemu_file_new_output(QIO_CHANNEL(ioc));
3184     object_unref(OBJECT(ioc));
3185     ret = qemu_save_device_state(f);
3186     if (ret < 0 || qemu_fclose(f) < 0) {
3187         error_setg(errp, "saving Xen device state failed");
3188     } else {
3189         /* libxl calls the QMP command "stop" before calling
3190          * "xen-save-devices-state" and in case of migration failure, libxl
3191          * would call "cont".
3192          * So call bdrv_inactivate_all (release locks) here to let the other
3193          * side of the migration take control of the images.
3194          */
3195         if (live && !saved_vm_running) {
3196             ret = bdrv_inactivate_all();
3197             if (ret) {
3198                 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
3199                            __func__, ret);
3200             }
3201         }
3202     }
3203 
3204  the_end:
3205     if (saved_vm_running) {
3206         vm_start();
3207     }
3208 }
3209 
3210 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3211 {
3212     QEMUFile *f;
3213     QIOChannelFile *ioc;
3214     int ret;
3215 
3216     /* Guest must be paused before loading the device state; the RAM state
3217      * will already have been loaded by xc
3218      */
3219     if (runstate_is_running()) {
3220         error_setg(errp, "Cannot update device state while vm is running");
3221         return;
3222     }
3223     vm_stop(RUN_STATE_RESTORE_VM);
3224 
3225     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3226     if (!ioc) {
3227         return;
3228     }
3229     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3230     f = qemu_file_new_input(QIO_CHANNEL(ioc));
3231     object_unref(OBJECT(ioc));
3232 
3233     ret = qemu_loadvm_state(f);
3234     qemu_fclose(f);
3235     if (ret < 0) {
3236         error_setg(errp, "loading Xen device state failed");
3237     }
3238     migration_incoming_state_destroy();
3239 }
3240 
3241 bool load_snapshot(const char *name, const char *vmstate,
3242                    bool has_devices, strList *devices, Error **errp)
3243 {
3244     BlockDriverState *bs_vm_state;
3245     QEMUSnapshotInfo sn;
3246     QEMUFile *f;
3247     int ret;
3248     MigrationIncomingState *mis = migration_incoming_get_current();
3249 
3250     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3251         return false;
3252     }
3253     ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3254     if (ret < 0) {
3255         return false;
3256     }
3257     if (ret == 0) {
3258         error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3259                    name);
3260         return false;
3261     }
3262 
3263     bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3264     if (!bs_vm_state) {
3265         return false;
3266     }
3267 
3268     /* Don't even try to load empty VM states */
3269     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3270     if (ret < 0) {
3271         error_setg(errp, "Snapshot can not be found");
3272         return false;
3273     } else if (sn.vm_state_size == 0) {
3274         error_setg(errp, "This is a disk-only snapshot. Revert to it "
3275                    " offline using qemu-img");
3276         return false;
3277     }
3278 
3279     /*
3280      * Flush the record/replay queue. Now the VM state is going
3281      * to change. Therefore we don't need to preserve its consistency
3282      */
3283     replay_flush_events();
3284 
3285     /* Flush all IO requests so they don't interfere with the new state.  */
3286     bdrv_drain_all_begin();
3287 
3288     ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3289     if (ret < 0) {
3290         goto err_drain;
3291     }
3292 
3293     /* restore the VM state */
3294     f = qemu_fopen_bdrv(bs_vm_state, 0);
3295     if (!f) {
3296         error_setg(errp, "Could not open VM state file");
3297         goto err_drain;
3298     }
3299 
3300     qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3301     mis->from_src_file = f;
3302 
3303     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3304         ret = -EINVAL;
3305         goto err_drain;
3306     }
3307     ret = qemu_loadvm_state(f);
3308     migration_incoming_state_destroy();
3309 
3310     bdrv_drain_all_end();
3311 
3312     if (ret < 0) {
3313         error_setg(errp, "Error %d while loading VM state", ret);
3314         return false;
3315     }
3316 
3317     return true;
3318 
3319 err_drain:
3320     bdrv_drain_all_end();
3321     return false;
3322 }
3323 
3324 void load_snapshot_resume(RunState state)
3325 {
3326     vm_resume(state);
3327     if (state == RUN_STATE_RUNNING && runstate_get() == RUN_STATE_SUSPENDED) {
3328         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, &error_abort);
3329     }
3330 }
3331 
3332 bool delete_snapshot(const char *name, bool has_devices,
3333                      strList *devices, Error **errp)
3334 {
3335     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3336         return false;
3337     }
3338 
3339     if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3340         return false;
3341     }
3342 
3343     return true;
3344 }
3345 
3346 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3347 {
3348     qemu_ram_set_idstr(mr->ram_block,
3349                        memory_region_name(mr), dev);
3350     qemu_ram_set_migratable(mr->ram_block);
3351 }
3352 
3353 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3354 {
3355     qemu_ram_unset_idstr(mr->ram_block);
3356     qemu_ram_unset_migratable(mr->ram_block);
3357 }
3358 
3359 void vmstate_register_ram_global(MemoryRegion *mr)
3360 {
3361     vmstate_register_ram(mr, NULL);
3362 }
3363 
3364 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3365 {
3366     /* check needed if --only-migratable is specified */
3367     if (!only_migratable) {
3368         return true;
3369     }
3370 
3371     return !(vmsd && vmsd->unmigratable);
3372 }
3373 
3374 typedef struct SnapshotJob {
3375     Job common;
3376     char *tag;
3377     char *vmstate;
3378     strList *devices;
3379     Coroutine *co;
3380     Error **errp;
3381     bool ret;
3382 } SnapshotJob;
3383 
3384 static void qmp_snapshot_job_free(SnapshotJob *s)
3385 {
3386     g_free(s->tag);
3387     g_free(s->vmstate);
3388     qapi_free_strList(s->devices);
3389 }
3390 
3391 
3392 static void snapshot_load_job_bh(void *opaque)
3393 {
3394     Job *job = opaque;
3395     SnapshotJob *s = container_of(job, SnapshotJob, common);
3396     RunState orig_state = runstate_get();
3397 
3398     job_progress_set_remaining(&s->common, 1);
3399 
3400     vm_stop(RUN_STATE_RESTORE_VM);
3401 
3402     s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3403     if (s->ret) {
3404         load_snapshot_resume(orig_state);
3405     }
3406 
3407     job_progress_update(&s->common, 1);
3408 
3409     qmp_snapshot_job_free(s);
3410     aio_co_wake(s->co);
3411 }
3412 
3413 static void snapshot_save_job_bh(void *opaque)
3414 {
3415     Job *job = opaque;
3416     SnapshotJob *s = container_of(job, SnapshotJob, common);
3417 
3418     job_progress_set_remaining(&s->common, 1);
3419     s->ret = save_snapshot(s->tag, false, s->vmstate,
3420                            true, s->devices, s->errp);
3421     job_progress_update(&s->common, 1);
3422 
3423     qmp_snapshot_job_free(s);
3424     aio_co_wake(s->co);
3425 }
3426 
3427 static void snapshot_delete_job_bh(void *opaque)
3428 {
3429     Job *job = opaque;
3430     SnapshotJob *s = container_of(job, SnapshotJob, common);
3431 
3432     job_progress_set_remaining(&s->common, 1);
3433     s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3434     job_progress_update(&s->common, 1);
3435 
3436     qmp_snapshot_job_free(s);
3437     aio_co_wake(s->co);
3438 }
3439 
3440 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3441 {
3442     SnapshotJob *s = container_of(job, SnapshotJob, common);
3443     s->errp = errp;
3444     s->co = qemu_coroutine_self();
3445     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3446                             snapshot_save_job_bh, job);
3447     qemu_coroutine_yield();
3448     return s->ret ? 0 : -1;
3449 }
3450 
3451 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3452 {
3453     SnapshotJob *s = container_of(job, SnapshotJob, common);
3454     s->errp = errp;
3455     s->co = qemu_coroutine_self();
3456     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3457                             snapshot_load_job_bh, job);
3458     qemu_coroutine_yield();
3459     return s->ret ? 0 : -1;
3460 }
3461 
3462 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3463 {
3464     SnapshotJob *s = container_of(job, SnapshotJob, common);
3465     s->errp = errp;
3466     s->co = qemu_coroutine_self();
3467     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3468                             snapshot_delete_job_bh, job);
3469     qemu_coroutine_yield();
3470     return s->ret ? 0 : -1;
3471 }
3472 
3473 
3474 static const JobDriver snapshot_load_job_driver = {
3475     .instance_size = sizeof(SnapshotJob),
3476     .job_type      = JOB_TYPE_SNAPSHOT_LOAD,
3477     .run           = snapshot_load_job_run,
3478 };
3479 
3480 static const JobDriver snapshot_save_job_driver = {
3481     .instance_size = sizeof(SnapshotJob),
3482     .job_type      = JOB_TYPE_SNAPSHOT_SAVE,
3483     .run           = snapshot_save_job_run,
3484 };
3485 
3486 static const JobDriver snapshot_delete_job_driver = {
3487     .instance_size = sizeof(SnapshotJob),
3488     .job_type      = JOB_TYPE_SNAPSHOT_DELETE,
3489     .run           = snapshot_delete_job_run,
3490 };
3491 
3492 
3493 void qmp_snapshot_save(const char *job_id,
3494                        const char *tag,
3495                        const char *vmstate,
3496                        strList *devices,
3497                        Error **errp)
3498 {
3499     SnapshotJob *s;
3500 
3501     s = job_create(job_id, &snapshot_save_job_driver, NULL,
3502                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3503                    NULL, NULL, errp);
3504     if (!s) {
3505         return;
3506     }
3507 
3508     s->tag = g_strdup(tag);
3509     s->vmstate = g_strdup(vmstate);
3510     s->devices = QAPI_CLONE(strList, devices);
3511 
3512     job_start(&s->common);
3513 }
3514 
3515 void qmp_snapshot_load(const char *job_id,
3516                        const char *tag,
3517                        const char *vmstate,
3518                        strList *devices,
3519                        Error **errp)
3520 {
3521     SnapshotJob *s;
3522 
3523     s = job_create(job_id, &snapshot_load_job_driver, NULL,
3524                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3525                    NULL, NULL, errp);
3526     if (!s) {
3527         return;
3528     }
3529 
3530     s->tag = g_strdup(tag);
3531     s->vmstate = g_strdup(vmstate);
3532     s->devices = QAPI_CLONE(strList, devices);
3533 
3534     job_start(&s->common);
3535 }
3536 
3537 void qmp_snapshot_delete(const char *job_id,
3538                          const char *tag,
3539                          strList *devices,
3540                          Error **errp)
3541 {
3542     SnapshotJob *s;
3543 
3544     s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3545                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3546                    NULL, NULL, errp);
3547     if (!s) {
3548         return;
3549     }
3550 
3551     s->tag = g_strdup(tag);
3552     s->devices = QAPI_CLONE(strList, devices);
3553 
3554     job_start(&s->common);
3555 }
3556