xref: /qemu/migration/savevm.c (revision 892b06c40e46656b07579b9f4fb7a8f2652cacf2)
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 "exec/memory.h"
52 #include "exec/target_page.h"
53 #include "trace.h"
54 #include "qemu/iov.h"
55 #include "qemu/job.h"
56 #include "qemu/main-loop.h"
57 #include "block/snapshot.h"
58 #include "block/thread-pool.h"
59 #include "qemu/cutils.h"
60 #include "io/channel-buffer.h"
61 #include "io/channel-file.h"
62 #include "system/replay.h"
63 #include "system/runstate.h"
64 #include "system/system.h"
65 #include "system/xen.h"
66 #include "migration/colo.h"
67 #include "qemu/bitmap.h"
68 #include "net/announce.h"
69 #include "qemu/yank.h"
70 #include "yank_functions.h"
71 #include "system/qtest.h"
72 #include "options.h"
73 
74 const unsigned int postcopy_ram_discard_version;
75 
76 /* Subcommands for QEMU_VM_COMMAND */
77 enum qemu_vm_cmd {
78     MIG_CMD_INVALID = 0,   /* Must be 0 */
79     MIG_CMD_OPEN_RETURN_PATH,  /* Tell the dest to open the Return path */
80     MIG_CMD_PING,              /* Request a PONG on the RP */
81 
82     MIG_CMD_POSTCOPY_ADVISE,       /* Prior to any page transfers, just
83                                       warn we might want to do PC */
84     MIG_CMD_POSTCOPY_LISTEN,       /* Start listening for incoming
85                                       pages as it's running. */
86     MIG_CMD_POSTCOPY_RUN,          /* Start execution */
87 
88     MIG_CMD_POSTCOPY_RAM_DISCARD,  /* A list of pages to discard that
89                                       were previously sent during
90                                       precopy but are dirty. */
91     MIG_CMD_PACKAGED,          /* Send a wrapped stream within this stream */
92     MIG_CMD_ENABLE_COLO,       /* Enable COLO */
93     MIG_CMD_POSTCOPY_RESUME,   /* resume postcopy on dest */
94     MIG_CMD_RECV_BITMAP,       /* Request for recved bitmap on dst */
95     MIG_CMD_SWITCHOVER_START,  /* Switchover start notification */
96     MIG_CMD_MAX
97 };
98 
99 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
100 static struct mig_cmd_args {
101     ssize_t     len; /* -1 = variable */
102     const char *name;
103 } mig_cmd_args[] = {
104     [MIG_CMD_INVALID]          = { .len = -1, .name = "INVALID" },
105     [MIG_CMD_OPEN_RETURN_PATH] = { .len =  0, .name = "OPEN_RETURN_PATH" },
106     [MIG_CMD_PING]             = { .len = sizeof(uint32_t), .name = "PING" },
107     [MIG_CMD_POSTCOPY_ADVISE]  = { .len = -1, .name = "POSTCOPY_ADVISE" },
108     [MIG_CMD_POSTCOPY_LISTEN]  = { .len =  0, .name = "POSTCOPY_LISTEN" },
109     [MIG_CMD_POSTCOPY_RUN]     = { .len =  0, .name = "POSTCOPY_RUN" },
110     [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
111                                    .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
112     [MIG_CMD_POSTCOPY_RESUME]  = { .len =  0, .name = "POSTCOPY_RESUME" },
113     [MIG_CMD_PACKAGED]         = { .len =  4, .name = "PACKAGED" },
114     [MIG_CMD_RECV_BITMAP]      = { .len = -1, .name = "RECV_BITMAP" },
115     [MIG_CMD_SWITCHOVER_START] = { .len =  0, .name = "SWITCHOVER_START" },
116     [MIG_CMD_MAX]              = { .len = -1, .name = "MAX" },
117 };
118 
119 /* Note for MIG_CMD_POSTCOPY_ADVISE:
120  * The format of arguments is depending on postcopy mode:
121  * - postcopy RAM only
122  *   uint64_t host page size
123  *   uint64_t target page size
124  *
125  * - postcopy RAM and postcopy dirty bitmaps
126  *   format is the same as for postcopy RAM only
127  *
128  * - postcopy dirty bitmaps only
129  *   Nothing. Command length field is 0.
130  *
131  * Be careful: adding a new postcopy entity with some other parameters should
132  * not break format self-description ability. Good way is to introduce some
133  * generic extendable format with an exception for two old entities.
134  */
135 
136 /***********************************************************/
137 /* Optional load threads pool support */
138 
139 static void qemu_loadvm_thread_pool_create(MigrationIncomingState *mis)
140 {
141     assert(!mis->load_threads);
142     mis->load_threads = thread_pool_new();
143     mis->load_threads_abort = false;
144 }
145 
146 static void qemu_loadvm_thread_pool_destroy(MigrationIncomingState *mis)
147 {
148     qatomic_set(&mis->load_threads_abort, true);
149 
150     bql_unlock(); /* Load threads might be waiting for BQL */
151     g_clear_pointer(&mis->load_threads, thread_pool_free);
152     bql_lock();
153 }
154 
155 static bool qemu_loadvm_thread_pool_wait(MigrationState *s,
156                                          MigrationIncomingState *mis)
157 {
158     bql_unlock(); /* Let load threads do work requiring BQL */
159     thread_pool_wait(mis->load_threads);
160     bql_lock();
161 
162     return !migrate_has_error(s);
163 }
164 
165 /***********************************************************/
166 /* savevm/loadvm support */
167 
168 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
169 {
170     if (is_writable) {
171         return qemu_file_new_output(QIO_CHANNEL(qio_channel_block_new(bs)));
172     } else {
173         return qemu_file_new_input(QIO_CHANNEL(qio_channel_block_new(bs)));
174     }
175 }
176 
177 
178 /* QEMUFile timer support.
179  * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
180  */
181 
182 void timer_put(QEMUFile *f, QEMUTimer *ts)
183 {
184     uint64_t expire_time;
185 
186     expire_time = timer_expire_time_ns(ts);
187     qemu_put_be64(f, expire_time);
188 }
189 
190 void timer_get(QEMUFile *f, QEMUTimer *ts)
191 {
192     uint64_t expire_time;
193 
194     expire_time = qemu_get_be64(f);
195     if (expire_time != -1) {
196         timer_mod_ns(ts, expire_time);
197     } else {
198         timer_del(ts);
199     }
200 }
201 
202 
203 /* VMState timer support.
204  * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
205  */
206 
207 static int get_timer(QEMUFile *f, void *pv, size_t size,
208                      const VMStateField *field)
209 {
210     QEMUTimer *v = pv;
211     timer_get(f, v);
212     return 0;
213 }
214 
215 static int put_timer(QEMUFile *f, void *pv, size_t size,
216                      const VMStateField *field, JSONWriter *vmdesc)
217 {
218     QEMUTimer *v = pv;
219     timer_put(f, v);
220 
221     return 0;
222 }
223 
224 const VMStateInfo vmstate_info_timer = {
225     .name = "timer",
226     .get  = get_timer,
227     .put  = put_timer,
228 };
229 
230 
231 typedef struct CompatEntry {
232     char idstr[256];
233     int instance_id;
234 } CompatEntry;
235 
236 typedef struct SaveStateEntry {
237     QTAILQ_ENTRY(SaveStateEntry) entry;
238     char idstr[256];
239     uint32_t instance_id;
240     int alias_id;
241     int version_id;
242     /* version id read from the stream */
243     int load_version_id;
244     int section_id;
245     /* section id read from the stream */
246     int load_section_id;
247     const SaveVMHandlers *ops;
248     const VMStateDescription *vmsd;
249     void *opaque;
250     CompatEntry *compat;
251     int is_ram;
252 } SaveStateEntry;
253 
254 typedef struct SaveState {
255     QTAILQ_HEAD(, SaveStateEntry) handlers;
256     SaveStateEntry *handler_pri_head[MIG_PRI_MAX + 1];
257     int global_section_id;
258     uint32_t len;
259     const char *name;
260     uint32_t target_page_bits;
261     uint32_t caps_count;
262     MigrationCapability *capabilities;
263     QemuUUID uuid;
264 } SaveState;
265 
266 static SaveState savevm_state = {
267     .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
268     .handler_pri_head = { [MIG_PRI_DEFAULT ... MIG_PRI_MAX] = NULL },
269     .global_section_id = 0,
270 };
271 
272 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id);
273 
274 static bool should_validate_capability(int capability)
275 {
276     assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
277     /* Validate only new capabilities to keep compatibility. */
278     switch (capability) {
279     case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
280     case MIGRATION_CAPABILITY_MAPPED_RAM:
281         return true;
282     default:
283         return false;
284     }
285 }
286 
287 static uint32_t get_validatable_capabilities_count(void)
288 {
289     MigrationState *s = migrate_get_current();
290     uint32_t result = 0;
291     int i;
292     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
293         if (should_validate_capability(i) && s->capabilities[i]) {
294             result++;
295         }
296     }
297     return result;
298 }
299 
300 static int configuration_pre_save(void *opaque)
301 {
302     SaveState *state = opaque;
303     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
304     MigrationState *s = migrate_get_current();
305     int i, j;
306 
307     state->len = strlen(current_name);
308     state->name = current_name;
309     state->target_page_bits = qemu_target_page_bits();
310 
311     state->caps_count = get_validatable_capabilities_count();
312     state->capabilities = g_renew(MigrationCapability, state->capabilities,
313                                   state->caps_count);
314     for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
315         if (should_validate_capability(i) && s->capabilities[i]) {
316             state->capabilities[j++] = i;
317         }
318     }
319     state->uuid = qemu_uuid;
320 
321     return 0;
322 }
323 
324 static int configuration_post_save(void *opaque)
325 {
326     SaveState *state = opaque;
327 
328     g_free(state->capabilities);
329     state->capabilities = NULL;
330     state->caps_count = 0;
331     return 0;
332 }
333 
334 static int configuration_pre_load(void *opaque)
335 {
336     SaveState *state = opaque;
337 
338     /* If there is no target-page-bits subsection it means the source
339      * predates the variable-target-page-bits support and is using the
340      * minimum possible value for this CPU.
341      */
342     state->target_page_bits = qemu_target_page_bits_min();
343     return 0;
344 }
345 
346 static bool configuration_validate_capabilities(SaveState *state)
347 {
348     bool ret = true;
349     MigrationState *s = migrate_get_current();
350     unsigned long *source_caps_bm;
351     int i;
352 
353     source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
354     for (i = 0; i < state->caps_count; i++) {
355         MigrationCapability capability = state->capabilities[i];
356         set_bit(capability, source_caps_bm);
357     }
358 
359     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
360         bool source_state, target_state;
361         if (!should_validate_capability(i)) {
362             continue;
363         }
364         source_state = test_bit(i, source_caps_bm);
365         target_state = s->capabilities[i];
366         if (source_state != target_state) {
367             error_report("Capability %s is %s, but received capability is %s",
368                          MigrationCapability_str(i),
369                          target_state ? "on" : "off",
370                          source_state ? "on" : "off");
371             ret = false;
372             /* Don't break here to report all failed capabilities */
373         }
374     }
375 
376     g_free(source_caps_bm);
377     return ret;
378 }
379 
380 static int configuration_post_load(void *opaque, int version_id)
381 {
382     SaveState *state = opaque;
383     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
384     int ret = 0;
385 
386     if (strncmp(state->name, current_name, state->len) != 0) {
387         error_report("Machine type received is '%.*s' and local is '%s'",
388                      (int) state->len, state->name, current_name);
389         ret = -EINVAL;
390         goto out;
391     }
392 
393     if (state->target_page_bits != qemu_target_page_bits()) {
394         error_report("Received TARGET_PAGE_BITS is %d but local is %d",
395                      state->target_page_bits, qemu_target_page_bits());
396         ret = -EINVAL;
397         goto out;
398     }
399 
400     if (!configuration_validate_capabilities(state)) {
401         ret = -EINVAL;
402         goto out;
403     }
404 
405 out:
406     g_free((void *)state->name);
407     state->name = NULL;
408     state->len = 0;
409     g_free(state->capabilities);
410     state->capabilities = NULL;
411     state->caps_count = 0;
412 
413     return ret;
414 }
415 
416 static int get_capability(QEMUFile *f, void *pv, size_t size,
417                           const VMStateField *field)
418 {
419     MigrationCapability *capability = pv;
420     char capability_str[UINT8_MAX + 1];
421     uint8_t len;
422     int i;
423 
424     len = qemu_get_byte(f);
425     qemu_get_buffer(f, (uint8_t *)capability_str, len);
426     capability_str[len] = '\0';
427     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
428         if (!strcmp(MigrationCapability_str(i), capability_str)) {
429             *capability = i;
430             return 0;
431         }
432     }
433     error_report("Received unknown capability %s", capability_str);
434     return -EINVAL;
435 }
436 
437 static int put_capability(QEMUFile *f, void *pv, size_t size,
438                           const VMStateField *field, JSONWriter *vmdesc)
439 {
440     MigrationCapability *capability = pv;
441     const char *capability_str = MigrationCapability_str(*capability);
442     size_t len = strlen(capability_str);
443     assert(len <= UINT8_MAX);
444 
445     qemu_put_byte(f, len);
446     qemu_put_buffer(f, (uint8_t *)capability_str, len);
447     return 0;
448 }
449 
450 static const VMStateInfo vmstate_info_capability = {
451     .name = "capability",
452     .get  = get_capability,
453     .put  = put_capability,
454 };
455 
456 /* The target-page-bits subsection is present only if the
457  * target page size is not the same as the default (ie the
458  * minimum page size for a variable-page-size guest CPU).
459  * If it is present then it contains the actual target page
460  * bits for the machine, and migration will fail if the
461  * two ends don't agree about it.
462  */
463 static bool vmstate_target_page_bits_needed(void *opaque)
464 {
465     return qemu_target_page_bits()
466         > qemu_target_page_bits_min();
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) {
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  * Calls the save_live_complete_postcopy methods
1489  * causing the last few pages to be sent immediately and doing any associated
1490  * cleanup.
1491  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1492  * all the other devices, but that happens at the point we switch to postcopy.
1493  */
1494 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1495 {
1496     SaveStateEntry *se;
1497     int ret;
1498 
1499     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1500         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1501             continue;
1502         }
1503         if (se->ops->is_active) {
1504             if (!se->ops->is_active(se->opaque)) {
1505                 continue;
1506             }
1507         }
1508         trace_savevm_section_start(se->idstr, se->section_id);
1509         /* Section type */
1510         qemu_put_byte(f, QEMU_VM_SECTION_END);
1511         qemu_put_be32(f, se->section_id);
1512 
1513         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1514         trace_savevm_section_end(se->idstr, se->section_id, ret);
1515         save_section_footer(f, se);
1516         if (ret < 0) {
1517             qemu_file_set_error(f, ret);
1518             return;
1519         }
1520     }
1521 
1522     qemu_put_byte(f, QEMU_VM_EOF);
1523     qemu_fflush(f);
1524 }
1525 
1526 int qemu_savevm_state_complete_precopy_iterable(QEMUFile *f, bool in_postcopy)
1527 {
1528     int64_t start_ts_each, end_ts_each;
1529     SaveStateEntry *se;
1530     int ret;
1531     bool multifd_device_state = multifd_device_state_supported();
1532 
1533     if (multifd_device_state) {
1534         QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1535             SaveLiveCompletePrecopyThreadHandler hdlr;
1536 
1537             if (!se->ops || (in_postcopy && se->ops->has_postcopy &&
1538                              se->ops->has_postcopy(se->opaque)) ||
1539                 !se->ops->save_live_complete_precopy_thread) {
1540                 continue;
1541             }
1542 
1543             hdlr = se->ops->save_live_complete_precopy_thread;
1544             multifd_spawn_device_state_save_thread(hdlr,
1545                                                    se->idstr, se->instance_id,
1546                                                    se->opaque);
1547         }
1548     }
1549 
1550     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1551         if (!se->ops ||
1552             (in_postcopy && se->ops->has_postcopy &&
1553              se->ops->has_postcopy(se->opaque)) ||
1554             !se->ops->save_live_complete_precopy) {
1555             continue;
1556         }
1557 
1558         if (se->ops->is_active) {
1559             if (!se->ops->is_active(se->opaque)) {
1560                 continue;
1561             }
1562         }
1563 
1564         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1565         trace_savevm_section_start(se->idstr, se->section_id);
1566 
1567         save_section_header(f, se, QEMU_VM_SECTION_END);
1568 
1569         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1570         trace_savevm_section_end(se->idstr, se->section_id, ret);
1571         save_section_footer(f, se);
1572         if (ret < 0) {
1573             qemu_file_set_error(f, ret);
1574             goto ret_fail_abort_threads;
1575         }
1576         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1577         trace_vmstate_downtime_save("iterable", se->idstr, se->instance_id,
1578                                     end_ts_each - start_ts_each);
1579     }
1580 
1581     if (multifd_device_state) {
1582         if (migrate_has_error(migrate_get_current())) {
1583             multifd_abort_device_state_save_threads();
1584         }
1585 
1586         if (!multifd_join_device_state_save_threads()) {
1587             qemu_file_set_error(f, -EINVAL);
1588             return -1;
1589         }
1590     }
1591 
1592     trace_vmstate_downtime_checkpoint("src-iterable-saved");
1593 
1594     return 0;
1595 
1596 ret_fail_abort_threads:
1597     if (multifd_device_state) {
1598         multifd_abort_device_state_save_threads();
1599         multifd_join_device_state_save_threads();
1600     }
1601 
1602     return -1;
1603 }
1604 
1605 int qemu_savevm_state_complete_precopy_non_iterable(QEMUFile *f,
1606                                                     bool in_postcopy)
1607 {
1608     MigrationState *ms = migrate_get_current();
1609     int64_t start_ts_each, end_ts_each;
1610     JSONWriter *vmdesc = ms->vmdesc;
1611     int vmdesc_len;
1612     SaveStateEntry *se;
1613     Error *local_err = NULL;
1614     int ret;
1615 
1616     /* Making sure cpu states are synchronized before saving non-iterable */
1617     cpu_synchronize_all_states();
1618 
1619     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1620         if (se->vmsd && se->vmsd->early_setup) {
1621             /* Already saved during qemu_savevm_state_setup(). */
1622             continue;
1623         }
1624 
1625         start_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1626 
1627         ret = vmstate_save(f, se, vmdesc, &local_err);
1628         if (ret) {
1629             migrate_set_error(ms, local_err);
1630             error_report_err(local_err);
1631             qemu_file_set_error(f, ret);
1632             return ret;
1633         }
1634 
1635         end_ts_each = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
1636         trace_vmstate_downtime_save("non-iterable", se->idstr, se->instance_id,
1637                                     end_ts_each - start_ts_each);
1638     }
1639 
1640     if (!in_postcopy) {
1641         /* Postcopy stream will still be going */
1642         qemu_put_byte(f, QEMU_VM_EOF);
1643 
1644         if (vmdesc) {
1645             json_writer_end_array(vmdesc);
1646             json_writer_end_object(vmdesc);
1647             vmdesc_len = strlen(json_writer_get(vmdesc));
1648 
1649             qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1650             qemu_put_be32(f, vmdesc_len);
1651             qemu_put_buffer(f, (uint8_t *)json_writer_get(vmdesc), vmdesc_len);
1652         }
1653     }
1654 
1655     trace_vmstate_downtime_checkpoint("src-non-iterable-saved");
1656 
1657     return 0;
1658 }
1659 
1660 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only)
1661 {
1662     int ret;
1663 
1664     ret = qemu_savevm_state_complete_precopy_iterable(f, false);
1665     if (ret) {
1666         return ret;
1667     }
1668 
1669     if (!iterable_only) {
1670         ret = qemu_savevm_state_complete_precopy_non_iterable(f, false);
1671         if (ret) {
1672             return ret;
1673         }
1674     }
1675 
1676     return qemu_fflush(f);
1677 }
1678 
1679 /* Give an estimate of the amount left to be transferred,
1680  * the result is split into the amount for units that can and
1681  * for units that can't do postcopy.
1682  */
1683 void qemu_savevm_state_pending_estimate(uint64_t *must_precopy,
1684                                         uint64_t *can_postcopy)
1685 {
1686     SaveStateEntry *se;
1687 
1688     *must_precopy = 0;
1689     *can_postcopy = 0;
1690 
1691     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1692         if (!se->ops || !se->ops->state_pending_estimate) {
1693             continue;
1694         }
1695         if (se->ops->is_active) {
1696             if (!se->ops->is_active(se->opaque)) {
1697                 continue;
1698             }
1699         }
1700         se->ops->state_pending_estimate(se->opaque, must_precopy, can_postcopy);
1701     }
1702 }
1703 
1704 void qemu_savevm_state_pending_exact(uint64_t *must_precopy,
1705                                      uint64_t *can_postcopy)
1706 {
1707     SaveStateEntry *se;
1708 
1709     *must_precopy = 0;
1710     *can_postcopy = 0;
1711 
1712     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1713         if (!se->ops || !se->ops->state_pending_exact) {
1714             continue;
1715         }
1716         if (se->ops->is_active) {
1717             if (!se->ops->is_active(se->opaque)) {
1718                 continue;
1719             }
1720         }
1721         se->ops->state_pending_exact(se->opaque, must_precopy, can_postcopy);
1722     }
1723 }
1724 
1725 void qemu_savevm_state_cleanup(void)
1726 {
1727     SaveStateEntry *se;
1728     Error *local_err = NULL;
1729 
1730     if (precopy_notify(PRECOPY_NOTIFY_CLEANUP, &local_err)) {
1731         error_report_err(local_err);
1732     }
1733 
1734     trace_savevm_state_cleanup();
1735     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1736         if (se->ops && se->ops->save_cleanup) {
1737             se->ops->save_cleanup(se->opaque);
1738         }
1739     }
1740 }
1741 
1742 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1743 {
1744     int ret;
1745     MigrationState *ms = migrate_get_current();
1746     MigrationStatus status;
1747 
1748     if (migration_is_running()) {
1749         error_setg(errp, "There's a migration process in progress");
1750         return -EINVAL;
1751     }
1752 
1753     ret = migrate_init(ms, errp);
1754     if (ret) {
1755         return ret;
1756     }
1757     ms->to_dst_file = f;
1758 
1759     qemu_savevm_state_header(f);
1760     ret = qemu_savevm_state_setup(f, errp);
1761     if (ret) {
1762         goto cleanup;
1763     }
1764 
1765     while (qemu_file_get_error(f) == 0) {
1766         if (qemu_savevm_state_iterate(f, false) > 0) {
1767             break;
1768         }
1769     }
1770 
1771     ret = qemu_file_get_error(f);
1772     if (ret == 0) {
1773         qemu_savevm_maybe_send_switchover_start(f);
1774         qemu_savevm_state_complete_precopy(f, false);
1775         ret = qemu_file_get_error(f);
1776     }
1777     if (ret != 0) {
1778         error_setg_errno(errp, -ret, "Error while writing VM state");
1779     }
1780 cleanup:
1781     qemu_savevm_state_cleanup();
1782 
1783     if (ret != 0) {
1784         status = MIGRATION_STATUS_FAILED;
1785     } else {
1786         status = MIGRATION_STATUS_COMPLETED;
1787     }
1788     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1789 
1790     /* f is outer parameter, it should not stay in global migration state after
1791      * this function finished */
1792     ms->to_dst_file = NULL;
1793 
1794     return ret;
1795 }
1796 
1797 void qemu_savevm_live_state(QEMUFile *f)
1798 {
1799     /* save QEMU_VM_SECTION_END section */
1800     qemu_savevm_state_complete_precopy(f, true);
1801     qemu_put_byte(f, QEMU_VM_EOF);
1802 }
1803 
1804 int qemu_save_device_state(QEMUFile *f)
1805 {
1806     MigrationState *ms = migrate_get_current();
1807     Error *local_err = NULL;
1808     SaveStateEntry *se;
1809 
1810     if (!migration_in_colo_state()) {
1811         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1812         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1813     }
1814     cpu_synchronize_all_states();
1815 
1816     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1817         int ret;
1818 
1819         if (se->is_ram) {
1820             continue;
1821         }
1822         ret = vmstate_save(f, se, NULL, &local_err);
1823         if (ret) {
1824             migrate_set_error(ms, local_err);
1825             error_report_err(local_err);
1826             return ret;
1827         }
1828     }
1829 
1830     qemu_put_byte(f, QEMU_VM_EOF);
1831 
1832     return qemu_file_get_error(f);
1833 }
1834 
1835 static SaveStateEntry *find_se(const char *idstr, uint32_t instance_id)
1836 {
1837     SaveStateEntry *se;
1838 
1839     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1840         if (!strcmp(se->idstr, idstr) &&
1841             (instance_id == se->instance_id ||
1842              instance_id == se->alias_id))
1843             return se;
1844         /* Migrating from an older version? */
1845         if (strstr(se->idstr, idstr) && se->compat) {
1846             if (!strcmp(se->compat->idstr, idstr) &&
1847                 (instance_id == se->compat->instance_id ||
1848                  instance_id == se->alias_id))
1849                 return se;
1850         }
1851     }
1852     return NULL;
1853 }
1854 
1855 enum LoadVMExitCodes {
1856     /* Allow a command to quit all layers of nested loadvm loops */
1857     LOADVM_QUIT     =  1,
1858 };
1859 
1860 /* ------ incoming postcopy messages ------ */
1861 /* 'advise' arrives before any transfers just to tell us that a postcopy
1862  * *might* happen - it might be skipped if precopy transferred everything
1863  * quickly.
1864  */
1865 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1866                                          uint16_t len)
1867 {
1868     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1869     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1870     size_t page_size = qemu_target_page_size();
1871     Error *local_err = NULL;
1872 
1873     trace_loadvm_postcopy_handle_advise();
1874     if (ps != POSTCOPY_INCOMING_NONE) {
1875         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1876         return -1;
1877     }
1878 
1879     switch (len) {
1880     case 0:
1881         if (migrate_postcopy_ram()) {
1882             error_report("RAM postcopy is enabled but have 0 byte advise");
1883             return -EINVAL;
1884         }
1885         return 0;
1886     case 8 + 8:
1887         if (!migrate_postcopy_ram()) {
1888             error_report("RAM postcopy is disabled but have 16 byte advise");
1889             return -EINVAL;
1890         }
1891         break;
1892     default:
1893         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1894         return -EINVAL;
1895     }
1896 
1897     if (!postcopy_ram_supported_by_host(mis, &local_err)) {
1898         error_report_err(local_err);
1899         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1900         return -1;
1901     }
1902 
1903     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1904     local_pagesize_summary = ram_pagesize_summary();
1905 
1906     if (remote_pagesize_summary != local_pagesize_summary)  {
1907         /*
1908          * This detects two potential causes of mismatch:
1909          *   a) A mismatch in host page sizes
1910          *      Some combinations of mismatch are probably possible but it gets
1911          *      a bit more complicated.  In particular we need to place whole
1912          *      host pages on the dest at once, and we need to ensure that we
1913          *      handle dirtying to make sure we never end up sending part of
1914          *      a hostpage on it's own.
1915          *   b) The use of different huge page sizes on source/destination
1916          *      a more fine grain test is performed during RAM block migration
1917          *      but this test here causes a nice early clear failure, and
1918          *      also fails when passed to an older qemu that doesn't
1919          *      do huge pages.
1920          */
1921         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1922                                                              " d=%" PRIx64 ")",
1923                      remote_pagesize_summary, local_pagesize_summary);
1924         return -1;
1925     }
1926 
1927     remote_tps = qemu_get_be64(mis->from_src_file);
1928     if (remote_tps != page_size) {
1929         /*
1930          * Again, some differences could be dealt with, but for now keep it
1931          * simple.
1932          */
1933         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1934                      (int)remote_tps, page_size);
1935         return -1;
1936     }
1937 
1938     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1939         error_report_err(local_err);
1940         return -1;
1941     }
1942 
1943     if (ram_postcopy_incoming_init(mis)) {
1944         return -1;
1945     }
1946 
1947     return 0;
1948 }
1949 
1950 /* After postcopy we will be told to throw some pages away since they're
1951  * dirty and will have to be demand fetched.  Must happen before CPU is
1952  * started.
1953  * There can be 0..many of these messages, each encoding multiple pages.
1954  */
1955 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1956                                               uint16_t len)
1957 {
1958     int tmp;
1959     char ramid[256];
1960     PostcopyState ps = postcopy_state_get();
1961 
1962     trace_loadvm_postcopy_ram_handle_discard();
1963 
1964     switch (ps) {
1965     case POSTCOPY_INCOMING_ADVISE:
1966         /* 1st discard */
1967         tmp = postcopy_ram_prepare_discard(mis);
1968         if (tmp) {
1969             return tmp;
1970         }
1971         break;
1972 
1973     case POSTCOPY_INCOMING_DISCARD:
1974         /* Expected state */
1975         break;
1976 
1977     default:
1978         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1979                      ps);
1980         return -1;
1981     }
1982     /* We're expecting a
1983      *    Version (0)
1984      *    a RAM ID string (length byte, name, 0 term)
1985      *    then at least 1 16 byte chunk
1986     */
1987     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1988         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1989         return -1;
1990     }
1991 
1992     tmp = qemu_get_byte(mis->from_src_file);
1993     if (tmp != postcopy_ram_discard_version) {
1994         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1995         return -1;
1996     }
1997 
1998     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1999         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
2000         return -1;
2001     }
2002     tmp = qemu_get_byte(mis->from_src_file);
2003     if (tmp != 0) {
2004         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
2005         return -1;
2006     }
2007 
2008     len -= 3 + strlen(ramid);
2009     if (len % 16) {
2010         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
2011         return -1;
2012     }
2013     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
2014     while (len) {
2015         uint64_t start_addr, block_length;
2016         start_addr = qemu_get_be64(mis->from_src_file);
2017         block_length = qemu_get_be64(mis->from_src_file);
2018 
2019         len -= 16;
2020         int ret = ram_discard_range(ramid, start_addr, block_length);
2021         if (ret) {
2022             return ret;
2023         }
2024     }
2025     trace_loadvm_postcopy_ram_handle_discard_end();
2026 
2027     return 0;
2028 }
2029 
2030 /*
2031  * Triggered by a postcopy_listen command; this thread takes over reading
2032  * the input stream, leaving the main thread free to carry on loading the rest
2033  * of the device state (from RAM).
2034  * (TODO:This could do with being in a postcopy file - but there again it's
2035  * just another input loop, not that postcopy specific)
2036  */
2037 static void *postcopy_ram_listen_thread(void *opaque)
2038 {
2039     MigrationIncomingState *mis = migration_incoming_get_current();
2040     QEMUFile *f = mis->from_src_file;
2041     int load_res;
2042     MigrationState *migr = migrate_get_current();
2043 
2044     object_ref(OBJECT(migr));
2045 
2046     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
2047                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
2048     qemu_sem_post(&mis->thread_sync_sem);
2049     trace_postcopy_ram_listen_thread_start();
2050 
2051     rcu_register_thread();
2052     /*
2053      * Because we're a thread and not a coroutine we can't yield
2054      * in qemu_file, and thus we must be blocking now.
2055      */
2056     qemu_file_set_blocking(f, true);
2057 
2058     /* TODO: sanity check that only postcopiable data will be loaded here */
2059     load_res = qemu_loadvm_state_main(f, mis);
2060 
2061     /*
2062      * This is tricky, but, mis->from_src_file can change after it
2063      * returns, when postcopy recovery happened. In the future, we may
2064      * want a wrapper for the QEMUFile handle.
2065      */
2066     f = mis->from_src_file;
2067 
2068     /* And non-blocking again so we don't block in any cleanup */
2069     qemu_file_set_blocking(f, false);
2070 
2071     trace_postcopy_ram_listen_thread_exit();
2072     if (load_res < 0) {
2073         qemu_file_set_error(f, load_res);
2074         dirty_bitmap_mig_cancel_incoming();
2075         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2076             !migrate_postcopy_ram() && migrate_dirty_bitmaps())
2077         {
2078             error_report("%s: loadvm failed during postcopy: %d. All states "
2079                          "are migrated except dirty bitmaps. Some dirty "
2080                          "bitmaps may be lost, and present migrated dirty "
2081                          "bitmaps are correctly migrated and valid.",
2082                          __func__, load_res);
2083             load_res = 0; /* prevent further exit() */
2084         } else {
2085             error_report("%s: loadvm failed: %d", __func__, load_res);
2086             migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2087                                            MIGRATION_STATUS_FAILED);
2088         }
2089     }
2090     if (load_res >= 0) {
2091         /*
2092          * This looks good, but it's possible that the device loading in the
2093          * main thread hasn't finished yet, and so we might not be in 'RUN'
2094          * state yet; wait for the end of the main thread.
2095          */
2096         qemu_event_wait(&mis->main_thread_load_event);
2097     }
2098     postcopy_ram_incoming_cleanup(mis);
2099 
2100     if (load_res < 0) {
2101         /*
2102          * If something went wrong then we have a bad state so exit;
2103          * depending how far we got it might be possible at this point
2104          * to leave the guest running and fire MCEs for pages that never
2105          * arrived as a desperate recovery step.
2106          */
2107         rcu_unregister_thread();
2108         exit(EXIT_FAILURE);
2109     }
2110 
2111     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2112                                    MIGRATION_STATUS_COMPLETED);
2113     /*
2114      * If everything has worked fine, then the main thread has waited
2115      * for us to start, and we're the last use of the mis.
2116      * (If something broke then qemu will have to exit anyway since it's
2117      * got a bad migration state).
2118      */
2119     bql_lock();
2120     migration_incoming_state_destroy();
2121     bql_unlock();
2122 
2123     rcu_unregister_thread();
2124     mis->have_listen_thread = false;
2125     postcopy_state_set(POSTCOPY_INCOMING_END);
2126 
2127     object_unref(OBJECT(migr));
2128 
2129     return NULL;
2130 }
2131 
2132 /* After this message we must be able to immediately receive postcopy data */
2133 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
2134 {
2135     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
2136     Error *local_err = NULL;
2137 
2138     trace_loadvm_postcopy_handle_listen("enter");
2139 
2140     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
2141         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
2142         return -1;
2143     }
2144     if (ps == POSTCOPY_INCOMING_ADVISE) {
2145         /*
2146          * A rare case, we entered listen without having to do any discards,
2147          * so do the setup that's normally done at the time of the 1st discard.
2148          */
2149         if (migrate_postcopy_ram()) {
2150             postcopy_ram_prepare_discard(mis);
2151         }
2152     }
2153 
2154     trace_loadvm_postcopy_handle_listen("after discard");
2155 
2156     /*
2157      * Sensitise RAM - can now generate requests for blocks that don't exist
2158      * However, at this point the CPU shouldn't be running, and the IO
2159      * shouldn't be doing anything yet so don't actually expect requests
2160      */
2161     if (migrate_postcopy_ram()) {
2162         if (postcopy_ram_incoming_setup(mis)) {
2163             postcopy_ram_incoming_cleanup(mis);
2164             return -1;
2165         }
2166     }
2167 
2168     trace_loadvm_postcopy_handle_listen("after uffd");
2169 
2170     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
2171         error_report_err(local_err);
2172         return -1;
2173     }
2174 
2175     mis->have_listen_thread = true;
2176     postcopy_thread_create(mis, &mis->listen_thread,
2177                            MIGRATION_THREAD_DST_LISTEN,
2178                            postcopy_ram_listen_thread, QEMU_THREAD_DETACHED);
2179     trace_loadvm_postcopy_handle_listen("return");
2180 
2181     return 0;
2182 }
2183 
2184 static void loadvm_postcopy_handle_run_bh(void *opaque)
2185 {
2186     MigrationIncomingState *mis = opaque;
2187 
2188     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-enter");
2189 
2190     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
2191      * in migration.c
2192      */
2193     cpu_synchronize_all_post_init();
2194 
2195     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cpu-synced");
2196 
2197     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
2198 
2199     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-announced");
2200 
2201     dirty_bitmap_mig_before_vm_start();
2202 
2203     if (autostart) {
2204         /*
2205          * Make sure all file formats throw away their mutable metadata.
2206          * If we get an error here, just don't restart the VM yet.
2207          */
2208         bool success = migration_block_activate(NULL);
2209 
2210         trace_vmstate_downtime_checkpoint("dst-postcopy-bh-cache-invalidated");
2211 
2212         if (success) {
2213             vm_start();
2214         }
2215     } else {
2216         /* leave it paused and let management decide when to start the CPU */
2217         runstate_set(RUN_STATE_PAUSED);
2218     }
2219 
2220     trace_vmstate_downtime_checkpoint("dst-postcopy-bh-vm-started");
2221 }
2222 
2223 /* After all discards we can start running and asking for pages */
2224 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
2225 {
2226     PostcopyState ps = postcopy_state_get();
2227 
2228     trace_loadvm_postcopy_handle_run();
2229     if (ps != POSTCOPY_INCOMING_LISTENING) {
2230         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
2231         return -1;
2232     }
2233 
2234     postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
2235     migration_bh_schedule(loadvm_postcopy_handle_run_bh, mis);
2236 
2237     /* We need to finish reading the stream from the package
2238      * and also stop reading anything more from the stream that loaded the
2239      * package (since it's now being read by the listener thread).
2240      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
2241      */
2242     return LOADVM_QUIT;
2243 }
2244 
2245 /* We must be with page_request_mutex held */
2246 static gboolean postcopy_sync_page_req(gpointer key, gpointer value,
2247                                        gpointer data)
2248 {
2249     MigrationIncomingState *mis = data;
2250     void *host_addr = (void *) key;
2251     ram_addr_t rb_offset;
2252     RAMBlock *rb;
2253     int ret;
2254 
2255     rb = qemu_ram_block_from_host(host_addr, true, &rb_offset);
2256     if (!rb) {
2257         /*
2258          * This should _never_ happen.  However be nice for a migrating VM to
2259          * not crash/assert.  Post an error (note: intended to not use *_once
2260          * because we do want to see all the illegal addresses; and this can
2261          * never be triggered by the guest so we're safe) and move on next.
2262          */
2263         error_report("%s: illegal host addr %p", __func__, host_addr);
2264         /* Try the next entry */
2265         return FALSE;
2266     }
2267 
2268     ret = migrate_send_rp_message_req_pages(mis, rb, rb_offset);
2269     if (ret) {
2270         /* Please refer to above comment. */
2271         error_report("%s: send rp message failed for addr %p",
2272                      __func__, host_addr);
2273         return FALSE;
2274     }
2275 
2276     trace_postcopy_page_req_sync(host_addr);
2277 
2278     return FALSE;
2279 }
2280 
2281 static void migrate_send_rp_req_pages_pending(MigrationIncomingState *mis)
2282 {
2283     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
2284         g_tree_foreach(mis->page_requested, postcopy_sync_page_req, mis);
2285     }
2286 }
2287 
2288 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
2289 {
2290     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
2291         error_report("%s: illegal resume received", __func__);
2292         /* Don't fail the load, only for this. */
2293         return 0;
2294     }
2295 
2296     /*
2297      * Reset the last_rb before we resend any page req to source again, since
2298      * the source should have it reset already.
2299      */
2300     mis->last_rb = NULL;
2301 
2302     /*
2303      * This means source VM is ready to resume the postcopy migration.
2304      */
2305     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2306                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2307 
2308     trace_loadvm_postcopy_handle_resume();
2309 
2310     /* Tell source that "we are ready" */
2311     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
2312 
2313     /*
2314      * After a postcopy recovery, the source should have lost the postcopy
2315      * queue, or potentially the requested pages could have been lost during
2316      * the network down phase.  Let's re-sync with the source VM by re-sending
2317      * all the pending pages that we eagerly need, so these threads won't get
2318      * blocked too long due to the recovery.
2319      *
2320      * Without this procedure, the faulted destination VM threads (waiting for
2321      * page requests right before the postcopy is interrupted) can keep hanging
2322      * until the pages are sent by the source during the background copying of
2323      * pages, or another thread faulted on the same address accidentally.
2324      */
2325     migrate_send_rp_req_pages_pending(mis);
2326 
2327     /*
2328      * It's time to switch state and release the fault thread to continue
2329      * service page faults.  Note that this should be explicitly after the
2330      * above call to migrate_send_rp_req_pages_pending().  In short:
2331      * migrate_send_rp_message_req_pages() is not thread safe, yet.
2332      */
2333     qemu_sem_post(&mis->postcopy_pause_sem_fault);
2334 
2335     if (migrate_postcopy_preempt()) {
2336         /*
2337          * The preempt channel will be created in async manner, now let's
2338          * wait for it and make sure it's created.
2339          */
2340         qemu_sem_wait(&mis->postcopy_qemufile_dst_done);
2341         assert(mis->postcopy_qemufile_dst);
2342         /* Kick the fast ram load thread too */
2343         qemu_sem_post(&mis->postcopy_pause_sem_fast_load);
2344     }
2345 
2346     return 0;
2347 }
2348 
2349 /**
2350  * Immediately following this command is a blob of data containing an embedded
2351  * chunk of migration stream; read it and load it.
2352  *
2353  * @mis: Incoming state
2354  * @length: Length of packaged data to read
2355  *
2356  * Returns: Negative values on error
2357  *
2358  */
2359 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
2360 {
2361     int ret;
2362     size_t length;
2363     QIOChannelBuffer *bioc;
2364 
2365     length = qemu_get_be32(mis->from_src_file);
2366     trace_loadvm_handle_cmd_packaged(length);
2367 
2368     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
2369         error_report("Unreasonably large packaged state: %zu", length);
2370         return -1;
2371     }
2372 
2373     bioc = qio_channel_buffer_new(length);
2374     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
2375     ret = qemu_get_buffer(mis->from_src_file,
2376                           bioc->data,
2377                           length);
2378     if (ret != length) {
2379         object_unref(OBJECT(bioc));
2380         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
2381                      ret, length);
2382         return (ret < 0) ? ret : -EAGAIN;
2383     }
2384     bioc->usage += length;
2385     trace_loadvm_handle_cmd_packaged_received(ret);
2386 
2387     QEMUFile *packf = qemu_file_new_input(QIO_CHANNEL(bioc));
2388 
2389     /*
2390      * Before loading the guest states, ensure that the preempt channel has
2391      * been ready to use, as some of the states (e.g. via virtio_load) might
2392      * trigger page faults that will be handled through the preempt channel.
2393      * So yield to the main thread in the case that the channel create event
2394      * hasn't been dispatched.
2395      *
2396      * TODO: if we can move migration loadvm out of main thread, then we
2397      * won't block main thread from polling the accept() fds.  We can drop
2398      * this as a whole when that is done.
2399      */
2400     do {
2401         if (!migrate_postcopy_preempt() || !qemu_in_coroutine() ||
2402             mis->postcopy_qemufile_dst) {
2403             break;
2404         }
2405 
2406         aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
2407         qemu_coroutine_yield();
2408     } while (1);
2409 
2410     ret = qemu_loadvm_state_main(packf, mis);
2411     trace_loadvm_handle_cmd_packaged_main(ret);
2412     qemu_fclose(packf);
2413     object_unref(OBJECT(bioc));
2414 
2415     return ret;
2416 }
2417 
2418 /*
2419  * Handle request that source requests for recved_bitmap on
2420  * destination. Payload format:
2421  *
2422  * len (1 byte) + ramblock_name (<255 bytes)
2423  */
2424 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
2425                                      uint16_t len)
2426 {
2427     QEMUFile *file = mis->from_src_file;
2428     RAMBlock *rb;
2429     char block_name[256];
2430     size_t cnt;
2431 
2432     cnt = qemu_get_counted_string(file, block_name);
2433     if (!cnt) {
2434         error_report("%s: failed to read block name", __func__);
2435         return -EINVAL;
2436     }
2437 
2438     /* Validate before using the data */
2439     if (qemu_file_get_error(file)) {
2440         return qemu_file_get_error(file);
2441     }
2442 
2443     if (len != cnt + 1) {
2444         error_report("%s: invalid payload length (%d)", __func__, len);
2445         return -EINVAL;
2446     }
2447 
2448     rb = qemu_ram_block_by_name(block_name);
2449     if (!rb) {
2450         error_report("%s: block '%s' not found", __func__, block_name);
2451         return -EINVAL;
2452     }
2453 
2454     migrate_send_rp_recv_bitmap(mis, block_name);
2455 
2456     trace_loadvm_handle_recv_bitmap(block_name);
2457 
2458     return 0;
2459 }
2460 
2461 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2462 {
2463     int ret = migration_incoming_enable_colo();
2464 
2465     if (!ret) {
2466         ret = colo_init_ram_cache();
2467         if (ret) {
2468             migration_incoming_disable_colo();
2469         }
2470     }
2471     return ret;
2472 }
2473 
2474 static int loadvm_postcopy_handle_switchover_start(void)
2475 {
2476     SaveStateEntry *se;
2477 
2478     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2479         int ret;
2480 
2481         if (!se->ops || !se->ops->switchover_start) {
2482             continue;
2483         }
2484 
2485         ret = se->ops->switchover_start(se->opaque);
2486         if (ret < 0) {
2487             return ret;
2488         }
2489     }
2490 
2491     return 0;
2492 }
2493 
2494 /*
2495  * Process an incoming 'QEMU_VM_COMMAND'
2496  * 0           just a normal return
2497  * LOADVM_QUIT All good, but exit the loop
2498  * <0          Error
2499  */
2500 static int loadvm_process_command(QEMUFile *f)
2501 {
2502     MigrationIncomingState *mis = migration_incoming_get_current();
2503     uint16_t cmd;
2504     uint16_t len;
2505     uint32_t tmp32;
2506 
2507     cmd = qemu_get_be16(f);
2508     len = qemu_get_be16(f);
2509 
2510     /* Check validity before continue processing of cmds */
2511     if (qemu_file_get_error(f)) {
2512         return qemu_file_get_error(f);
2513     }
2514 
2515     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2516         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2517         return -EINVAL;
2518     }
2519 
2520     trace_loadvm_process_command(mig_cmd_args[cmd].name, len);
2521 
2522     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2523         error_report("%s received with bad length - expecting %zu, got %d",
2524                      mig_cmd_args[cmd].name,
2525                      (size_t)mig_cmd_args[cmd].len, len);
2526         return -ERANGE;
2527     }
2528 
2529     switch (cmd) {
2530     case MIG_CMD_OPEN_RETURN_PATH:
2531         if (mis->to_src_file) {
2532             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2533             /* Not really a problem, so don't give up */
2534             return 0;
2535         }
2536         mis->to_src_file = qemu_file_get_return_path(f);
2537         if (!mis->to_src_file) {
2538             error_report("CMD_OPEN_RETURN_PATH failed");
2539             return -1;
2540         }
2541 
2542         /*
2543          * Switchover ack is enabled but no device uses it, so send an ACK to
2544          * source that it's OK to switchover. Do it here, after return path has
2545          * been created.
2546          */
2547         if (migrate_switchover_ack() && !mis->switchover_ack_pending_num) {
2548             int ret = migrate_send_rp_switchover_ack(mis);
2549             if (ret) {
2550                 error_report(
2551                     "Could not send switchover ack RP MSG, err %d (%s)", ret,
2552                     strerror(-ret));
2553                 return ret;
2554             }
2555         }
2556         break;
2557 
2558     case MIG_CMD_PING:
2559         tmp32 = qemu_get_be32(f);
2560         trace_loadvm_process_command_ping(tmp32);
2561         if (!mis->to_src_file) {
2562             error_report("CMD_PING (0x%x) received with no return path",
2563                          tmp32);
2564             return -1;
2565         }
2566         migrate_send_rp_pong(mis, tmp32);
2567         break;
2568 
2569     case MIG_CMD_PACKAGED:
2570         return loadvm_handle_cmd_packaged(mis);
2571 
2572     case MIG_CMD_POSTCOPY_ADVISE:
2573         return loadvm_postcopy_handle_advise(mis, len);
2574 
2575     case MIG_CMD_POSTCOPY_LISTEN:
2576         return loadvm_postcopy_handle_listen(mis);
2577 
2578     case MIG_CMD_POSTCOPY_RUN:
2579         return loadvm_postcopy_handle_run(mis);
2580 
2581     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2582         return loadvm_postcopy_ram_handle_discard(mis, len);
2583 
2584     case MIG_CMD_POSTCOPY_RESUME:
2585         return loadvm_postcopy_handle_resume(mis);
2586 
2587     case MIG_CMD_RECV_BITMAP:
2588         return loadvm_handle_recv_bitmap(mis, len);
2589 
2590     case MIG_CMD_ENABLE_COLO:
2591         return loadvm_process_enable_colo(mis);
2592 
2593     case MIG_CMD_SWITCHOVER_START:
2594         return loadvm_postcopy_handle_switchover_start();
2595     }
2596 
2597     return 0;
2598 }
2599 
2600 /*
2601  * Read a footer off the wire and check that it matches the expected section
2602  *
2603  * Returns: true if the footer was good
2604  *          false if there is a problem (and calls error_report to say why)
2605  */
2606 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2607 {
2608     int ret;
2609     uint8_t read_mark;
2610     uint32_t read_section_id;
2611 
2612     if (!migrate_get_current()->send_section_footer) {
2613         /* No footer to check */
2614         return true;
2615     }
2616 
2617     read_mark = qemu_get_byte(f);
2618 
2619     ret = qemu_file_get_error(f);
2620     if (ret) {
2621         error_report("%s: Read section footer failed: %d",
2622                      __func__, ret);
2623         return false;
2624     }
2625 
2626     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2627         error_report("Missing section footer for %s", se->idstr);
2628         return false;
2629     }
2630 
2631     read_section_id = qemu_get_be32(f);
2632     if (read_section_id != se->load_section_id) {
2633         error_report("Mismatched section id in footer for %s -"
2634                      " read 0x%x expected 0x%x",
2635                      se->idstr, read_section_id, se->load_section_id);
2636         return false;
2637     }
2638 
2639     /* All good */
2640     return true;
2641 }
2642 
2643 static int
2644 qemu_loadvm_section_start_full(QEMUFile *f, uint8_t type)
2645 {
2646     bool trace_downtime = (type == QEMU_VM_SECTION_FULL);
2647     uint32_t instance_id, version_id, section_id;
2648     int64_t start_ts, end_ts;
2649     SaveStateEntry *se;
2650     char idstr[256];
2651     int ret;
2652 
2653     /* Read section start */
2654     section_id = qemu_get_be32(f);
2655     if (!qemu_get_counted_string(f, idstr)) {
2656         error_report("Unable to read ID string for section %u",
2657                      section_id);
2658         return -EINVAL;
2659     }
2660     instance_id = qemu_get_be32(f);
2661     version_id = qemu_get_be32(f);
2662 
2663     ret = qemu_file_get_error(f);
2664     if (ret) {
2665         error_report("%s: Failed to read instance/version ID: %d",
2666                      __func__, ret);
2667         return ret;
2668     }
2669 
2670     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2671             instance_id, version_id);
2672     /* Find savevm section */
2673     se = find_se(idstr, instance_id);
2674     if (se == NULL) {
2675         error_report("Unknown savevm section or instance '%s' %"PRIu32". "
2676                      "Make sure that your current VM setup matches your "
2677                      "saved VM setup, including any hotplugged devices",
2678                      idstr, instance_id);
2679         return -EINVAL;
2680     }
2681 
2682     /* Validate version */
2683     if (version_id > se->version_id) {
2684         error_report("savevm: unsupported version %d for '%s' v%d",
2685                      version_id, idstr, se->version_id);
2686         return -EINVAL;
2687     }
2688     se->load_version_id = version_id;
2689     se->load_section_id = section_id;
2690 
2691     /* Validate if it is a device's state */
2692     if (xen_enabled() && se->is_ram) {
2693         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2694         return -EINVAL;
2695     }
2696 
2697     if (trace_downtime) {
2698         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2699     }
2700 
2701     ret = vmstate_load(f, se);
2702     if (ret < 0) {
2703         error_report("error while loading state for instance 0x%"PRIx32" of"
2704                      " device '%s'", instance_id, idstr);
2705         return ret;
2706     }
2707 
2708     if (trace_downtime) {
2709         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2710         trace_vmstate_downtime_load("non-iterable", se->idstr,
2711                                     se->instance_id, end_ts - start_ts);
2712     }
2713 
2714     if (!check_section_footer(f, se)) {
2715         return -EINVAL;
2716     }
2717 
2718     return 0;
2719 }
2720 
2721 static int
2722 qemu_loadvm_section_part_end(QEMUFile *f, uint8_t type)
2723 {
2724     bool trace_downtime = (type == QEMU_VM_SECTION_END);
2725     int64_t start_ts, end_ts;
2726     uint32_t section_id;
2727     SaveStateEntry *se;
2728     int ret;
2729 
2730     section_id = qemu_get_be32(f);
2731 
2732     ret = qemu_file_get_error(f);
2733     if (ret) {
2734         error_report("%s: Failed to read section ID: %d",
2735                      __func__, ret);
2736         return ret;
2737     }
2738 
2739     trace_qemu_loadvm_state_section_partend(section_id);
2740     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2741         if (se->load_section_id == section_id) {
2742             break;
2743         }
2744     }
2745     if (se == NULL) {
2746         error_report("Unknown savevm section %d", section_id);
2747         return -EINVAL;
2748     }
2749 
2750     if (trace_downtime) {
2751         start_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2752     }
2753 
2754     ret = vmstate_load(f, se);
2755     if (ret < 0) {
2756         error_report("error while loading state section id %d(%s)",
2757                      section_id, se->idstr);
2758         return ret;
2759     }
2760 
2761     if (trace_downtime) {
2762         end_ts = qemu_clock_get_us(QEMU_CLOCK_REALTIME);
2763         trace_vmstate_downtime_load("iterable", se->idstr,
2764                                     se->instance_id, end_ts - start_ts);
2765     }
2766 
2767     if (!check_section_footer(f, se)) {
2768         return -EINVAL;
2769     }
2770 
2771     return 0;
2772 }
2773 
2774 static int qemu_loadvm_state_header(QEMUFile *f)
2775 {
2776     unsigned int v;
2777     int ret;
2778 
2779     v = qemu_get_be32(f);
2780     if (v != QEMU_VM_FILE_MAGIC) {
2781         error_report("Not a migration stream");
2782         return -EINVAL;
2783     }
2784 
2785     v = qemu_get_be32(f);
2786     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2787         error_report("SaveVM v2 format is obsolete and don't work anymore");
2788         return -ENOTSUP;
2789     }
2790     if (v != QEMU_VM_FILE_VERSION) {
2791         error_report("Unsupported migration stream version");
2792         return -ENOTSUP;
2793     }
2794 
2795     if (migrate_get_current()->send_configuration) {
2796         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2797             error_report("Configuration section missing");
2798             return -EINVAL;
2799         }
2800         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2801 
2802         if (ret) {
2803             return ret;
2804         }
2805     }
2806     return 0;
2807 }
2808 
2809 static void qemu_loadvm_state_switchover_ack_needed(MigrationIncomingState *mis)
2810 {
2811     SaveStateEntry *se;
2812 
2813     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2814         if (!se->ops || !se->ops->switchover_ack_needed) {
2815             continue;
2816         }
2817 
2818         if (se->ops->switchover_ack_needed(se->opaque)) {
2819             mis->switchover_ack_pending_num++;
2820         }
2821     }
2822 
2823     trace_loadvm_state_switchover_ack_needed(mis->switchover_ack_pending_num);
2824 }
2825 
2826 static int qemu_loadvm_state_setup(QEMUFile *f, Error **errp)
2827 {
2828     ERRP_GUARD();
2829     SaveStateEntry *se;
2830     int ret;
2831 
2832     trace_loadvm_state_setup();
2833     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2834         if (!se->ops || !se->ops->load_setup) {
2835             continue;
2836         }
2837         if (se->ops->is_active) {
2838             if (!se->ops->is_active(se->opaque)) {
2839                 continue;
2840             }
2841         }
2842 
2843         ret = se->ops->load_setup(f, se->opaque, errp);
2844         if (ret < 0) {
2845             error_prepend(errp, "Load state of device %s failed: ",
2846                           se->idstr);
2847             qemu_file_set_error(f, ret);
2848             return ret;
2849         }
2850     }
2851     return 0;
2852 }
2853 
2854 struct LoadThreadData {
2855     MigrationLoadThread function;
2856     void *opaque;
2857 };
2858 
2859 static int qemu_loadvm_load_thread(void *thread_opaque)
2860 {
2861     struct LoadThreadData *data = thread_opaque;
2862     MigrationIncomingState *mis = migration_incoming_get_current();
2863     g_autoptr(Error) local_err = NULL;
2864 
2865     if (!data->function(data->opaque, &mis->load_threads_abort, &local_err)) {
2866         MigrationState *s = migrate_get_current();
2867 
2868         /*
2869          * Can't set load_threads_abort here since processing of main migration
2870          * channel data could still be happening, resulting in launching of new
2871          * load threads.
2872          */
2873 
2874         assert(local_err);
2875 
2876         /*
2877          * In case of multiple load threads failing which thread error
2878          * return we end setting is purely arbitrary.
2879          */
2880         migrate_set_error(s, local_err);
2881     }
2882 
2883     return 0;
2884 }
2885 
2886 void qemu_loadvm_start_load_thread(MigrationLoadThread function,
2887                                    void *opaque)
2888 {
2889     MigrationIncomingState *mis = migration_incoming_get_current();
2890     struct LoadThreadData *data;
2891 
2892     /* We only set it from this thread so it's okay to read it directly */
2893     assert(!mis->load_threads_abort);
2894 
2895     data = g_new(struct LoadThreadData, 1);
2896     data->function = function;
2897     data->opaque = opaque;
2898 
2899     thread_pool_submit_immediate(mis->load_threads, qemu_loadvm_load_thread,
2900                                  data, g_free);
2901 }
2902 
2903 void qemu_loadvm_state_cleanup(MigrationIncomingState *mis)
2904 {
2905     SaveStateEntry *se;
2906 
2907     trace_loadvm_state_cleanup();
2908 
2909     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2910         if (se->ops && se->ops->load_cleanup) {
2911             se->ops->load_cleanup(se->opaque);
2912         }
2913     }
2914 
2915     qemu_loadvm_thread_pool_destroy(mis);
2916 }
2917 
2918 /* Return true if we should continue the migration, or false. */
2919 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2920 {
2921     int i;
2922 
2923     trace_postcopy_pause_incoming();
2924 
2925     assert(migrate_postcopy_ram());
2926 
2927     /*
2928      * Unregister yank with either from/to src would work, since ioc behind it
2929      * is the same
2930      */
2931     migration_ioc_unregister_yank_from_file(mis->from_src_file);
2932 
2933     assert(mis->from_src_file);
2934     qemu_file_shutdown(mis->from_src_file);
2935     qemu_fclose(mis->from_src_file);
2936     mis->from_src_file = NULL;
2937 
2938     assert(mis->to_src_file);
2939     qemu_file_shutdown(mis->to_src_file);
2940     qemu_mutex_lock(&mis->rp_mutex);
2941     qemu_fclose(mis->to_src_file);
2942     mis->to_src_file = NULL;
2943     qemu_mutex_unlock(&mis->rp_mutex);
2944 
2945     /*
2946      * NOTE: this must happen before reset the PostcopyTmpPages below,
2947      * otherwise it's racy to reset those fields when the fast load thread
2948      * can be accessing it in parallel.
2949      */
2950     if (mis->postcopy_qemufile_dst) {
2951         qemu_file_shutdown(mis->postcopy_qemufile_dst);
2952         /* Take the mutex to make sure the fast ram load thread halted */
2953         qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
2954         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
2955         qemu_fclose(mis->postcopy_qemufile_dst);
2956         mis->postcopy_qemufile_dst = NULL;
2957         qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
2958     }
2959 
2960     /* Current state can be either ACTIVE or RECOVER */
2961     migrate_set_state(&mis->state, mis->state,
2962                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2963 
2964     /* Notify the fault thread for the invalidated file handle */
2965     postcopy_fault_thread_notify(mis);
2966 
2967     /*
2968      * If network is interrupted, any temp page we received will be useless
2969      * because we didn't mark them as "received" in receivedmap.  After a
2970      * proper recovery later (which will sync src dirty bitmap with receivedmap
2971      * on dest) these cached small pages will be resent again.
2972      */
2973     for (i = 0; i < mis->postcopy_channels; i++) {
2974         postcopy_temp_page_reset(&mis->postcopy_tmp_pages[i]);
2975     }
2976 
2977     error_report("Detected IO failure for postcopy. "
2978                  "Migration paused.");
2979 
2980     do {
2981         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2982     } while (postcopy_is_paused(mis->state));
2983 
2984     trace_postcopy_pause_incoming_continued();
2985 
2986     return true;
2987 }
2988 
2989 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2990 {
2991     uint8_t section_type;
2992     int ret = 0;
2993 
2994 retry:
2995     while (true) {
2996         section_type = qemu_get_byte(f);
2997 
2998         ret = qemu_file_get_error_obj_any(f, mis->postcopy_qemufile_dst, NULL);
2999         if (ret) {
3000             break;
3001         }
3002 
3003         trace_qemu_loadvm_state_section(section_type);
3004         switch (section_type) {
3005         case QEMU_VM_SECTION_START:
3006         case QEMU_VM_SECTION_FULL:
3007             ret = qemu_loadvm_section_start_full(f, section_type);
3008             if (ret < 0) {
3009                 goto out;
3010             }
3011             break;
3012         case QEMU_VM_SECTION_PART:
3013         case QEMU_VM_SECTION_END:
3014             ret = qemu_loadvm_section_part_end(f, section_type);
3015             if (ret < 0) {
3016                 goto out;
3017             }
3018             break;
3019         case QEMU_VM_COMMAND:
3020             ret = loadvm_process_command(f);
3021             trace_qemu_loadvm_state_section_command(ret);
3022             if ((ret < 0) || (ret == LOADVM_QUIT)) {
3023                 goto out;
3024             }
3025             break;
3026         case QEMU_VM_EOF:
3027             /* This is the end of migration */
3028             goto out;
3029         default:
3030             error_report("Unknown savevm section type %d", section_type);
3031             ret = -EINVAL;
3032             goto out;
3033         }
3034     }
3035 
3036 out:
3037     if (ret < 0) {
3038         qemu_file_set_error(f, ret);
3039 
3040         /* Cancel bitmaps incoming regardless of recovery */
3041         dirty_bitmap_mig_cancel_incoming();
3042 
3043         /*
3044          * If we are during an active postcopy, then we pause instead
3045          * of bail out to at least keep the VM's dirty data.  Note
3046          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
3047          * during which we're still receiving device states and we
3048          * still haven't yet started the VM on destination.
3049          *
3050          * Only RAM postcopy supports recovery. Still, if RAM postcopy is
3051          * enabled, canceled bitmaps postcopy will not affect RAM postcopy
3052          * recovering.
3053          */
3054         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
3055             migrate_postcopy_ram() && postcopy_pause_incoming(mis)) {
3056             /* Reset f to point to the newly created channel */
3057             f = mis->from_src_file;
3058             goto retry;
3059         }
3060     }
3061     return ret;
3062 }
3063 
3064 int qemu_loadvm_state(QEMUFile *f)
3065 {
3066     MigrationState *s = migrate_get_current();
3067     MigrationIncomingState *mis = migration_incoming_get_current();
3068     Error *local_err = NULL;
3069     int ret;
3070 
3071     if (qemu_savevm_state_blocked(&local_err)) {
3072         error_report_err(local_err);
3073         return -EINVAL;
3074     }
3075 
3076     qemu_loadvm_thread_pool_create(mis);
3077 
3078     ret = qemu_loadvm_state_header(f);
3079     if (ret) {
3080         return ret;
3081     }
3082 
3083     if (qemu_loadvm_state_setup(f, &local_err) != 0) {
3084         error_report_err(local_err);
3085         return -EINVAL;
3086     }
3087 
3088     if (migrate_switchover_ack()) {
3089         qemu_loadvm_state_switchover_ack_needed(mis);
3090     }
3091 
3092     cpu_synchronize_all_pre_loadvm();
3093 
3094     ret = qemu_loadvm_state_main(f, mis);
3095     qemu_event_set(&mis->main_thread_load_event);
3096 
3097     trace_qemu_loadvm_state_post_main(ret);
3098 
3099     if (mis->have_listen_thread) {
3100         /*
3101          * Postcopy listen thread still going, don't synchronize the
3102          * cpus yet.
3103          */
3104         return ret;
3105     }
3106 
3107     /* When reaching here, it must be precopy */
3108     if (ret == 0) {
3109         if (migrate_has_error(migrate_get_current()) ||
3110             !qemu_loadvm_thread_pool_wait(s, mis)) {
3111             ret = -EINVAL;
3112         } else {
3113             ret = qemu_file_get_error(f);
3114         }
3115     }
3116     /*
3117      * Set this flag unconditionally so we'll catch further attempts to
3118      * start additional threads via an appropriate assert()
3119      */
3120     qatomic_set(&mis->load_threads_abort, true);
3121 
3122     /*
3123      * Try to read in the VMDESC section as well, so that dumping tools that
3124      * intercept our migration stream have the chance to see it.
3125      */
3126 
3127     /* We've got to be careful; if we don't read the data and just shut the fd
3128      * then the sender can error if we close while it's still sending.
3129      * We also mustn't read data that isn't there; some transports (RDMA)
3130      * will stall waiting for that data when the source has already closed.
3131      */
3132     if (ret == 0 && should_send_vmdesc()) {
3133         uint8_t *buf;
3134         uint32_t size;
3135         uint8_t  section_type = qemu_get_byte(f);
3136 
3137         if (section_type != QEMU_VM_VMDESCRIPTION) {
3138             error_report("Expected vmdescription section, but got %d",
3139                          section_type);
3140             /*
3141              * It doesn't seem worth failing at this point since
3142              * we apparently have an otherwise valid VM state
3143              */
3144         } else {
3145             buf = g_malloc(0x1000);
3146             size = qemu_get_be32(f);
3147 
3148             while (size > 0) {
3149                 uint32_t read_chunk = MIN(size, 0x1000);
3150                 qemu_get_buffer(f, buf, read_chunk);
3151                 size -= read_chunk;
3152             }
3153             g_free(buf);
3154         }
3155     }
3156 
3157     cpu_synchronize_all_post_init();
3158 
3159     return ret;
3160 }
3161 
3162 int qemu_load_device_state(QEMUFile *f)
3163 {
3164     MigrationIncomingState *mis = migration_incoming_get_current();
3165     int ret;
3166 
3167     /* Load QEMU_VM_SECTION_FULL section */
3168     ret = qemu_loadvm_state_main(f, mis);
3169     if (ret < 0) {
3170         error_report("Failed to load device state: %d", ret);
3171         return ret;
3172     }
3173 
3174     cpu_synchronize_all_post_init();
3175     return 0;
3176 }
3177 
3178 int qemu_loadvm_approve_switchover(void)
3179 {
3180     MigrationIncomingState *mis = migration_incoming_get_current();
3181 
3182     if (!mis->switchover_ack_pending_num) {
3183         return -EINVAL;
3184     }
3185 
3186     mis->switchover_ack_pending_num--;
3187     trace_loadvm_approve_switchover(mis->switchover_ack_pending_num);
3188 
3189     if (mis->switchover_ack_pending_num) {
3190         return 0;
3191     }
3192 
3193     return migrate_send_rp_switchover_ack(mis);
3194 }
3195 
3196 bool qemu_loadvm_load_state_buffer(const char *idstr, uint32_t instance_id,
3197                                    char *buf, size_t len, Error **errp)
3198 {
3199     SaveStateEntry *se;
3200 
3201     se = find_se(idstr, instance_id);
3202     if (!se) {
3203         error_setg(errp,
3204                    "Unknown idstr %s or instance id %u for load state buffer",
3205                    idstr, instance_id);
3206         return false;
3207     }
3208 
3209     if (!se->ops || !se->ops->load_state_buffer) {
3210         error_setg(errp,
3211                    "idstr %s / instance %u has no load state buffer operation",
3212                    idstr, instance_id);
3213         return false;
3214     }
3215 
3216     return se->ops->load_state_buffer(se->opaque, buf, len, errp);
3217 }
3218 
3219 bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
3220                   bool has_devices, strList *devices, Error **errp)
3221 {
3222     BlockDriverState *bs;
3223     QEMUSnapshotInfo sn1, *sn = &sn1;
3224     int ret = -1, ret2;
3225     QEMUFile *f;
3226     RunState saved_state = runstate_get();
3227     uint64_t vm_state_size;
3228     g_autoptr(GDateTime) now = g_date_time_new_now_local();
3229 
3230     GLOBAL_STATE_CODE();
3231 
3232     if (migration_is_blocked(errp)) {
3233         return false;
3234     }
3235 
3236     if (!replay_can_snapshot()) {
3237         error_setg(errp, "Record/replay does not allow making snapshot "
3238                    "right now. Try once more later.");
3239         return false;
3240     }
3241 
3242     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3243         return false;
3244     }
3245 
3246     /* Delete old snapshots of the same name */
3247     if (name) {
3248         if (overwrite) {
3249             if (bdrv_all_delete_snapshot(name, has_devices,
3250                                          devices, errp) < 0) {
3251                 return false;
3252             }
3253         } else {
3254             ret2 = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3255             if (ret2 < 0) {
3256                 return false;
3257             }
3258             if (ret2 == 1) {
3259                 error_setg(errp,
3260                            "Snapshot '%s' already exists in one or more devices",
3261                            name);
3262                 return false;
3263             }
3264         }
3265     }
3266 
3267     bs = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3268     if (bs == NULL) {
3269         return false;
3270     }
3271 
3272     global_state_store();
3273     vm_stop(RUN_STATE_SAVE_VM);
3274 
3275     bdrv_drain_all_begin();
3276 
3277     memset(sn, 0, sizeof(*sn));
3278 
3279     /* fill auxiliary fields */
3280     sn->date_sec = g_date_time_to_unix(now);
3281     sn->date_nsec = g_date_time_get_microsecond(now) * 1000;
3282     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
3283     if (replay_mode != REPLAY_MODE_NONE) {
3284         sn->icount = replay_get_current_icount();
3285     } else {
3286         sn->icount = -1ULL;
3287     }
3288 
3289     if (name) {
3290         pstrcpy(sn->name, sizeof(sn->name), name);
3291     } else {
3292         g_autofree char *autoname = g_date_time_format(now,  "vm-%Y%m%d%H%M%S");
3293         pstrcpy(sn->name, sizeof(sn->name), autoname);
3294     }
3295 
3296     /* save the VM state */
3297     f = qemu_fopen_bdrv(bs, 1);
3298     if (!f) {
3299         error_setg(errp, "Could not open VM state file");
3300         goto the_end;
3301     }
3302     ret = qemu_savevm_state(f, errp);
3303     vm_state_size = qemu_file_transferred(f);
3304     ret2 = qemu_fclose(f);
3305     if (ret < 0) {
3306         goto the_end;
3307     }
3308     if (ret2 < 0) {
3309         ret = ret2;
3310         goto the_end;
3311     }
3312 
3313     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size,
3314                                    has_devices, devices, errp);
3315     if (ret < 0) {
3316         bdrv_all_delete_snapshot(sn->name, has_devices, devices, NULL);
3317         goto the_end;
3318     }
3319 
3320     ret = 0;
3321 
3322  the_end:
3323     bdrv_drain_all_end();
3324 
3325     vm_resume(saved_state);
3326     return ret == 0;
3327 }
3328 
3329 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
3330                                 Error **errp)
3331 {
3332     QEMUFile *f;
3333     QIOChannelFile *ioc;
3334     int saved_vm_running;
3335     int ret;
3336 
3337     if (!has_live) {
3338         /* live default to true so old version of Xen tool stack can have a
3339          * successful live migration */
3340         live = true;
3341     }
3342 
3343     saved_vm_running = runstate_is_running();
3344     vm_stop(RUN_STATE_SAVE_VM);
3345     global_state_store_running();
3346 
3347     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT | O_TRUNC,
3348                                     0660, errp);
3349     if (!ioc) {
3350         goto the_end;
3351     }
3352     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
3353     f = qemu_file_new_output(QIO_CHANNEL(ioc));
3354     object_unref(OBJECT(ioc));
3355     ret = qemu_save_device_state(f);
3356     if (ret < 0 || qemu_fclose(f) < 0) {
3357         error_setg(errp, "saving Xen device state failed");
3358     } else {
3359         /* libxl calls the QMP command "stop" before calling
3360          * "xen-save-devices-state" and in case of migration failure, libxl
3361          * would call "cont".
3362          * So call bdrv_inactivate_all (release locks) here to let the other
3363          * side of the migration take control of the images.
3364          */
3365         if (live && !saved_vm_running) {
3366             migration_block_inactivate();
3367         }
3368     }
3369 
3370  the_end:
3371     if (saved_vm_running) {
3372         vm_start();
3373     }
3374 }
3375 
3376 void qmp_xen_load_devices_state(const char *filename, Error **errp)
3377 {
3378     QEMUFile *f;
3379     QIOChannelFile *ioc;
3380     int ret;
3381 
3382     /* Guest must be paused before loading the device state; the RAM state
3383      * will already have been loaded by xc
3384      */
3385     if (runstate_is_running()) {
3386         error_setg(errp, "Cannot update device state while vm is running");
3387         return;
3388     }
3389     vm_stop(RUN_STATE_RESTORE_VM);
3390 
3391     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
3392     if (!ioc) {
3393         return;
3394     }
3395     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
3396     f = qemu_file_new_input(QIO_CHANNEL(ioc));
3397     object_unref(OBJECT(ioc));
3398 
3399     ret = qemu_loadvm_state(f);
3400     qemu_fclose(f);
3401     if (ret < 0) {
3402         error_setg(errp, "loading Xen device state failed");
3403     }
3404     migration_incoming_state_destroy();
3405 }
3406 
3407 bool load_snapshot(const char *name, const char *vmstate,
3408                    bool has_devices, strList *devices, Error **errp)
3409 {
3410     BlockDriverState *bs_vm_state;
3411     QEMUSnapshotInfo sn;
3412     QEMUFile *f;
3413     int ret;
3414     MigrationIncomingState *mis = migration_incoming_get_current();
3415 
3416     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3417         return false;
3418     }
3419     ret = bdrv_all_has_snapshot(name, has_devices, devices, errp);
3420     if (ret < 0) {
3421         return false;
3422     }
3423     if (ret == 0) {
3424         error_setg(errp, "Snapshot '%s' does not exist in one or more devices",
3425                    name);
3426         return false;
3427     }
3428 
3429     bs_vm_state = bdrv_all_find_vmstate_bs(vmstate, has_devices, devices, errp);
3430     if (!bs_vm_state) {
3431         return false;
3432     }
3433 
3434     /* Don't even try to load empty VM states */
3435     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
3436     if (ret < 0) {
3437         error_setg(errp, "Snapshot can not be found");
3438         return false;
3439     } else if (sn.vm_state_size == 0) {
3440         error_setg(errp, "This is a disk-only snapshot. Revert to it "
3441                    " offline using qemu-img");
3442         return false;
3443     }
3444 
3445     /*
3446      * Flush the record/replay queue. Now the VM state is going
3447      * to change. Therefore we don't need to preserve its consistency
3448      */
3449     replay_flush_events();
3450 
3451     /* Flush all IO requests so they don't interfere with the new state.  */
3452     bdrv_drain_all_begin();
3453 
3454     ret = bdrv_all_goto_snapshot(name, has_devices, devices, errp);
3455     if (ret < 0) {
3456         goto err_drain;
3457     }
3458 
3459     /* restore the VM state */
3460     f = qemu_fopen_bdrv(bs_vm_state, 0);
3461     if (!f) {
3462         error_setg(errp, "Could not open VM state file");
3463         goto err_drain;
3464     }
3465 
3466     qemu_system_reset(SHUTDOWN_CAUSE_SNAPSHOT_LOAD);
3467     mis->from_src_file = f;
3468 
3469     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
3470         ret = -EINVAL;
3471         goto err_drain;
3472     }
3473     ret = qemu_loadvm_state(f);
3474     migration_incoming_state_destroy();
3475 
3476     bdrv_drain_all_end();
3477 
3478     if (ret < 0) {
3479         error_setg(errp, "Error %d while loading VM state", ret);
3480         return false;
3481     }
3482 
3483     return true;
3484 
3485 err_drain:
3486     bdrv_drain_all_end();
3487     return false;
3488 }
3489 
3490 void load_snapshot_resume(RunState state)
3491 {
3492     vm_resume(state);
3493     if (state == RUN_STATE_RUNNING && runstate_get() == RUN_STATE_SUSPENDED) {
3494         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, &error_abort);
3495     }
3496 }
3497 
3498 bool delete_snapshot(const char *name, bool has_devices,
3499                      strList *devices, Error **errp)
3500 {
3501     if (!bdrv_all_can_snapshot(has_devices, devices, errp)) {
3502         return false;
3503     }
3504 
3505     if (bdrv_all_delete_snapshot(name, has_devices, devices, errp) < 0) {
3506         return false;
3507     }
3508 
3509     return true;
3510 }
3511 
3512 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
3513 {
3514     qemu_ram_set_idstr(mr->ram_block,
3515                        memory_region_name(mr), dev);
3516     qemu_ram_set_migratable(mr->ram_block);
3517 }
3518 
3519 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
3520 {
3521     qemu_ram_unset_idstr(mr->ram_block);
3522     qemu_ram_unset_migratable(mr->ram_block);
3523 }
3524 
3525 void vmstate_register_ram_global(MemoryRegion *mr)
3526 {
3527     vmstate_register_ram(mr, NULL);
3528 }
3529 
3530 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
3531 {
3532     /* check needed if --only-migratable is specified */
3533     if (!only_migratable) {
3534         return true;
3535     }
3536 
3537     return !(vmsd && vmsd->unmigratable);
3538 }
3539 
3540 typedef struct SnapshotJob {
3541     Job common;
3542     char *tag;
3543     char *vmstate;
3544     strList *devices;
3545     Coroutine *co;
3546     Error **errp;
3547     bool ret;
3548 } SnapshotJob;
3549 
3550 static void qmp_snapshot_job_free(SnapshotJob *s)
3551 {
3552     g_free(s->tag);
3553     g_free(s->vmstate);
3554     qapi_free_strList(s->devices);
3555 }
3556 
3557 
3558 static void snapshot_load_job_bh(void *opaque)
3559 {
3560     Job *job = opaque;
3561     SnapshotJob *s = container_of(job, SnapshotJob, common);
3562     RunState orig_state = runstate_get();
3563 
3564     job_progress_set_remaining(&s->common, 1);
3565 
3566     vm_stop(RUN_STATE_RESTORE_VM);
3567 
3568     s->ret = load_snapshot(s->tag, s->vmstate, true, s->devices, s->errp);
3569     if (s->ret) {
3570         load_snapshot_resume(orig_state);
3571     }
3572 
3573     job_progress_update(&s->common, 1);
3574 
3575     qmp_snapshot_job_free(s);
3576     aio_co_wake(s->co);
3577 }
3578 
3579 static void snapshot_save_job_bh(void *opaque)
3580 {
3581     Job *job = opaque;
3582     SnapshotJob *s = container_of(job, SnapshotJob, common);
3583 
3584     job_progress_set_remaining(&s->common, 1);
3585     s->ret = save_snapshot(s->tag, false, s->vmstate,
3586                            true, s->devices, s->errp);
3587     job_progress_update(&s->common, 1);
3588 
3589     qmp_snapshot_job_free(s);
3590     aio_co_wake(s->co);
3591 }
3592 
3593 static void snapshot_delete_job_bh(void *opaque)
3594 {
3595     Job *job = opaque;
3596     SnapshotJob *s = container_of(job, SnapshotJob, common);
3597 
3598     job_progress_set_remaining(&s->common, 1);
3599     s->ret = delete_snapshot(s->tag, true, s->devices, s->errp);
3600     job_progress_update(&s->common, 1);
3601 
3602     qmp_snapshot_job_free(s);
3603     aio_co_wake(s->co);
3604 }
3605 
3606 static int coroutine_fn snapshot_save_job_run(Job *job, Error **errp)
3607 {
3608     SnapshotJob *s = container_of(job, SnapshotJob, common);
3609     s->errp = errp;
3610     s->co = qemu_coroutine_self();
3611     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3612                             snapshot_save_job_bh, job);
3613     qemu_coroutine_yield();
3614     return s->ret ? 0 : -1;
3615 }
3616 
3617 static int coroutine_fn snapshot_load_job_run(Job *job, Error **errp)
3618 {
3619     SnapshotJob *s = container_of(job, SnapshotJob, common);
3620     s->errp = errp;
3621     s->co = qemu_coroutine_self();
3622     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3623                             snapshot_load_job_bh, job);
3624     qemu_coroutine_yield();
3625     return s->ret ? 0 : -1;
3626 }
3627 
3628 static int coroutine_fn snapshot_delete_job_run(Job *job, Error **errp)
3629 {
3630     SnapshotJob *s = container_of(job, SnapshotJob, common);
3631     s->errp = errp;
3632     s->co = qemu_coroutine_self();
3633     aio_bh_schedule_oneshot(qemu_get_aio_context(),
3634                             snapshot_delete_job_bh, job);
3635     qemu_coroutine_yield();
3636     return s->ret ? 0 : -1;
3637 }
3638 
3639 
3640 static const JobDriver snapshot_load_job_driver = {
3641     .instance_size = sizeof(SnapshotJob),
3642     .job_type      = JOB_TYPE_SNAPSHOT_LOAD,
3643     .run           = snapshot_load_job_run,
3644 };
3645 
3646 static const JobDriver snapshot_save_job_driver = {
3647     .instance_size = sizeof(SnapshotJob),
3648     .job_type      = JOB_TYPE_SNAPSHOT_SAVE,
3649     .run           = snapshot_save_job_run,
3650 };
3651 
3652 static const JobDriver snapshot_delete_job_driver = {
3653     .instance_size = sizeof(SnapshotJob),
3654     .job_type      = JOB_TYPE_SNAPSHOT_DELETE,
3655     .run           = snapshot_delete_job_run,
3656 };
3657 
3658 
3659 void qmp_snapshot_save(const char *job_id,
3660                        const char *tag,
3661                        const char *vmstate,
3662                        strList *devices,
3663                        Error **errp)
3664 {
3665     SnapshotJob *s;
3666 
3667     s = job_create(job_id, &snapshot_save_job_driver, NULL,
3668                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3669                    NULL, NULL, errp);
3670     if (!s) {
3671         return;
3672     }
3673 
3674     s->tag = g_strdup(tag);
3675     s->vmstate = g_strdup(vmstate);
3676     s->devices = QAPI_CLONE(strList, devices);
3677 
3678     job_start(&s->common);
3679 }
3680 
3681 void qmp_snapshot_load(const char *job_id,
3682                        const char *tag,
3683                        const char *vmstate,
3684                        strList *devices,
3685                        Error **errp)
3686 {
3687     SnapshotJob *s;
3688 
3689     s = job_create(job_id, &snapshot_load_job_driver, NULL,
3690                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3691                    NULL, NULL, errp);
3692     if (!s) {
3693         return;
3694     }
3695 
3696     s->tag = g_strdup(tag);
3697     s->vmstate = g_strdup(vmstate);
3698     s->devices = QAPI_CLONE(strList, devices);
3699 
3700     job_start(&s->common);
3701 }
3702 
3703 void qmp_snapshot_delete(const char *job_id,
3704                          const char *tag,
3705                          strList *devices,
3706                          Error **errp)
3707 {
3708     SnapshotJob *s;
3709 
3710     s = job_create(job_id, &snapshot_delete_job_driver, NULL,
3711                    qemu_get_aio_context(), JOB_MANUAL_DISMISS,
3712                    NULL, NULL, errp);
3713     if (!s) {
3714         return;
3715     }
3716 
3717     s->tag = g_strdup(tag);
3718     s->devices = QAPI_CLONE(strList, devices);
3719 
3720     job_start(&s->common);
3721 }
3722