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