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