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