xref: /qemu/migration/savevm.c (revision f07a5674cf97b8473e5d06d7b1df9b51e97d553f)
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 "system/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 "system/replay.h"
61 #include "system/runstate.h"
62 #include "system/system.h"
63 #include "system/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 "system/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     JSONWriter *vmdesc = s->vmdesc;
1235 
1236     trace_savevm_state_header();
1237     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1238     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1239 
1240     if (s->send_configuration) {
1241         qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1242 
1243         if (vmdesc) {
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(vmdesc, NULL);
1250             json_writer_start_object(vmdesc, "configuration");
1251         }
1252 
1253         vmstate_save_state(f, &vmstate_configuration, &savevm_state, vmdesc);
1254 
1255         if (vmdesc) {
1256             json_writer_end_object(vmdesc);
1257         }
1258     }
1259 }
1260 
1261 bool qemu_savevm_state_guest_unplug_pending(void)
1262 {
1263     SaveStateEntry *se;
1264 
1265     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1266         if (se->vmsd && se->vmsd->dev_unplug_pending &&
1267             se->vmsd->dev_unplug_pending(se->opaque)) {
1268             return true;
1269         }
1270     }
1271 
1272     return false;
1273 }
1274 
1275 int qemu_savevm_state_prepare(Error **errp)
1276 {
1277     SaveStateEntry *se;
1278     int ret;
1279 
1280     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1281         if (!se->ops || !se->ops->save_prepare) {
1282             continue;
1283         }
1284         if (se->ops->is_active) {
1285             if (!se->ops->is_active(se->opaque)) {
1286                 continue;
1287             }
1288         }
1289 
1290         ret = se->ops->save_prepare(se->opaque, errp);
1291         if (ret < 0) {
1292             return ret;
1293         }
1294     }
1295 
1296     return 0;
1297 }
1298 
1299 int qemu_savevm_state_setup(QEMUFile *f, Error **errp)
1300 {
1301     ERRP_GUARD();
1302     MigrationState *ms = migrate_get_current();
1303     JSONWriter *vmdesc = ms->vmdesc;
1304     SaveStateEntry *se;
1305     int ret = 0;
1306 
1307     if (vmdesc) {
1308         json_writer_int64(vmdesc, "page_size", qemu_target_page_size());
1309         json_writer_start_array(vmdesc, "devices");
1310     }
1311 
1312     trace_savevm_state_setup();
1313     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1314         if (se->vmsd && se->vmsd->early_setup) {
1315             ret = vmstate_save(f, se, vmdesc, errp);
1316             if (ret) {
1317                 migrate_set_error(ms, *errp);
1318                 qemu_file_set_error(f, ret);
1319                 break;
1320             }
1321             continue;
1322         }
1323 
1324         if (!se->ops || !se->ops->save_setup) {
1325             continue;
1326         }
1327         if (se->ops->is_active) {
1328             if (!se->ops->is_active(se->opaque)) {
1329                 continue;
1330             }
1331         }
1332         save_section_header(f, se, QEMU_VM_SECTION_START);
1333 
1334         ret = se->ops->save_setup(f, se->opaque, errp);
1335         save_section_footer(f, se);
1336         if (ret < 0) {
1337             qemu_file_set_error(f, ret);
1338             break;
1339         }
1340     }
1341 
1342     if (ret) {
1343         return ret;
1344     }
1345 
1346     /* TODO: Should we check that errp is set in case of failure ? */
1347     return precopy_notify(PRECOPY_NOTIFY_SETUP, errp);
1348 }
1349 
1350 int qemu_savevm_state_resume_prepare(MigrationState *s)
1351 {
1352     SaveStateEntry *se;
1353     int ret;
1354 
1355     trace_savevm_state_resume_prepare();
1356 
1357     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1358         if (!se->ops || !se->ops->resume_prepare) {
1359             continue;
1360         }
1361         if (se->ops->is_active) {
1362             if (!se->ops->is_active(se->opaque)) {
1363                 continue;
1364             }
1365         }
1366         ret = se->ops->resume_prepare(s, se->opaque);
1367         if (ret < 0) {
1368             return ret;
1369         }
1370     }
1371 
1372     return 0;
1373 }
1374 
1375 /*
1376  * this function has three return values:
1377  *   negative: there was one error, and we have -errno.
1378  *   0 : We haven't finished, caller have to go again
1379  *   1 : We have finished, we can go to complete phase
1380  */
1381 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1382 {
1383     SaveStateEntry *se;
1384     bool all_finished = true;
1385     int ret;
1386 
1387     trace_savevm_state_iterate();
1388     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1389         if (!se->ops || !se->ops->save_live_iterate) {
1390             continue;
1391         }
1392         if (se->ops->is_active &&
1393             !se->ops->is_active(se->opaque)) {
1394             continue;
1395         }
1396         if (se->ops->is_active_iterate &&
1397             !se->ops->is_active_iterate(se->opaque)) {
1398             continue;
1399         }
1400         /*
1401          * In the postcopy phase, any device that doesn't know how to
1402          * do postcopy should have saved it's state in the _complete
1403          * call that's already run, it might get confused if we call
1404          * iterate afterwards.
1405          */
1406         if (postcopy &&
1407             !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1408             continue;
1409         }
1410         if (migration_rate_exceeded(f)) {
1411             return 0;
1412         }
1413         trace_savevm_section_start(se->idstr, se->section_id);
1414 
1415         save_section_header(f, se, QEMU_VM_SECTION_PART);
1416 
1417         ret = se->ops->save_live_iterate(f, se->opaque);
1418         trace_savevm_section_end(se->idstr, se->section_id, ret);
1419         save_section_footer(f, se);
1420 
1421         if (ret < 0) {
1422             error_report("failed to save SaveStateEntry with id(name): "
1423                          "%d(%s): %d",
1424                          se->section_id, se->idstr, ret);
1425             qemu_file_set_error(f, ret);
1426             return ret;
1427         } else if (!ret) {
1428             all_finished = false;
1429         }
1430     }
1431     return all_finished;
1432 }
1433 
1434 bool should_send_vmdesc(void)
1435 {
1436     MachineState *machine = MACHINE(qdev_get_machine());
1437 
1438     return !machine->suppress_vmdesc;
1439 }
1440 
1441 /*
1442  * Calls the save_live_complete_postcopy methods
1443  * causing the last few pages to be sent immediately and doing any associated
1444  * cleanup.
1445  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1446  * all the other devices, but that happens at the point we switch to postcopy.
1447  */
1448 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1449 {
1450     SaveStateEntry *se;
1451     int ret;
1452 
1453     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1454         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1455             continue;
1456         }
1457         if (se->ops->is_active) {
1458             if (!se->ops->is_active(se->opaque)) {
1459                 continue;
1460             }
1461         }
1462         trace_savevm_section_start(se->idstr, se->section_id);
1463         /* Section type */
1464         qemu_put_byte(f, QEMU_VM_SECTION_END);
1465         qemu_put_be32(f, se->section_id);
1466 
1467         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1468         trace_savevm_section_end(se->idstr, se->section_id, ret);
1469         save_section_footer(f, se);
1470         if (ret < 0) {
1471             qemu_file_set_error(f, ret);
1472             return;
1473         }
1474     }
1475 
1476     qemu_put_byte(f, QEMU_VM_EOF);
1477     qemu_fflush(f);
1478 }
1479 
1480 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1481 {
1482     int64_t start_ts_each, end_ts_each;
1483     SaveStateEntry *se;
1484     int ret;
1485 
1486     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1487         if (!se->ops ||
1488             (in_postcopy && se->ops->has_postcopy &&
1489              se->ops->has_postcopy(se->opaque)) ||
1490             !se->ops->save_live_complete_precopy) {
1491             continue;
1492         }
1493 
1494         if (se->ops->is_active) {
1495             if (!se->ops->is_active(se->opaque)) {
1496                 continue;
1497             }
1498         }
1499 
1500         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1501         trace_savevm_section_start(se->idstr, se->section_id);
1502 
1503         save_section_header(f, se, QEMU_VM_SECTION_END);
1504 
1505         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1506         trace_savevm_section_end(se->idstr, se->section_id, ret);
1507         save_section_footer(f, se);
1508         if (ret < 0) {
1509             qemu_file_set_error(f, ret);
1510             return -1;
1511         }
1512         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1513         trace_vmstate_downtime_save("iterable", se->idstr, se->instance_id,
1514                                     end_ts_each - start_ts_each);
1515     }
1516 
1517     trace_vmstate_downtime_checkpoint("src-iterable-saved");
1518 
1519     return 0;
1520 }
1521 
1522 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1523                                                     bool in_postcopy)
1524 {
1525     MigrationState *ms = migrate_get_current();
1526     int64_t start_ts_each, end_ts_each;
1527     JSONWriter *vmdesc = ms->vmdesc;
1528     int vmdesc_len;
1529     SaveStateEntry *se;
1530     Error *local_err = NULL;
1531     int ret;
1532 
1533     /* Making sure cpu states are synchronized before saving non-iterable */
1534     cpu_synchronize_all_states();
1535 
1536     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1537         if (se->vmsd && se->vmsd->early_setup) {
1538             /* Already saved during qemu_savevm_state_setup(). */
1539             continue;
1540         }
1541 
1542         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1543 
1544         ret = vmstate_save(f, se, vmdesc, &local_err);
1545         if (ret) {
1546             migrate_set_error(ms, local_err);
1547             error_report_err(local_err);
1548             qemu_file_set_error(f, ret);
1549             return ret;
1550         }
1551 
1552         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1553         trace_vmstate_downtime_save("non-iterable", se->idstr, se->instance_id,
1554                                     end_ts_each - start_ts_each);
1555     }
1556 
1557     if (!in_postcopy) {
1558         /* Postcopy stream will still be going */
1559         qemu_put_byte(f, QEMU_VM_EOF);
1560 
1561         if (vmdesc) {
1562             json_writer_end_array(vmdesc);
1563             json_writer_end_object(vmdesc);
1564             vmdesc_len = strlen(json_writer_get(vmdesc));
1565 
1566             qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1567             qemu_put_be32(f, vmdesc_len);
1568             qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1569         }
1570     }
1571 
1572     trace_vmstate_downtime_checkpoint("src-non-iterable-saved");
1573 
1574     return 0;
1575 }
1576 
1577 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only)
1578 {
1579     int ret;
1580 
1581     ret = qemu_savevm_state_complete_precopy_iterable(f, false);
1582     if (ret) {
1583         return ret;
1584     }
1585 
1586     if (!iterable_only) {
1587         ret = qemu_savevm_state_complete_precopy_non_iterable(f, false);
1588         if (ret) {
1589             return ret;
1590         }
1591     }
1592 
1593     return qemu_fflush(f);
1594 }
1595 
1596 /* Give an estimate of the amount left to be transferred,
1597  * the result is split into the amount for units that can and
1598  * for units that can't do postcopy.
1599  */
1600 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1601                                         uint64_t *can_postcopy)
1602 {
1603     SaveStateEntry *se;
1604 
1605     *must_precopy = 0;
1606     *can_postcopy = 0;
1607 
1608     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1609         if (!se->ops || !se->ops->state_pending_estimate) {
1610             continue;
1611         }
1612         if (se->ops->is_active) {
1613             if (!se->ops->is_active(se->opaque)) {
1614                 continue;
1615             }
1616         }
1617         se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1618     }
1619 }
1620 
1621 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1622                                      uint64_t *can_postcopy)
1623 {
1624     SaveStateEntry *se;
1625 
1626     *must_precopy = 0;
1627     *can_postcopy = 0;
1628 
1629     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1630         if (!se->ops || !se->ops->state_pending_exact) {
1631             continue;
1632         }
1633         if (se->ops->is_active) {
1634             if (!se->ops->is_active(se->opaque)) {
1635                 continue;
1636             }
1637         }
1638         se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1639     }
1640 }
1641 
1642 void qemu_savevm_state_cleanup(void)
1643 {
1644     SaveStateEntry *se;
1645     Error *local_err = NULL;
1646 
1647     if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1648         error_report_err(local_err);
1649     }
1650 
1651     trace_savevm_state_cleanup();
1652     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1653         if (se->ops && se->ops->save_cleanup) {
1654             se->ops->save_cleanup(se->opaque);
1655         }
1656     }
1657 }
1658 
1659 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1660 {
1661     int ret;
1662     MigrationState *ms = migrate_get_current();
1663     MigrationStatus status;
1664 
1665     if (migration_is_running()) {
1666         error_setg(errp, "There's a migration process in progress");
1667         return -EINVAL;
1668     }
1669 
1670     ret = migrate_init(ms, errp);
1671     if (ret) {
1672         return ret;
1673     }
1674     ms->to_dst_file = f;
1675 
1676     qemu_savevm_state_header(f);
1677     ret = qemu_savevm_state_setup(f, errp);
1678     if (ret) {
1679         goto cleanup;
1680     }
1681 
1682     while (qemu_file_get_error(f) == 0) {
1683         if (qemu_savevm_state_iterate(f, false) > 0) {
1684             break;
1685         }
1686     }
1687 
1688     ret = qemu_file_get_error(f);
1689     if (ret == 0) {
1690         qemu_savevm_state_complete_precopy(f, false);
1691         ret = qemu_file_get_error(f);
1692     }
1693     if (ret != 0) {
1694         error_setg_errno(errp, -ret, "Error while writing VM state");
1695     }
1696 cleanup:
1697     qemu_savevm_state_cleanup();
1698 
1699     if (ret != 0) {
1700         status = MIGRATION_STATUS_FAILED;
1701     } else {
1702         status = MIGRATION_STATUS_COMPLETED;
1703     }
1704     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1705 
1706     /* f is outer parameter, it should not stay in global migration state after
1707      * this function finished */
1708     ms->to_dst_file = NULL;
1709 
1710     return ret;
1711 }
1712 
1713 void qemu_savevm_live_state(QEMUFile *f)
1714 {
1715     /* save QEMU_VM_SECTION_END section */
1716     qemu_savevm_state_complete_precopy(f, true);
1717     qemu_put_byte(f, QEMU_VM_EOF);
1718 }
1719 
1720 int qemu_save_device_state(QEMUFile *f)
1721 {
1722     MigrationState *ms = migrate_get_current();
1723     Error *local_err = NULL;
1724     SaveStateEntry *se;
1725 
1726     if (!migration_in_colo_state()) {
1727         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1728         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1729     }
1730     cpu_synchronize_all_states();
1731 
1732     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1733         int ret;
1734 
1735         if (se->is_ram) {
1736             continue;
1737         }
1738         ret = vmstate_save(f, se, NULL, &local_err);
1739         if (ret) {
1740             migrate_set_error(ms, local_err);
1741             error_report_err(local_err);
1742             return ret;
1743         }
1744     }
1745 
1746     qemu_put_byte(f, QEMU_VM_EOF);
1747 
1748     return qemu_file_get_error(f);
1749 }
1750 
1751 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1752 {
1753     SaveStateEntry *se;
1754 
1755     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1756         if (!strcmp(se->idstr, idstr) &&
1757             (instance_id == se->instance_id ||
1758              instance_id == se->alias_id))
1759             return se;
1760         /* Migrating from an older version? */
1761         if (strstr(se->idstr, idstr) && se->compat) {
1762             if (!strcmp(se->compat->idstr, idstr) &&
1763                 (instance_id == se->compat->instance_id ||
1764                  instance_id == se->alias_id))
1765                 return se;
1766         }
1767     }
1768     return NULL;
1769 }
1770 
1771 enum LoadVMExitCodes {
1772     /* Allow a command to quit all layers of nested loadvm loops */
1773     LOADVM_QUIT     =  1,
1774 };
1775 
1776 /* ------ incoming postcopy messages ------ */
1777 /* 'advise' arrives before any transfers just to tell us that a postcopy
1778  * *might* happen - it might be skipped if precopy transferred everything
1779  * quickly.
1780  */
1781 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1782                                          uint16_t len)
1783 {
1784     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1785     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1786     size_t page_size = qemu_target_page_size();
1787     Error *local_err = NULL;
1788 
1789     trace_loadvm_postcopy_handle_advise();
1790     if (ps != POSTCOPY_INCOMING_NONE) {
1791         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1792         return -1;
1793     }
1794 
1795     switch (len) {
1796     case 0:
1797         if (migrate_postcopy_ram()) {
1798             error_report("RAM postcopy is enabled but have 0 byte advise");
1799             return -EINVAL;
1800         }
1801         return 0;
1802     case 8 + 8:
1803         if (!migrate_postcopy_ram()) {
1804             error_report("RAM postcopy is disabled but have 16 byte advise");
1805             return -EINVAL;
1806         }
1807         break;
1808     default:
1809         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1810         return -EINVAL;
1811     }
1812 
1813     if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1814         error_report_err(local_err);
1815         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1816         return -1;
1817     }
1818 
1819     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1820     local_pagesize_summary = ram_pagesize_summary();
1821 
1822     if (remote_pagesize_summary != local_pagesize_summary)  {
1823         /*
1824          * This detects two potential causes of mismatch:
1825          *   a) A mismatch in host page sizes
1826          *      Some combinations of mismatch are probably possible but it gets
1827          *      a bit more complicated.  In particular we need to place whole
1828          *      host pages on the dest at once, and we need to ensure that we
1829          *      handle dirtying to make sure we never end up sending part of
1830          *      a hostpage on it's own.
1831          *   b) The use of different huge page sizes on source/destination
1832          *      a more fine grain test is performed during RAM block migration
1833          *      but this test here causes a nice early clear failure, and
1834          *      also fails when passed to an older qemu that doesn't
1835          *      do huge pages.
1836          */
1837         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1838                                                              " d=%" PRIx64 ")",
1839                      remote_pagesize_summary, local_pagesize_summary);
1840         return -1;
1841     }
1842 
1843     remote_tps = qemu_get_be64(mis->from_src_file);
1844     if (remote_tps != page_size) {
1845         /*
1846          * Again, some differences could be dealt with, but for now keep it
1847          * simple.
1848          */
1849         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1850                      (int)remote_tps, page_size);
1851         return -1;
1852     }
1853 
1854     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1855         error_report_err(local_err);
1856         return -1;
1857     }
1858 
1859     if (ram_postcopy_incoming_init(mis)) {
1860         return -1;
1861     }
1862 
1863     return 0;
1864 }
1865 
1866 /* After postcopy we will be told to throw some pages away since they're
1867  * dirty and will have to be demand fetched.  Must happen before CPU is
1868  * started.
1869  * There can be 0..many of these messages, each encoding multiple pages.
1870  */
1871 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1872                                               uint16_t len)
1873 {
1874     int tmp;
1875     char ramid[256];
1876     PostcopyState ps = postcopy_state_get();
1877 
1878     trace_loadvm_postcopy_ram_handle_discard();
1879 
1880     switch (ps) {
1881     case POSTCOPY_INCOMING_ADVISE:
1882         /* 1st discard */
1883         tmp = postcopy_ram_prepare_discard(mis);
1884         if (tmp) {
1885             return tmp;
1886         }
1887         break;
1888 
1889     case POSTCOPY_INCOMING_DISCARD:
1890         /* Expected state */
1891         break;
1892 
1893     default:
1894         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1895                      ps);
1896         return -1;
1897     }
1898     /* We're expecting a
1899      *    Version (0)
1900      *    a RAM ID string (length byte, name, 0 term)
1901      *    then at least 1 16 byte chunk
1902     */
1903     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1904         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1905         return -1;
1906     }
1907 
1908     tmp = qemu_get_byte(mis->from_src_file);
1909     if (tmp != postcopy_ram_discard_version) {
1910         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1911         return -1;
1912     }
1913 
1914     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1915         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1916         return -1;
1917     }
1918     tmp = qemu_get_byte(mis->from_src_file);
1919     if (tmp != 0) {
1920         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1921         return -1;
1922     }
1923 
1924     len -= 3 + strlen(ramid);
1925     if (len % 16) {
1926         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1927         return -1;
1928     }
1929     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1930     while (len) {
1931         uint64_t start_addr, block_length;
1932         start_addr = qemu_get_be64(mis->from_src_file);
1933         block_length = qemu_get_be64(mis->from_src_file);
1934 
1935         len -= 16;
1936         int ret = ram_discard_range(ramid, start_addr, block_length);
1937         if (ret) {
1938             return ret;
1939         }
1940     }
1941     trace_loadvm_postcopy_ram_handle_discard_end();
1942 
1943     return 0;
1944 }
1945 
1946 /*
1947  * Triggered by a postcopy_listen command; this thread takes over reading
1948  * the input stream, leaving the main thread free to carry on loading the rest
1949  * of the device state (from RAM).
1950  * (TODO:This could do with being in a postcopy file - but there again it's
1951  * just another input loop, not that postcopy specific)
1952  */
1953 static void *postcopy_ram_listen_thread(void *opaque)
1954 {
1955     MigrationIncomingState *mis = migration_incoming_get_current();
1956     QEMUFile *f = mis->from_src_file;
1957     int load_res;
1958     MigrationState *migr = migrate_get_current();
1959 
1960     object_ref(OBJECT(migr));
1961 
1962     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1963                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
1964     qemu_sem_post(&mis->thread_sync_sem);
1965     trace_postcopy_ram_listen_thread_start();
1966 
1967     rcu_register_thread();
1968     /*
1969      * Because we're a thread and not a coroutine we can't yield
1970      * in qemu_file, and thus we must be blocking now.
1971      */
1972     qemu_file_set_blocking(f, true);
1973     load_res = qemu_loadvm_state_main(f, mis);
1974 
1975     /*
1976      * This is tricky, but, mis->from_src_file can change after it
1977      * returns, when postcopy recovery happened. In the future, we may
1978      * want a wrapper for the QEMUFile handle.
1979      */
1980     f = mis->from_src_file;
1981 
1982     /* And non-blocking again so we don't block in any cleanup */
1983     qemu_file_set_blocking(f, false);
1984 
1985     trace_postcopy_ram_listen_thread_exit();
1986     if (load_res < 0) {
1987         qemu_file_set_error(f, load_res);
1988         dirty_bitmap_mig_cancel_incoming();
1989         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
1990             !migrate_postcopy_ram() && migrate_dirty_bitmaps())
1991         {
1992             error_report("%s: loadvm failed during postcopy: %d. All states "
1993                          "are migrated except dirty bitmaps. Some dirty "
1994                          "bitmaps may be lost, and present migrated dirty "
1995                          "bitmaps are correctly migrated and valid.",
1996                          __func__, load_res);
1997             load_res = 0; /* prevent further exit() */
1998         } else {
1999             error_report("%s: loadvm failed: %d", __func__, load_res);
2000             migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2001                                            MIGRATION_STATUS_FAILED);
2002         }
2003     }
2004     if (load_res >= 0) {
2005         /*
2006          * This looks good, but it's possible that the device loading in the
2007          * main thread hasn't finished yet, and so we might not be in 'RUN'
2008          * state yet; wait for the end of the main thread.
2009          */
2010         qemu_event_wait(&mis->main_thread_load_event);
2011     }
2012     postcopy_ram_incoming_cleanup(mis);
2013 
2014     if (load_res < 0) {
2015         /*
2016          * If something went wrong then we have a bad state so exit;
2017          * depending how far we got it might be possible at this point
2018          * to leave the guest running and fire MCEs for pages that never
2019          * arrived as a desperate recovery step.
2020          */
2021         rcu_unregister_thread();
2022         exit(EXIT_FAILURE);
2023     }
2024 
2025     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2026                                    MIGRATION_STATUS_COMPLETED);
2027     /*
2028      * If everything has worked fine, then the main thread has waited
2029      * for us to start, and we're the last use of the mis.
2030      * (If something broke then qemu will have to exit anyway since it's
2031      * got a bad migration state).
2032      */
2033     migration_incoming_state_destroy();
2034 
2035     rcu_unregister_thread();
2036     mis->have_listen_thread = false;
2037     postcopy_state_set(POSTCOPY_INCOMING_END);
2038 
2039     object_unref(OBJECT(migr));
2040 
2041     return NULL;
2042 }
2043 
2044 /* After this message we must be able to immediately receive postcopy data */
2045 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2046 {
2047     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2048     Error *local_err = NULL;
2049 
2050     trace_loadvm_postcopy_handle_listen("enter");
2051 
2052     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2053         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2054         return -1;
2055     }
2056     if (ps == POSTCOPY_INCOMING_ADVISE) {
2057         /*
2058          * A rare case, we entered listen without having to do any discards,
2059          * so do the setup that's normally done at the time of the 1st discard.
2060          */
2061         if (migrate_postcopy_ram()) {
2062             postcopy_ram_prepare_discard(mis);
2063         }
2064     }
2065 
2066     trace_loadvm_postcopy_handle_listen("after discard");
2067 
2068     /*
2069      * Sensitise RAM - can now generate requests for blocks that don't exist
2070      * However, at this point the CPU shouldn't be running, and the IO
2071      * shouldn't be doing anything yet so don't actually expect requests
2072      */
2073     if (migrate_postcopy_ram()) {
2074         if (postcopy_ram_incoming_setup(mis)) {
2075             postcopy_ram_incoming_cleanup(mis);
2076             return -1;
2077         }
2078     }
2079 
2080     trace_loadvm_postcopy_handle_listen("after uffd");
2081 
2082     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2083         error_report_err(local_err);
2084         return -1;
2085     }
2086 
2087     mis->have_listen_thread = true;
2088     postcopy_thread_create(mis, &mis->listen_thread,
2089                            MIGRATION_THREAD_DST_LISTEN,
2090                            postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2091     trace_loadvm_postcopy_handle_listen("return");
2092 
2093     return 0;
2094 }
2095 
2096 static void loadvm_postcopy_handle_run_bh(void *opaque)
2097 {
2098     MigrationIncomingState *mis = opaque;
2099 
2100     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-enter");
2101 
2102     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2103      * in migration.c
2104      */
2105     cpu_synchronize_all_post_init();
2106 
2107     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cpu-synced");
2108 
2109     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2110 
2111     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-announced");
2112 
2113     dirty_bitmap_mig_before_vm_start();
2114 
2115     if (autostart) {
2116         /*
2117          * Make sure all file formats throw away their mutable metadata.
2118          * If we get an error here, just don't restart the VM yet.
2119          */
2120         bool success = migration_block_activate(NULL);
2121 
2122         trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cache-invalidated");
2123 
2124         if (success) {
2125             vm_start();
2126         }
2127     } else {
2128         /* leave it paused and let management decide when to start the CPU */
2129         runstate_set(RUN_STATE_PAUSED);
2130     }
2131 
2132     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-vm-started");
2133 }
2134 
2135 /* After all discards we can start running and asking for pages */
2136 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2137 {
2138     PostcopyState ps = postcopy_state_get();
2139 
2140     trace_loadvm_postcopy_handle_run();
2141     if (ps != POSTCOPY_INCOMING_LISTENING) {
2142         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2143         return -1;
2144     }
2145 
2146     postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2147     migration_bh_schedule(loadvm_postcopy_handle_run_bh, mis);
2148 
2149     /* We need to finish reading the stream from the package
2150      * and also stop reading anything more from the stream that loaded the
2151      * package (since it's now being read by the listener thread).
2152      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2153      */
2154     return LOADVM_QUIT;
2155 }
2156 
2157 /* We must be with page_request_mutex held */
2158 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2159                                        gpointer data)
2160 {
2161     MigrationIncomingState *mis = data;
2162     void *host_addr = (void *) key;
2163     ram_addr_t rb_offset;
2164     RAMBlock *rb;
2165     int ret;
2166 
2167     rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2168     if (!rb) {
2169         /*
2170          * This should _never_ happen.  However be nice for a migrating VM to
2171          * not crash/assert.  Post an error (note: intended to not use *_once
2172          * because we do want to see all the illegal addresses; and this can
2173          * never be triggered by the guest so we're safe) and move on next.
2174          */
2175         error_report("%s: illegal host addr %p", __func__, host_addr);
2176         /* Try the next entry */
2177         return FALSE;
2178     }
2179 
2180     ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2181     if (ret) {
2182         /* Please refer to above comment. */
2183         error_report("%s: send rp message failed for addr %p",
2184                      __func__, host_addr);
2185         return FALSE;
2186     }
2187 
2188     trace_postcopy_page_req_sync(host_addr);
2189 
2190     return FALSE;
2191 }
2192 
2193 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2194 {
2195     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2196         g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2197     }
2198 }
2199 
2200 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2201 {
2202     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2203         error_report("%s: illegal resume received", __func__);
2204         /* Don't fail the load, only for this. */
2205         return 0;
2206     }
2207 
2208     /*
2209      * Reset the last_rb before we resend any page req to source again, since
2210      * the source should have it reset already.
2211      */
2212     mis->last_rb = NULL;
2213 
2214     /*
2215      * This means source VM is ready to resume the postcopy migration.
2216      */
2217     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2218                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2219 
2220     trace_loadvm_postcopy_handle_resume();
2221 
2222     /* Tell source that "we are ready" */
2223     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2224 
2225     /*
2226      * After a postcopy recovery, the source should have lost the postcopy
2227      * queue, or potentially the requested pages could have been lost during
2228      * the network down phase.  Let's re-sync with the source VM by re-sending
2229      * all the pending pages that we eagerly need, so these threads won't get
2230      * blocked too long due to the recovery.
2231      *
2232      * Without this procedure, the faulted destination VM threads (waiting for
2233      * page requests right before the postcopy is interrupted) can keep hanging
2234      * until the pages are sent by the source during the background copying of
2235      * pages, or another thread faulted on the same address accidentally.
2236      */
2237     migrate_send_rp_req_pages_pending(mis);
2238 
2239     /*
2240      * It's time to switch state and release the fault thread to continue
2241      * service page faults.  Note that this should be explicitly after the
2242      * above call to migrate_send_rp_req_pages_pending().  In short:
2243      * migrate_send_rp_message_req_pages() is not thread safe, yet.
2244      */
2245     qemu_sem_post(&mis->postcopy_pause_sem_fault);
2246 
2247     if (migrate_postcopy_preempt()) {
2248         /*
2249          * The preempt channel will be created in async manner, now let's
2250          * wait for it and make sure it's created.
2251          */
2252         qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2253         assert(mis->postcopy_qemufile_dst);
2254         /* Kick the fast ram load thread too */
2255         qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2256     }
2257 
2258     return 0;
2259 }
2260 
2261 /**
2262  * Immediately following this command is a blob of data containing an embedded
2263  * chunk of migration stream; read it and load it.
2264  *
2265  * @mis: Incoming state
2266  * @length: Length of packaged data to read
2267  *
2268  * Returns: Negative values on error
2269  *
2270  */
2271 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2272 {
2273     int ret;
2274     size_t length;
2275     QIOChannelBuffer *bioc;
2276 
2277     length = qemu_get_be32(mis->from_src_file);
2278     trace_loadvm_handle_cmd_packaged(length);
2279 
2280     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2281         error_report("Unreasonably large packaged state: %zu", length);
2282         return -1;
2283     }
2284 
2285     bioc = qio_channel_buffer_new(length);
2286     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2287     ret = qemu_get_buffer(mis->from_src_file,
2288                           bioc->data,
2289                           length);
2290     if (ret != length) {
2291         object_unref(OBJECT(bioc));
2292         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2293                      ret, length);
2294         return (ret < 0) ? ret : -EAGAIN;
2295     }
2296     bioc->usage += length;
2297     trace_loadvm_handle_cmd_packaged_received(ret);
2298 
2299     QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2300 
2301     /*
2302      * Before loading the guest states, ensure that the preempt channel has
2303      * been ready to use, as some of the states (e.g. via virtio_load) might
2304      * trigger page faults that will be handled through the preempt channel.
2305      * So yield to the main thread in the case that the channel create event
2306      * hasn't been dispatched.
2307      *
2308      * TODO: if we can move migration loadvm out of main thread, then we
2309      * won't block main thread from polling the accept() fds.  We can drop
2310      * this as a whole when that is done.
2311      */
2312     do {
2313         if (!migrate_postcopy_preempt() || !qemu_in_coroutine() ||
2314             mis->postcopy_qemufile_dst) {
2315             break;
2316         }
2317 
2318         aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
2319         qemu_coroutine_yield();
2320     } while (1);
2321 
2322     ret = qemu_loadvm_state_main(packf, mis);
2323     trace_loadvm_handle_cmd_packaged_main(ret);
2324     qemu_fclose(packf);
2325     object_unref(OBJECT(bioc));
2326 
2327     return ret;
2328 }
2329 
2330 /*
2331  * Handle request that source requests for recved_bitmap on
2332  * destination. Payload format:
2333  *
2334  * len (1 byte) + ramblock_name (<255 bytes)
2335  */
2336 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2337                                      uint16_t len)
2338 {
2339     QEMUFile *file = mis->from_src_file;
2340     RAMBlock *rb;
2341     char block_name[256];
2342     size_t cnt;
2343 
2344     cnt = qemu_get_counted_string(file, block_name);
2345     if (!cnt) {
2346         error_report("%s: failed to read block name", __func__);
2347         return -EINVAL;
2348     }
2349 
2350     /* Validate before using the data */
2351     if (qemu_file_get_error(file)) {
2352         return qemu_file_get_error(file);
2353     }
2354 
2355     if (len != cnt + 1) {
2356         error_report("%s: invalid payload length (%d)", __func__, len);
2357         return -EINVAL;
2358     }
2359 
2360     rb = qemu_ram_block_by_name(block_name);
2361     if (!rb) {
2362         error_report("%s: block '%s' not found", __func__, block_name);
2363         return -EINVAL;
2364     }
2365 
2366     migrate_send_rp_recv_bitmap(mis, block_name);
2367 
2368     trace_loadvm_handle_recv_bitmap(block_name);
2369 
2370     return 0;
2371 }
2372 
2373 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2374 {
2375     int ret = migration_incoming_enable_colo();
2376 
2377     if (!ret) {
2378         ret = colo_init_ram_cache();
2379         if (ret) {
2380             migration_incoming_disable_colo();
2381         }
2382     }
2383     return ret;
2384 }
2385 
2386 /*
2387  * Process an incoming 'QEMU_VM_COMMAND'
2388  * 0           just a normal return
2389  * LOADVM_QUIT All good, but exit the loop
2390  * <0          Error
2391  */
2392 static int loadvm_process_command(QEMUFile *f)
2393 {
2394     MigrationIncomingState *mis = migration_incoming_get_current();
2395     uint16_t cmd;
2396     uint16_t len;
2397     uint32_t tmp32;
2398 
2399     cmd = qemu_get_be16(f);
2400     len = qemu_get_be16(f);
2401 
2402     /* Check validity before continue processing of cmds */
2403     if (qemu_file_get_error(f)) {
2404         return qemu_file_get_error(f);
2405     }
2406 
2407     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2408         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2409         return -EINVAL;
2410     }
2411 
2412     trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2413 
2414     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2415         error_report("%s received with bad length - expecting %zu, got %d",
2416                      mig_cmd_args[cmd].name,
2417                      (size_t)mig_cmd_args[cmd].len, len);
2418         return -ERANGE;
2419     }
2420 
2421     switch (cmd) {
2422     case MIG_CMD_OPEN_RETURN_PATH:
2423         if (mis->to_src_file) {
2424             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2425             /* Not really a problem, so don't give up */
2426             return 0;
2427         }
2428         mis->to_src_file = qemu_file_get_return_path(f);
2429         if (!mis->to_src_file) {
2430             error_report("CMD_OPEN_RETURN_PATH failed");
2431             return -1;
2432         }
2433 
2434         /*
2435          * Switchover ack is enabled but no device uses it, so send an ACK to
2436          * source that it's OK to switchover. Do it here, after return path has
2437          * been created.
2438          */
2439         if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2440             int ret = migrate_send_rp_switchover_ack(mis);
2441             if (ret) {
2442                 error_report(
2443                     "Could not send switchover ack RP MSG, err %d (%s)", ret,
2444                     strerror(-ret));
2445                 return ret;
2446             }
2447         }
2448         break;
2449 
2450     case MIG_CMD_PING:
2451         tmp32 = qemu_get_be32(f);
2452         trace_loadvm_process_command_ping(tmp32);
2453         if (!mis->to_src_file) {
2454             error_report("CMD_PING (0x%x) received with no return path",
2455                          tmp32);
2456             return -1;
2457         }
2458         migrate_send_rp_pong(mis, tmp32);
2459         break;
2460 
2461     case MIG_CMD_PACKAGED:
2462         return loadvm_handle_cmd_packaged(mis);
2463 
2464     case MIG_CMD_POSTCOPY_ADVISE:
2465         return loadvm_postcopy_handle_advise(mis, len);
2466 
2467     case MIG_CMD_POSTCOPY_LISTEN:
2468         return loadvm_postcopy_handle_listen(mis);
2469 
2470     case MIG_CMD_POSTCOPY_RUN:
2471         return loadvm_postcopy_handle_run(mis);
2472 
2473     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2474         return loadvm_postcopy_ram_handle_discard(mis, len);
2475 
2476     case MIG_CMD_POSTCOPY_RESUME:
2477         return loadvm_postcopy_handle_resume(mis);
2478 
2479     case MIG_CMD_RECV_BITMAP:
2480         return loadvm_handle_recv_bitmap(mis, len);
2481 
2482     case MIG_CMD_ENABLE_COLO:
2483         return loadvm_process_enable_colo(mis);
2484     }
2485 
2486     return 0;
2487 }
2488 
2489 /*
2490  * Read a footer off the wire and check that it matches the expected section
2491  *
2492  * Returns: true if the footer was good
2493  *          false if there is a problem (and calls error_report to say why)
2494  */
2495 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2496 {
2497     int ret;
2498     uint8_t read_mark;
2499     uint32_t read_section_id;
2500 
2501     if (!migrate_get_current()->send_section_footer) {
2502         /* No footer to check */
2503         return true;
2504     }
2505 
2506     read_mark = qemu_get_byte(f);
2507 
2508     ret = qemu_file_get_error(f);
2509     if (ret) {
2510         error_report("%s: Read section footer failed: %d",
2511                      __func__, ret);
2512         return false;
2513     }
2514 
2515     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2516         error_report("Missing section footer for %s", se->idstr);
2517         return false;
2518     }
2519 
2520     read_section_id = qemu_get_be32(f);
2521     if (read_section_id != se->load_section_id) {
2522         error_report("Mismatched section id in footer for %s -"
2523                      " read 0x%x expected 0x%x",
2524                      se->idstr, read_section_id, se->load_section_id);
2525         return false;
2526     }
2527 
2528     /* All good */
2529     return true;
2530 }
2531 
2532 static int
2533 qemu_loadvm_section_start_full(QEMUFile *f, uint8_t type)
2534 {
2535     bool trace_downtime = (type == QEMU_VM_SECTION_FULL);
2536     uint32_t instance_id, version_id, section_id;
2537     int64_t start_ts, end_ts;
2538     SaveStateEntry *se;
2539     char idstr[256];
2540     int ret;
2541 
2542     /* Read section start */
2543     section_id = qemu_get_be32(f);
2544     if (!qemu_get_counted_string(f, idstr)) {
2545         error_report("Unable to read ID string for section %u",
2546                      section_id);
2547         return -EINVAL;
2548     }
2549     instance_id = qemu_get_be32(f);
2550     version_id = qemu_get_be32(f);
2551 
2552     ret = qemu_file_get_error(f);
2553     if (ret) {
2554         error_report("%s: Failed to read instance/version ID: %d",
2555                      __func__, ret);
2556         return ret;
2557     }
2558 
2559     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2560             instance_id, version_id);
2561     /* Find savevm section */
2562     se = find_se(idstr, instance_id);
2563     if (se == NULL) {
2564         error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2565                      "Make sure that your current VM setup matches your "
2566                      "saved VM setup, including any hotplugged devices",
2567                      idstr, instance_id);
2568         return -EINVAL;
2569     }
2570 
2571     /* Validate version */
2572     if (version_id > se->version_id) {
2573         error_report("savevm: unsupported version %d for '%s' v%d",
2574                      version_id, idstr, se->version_id);
2575         return -EINVAL;
2576     }
2577     se->load_version_id = version_id;
2578     se->load_section_id = section_id;
2579 
2580     /* Validate if it is a device's state */
2581     if (xen_enabled() && se->is_ram) {
2582         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2583         return -EINVAL;
2584     }
2585 
2586     if (trace_downtime) {
2587         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2588     }
2589 
2590     ret = vmstate_load(f, se);
2591     if (ret < 0) {
2592         error_report("error while loading state for instance 0x%"PRIx32" of"
2593                      " device '%s'", instance_id, idstr);
2594         return ret;
2595     }
2596 
2597     if (trace_downtime) {
2598         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2599         trace_vmstate_downtime_load("non-iterable", se->idstr,
2600                                     se->instance_id, end_ts - start_ts);
2601     }
2602 
2603     if (!check_section_footer(f, se)) {
2604         return -EINVAL;
2605     }
2606 
2607     return 0;
2608 }
2609 
2610 static int
2611 qemu_loadvm_section_part_end(QEMUFile *f, uint8_t type)
2612 {
2613     bool trace_downtime = (type == QEMU_VM_SECTION_END);
2614     int64_t start_ts, end_ts;
2615     uint32_t section_id;
2616     SaveStateEntry *se;
2617     int ret;
2618 
2619     section_id = qemu_get_be32(f);
2620 
2621     ret = qemu_file_get_error(f);
2622     if (ret) {
2623         error_report("%s: Failed to read section ID: %d",
2624                      __func__, ret);
2625         return ret;
2626     }
2627 
2628     trace_qemu_loadvm_state_section_partend(section_id);
2629     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2630         if (se->load_section_id == section_id) {
2631             break;
2632         }
2633     }
2634     if (se == NULL) {
2635         error_report("Unknown savevm section %d", section_id);
2636         return -EINVAL;
2637     }
2638 
2639     if (trace_downtime) {
2640         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2641     }
2642 
2643     ret = vmstate_load(f, se);
2644     if (ret < 0) {
2645         error_report("error while loading state section id %d(%s)",
2646                      section_id, se->idstr);
2647         return ret;
2648     }
2649 
2650     if (trace_downtime) {
2651         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2652         trace_vmstate_downtime_load("iterable", se->idstr,
2653                                     se->instance_id, end_ts - start_ts);
2654     }
2655 
2656     if (!check_section_footer(f, se)) {
2657         return -EINVAL;
2658     }
2659 
2660     return 0;
2661 }
2662 
2663 static int qemu_loadvm_state_header(QEMUFile *f)
2664 {
2665     unsigned int v;
2666     int ret;
2667 
2668     v = qemu_get_be32(f);
2669     if (v != QEMU_VM_FILE_MAGIC) {
2670         error_report("Not a migration stream");
2671         return -EINVAL;
2672     }
2673 
2674     v = qemu_get_be32(f);
2675     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2676         error_report("SaveVM v2 format is obsolete and don't work anymore");
2677         return -ENOTSUP;
2678     }
2679     if (v != QEMU_VM_FILE_VERSION) {
2680         error_report("Unsupported migration stream version");
2681         return -ENOTSUP;
2682     }
2683 
2684     if (migrate_get_current()->send_configuration) {
2685         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2686             error_report("Configuration section missing");
2687             return -EINVAL;
2688         }
2689         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2690 
2691         if (ret) {
2692             return ret;
2693         }
2694     }
2695     return 0;
2696 }
2697 
2698 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2699 {
2700     SaveStateEntry *se;
2701 
2702     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2703         if (!se->ops || !se->ops->switchover_ack_needed) {
2704             continue;
2705         }
2706 
2707         if (se->ops->switchover_ack_needed(se->opaque)) {
2708             mis->switchover_ack_pending_num++;
2709         }
2710     }
2711 
2712     trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2713 }
2714 
2715 static int qemu_loadvm_state_setup(QEMUFile *f, Error **errp)
2716 {
2717     ERRP_GUARD();
2718     SaveStateEntry *se;
2719     int ret;
2720 
2721     trace_loadvm_state_setup();
2722     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2723         if (!se->ops || !se->ops->load_setup) {
2724             continue;
2725         }
2726         if (se->ops->is_active) {
2727             if (!se->ops->is_active(se->opaque)) {
2728                 continue;
2729             }
2730         }
2731 
2732         ret = se->ops->load_setup(f, se->opaque, errp);
2733         if (ret < 0) {
2734             error_prepend(errp, "Load state of device %s failed: ",
2735                           se->idstr);
2736             qemu_file_set_error(f, ret);
2737             return ret;
2738         }
2739     }
2740     return 0;
2741 }
2742 
2743 void qemu_loadvm_state_cleanup(void)
2744 {
2745     SaveStateEntry *se;
2746 
2747     trace_loadvm_state_cleanup();
2748     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2749         if (se->ops && se->ops->load_cleanup) {
2750             se->ops->load_cleanup(se->opaque);
2751         }
2752     }
2753 }
2754 
2755 /* Return true if we should continue the migration, or false. */
2756 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2757 {
2758     int i;
2759 
2760     trace_postcopy_pause_incoming();
2761 
2762     assert(migrate_postcopy_ram());
2763 
2764     /*
2765      * Unregister yank with either from/to src would work, since ioc behind it
2766      * is the same
2767      */
2768     migration_ioc_unregister_yank_from_file(mis->from_src_file);
2769 
2770     assert(mis->from_src_file);
2771     qemu_file_shutdown(mis->from_src_file);
2772     qemu_fclose(mis->from_src_file);
2773     mis->from_src_file = NULL;
2774 
2775     assert(mis->to_src_file);
2776     qemu_file_shutdown(mis->to_src_file);
2777     qemu_mutex_lock(&mis->rp_mutex);
2778     qemu_fclose(mis->to_src_file);
2779     mis->to_src_file = NULL;
2780     qemu_mutex_unlock(&mis->rp_mutex);
2781 
2782     /*
2783      * NOTE: this must happen before reset the PostcopyTmpPages below,
2784      * otherwise it's racy to reset those fields when the fast load thread
2785      * can be accessing it in parallel.
2786      */
2787     if (mis->postcopy_qemufile_dst) {
2788         qemu_file_shutdown(mis->postcopy_qemufile_dst);
2789         /* Take the mutex to make sure the fast ram load thread halted */
2790         qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2791         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2792         qemu_fclose(mis->postcopy_qemufile_dst);
2793         mis->postcopy_qemufile_dst = NULL;
2794         qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2795     }
2796 
2797     /* Current state can be either ACTIVE or RECOVER */
2798     migrate_set_state(&mis->state, mis->state,
2799                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2800 
2801     /* Notify the fault thread for the invalidated file handle */
2802     postcopy_fault_thread_notify(mis);
2803 
2804     /*
2805      * If network is interrupted, any temp page we received will be useless
2806      * because we didn't mark them as "received" in receivedmap.  After a
2807      * proper recovery later (which will sync src dirty bitmap with receivedmap
2808      * on dest) these cached small pages will be resent again.
2809      */
2810     for (i = 0; i < mis->postcopy_channels; i++) {
2811         postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2812     }
2813 
2814     error_report("Detected IO failure for postcopy. "
2815                  "Migration paused.");
2816 
2817     do {
2818         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2819     } while (postcopy_is_paused(mis->state));
2820 
2821     trace_postcopy_pause_incoming_continued();
2822 
2823     return true;
2824 }
2825 
2826 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2827 {
2828     uint8_t section_type;
2829     int ret = 0;
2830 
2831 retry:
2832     while (true) {
2833         section_type = qemu_get_byte(f);
2834 
2835         ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2836         if (ret) {
2837             break;
2838         }
2839 
2840         trace_qemu_loadvm_state_section(section_type);
2841         switch (section_type) {
2842         case QEMU_VM_SECTION_START:
2843         case QEMU_VM_SECTION_FULL:
2844             ret = qemu_loadvm_section_start_full(f, section_type);
2845             if (ret < 0) {
2846                 goto out;
2847             }
2848             break;
2849         case QEMU_VM_SECTION_PART:
2850         case QEMU_VM_SECTION_END:
2851             ret = qemu_loadvm_section_part_end(f, section_type);
2852             if (ret < 0) {
2853                 goto out;
2854             }
2855             break;
2856         case QEMU_VM_COMMAND:
2857             ret = loadvm_process_command(f);
2858             trace_qemu_loadvm_state_section_command(ret);
2859             if ((ret < 0) || (ret == LOADVM_QUIT)) {
2860                 goto out;
2861             }
2862             break;
2863         case QEMU_VM_EOF:
2864             /* This is the end of migration */
2865             goto out;
2866         default:
2867             error_report("Unknown savevm section type %d", section_type);
2868             ret = -EINVAL;
2869             goto out;
2870         }
2871     }
2872 
2873 out:
2874     if (ret < 0) {
2875         qemu_file_set_error(f, ret);
2876 
2877         /* Cancel bitmaps incoming regardless of recovery */
2878         dirty_bitmap_mig_cancel_incoming();
2879 
2880         /*
2881          * If we are during an active postcopy, then we pause instead
2882          * of bail out to at least keep the VM's dirty data.  Note
2883          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2884          * during which we're still receiving device states and we
2885          * still haven't yet started the VM on destination.
2886          *
2887          * Only RAM postcopy supports recovery. Still, if RAM postcopy is
2888          * enabled, canceled bitmaps postcopy will not affect RAM postcopy
2889          * recovering.
2890          */
2891         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2892             migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
2893             /* Reset f to point to the newly created channel */
2894             f = mis->from_src_file;
2895             goto retry;
2896         }
2897     }
2898     return ret;
2899 }
2900 
2901 int qemu_loadvm_state(QEMUFile *f)
2902 {
2903     MigrationIncomingState *mis = migration_incoming_get_current();
2904     Error *local_err = NULL;
2905     int ret;
2906 
2907     if (qemu_savevm_state_blocked(&local_err)) {
2908         error_report_err(local_err);
2909         return -EINVAL;
2910     }
2911 
2912     ret = qemu_loadvm_state_header(f);
2913     if (ret) {
2914         return ret;
2915     }
2916 
2917     if (qemu_loadvm_state_setup(f, &local_err) != 0) {
2918         error_report_err(local_err);
2919         return -EINVAL;
2920     }
2921 
2922     if (migrate_switchover_ack()) {
2923         qemu_loadvm_state_switchover_ack_needed(mis);
2924     }
2925 
2926     cpu_synchronize_all_pre_loadvm();
2927 
2928     ret = qemu_loadvm_state_main(f, mis);
2929     qemu_event_set(&mis->main_thread_load_event);
2930 
2931     trace_qemu_loadvm_state_post_main(ret);
2932 
2933     if (mis->have_listen_thread) {
2934         /*
2935          * Postcopy listen thread still going, don't synchronize the
2936          * cpus yet.
2937          */
2938         return ret;
2939     }
2940 
2941     /* When reaching here, it must be precopy */
2942     if (ret == 0) {
2943         if (migrate_has_error(migrate_get_current())) {
2944             ret = -EINVAL;
2945         } else {
2946             ret = qemu_file_get_error(f);
2947         }
2948     }
2949 
2950     /*
2951      * Try to read in the VMDESC section as well, so that dumping tools that
2952      * intercept our migration stream have the chance to see it.
2953      */
2954 
2955     /* We've got to be careful; if we don't read the data and just shut the fd
2956      * then the sender can error if we close while it's still sending.
2957      * We also mustn't read data that isn't there; some transports (RDMA)
2958      * will stall waiting for that data when the source has already closed.
2959      */
2960     if (ret == 0 && should_send_vmdesc()) {
2961         uint8_t *buf;
2962         uint32_t size;
2963         uint8_t  section_type = qemu_get_byte(f);
2964 
2965         if (section_type != QEMU_VM_VMDESCRIPTION) {
2966             error_report("Expected vmdescription section, but got %d",
2967                          section_type);
2968             /*
2969              * It doesn't seem worth failing at this point since
2970              * we apparently have an otherwise valid VM state
2971              */
2972         } else {
2973             buf = g_malloc(0x1000);
2974             size = qemu_get_be32(f);
2975 
2976             while (size > 0) {
2977                 uint32_t read_chunk = MIN(size, 0x1000);
2978                 qemu_get_buffer(f, buf, read_chunk);
2979                 size -= read_chunk;
2980             }
2981             g_free(buf);
2982         }
2983     }
2984 
2985     cpu_synchronize_all_post_init();
2986 
2987     return ret;
2988 }
2989 
2990 int qemu_load_device_state(QEMUFile *f)
2991 {
2992     MigrationIncomingState *mis = migration_incoming_get_current();
2993     int ret;
2994 
2995     /* Load QEMU_VM_SECTION_FULL section */
2996     ret = qemu_loadvm_state_main(f, mis);
2997     if (ret < 0) {
2998         error_report("Failed to load device state: %d", ret);
2999         return ret;
3000     }
3001 
3002     cpu_synchronize_all_post_init();
3003     return 0;
3004 }
3005 
3006 int qemu_loadvm_approve_switchover(void)
3007 {
3008     MigrationIncomingState *mis = migration_incoming_get_current();
3009 
3010     if (!mis->switchover_ack_pending_num) {
3011         return -EINVAL;
3012     }
3013 
3014     mis->switchover_ack_pending_num--;
3015     trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
3016 
3017     if (mis->switchover_ack_pending_num) {
3018         return 0;
3019     }
3020 
3021     return migrate_send_rp_switchover_ack(mis);
3022 }
3023 
3024 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
3025                   bool has_devices, strList *devices, Error **errp)
3026 {
3027     BlockDriverState *bs;
3028     QEMUSnapshotInfo sn1, *sn = &sn1;
3029     int ret = -1, ret2;
3030     QEMUFile *f;
3031     RunState saved_state = runstate_get();
3032     uint64_t vm_state_size;
3033     g_autoptr(GDateTime) now = g_date_time_new_now_local();
3034 
3035     GLOBAL_STATE_CODE();
3036 
3037     if (migration_is_blocked(errp)) {
3038         return false;
3039     }
3040 
3041     if (!replay_can_snapshot()) {
3042         error_setg(errp, "Record/replay does not allow making snapshot "
3043                    "right now. Try once more later.");
3044         return false;
3045     }
3046 
3047     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3048         return false;
3049     }
3050 
3051     /* Delete old snapshots of the same name */
3052     if (name) {
3053         if (overwrite) {
3054             if (bdrv_all_delete_snapshot(name, has_devices,
3055                                          devices, errp) < 0) {
3056                 return false;
3057             }
3058         } else {
3059             ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3060             if (ret2 < 0) {
3061                 return false;
3062             }
3063             if (ret2 == 1) {
3064                 error_setg(errp,
3065                            "Snapshot '%s' already exists in one or more devices",
3066                            name);
3067                 return false;
3068             }
3069         }
3070     }
3071 
3072     bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3073     if (bs == NULL) {
3074         return false;
3075     }
3076 
3077     global_state_store();
3078     vm_stop(RUN_STATE_SAVE_VM);
3079 
3080     bdrv_drain_all_begin();
3081 
3082     memset(sn, 0, sizeof(*sn));
3083 
3084     /* fill auxiliary fields */
3085     sn->date_sec = g_date_time_to_unix(now);
3086     sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3087     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3088     if (replay_mode != REPLAY_MODE_NONE) {
3089         sn->icount = replay_get_current_icount();
3090     } else {
3091         sn->icount = -1ULL;
3092     }
3093 
3094     if (name) {
3095         pstrcpy(sn->name, sizeof(sn->name), name);
3096     } else {
3097         g_autofree char *autoname = g_date_time_format(now,  "vm-%Y%m%d%H%M%S");
3098         pstrcpy(sn->name, sizeof(sn->name), autoname);
3099     }
3100 
3101     /* save the VM state */
3102     f = qemu_fopen_bdrv(bs, 1);
3103     if (!f) {
3104         error_setg(errp, "Could not open VM state file");
3105         goto the_end;
3106     }
3107     ret = qemu_savevm_state(f, errp);
3108     vm_state_size = qemu_file_transferred(f);
3109     ret2 = qemu_fclose(f);
3110     if (ret < 0) {
3111         goto the_end;
3112     }
3113     if (ret2 < 0) {
3114         ret = ret2;
3115         goto the_end;
3116     }
3117 
3118     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3119                                    has_devices, devices, errp);
3120     if (ret < 0) {
3121         bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3122         goto the_end;
3123     }
3124 
3125     ret = 0;
3126 
3127  the_end:
3128     bdrv_drain_all_end();
3129 
3130     vm_resume(saved_state);
3131     return ret == 0;
3132 }
3133 
3134 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3135                                 Error **errp)
3136 {
3137     QEMUFile *f;
3138     QIOChannelFile *ioc;
3139     int saved_vm_running;
3140     int ret;
3141 
3142     if (!has_live) {
3143         /* live default to true so old version of Xen tool stack can have a
3144          * successful live migration */
3145         live = true;
3146     }
3147 
3148     saved_vm_running = runstate_is_running();
3149     vm_stop(RUN_STATE_SAVE_VM);
3150     global_state_store_running();
3151 
3152     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3153                                     0660, errp);
3154     if (!ioc) {
3155         goto the_end;
3156     }
3157     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3158     f = qemu_file_new_output(QIO_CHANNEL(ioc));
3159     object_unref(OBJECT(ioc));
3160     ret = qemu_save_device_state(f);
3161     if (ret < 0 || qemu_fclose(f) < 0) {
3162         error_setg(errp, "saving Xen device state failed");
3163     } else {
3164         /* libxl calls the QMP command "stop" before calling
3165          * "xen-save-devices-state" and in case of migration failure, libxl
3166          * would call "cont".
3167          * So call bdrv_inactivate_all (release locks) here to let the other
3168          * side of the migration take control of the images.
3169          */
3170         if (live && !saved_vm_running) {
3171             migration_block_inactivate();
3172         }
3173     }
3174 
3175  the_end:
3176     if (saved_vm_running) {
3177         vm_start();
3178     }
3179 }
3180 
3181 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3182 {
3183     QEMUFile *f;
3184     QIOChannelFile *ioc;
3185     int ret;
3186 
3187     /* Guest must be paused before loading the device state; the RAM state
3188      * will already have been loaded by xc
3189      */
3190     if (runstate_is_running()) {
3191         error_setg(errp, "Cannot update device state while vm is running");
3192         return;
3193     }
3194     vm_stop(RUN_STATE_RESTORE_VM);
3195 
3196     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3197     if (!ioc) {
3198         return;
3199     }
3200     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3201     f = qemu_file_new_input(QIO_CHANNEL(ioc));
3202     object_unref(OBJECT(ioc));
3203 
3204     ret = qemu_loadvm_state(f);
3205     qemu_fclose(f);
3206     if (ret < 0) {
3207         error_setg(errp, "loading Xen device state failed");
3208     }
3209     migration_incoming_state_destroy();
3210 }
3211 
3212 bool load_snapshot(const char *name, const char *vmstate,
3213                    bool has_devices, strList *devices, Error **errp)
3214 {
3215     BlockDriverState *bs_vm_state;
3216     QEMUSnapshotInfo sn;
3217     QEMUFile *f;
3218     int ret;
3219     MigrationIncomingState *mis = migration_incoming_get_current();
3220 
3221     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3222         return false;
3223     }
3224     ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3225     if (ret < 0) {
3226         return false;
3227     }
3228     if (ret == 0) {
3229         error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3230                    name);
3231         return false;
3232     }
3233 
3234     bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3235     if (!bs_vm_state) {
3236         return false;
3237     }
3238 
3239     /* Don't even try to load empty VM states */
3240     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3241     if (ret < 0) {
3242         error_setg(errp, "Snapshot can not be found");
3243         return false;
3244     } else if (sn.vm_state_size == 0) {
3245         error_setg(errp, "This is a disk-only snapshot. Revert to it "
3246                    " offline using qemu-img");
3247         return false;
3248     }
3249 
3250     /*
3251      * Flush the record/replay queue. Now the VM state is going
3252      * to change. Therefore we don't need to preserve its consistency
3253      */
3254     replay_flush_events();
3255 
3256     /* Flush all IO requests so they don't interfere with the new state.  */
3257     bdrv_drain_all_begin();
3258 
3259     ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3260     if (ret < 0) {
3261         goto err_drain;
3262     }
3263 
3264     /* restore the VM state */
3265     f = qemu_fopen_bdrv(bs_vm_state, 0);
3266     if (!f) {
3267         error_setg(errp, "Could not open VM state file");
3268         goto err_drain;
3269     }
3270 
3271     qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3272     mis->from_src_file = f;
3273 
3274     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3275         ret = -EINVAL;
3276         goto err_drain;
3277     }
3278     ret = qemu_loadvm_state(f);
3279     migration_incoming_state_destroy();
3280 
3281     bdrv_drain_all_end();
3282 
3283     if (ret < 0) {
3284         error_setg(errp, "Error %d while loading VM state", ret);
3285         return false;
3286     }
3287 
3288     return true;
3289 
3290 err_drain:
3291     bdrv_drain_all_end();
3292     return false;
3293 }
3294 
3295 void load_snapshot_resume(RunState state)
3296 {
3297     vm_resume(state);
3298     if (state == RUN_STATE_RUNNING && runstate_get() == RUN_STATE_SUSPENDED) {
3299         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, &error_abort);
3300     }
3301 }
3302 
3303 bool delete_snapshot(const char *name, bool has_devices,
3304                      strList *devices, Error **errp)
3305 {
3306     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3307         return false;
3308     }
3309 
3310     if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3311         return false;
3312     }
3313 
3314     return true;
3315 }
3316 
3317 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3318 {
3319     qemu_ram_set_idstr(mr->ram_block,
3320                        memory_region_name(mr), dev);
3321     qemu_ram_set_migratable(mr->ram_block);
3322 }
3323 
3324 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3325 {
3326     qemu_ram_unset_idstr(mr->ram_block);
3327     qemu_ram_unset_migratable(mr->ram_block);
3328 }
3329 
3330 void vmstate_register_ram_global(MemoryRegion *mr)
3331 {
3332     vmstate_register_ram(mr, NULL);
3333 }
3334 
3335 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3336 {
3337     /* check needed if --only-migratable is specified */
3338     if (!only_migratable) {
3339         return true;
3340     }
3341 
3342     return !(vmsd && vmsd->unmigratable);
3343 }
3344 
3345 typedef struct SnapshotJob {
3346     Job common;
3347     char *tag;
3348     char *vmstate;
3349     strList *devices;
3350     Coroutine *co;
3351     Error **errp;
3352     bool ret;
3353 } SnapshotJob;
3354 
3355 static void qmp_snapshot_job_free(SnapshotJob *s)
3356 {
3357     g_free(s->tag);
3358     g_free(s->vmstate);
3359     qapi_free_strList(s->devices);
3360 }
3361 
3362 
3363 static void snapshot_load_job_bh(void *opaque)
3364 {
3365     Job *job = opaque;
3366     SnapshotJob *s = container_of(job, SnapshotJob, common);
3367     RunState orig_state = runstate_get();
3368 
3369     job_progress_set_remaining(&s->common, 1);
3370 
3371     vm_stop(RUN_STATE_RESTORE_VM);
3372 
3373     s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3374     if (s->ret) {
3375         load_snapshot_resume(orig_state);
3376     }
3377 
3378     job_progress_update(&s->common, 1);
3379 
3380     qmp_snapshot_job_free(s);
3381     aio_co_wake(s->co);
3382 }
3383 
3384 static void snapshot_save_job_bh(void *opaque)
3385 {
3386     Job *job = opaque;
3387     SnapshotJob *s = container_of(job, SnapshotJob, common);
3388 
3389     job_progress_set_remaining(&s->common, 1);
3390     s->ret = save_snapshot(s->tag, false, s->vmstate,
3391                            true, s->devices, s->errp);
3392     job_progress_update(&s->common, 1);
3393 
3394     qmp_snapshot_job_free(s);
3395     aio_co_wake(s->co);
3396 }
3397 
3398 static void snapshot_delete_job_bh(void *opaque)
3399 {
3400     Job *job = opaque;
3401     SnapshotJob *s = container_of(job, SnapshotJob, common);
3402 
3403     job_progress_set_remaining(&s->common, 1);
3404     s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3405     job_progress_update(&s->common, 1);
3406 
3407     qmp_snapshot_job_free(s);
3408     aio_co_wake(s->co);
3409 }
3410 
3411 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3412 {
3413     SnapshotJob *s = container_of(job, SnapshotJob, common);
3414     s->errp = errp;
3415     s->co = qemu_coroutine_self();
3416     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3417                             snapshot_save_job_bh, job);
3418     qemu_coroutine_yield();
3419     return s->ret ? 0 : -1;
3420 }
3421 
3422 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3423 {
3424     SnapshotJob *s = container_of(job, SnapshotJob, common);
3425     s->errp = errp;
3426     s->co = qemu_coroutine_self();
3427     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3428                             snapshot_load_job_bh, job);
3429     qemu_coroutine_yield();
3430     return s->ret ? 0 : -1;
3431 }
3432 
3433 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3434 {
3435     SnapshotJob *s = container_of(job, SnapshotJob, common);
3436     s->errp = errp;
3437     s->co = qemu_coroutine_self();
3438     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3439                             snapshot_delete_job_bh, job);
3440     qemu_coroutine_yield();
3441     return s->ret ? 0 : -1;
3442 }
3443 
3444 
3445 static const JobDriver snapshot_load_job_driver = {
3446     .instance_size = sizeof(SnapshotJob),
3447     .job_type      = JOB_TYPE_SNAPSHOT_LOAD,
3448     .run           = snapshot_load_job_run,
3449 };
3450 
3451 static const JobDriver snapshot_save_job_driver = {
3452     .instance_size = sizeof(SnapshotJob),
3453     .job_type      = JOB_TYPE_SNAPSHOT_SAVE,
3454     .run           = snapshot_save_job_run,
3455 };
3456 
3457 static const JobDriver snapshot_delete_job_driver = {
3458     .instance_size = sizeof(SnapshotJob),
3459     .job_type      = JOB_TYPE_SNAPSHOT_DELETE,
3460     .run           = snapshot_delete_job_run,
3461 };
3462 
3463 
3464 void qmp_snapshot_save(const char *job_id,
3465                        const char *tag,
3466                        const char *vmstate,
3467                        strList *devices,
3468                        Error **errp)
3469 {
3470     SnapshotJob *s;
3471 
3472     s = job_create(job_id, &snapshot_save_job_driver, NULL,
3473                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3474                    NULL, NULL, errp);
3475     if (!s) {
3476         return;
3477     }
3478 
3479     s->tag = g_strdup(tag);
3480     s->vmstate = g_strdup(vmstate);
3481     s->devices = QAPI_CLONE(strList, devices);
3482 
3483     job_start(&s->common);
3484 }
3485 
3486 void qmp_snapshot_load(const char *job_id,
3487                        const char *tag,
3488                        const char *vmstate,
3489                        strList *devices,
3490                        Error **errp)
3491 {
3492     SnapshotJob *s;
3493 
3494     s = job_create(job_id, &snapshot_load_job_driver, NULL,
3495                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3496                    NULL, NULL, errp);
3497     if (!s) {
3498         return;
3499     }
3500 
3501     s->tag = g_strdup(tag);
3502     s->vmstate = g_strdup(vmstate);
3503     s->devices = QAPI_CLONE(strList, devices);
3504 
3505     job_start(&s->common);
3506 }
3507 
3508 void qmp_snapshot_delete(const char *job_id,
3509                          const char *tag,
3510                          strList *devices,
3511                          Error **errp)
3512 {
3513     SnapshotJob *s;
3514 
3515     s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3516                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3517                    NULL, NULL, errp);
3518     if (!s) {
3519         return;
3520     }
3521 
3522     s->tag = g_strdup(tag);
3523     s->devices = QAPI_CLONE(strList, devices);
3524 
3525     job_start(&s->common);
3526 }
3527