]> Git Repo - qemu.git/blob - migration/savevm.c
migration: Add capabilities validation
[qemu.git] / migration / savevm.c
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 <[email protected]>
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 "hw/xen/xen.h"
32 #include "net/net.h"
33 #include "migration.h"
34 #include "migration/snapshot.h"
35 #include "migration/misc.h"
36 #include "migration/register.h"
37 #include "migration/global_state.h"
38 #include "ram.h"
39 #include "qemu-file-channel.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/qapi-commands-misc.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qemu/error-report.h"
48 #include "sysemu/cpus.h"
49 #include "exec/memory.h"
50 #include "exec/target_page.h"
51 #include "trace.h"
52 #include "qemu/iov.h"
53 #include "block/snapshot.h"
54 #include "qemu/cutils.h"
55 #include "io/channel-buffer.h"
56 #include "io/channel-file.h"
57 #include "sysemu/replay.h"
58 #include "qjson.h"
59 #include "migration/colo.h"
60 #include "qemu/bitmap.h"
61 #include "net/announce.h"
62
63 const unsigned int postcopy_ram_discard_version = 0;
64
65 /* Subcommands for QEMU_VM_COMMAND */
66 enum qemu_vm_cmd {
67     MIG_CMD_INVALID = 0,   /* Must be 0 */
68     MIG_CMD_OPEN_RETURN_PATH,  /* Tell the dest to open the Return path */
69     MIG_CMD_PING,              /* Request a PONG on the RP */
70
71     MIG_CMD_POSTCOPY_ADVISE,       /* Prior to any page transfers, just
72                                       warn we might want to do PC */
73     MIG_CMD_POSTCOPY_LISTEN,       /* Start listening for incoming
74                                       pages as it's running. */
75     MIG_CMD_POSTCOPY_RUN,          /* Start execution */
76
77     MIG_CMD_POSTCOPY_RAM_DISCARD,  /* A list of pages to discard that
78                                       were previously sent during
79                                       precopy but are dirty. */
80     MIG_CMD_PACKAGED,          /* Send a wrapped stream within this stream */
81     MIG_CMD_ENABLE_COLO,       /* Enable COLO */
82     MIG_CMD_POSTCOPY_RESUME,   /* resume postcopy on dest */
83     MIG_CMD_RECV_BITMAP,       /* Request for recved bitmap on dst */
84     MIG_CMD_MAX
85 };
86
87 #define MAX_VM_CMD_PACKAGED_SIZE UINT32_MAX
88 static struct mig_cmd_args {
89     ssize_t     len; /* -1 = variable */
90     const char *name;
91 } mig_cmd_args[] = {
92     [MIG_CMD_INVALID]          = { .len = -1, .name = "INVALID" },
93     [MIG_CMD_OPEN_RETURN_PATH] = { .len =  0, .name = "OPEN_RETURN_PATH" },
94     [MIG_CMD_PING]             = { .len = sizeof(uint32_t), .name = "PING" },
95     [MIG_CMD_POSTCOPY_ADVISE]  = { .len = -1, .name = "POSTCOPY_ADVISE" },
96     [MIG_CMD_POSTCOPY_LISTEN]  = { .len =  0, .name = "POSTCOPY_LISTEN" },
97     [MIG_CMD_POSTCOPY_RUN]     = { .len =  0, .name = "POSTCOPY_RUN" },
98     [MIG_CMD_POSTCOPY_RAM_DISCARD] = {
99                                    .len = -1, .name = "POSTCOPY_RAM_DISCARD" },
100     [MIG_CMD_POSTCOPY_RESUME]  = { .len =  0, .name = "POSTCOPY_RESUME" },
101     [MIG_CMD_PACKAGED]         = { .len =  4, .name = "PACKAGED" },
102     [MIG_CMD_RECV_BITMAP]      = { .len = -1, .name = "RECV_BITMAP" },
103     [MIG_CMD_MAX]              = { .len = -1, .name = "MAX" },
104 };
105
106 /* Note for MIG_CMD_POSTCOPY_ADVISE:
107  * The format of arguments is depending on postcopy mode:
108  * - postcopy RAM only
109  *   uint64_t host page size
110  *   uint64_t taget page size
111  *
112  * - postcopy RAM and postcopy dirty bitmaps
113  *   format is the same as for postcopy RAM only
114  *
115  * - postcopy dirty bitmaps only
116  *   Nothing. Command length field is 0.
117  *
118  * Be careful: adding a new postcopy entity with some other parameters should
119  * not break format self-description ability. Good way is to introduce some
120  * generic extendable format with an exception for two old entities.
121  */
122
123 /***********************************************************/
124 /* savevm/loadvm support */
125
126 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
127                                    int64_t pos)
128 {
129     int ret;
130     QEMUIOVector qiov;
131
132     qemu_iovec_init_external(&qiov, iov, iovcnt);
133     ret = bdrv_writev_vmstate(opaque, &qiov, pos);
134     if (ret < 0) {
135         return ret;
136     }
137
138     return qiov.size;
139 }
140
141 static ssize_t block_get_buffer(void *opaque, uint8_t *buf, int64_t pos,
142                                 size_t size)
143 {
144     return bdrv_load_vmstate(opaque, buf, pos, size);
145 }
146
147 static int bdrv_fclose(void *opaque)
148 {
149     return bdrv_flush(opaque);
150 }
151
152 static const QEMUFileOps bdrv_read_ops = {
153     .get_buffer = block_get_buffer,
154     .close =      bdrv_fclose
155 };
156
157 static const QEMUFileOps bdrv_write_ops = {
158     .writev_buffer  = block_writev_buffer,
159     .close          = bdrv_fclose
160 };
161
162 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
163 {
164     if (is_writable) {
165         return qemu_fopen_ops(bs, &bdrv_write_ops);
166     }
167     return qemu_fopen_ops(bs, &bdrv_read_ops);
168 }
169
170
171 /* QEMUFile timer support.
172  * Not in qemu-file.c to not add qemu-timer.c as dependency to qemu-file.c
173  */
174
175 void timer_put(QEMUFile *f, QEMUTimer *ts)
176 {
177     uint64_t expire_time;
178
179     expire_time = timer_expire_time_ns(ts);
180     qemu_put_be64(f, expire_time);
181 }
182
183 void timer_get(QEMUFile *f, QEMUTimer *ts)
184 {
185     uint64_t expire_time;
186
187     expire_time = qemu_get_be64(f);
188     if (expire_time != -1) {
189         timer_mod_ns(ts, expire_time);
190     } else {
191         timer_del(ts);
192     }
193 }
194
195
196 /* VMState timer support.
197  * Not in vmstate.c to not add qemu-timer.c as dependency to vmstate.c
198  */
199
200 static int get_timer(QEMUFile *f, void *pv, size_t size,
201                      const VMStateField *field)
202 {
203     QEMUTimer *v = pv;
204     timer_get(f, v);
205     return 0;
206 }
207
208 static int put_timer(QEMUFile *f, void *pv, size_t size,
209                      const VMStateField *field, QJSON *vmdesc)
210 {
211     QEMUTimer *v = pv;
212     timer_put(f, v);
213
214     return 0;
215 }
216
217 const VMStateInfo vmstate_info_timer = {
218     .name = "timer",
219     .get  = get_timer,
220     .put  = put_timer,
221 };
222
223
224 typedef struct CompatEntry {
225     char idstr[256];
226     int instance_id;
227 } CompatEntry;
228
229 typedef struct SaveStateEntry {
230     QTAILQ_ENTRY(SaveStateEntry) entry;
231     char idstr[256];
232     int instance_id;
233     int alias_id;
234     int version_id;
235     /* version id read from the stream */
236     int load_version_id;
237     int section_id;
238     /* section id read from the stream */
239     int load_section_id;
240     const SaveVMHandlers *ops;
241     const VMStateDescription *vmsd;
242     void *opaque;
243     CompatEntry *compat;
244     int is_ram;
245 } SaveStateEntry;
246
247 typedef struct SaveState {
248     QTAILQ_HEAD(, SaveStateEntry) handlers;
249     int global_section_id;
250     uint32_t len;
251     const char *name;
252     uint32_t target_page_bits;
253     uint32_t caps_count;
254     MigrationCapability *capabilities;
255 } SaveState;
256
257 static SaveState savevm_state = {
258     .handlers = QTAILQ_HEAD_INITIALIZER(savevm_state.handlers),
259     .global_section_id = 0,
260 };
261
262 static bool should_validate_capability(int capability)
263 {
264     assert(capability >= 0 && capability < MIGRATION_CAPABILITY__MAX);
265     /* Validate only new capabilities to keep compatibility. */
266     switch (capability) {
267     case MIGRATION_CAPABILITY_X_IGNORE_SHARED:
268         return true;
269     default:
270         return false;
271     }
272 }
273
274 static uint32_t get_validatable_capabilities_count(void)
275 {
276     MigrationState *s = migrate_get_current();
277     uint32_t result = 0;
278     int i;
279     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
280         if (should_validate_capability(i) && s->enabled_capabilities[i]) {
281             result++;
282         }
283     }
284     return result;
285 }
286
287 static int configuration_pre_save(void *opaque)
288 {
289     SaveState *state = opaque;
290     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
291     MigrationState *s = migrate_get_current();
292     int i, j;
293
294     state->len = strlen(current_name);
295     state->name = current_name;
296     state->target_page_bits = qemu_target_page_bits();
297
298     state->caps_count = get_validatable_capabilities_count();
299     state->capabilities = g_renew(MigrationCapability, state->capabilities,
300                                   state->caps_count);
301     for (i = j = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
302         if (should_validate_capability(i) && s->enabled_capabilities[i]) {
303             state->capabilities[j++] = i;
304         }
305     }
306
307     return 0;
308 }
309
310 static int configuration_pre_load(void *opaque)
311 {
312     SaveState *state = opaque;
313
314     /* If there is no target-page-bits subsection it means the source
315      * predates the variable-target-page-bits support and is using the
316      * minimum possible value for this CPU.
317      */
318     state->target_page_bits = qemu_target_page_bits_min();
319     return 0;
320 }
321
322 static bool configuration_validate_capabilities(SaveState *state)
323 {
324     bool ret = true;
325     MigrationState *s = migrate_get_current();
326     unsigned long *source_caps_bm;
327     int i;
328
329     source_caps_bm = bitmap_new(MIGRATION_CAPABILITY__MAX);
330     for (i = 0; i < state->caps_count; i++) {
331         MigrationCapability capability = state->capabilities[i];
332         set_bit(capability, source_caps_bm);
333     }
334
335     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
336         bool source_state, target_state;
337         if (!should_validate_capability(i)) {
338             continue;
339         }
340         source_state = test_bit(i, source_caps_bm);
341         target_state = s->enabled_capabilities[i];
342         if (source_state != target_state) {
343             error_report("Capability %s is %s, but received capability is %s",
344                          MigrationCapability_str(i),
345                          target_state ? "on" : "off",
346                          source_state ? "on" : "off");
347             ret = false;
348             /* Don't break here to report all failed capabilities */
349         }
350     }
351
352     g_free(source_caps_bm);
353     return ret;
354 }
355
356 static int configuration_post_load(void *opaque, int version_id)
357 {
358     SaveState *state = opaque;
359     const char *current_name = MACHINE_GET_CLASS(current_machine)->name;
360
361     if (strncmp(state->name, current_name, state->len) != 0) {
362         error_report("Machine type received is '%.*s' and local is '%s'",
363                      (int) state->len, state->name, current_name);
364         return -EINVAL;
365     }
366
367     if (state->target_page_bits != qemu_target_page_bits()) {
368         error_report("Received TARGET_PAGE_BITS is %d but local is %d",
369                      state->target_page_bits, qemu_target_page_bits());
370         return -EINVAL;
371     }
372
373     if (!configuration_validate_capabilities(state)) {
374         return -EINVAL;
375     }
376
377     return 0;
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, QJSON *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 const VMStateDescription vmstate_configuration = {
464     .name = "configuration",
465     .version_id = 1,
466     .pre_load = configuration_pre_load,
467     .post_load = configuration_post_load,
468     .pre_save = configuration_pre_save,
469     .fields = (VMStateField[]) {
470         VMSTATE_UINT32(len, SaveState),
471         VMSTATE_VBUFFER_ALLOC_UINT32(name, SaveState, 0, NULL, len),
472         VMSTATE_END_OF_LIST()
473     },
474     .subsections = (const VMStateDescription*[]) {
475         &vmstate_target_page_bits,
476         &vmstate_capabilites,
477         NULL
478     }
479 };
480
481 static void dump_vmstate_vmsd(FILE *out_file,
482                               const VMStateDescription *vmsd, int indent,
483                               bool is_subsection);
484
485 static void dump_vmstate_vmsf(FILE *out_file, const VMStateField *field,
486                               int indent)
487 {
488     fprintf(out_file, "%*s{\n", indent, "");
489     indent += 2;
490     fprintf(out_file, "%*s\"field\": \"%s\",\n", indent, "", field->name);
491     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
492             field->version_id);
493     fprintf(out_file, "%*s\"field_exists\": %s,\n", indent, "",
494             field->field_exists ? "true" : "false");
495     fprintf(out_file, "%*s\"size\": %zu", indent, "", field->size);
496     if (field->vmsd != NULL) {
497         fprintf(out_file, ",\n");
498         dump_vmstate_vmsd(out_file, field->vmsd, indent, false);
499     }
500     fprintf(out_file, "\n%*s}", indent - 2, "");
501 }
502
503 static void dump_vmstate_vmss(FILE *out_file,
504                               const VMStateDescription **subsection,
505                               int indent)
506 {
507     if (*subsection != NULL) {
508         dump_vmstate_vmsd(out_file, *subsection, indent, true);
509     }
510 }
511
512 static void dump_vmstate_vmsd(FILE *out_file,
513                               const VMStateDescription *vmsd, int indent,
514                               bool is_subsection)
515 {
516     if (is_subsection) {
517         fprintf(out_file, "%*s{\n", indent, "");
518     } else {
519         fprintf(out_file, "%*s\"%s\": {\n", indent, "", "Description");
520     }
521     indent += 2;
522     fprintf(out_file, "%*s\"name\": \"%s\",\n", indent, "", vmsd->name);
523     fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
524             vmsd->version_id);
525     fprintf(out_file, "%*s\"minimum_version_id\": %d", indent, "",
526             vmsd->minimum_version_id);
527     if (vmsd->fields != NULL) {
528         const VMStateField *field = vmsd->fields;
529         bool first;
530
531         fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
532         first = true;
533         while (field->name != NULL) {
534             if (field->flags & VMS_MUST_EXIST) {
535                 /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
536                 field++;
537                 continue;
538             }
539             if (!first) {
540                 fprintf(out_file, ",\n");
541             }
542             dump_vmstate_vmsf(out_file, field, indent + 2);
543             field++;
544             first = false;
545         }
546         fprintf(out_file, "\n%*s]", indent, "");
547     }
548     if (vmsd->subsections != NULL) {
549         const VMStateDescription **subsection = vmsd->subsections;
550         bool first;
551
552         fprintf(out_file, ",\n%*s\"Subsections\": [\n", indent, "");
553         first = true;
554         while (*subsection != NULL) {
555             if (!first) {
556                 fprintf(out_file, ",\n");
557             }
558             dump_vmstate_vmss(out_file, subsection, indent + 2);
559             subsection++;
560             first = false;
561         }
562         fprintf(out_file, "\n%*s]", indent, "");
563     }
564     fprintf(out_file, "\n%*s}", indent - 2, "");
565 }
566
567 static void dump_machine_type(FILE *out_file)
568 {
569     MachineClass *mc;
570
571     mc = MACHINE_GET_CLASS(current_machine);
572
573     fprintf(out_file, "  \"vmschkmachine\": {\n");
574     fprintf(out_file, "    \"Name\": \"%s\"\n", mc->name);
575     fprintf(out_file, "  },\n");
576 }
577
578 void dump_vmstate_json_to_file(FILE *out_file)
579 {
580     GSList *list, *elt;
581     bool first;
582
583     fprintf(out_file, "{\n");
584     dump_machine_type(out_file);
585
586     first = true;
587     list = object_class_get_list(TYPE_DEVICE, true);
588     for (elt = list; elt; elt = elt->next) {
589         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
590                                              TYPE_DEVICE);
591         const char *name;
592         int indent = 2;
593
594         if (!dc->vmsd) {
595             continue;
596         }
597
598         if (!first) {
599             fprintf(out_file, ",\n");
600         }
601         name = object_class_get_name(OBJECT_CLASS(dc));
602         fprintf(out_file, "%*s\"%s\": {\n", indent, "", name);
603         indent += 2;
604         fprintf(out_file, "%*s\"Name\": \"%s\",\n", indent, "", name);
605         fprintf(out_file, "%*s\"version_id\": %d,\n", indent, "",
606                 dc->vmsd->version_id);
607         fprintf(out_file, "%*s\"minimum_version_id\": %d,\n", indent, "",
608                 dc->vmsd->minimum_version_id);
609
610         dump_vmstate_vmsd(out_file, dc->vmsd, indent, false);
611
612         fprintf(out_file, "\n%*s}", indent - 2, "");
613         first = false;
614     }
615     fprintf(out_file, "\n}\n");
616     fclose(out_file);
617 }
618
619 static int calculate_new_instance_id(const char *idstr)
620 {
621     SaveStateEntry *se;
622     int instance_id = 0;
623
624     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
625         if (strcmp(idstr, se->idstr) == 0
626             && instance_id <= se->instance_id) {
627             instance_id = se->instance_id + 1;
628         }
629     }
630     return instance_id;
631 }
632
633 static int calculate_compat_instance_id(const char *idstr)
634 {
635     SaveStateEntry *se;
636     int instance_id = 0;
637
638     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
639         if (!se->compat) {
640             continue;
641         }
642
643         if (strcmp(idstr, se->compat->idstr) == 0
644             && instance_id <= se->compat->instance_id) {
645             instance_id = se->compat->instance_id + 1;
646         }
647     }
648     return instance_id;
649 }
650
651 static inline MigrationPriority save_state_priority(SaveStateEntry *se)
652 {
653     if (se->vmsd) {
654         return se->vmsd->priority;
655     }
656     return MIG_PRI_DEFAULT;
657 }
658
659 static void savevm_state_handler_insert(SaveStateEntry *nse)
660 {
661     MigrationPriority priority = save_state_priority(nse);
662     SaveStateEntry *se;
663
664     assert(priority <= MIG_PRI_MAX);
665
666     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
667         if (save_state_priority(se) < priority) {
668             break;
669         }
670     }
671
672     if (se) {
673         QTAILQ_INSERT_BEFORE(se, nse, entry);
674     } else {
675         QTAILQ_INSERT_TAIL(&savevm_state.handlers, nse, entry);
676     }
677 }
678
679 /* TODO: Individual devices generally have very little idea about the rest
680    of the system, so instance_id should be removed/replaced.
681    Meanwhile pass -1 as instance_id if you do not already have a clearly
682    distinguishing id for all instances of your device class. */
683 int register_savevm_live(DeviceState *dev,
684                          const char *idstr,
685                          int instance_id,
686                          int version_id,
687                          const SaveVMHandlers *ops,
688                          void *opaque)
689 {
690     SaveStateEntry *se;
691
692     se = g_new0(SaveStateEntry, 1);
693     se->version_id = version_id;
694     se->section_id = savevm_state.global_section_id++;
695     se->ops = ops;
696     se->opaque = opaque;
697     se->vmsd = NULL;
698     /* if this is a live_savem then set is_ram */
699     if (ops->save_setup != NULL) {
700         se->is_ram = 1;
701     }
702
703     if (dev) {
704         char *id = qdev_get_dev_path(dev);
705         if (id) {
706             if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
707                 sizeof(se->idstr)) {
708                 error_report("Path too long for VMState (%s)", id);
709                 g_free(id);
710                 g_free(se);
711
712                 return -1;
713             }
714             g_free(id);
715
716             se->compat = g_new0(CompatEntry, 1);
717             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
718             se->compat->instance_id = instance_id == -1 ?
719                          calculate_compat_instance_id(idstr) : instance_id;
720             instance_id = -1;
721         }
722     }
723     pstrcat(se->idstr, sizeof(se->idstr), idstr);
724
725     if (instance_id == -1) {
726         se->instance_id = calculate_new_instance_id(se->idstr);
727     } else {
728         se->instance_id = instance_id;
729     }
730     assert(!se->compat || se->instance_id == 0);
731     savevm_state_handler_insert(se);
732     return 0;
733 }
734
735 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
736 {
737     SaveStateEntry *se, *new_se;
738     char id[256] = "";
739
740     if (dev) {
741         char *path = qdev_get_dev_path(dev);
742         if (path) {
743             pstrcpy(id, sizeof(id), path);
744             pstrcat(id, sizeof(id), "/");
745             g_free(path);
746         }
747     }
748     pstrcat(id, sizeof(id), idstr);
749
750     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
751         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
752             QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
753             g_free(se->compat);
754             g_free(se);
755         }
756     }
757 }
758
759 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
760                                    const VMStateDescription *vmsd,
761                                    void *opaque, int alias_id,
762                                    int required_for_version,
763                                    Error **errp)
764 {
765     SaveStateEntry *se;
766
767     /* If this triggers, alias support can be dropped for the vmsd. */
768     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
769
770     se = g_new0(SaveStateEntry, 1);
771     se->version_id = vmsd->version_id;
772     se->section_id = savevm_state.global_section_id++;
773     se->opaque = opaque;
774     se->vmsd = vmsd;
775     se->alias_id = alias_id;
776
777     if (dev) {
778         char *id = qdev_get_dev_path(dev);
779         if (id) {
780             if (snprintf(se->idstr, sizeof(se->idstr), "%s/", id) >=
781                 sizeof(se->idstr)) {
782                 error_setg(errp, "Path too long for VMState (%s)", id);
783                 g_free(id);
784                 g_free(se);
785
786                 return -1;
787             }
788             g_free(id);
789
790             se->compat = g_new0(CompatEntry, 1);
791             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
792             se->compat->instance_id = instance_id == -1 ?
793                          calculate_compat_instance_id(vmsd->name) : instance_id;
794             instance_id = -1;
795         }
796     }
797     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
798
799     if (instance_id == -1) {
800         se->instance_id = calculate_new_instance_id(se->idstr);
801     } else {
802         se->instance_id = instance_id;
803     }
804     assert(!se->compat || se->instance_id == 0);
805     savevm_state_handler_insert(se);
806     return 0;
807 }
808
809 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
810                         void *opaque)
811 {
812     SaveStateEntry *se, *new_se;
813
814     QTAILQ_FOREACH_SAFE(se, &savevm_state.handlers, entry, new_se) {
815         if (se->vmsd == vmsd && se->opaque == opaque) {
816             QTAILQ_REMOVE(&savevm_state.handlers, se, entry);
817             g_free(se->compat);
818             g_free(se);
819         }
820     }
821 }
822
823 static int vmstate_load(QEMUFile *f, SaveStateEntry *se)
824 {
825     trace_vmstate_load(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
826     if (!se->vmsd) {         /* Old style */
827         return se->ops->load_state(f, se->opaque, se->load_version_id);
828     }
829     return vmstate_load_state(f, se->vmsd, se->opaque, se->load_version_id);
830 }
831
832 static void vmstate_save_old_style(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
833 {
834     int64_t old_offset, size;
835
836     old_offset = qemu_ftell_fast(f);
837     se->ops->save_state(f, se->opaque);
838     size = qemu_ftell_fast(f) - old_offset;
839
840     if (vmdesc) {
841         json_prop_int(vmdesc, "size", size);
842         json_start_array(vmdesc, "fields");
843         json_start_object(vmdesc, NULL);
844         json_prop_str(vmdesc, "name", "data");
845         json_prop_int(vmdesc, "size", size);
846         json_prop_str(vmdesc, "type", "buffer");
847         json_end_object(vmdesc);
848         json_end_array(vmdesc);
849     }
850 }
851
852 static int vmstate_save(QEMUFile *f, SaveStateEntry *se, QJSON *vmdesc)
853 {
854     trace_vmstate_save(se->idstr, se->vmsd ? se->vmsd->name : "(old)");
855     if (!se->vmsd) {
856         vmstate_save_old_style(f, se, vmdesc);
857         return 0;
858     }
859     return vmstate_save_state(f, se->vmsd, se->opaque, vmdesc);
860 }
861
862 /*
863  * Write the header for device section (QEMU_VM_SECTION START/END/PART/FULL)
864  */
865 static void save_section_header(QEMUFile *f, SaveStateEntry *se,
866                                 uint8_t section_type)
867 {
868     qemu_put_byte(f, section_type);
869     qemu_put_be32(f, se->section_id);
870
871     if (section_type == QEMU_VM_SECTION_FULL ||
872         section_type == QEMU_VM_SECTION_START) {
873         /* ID string */
874         size_t len = strlen(se->idstr);
875         qemu_put_byte(f, len);
876         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
877
878         qemu_put_be32(f, se->instance_id);
879         qemu_put_be32(f, se->version_id);
880     }
881 }
882
883 /*
884  * Write a footer onto device sections that catches cases misformatted device
885  * sections.
886  */
887 static void save_section_footer(QEMUFile *f, SaveStateEntry *se)
888 {
889     if (migrate_get_current()->send_section_footer) {
890         qemu_put_byte(f, QEMU_VM_SECTION_FOOTER);
891         qemu_put_be32(f, se->section_id);
892     }
893 }
894
895 /**
896  * qemu_savevm_command_send: Send a 'QEMU_VM_COMMAND' type element with the
897  *                           command and associated data.
898  *
899  * @f: File to send command on
900  * @command: Command type to send
901  * @len: Length of associated data
902  * @data: Data associated with command.
903  */
904 static void qemu_savevm_command_send(QEMUFile *f,
905                                      enum qemu_vm_cmd command,
906                                      uint16_t len,
907                                      uint8_t *data)
908 {
909     trace_savevm_command_send(command, len);
910     qemu_put_byte(f, QEMU_VM_COMMAND);
911     qemu_put_be16(f, (uint16_t)command);
912     qemu_put_be16(f, len);
913     qemu_put_buffer(f, data, len);
914     qemu_fflush(f);
915 }
916
917 void qemu_savevm_send_colo_enable(QEMUFile *f)
918 {
919     trace_savevm_send_colo_enable();
920     qemu_savevm_command_send(f, MIG_CMD_ENABLE_COLO, 0, NULL);
921 }
922
923 void qemu_savevm_send_ping(QEMUFile *f, uint32_t value)
924 {
925     uint32_t buf;
926
927     trace_savevm_send_ping(value);
928     buf = cpu_to_be32(value);
929     qemu_savevm_command_send(f, MIG_CMD_PING, sizeof(value), (uint8_t *)&buf);
930 }
931
932 void qemu_savevm_send_open_return_path(QEMUFile *f)
933 {
934     trace_savevm_send_open_return_path();
935     qemu_savevm_command_send(f, MIG_CMD_OPEN_RETURN_PATH, 0, NULL);
936 }
937
938 /* We have a buffer of data to send; we don't want that all to be loaded
939  * by the command itself, so the command contains just the length of the
940  * extra buffer that we then send straight after it.
941  * TODO: Must be a better way to organise that
942  *
943  * Returns:
944  *    0 on success
945  *    -ve on error
946  */
947 int qemu_savevm_send_packaged(QEMUFile *f, const uint8_t *buf, size_t len)
948 {
949     uint32_t tmp;
950
951     if (len > MAX_VM_CMD_PACKAGED_SIZE) {
952         error_report("%s: Unreasonably large packaged state: %zu",
953                      __func__, len);
954         return -1;
955     }
956
957     tmp = cpu_to_be32(len);
958
959     trace_qemu_savevm_send_packaged();
960     qemu_savevm_command_send(f, MIG_CMD_PACKAGED, 4, (uint8_t *)&tmp);
961
962     qemu_put_buffer(f, buf, len);
963
964     return 0;
965 }
966
967 /* Send prior to any postcopy transfer */
968 void qemu_savevm_send_postcopy_advise(QEMUFile *f)
969 {
970     if (migrate_postcopy_ram()) {
971         uint64_t tmp[2];
972         tmp[0] = cpu_to_be64(ram_pagesize_summary());
973         tmp[1] = cpu_to_be64(qemu_target_page_size());
974
975         trace_qemu_savevm_send_postcopy_advise();
976         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE,
977                                  16, (uint8_t *)tmp);
978     } else {
979         qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_ADVISE, 0, NULL);
980     }
981 }
982
983 /* Sent prior to starting the destination running in postcopy, discard pages
984  * that have already been sent but redirtied on the source.
985  * CMD_POSTCOPY_RAM_DISCARD consist of:
986  *      byte   version (0)
987  *      byte   Length of name field (not including 0)
988  *  n x byte   RAM block name
989  *      byte   0 terminator (just for safety)
990  *  n x        Byte ranges within the named RAMBlock
991  *      be64   Start of the range
992  *      be64   Length
993  *
994  *  name:  RAMBlock name that these entries are part of
995  *  len: Number of page entries
996  *  start_list: 'len' addresses
997  *  length_list: 'len' addresses
998  *
999  */
1000 void qemu_savevm_send_postcopy_ram_discard(QEMUFile *f, const char *name,
1001                                            uint16_t len,
1002                                            uint64_t *start_list,
1003                                            uint64_t *length_list)
1004 {
1005     uint8_t *buf;
1006     uint16_t tmplen;
1007     uint16_t t;
1008     size_t name_len = strlen(name);
1009
1010     trace_qemu_savevm_send_postcopy_ram_discard(name, len);
1011     assert(name_len < 256);
1012     buf = g_malloc0(1 + 1 + name_len + 1 + (8 + 8) * len);
1013     buf[0] = postcopy_ram_discard_version;
1014     buf[1] = name_len;
1015     memcpy(buf + 2, name, name_len);
1016     tmplen = 2 + name_len;
1017     buf[tmplen++] = '\0';
1018
1019     for (t = 0; t < len; t++) {
1020         stq_be_p(buf + tmplen, start_list[t]);
1021         tmplen += 8;
1022         stq_be_p(buf + tmplen, length_list[t]);
1023         tmplen += 8;
1024     }
1025     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RAM_DISCARD, tmplen, buf);
1026     g_free(buf);
1027 }
1028
1029 /* Get the destination into a state where it can receive postcopy data. */
1030 void qemu_savevm_send_postcopy_listen(QEMUFile *f)
1031 {
1032     trace_savevm_send_postcopy_listen();
1033     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_LISTEN, 0, NULL);
1034 }
1035
1036 /* Kick the destination into running */
1037 void qemu_savevm_send_postcopy_run(QEMUFile *f)
1038 {
1039     trace_savevm_send_postcopy_run();
1040     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RUN, 0, NULL);
1041 }
1042
1043 void qemu_savevm_send_postcopy_resume(QEMUFile *f)
1044 {
1045     trace_savevm_send_postcopy_resume();
1046     qemu_savevm_command_send(f, MIG_CMD_POSTCOPY_RESUME, 0, NULL);
1047 }
1048
1049 void qemu_savevm_send_recv_bitmap(QEMUFile *f, char *block_name)
1050 {
1051     size_t len;
1052     char buf[256];
1053
1054     trace_savevm_send_recv_bitmap(block_name);
1055
1056     buf[0] = len = strlen(block_name);
1057     memcpy(buf + 1, block_name, len);
1058
1059     qemu_savevm_command_send(f, MIG_CMD_RECV_BITMAP, len + 1, (uint8_t *)buf);
1060 }
1061
1062 bool qemu_savevm_state_blocked(Error **errp)
1063 {
1064     SaveStateEntry *se;
1065
1066     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1067         if (se->vmsd && se->vmsd->unmigratable) {
1068             error_setg(errp, "State blocked by non-migratable device '%s'",
1069                        se->idstr);
1070             return true;
1071         }
1072     }
1073     return false;
1074 }
1075
1076 void qemu_savevm_state_header(QEMUFile *f)
1077 {
1078     trace_savevm_state_header();
1079     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1080     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1081
1082     if (migrate_get_current()->send_configuration) {
1083         qemu_put_byte(f, QEMU_VM_CONFIGURATION);
1084         vmstate_save_state(f, &vmstate_configuration, &savevm_state, 0);
1085     }
1086 }
1087
1088 void qemu_savevm_state_setup(QEMUFile *f)
1089 {
1090     SaveStateEntry *se;
1091     int ret;
1092
1093     trace_savevm_state_setup();
1094     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1095         if (!se->ops || !se->ops->save_setup) {
1096             continue;
1097         }
1098         if (se->ops && se->ops->is_active) {
1099             if (!se->ops->is_active(se->opaque)) {
1100                 continue;
1101             }
1102         }
1103         save_section_header(f, se, QEMU_VM_SECTION_START);
1104
1105         ret = se->ops->save_setup(f, se->opaque);
1106         save_section_footer(f, se);
1107         if (ret < 0) {
1108             qemu_file_set_error(f, ret);
1109             break;
1110         }
1111     }
1112 }
1113
1114 int qemu_savevm_state_resume_prepare(MigrationState *s)
1115 {
1116     SaveStateEntry *se;
1117     int ret;
1118
1119     trace_savevm_state_resume_prepare();
1120
1121     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1122         if (!se->ops || !se->ops->resume_prepare) {
1123             continue;
1124         }
1125         if (se->ops && se->ops->is_active) {
1126             if (!se->ops->is_active(se->opaque)) {
1127                 continue;
1128             }
1129         }
1130         ret = se->ops->resume_prepare(s, se->opaque);
1131         if (ret < 0) {
1132             return ret;
1133         }
1134     }
1135
1136     return 0;
1137 }
1138
1139 /*
1140  * this function has three return values:
1141  *   negative: there was one error, and we have -errno.
1142  *   0 : We haven't finished, caller have to go again
1143  *   1 : We have finished, we can go to complete phase
1144  */
1145 int qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
1146 {
1147     SaveStateEntry *se;
1148     int ret = 1;
1149
1150     trace_savevm_state_iterate();
1151     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1152         if (!se->ops || !se->ops->save_live_iterate) {
1153             continue;
1154         }
1155         if (se->ops && se->ops->is_active) {
1156             if (!se->ops->is_active(se->opaque)) {
1157                 continue;
1158             }
1159         }
1160         if (se->ops && se->ops->is_active_iterate) {
1161             if (!se->ops->is_active_iterate(se->opaque)) {
1162                 continue;
1163             }
1164         }
1165         /*
1166          * In the postcopy phase, any device that doesn't know how to
1167          * do postcopy should have saved it's state in the _complete
1168          * call that's already run, it might get confused if we call
1169          * iterate afterwards.
1170          */
1171         if (postcopy &&
1172             !(se->ops->has_postcopy && se->ops->has_postcopy(se->opaque))) {
1173             continue;
1174         }
1175         if (qemu_file_rate_limit(f)) {
1176             return 0;
1177         }
1178         trace_savevm_section_start(se->idstr, se->section_id);
1179
1180         save_section_header(f, se, QEMU_VM_SECTION_PART);
1181
1182         ret = se->ops->save_live_iterate(f, se->opaque);
1183         trace_savevm_section_end(se->idstr, se->section_id, ret);
1184         save_section_footer(f, se);
1185
1186         if (ret < 0) {
1187             qemu_file_set_error(f, ret);
1188         }
1189         if (ret <= 0) {
1190             /* Do not proceed to the next vmstate before this one reported
1191                completion of the current stage. This serializes the migration
1192                and reduces the probability that a faster changing state is
1193                synchronized over and over again. */
1194             break;
1195         }
1196     }
1197     return ret;
1198 }
1199
1200 static bool should_send_vmdesc(void)
1201 {
1202     MachineState *machine = MACHINE(qdev_get_machine());
1203     bool in_postcopy = migration_in_postcopy();
1204     return !machine->suppress_vmdesc && !in_postcopy;
1205 }
1206
1207 /*
1208  * Calls the save_live_complete_postcopy methods
1209  * causing the last few pages to be sent immediately and doing any associated
1210  * cleanup.
1211  * Note postcopy also calls qemu_savevm_state_complete_precopy to complete
1212  * all the other devices, but that happens at the point we switch to postcopy.
1213  */
1214 void qemu_savevm_state_complete_postcopy(QEMUFile *f)
1215 {
1216     SaveStateEntry *se;
1217     int ret;
1218
1219     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1220         if (!se->ops || !se->ops->save_live_complete_postcopy) {
1221             continue;
1222         }
1223         if (se->ops && se->ops->is_active) {
1224             if (!se->ops->is_active(se->opaque)) {
1225                 continue;
1226             }
1227         }
1228         trace_savevm_section_start(se->idstr, se->section_id);
1229         /* Section type */
1230         qemu_put_byte(f, QEMU_VM_SECTION_END);
1231         qemu_put_be32(f, se->section_id);
1232
1233         ret = se->ops->save_live_complete_postcopy(f, se->opaque);
1234         trace_savevm_section_end(se->idstr, se->section_id, ret);
1235         save_section_footer(f, se);
1236         if (ret < 0) {
1237             qemu_file_set_error(f, ret);
1238             return;
1239         }
1240     }
1241
1242     qemu_put_byte(f, QEMU_VM_EOF);
1243     qemu_fflush(f);
1244 }
1245
1246 int qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only,
1247                                        bool inactivate_disks)
1248 {
1249     QJSON *vmdesc;
1250     int vmdesc_len;
1251     SaveStateEntry *se;
1252     int ret;
1253     bool in_postcopy = migration_in_postcopy();
1254
1255     trace_savevm_state_complete_precopy();
1256
1257     cpu_synchronize_all_states();
1258
1259     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1260         if (!se->ops ||
1261             (in_postcopy && se->ops->has_postcopy &&
1262              se->ops->has_postcopy(se->opaque)) ||
1263             (in_postcopy && !iterable_only) ||
1264             !se->ops->save_live_complete_precopy) {
1265             continue;
1266         }
1267
1268         if (se->ops && se->ops->is_active) {
1269             if (!se->ops->is_active(se->opaque)) {
1270                 continue;
1271             }
1272         }
1273         trace_savevm_section_start(se->idstr, se->section_id);
1274
1275         save_section_header(f, se, QEMU_VM_SECTION_END);
1276
1277         ret = se->ops->save_live_complete_precopy(f, se->opaque);
1278         trace_savevm_section_end(se->idstr, se->section_id, ret);
1279         save_section_footer(f, se);
1280         if (ret < 0) {
1281             qemu_file_set_error(f, ret);
1282             return -1;
1283         }
1284     }
1285
1286     if (iterable_only) {
1287         return 0;
1288     }
1289
1290     vmdesc = qjson_new();
1291     json_prop_int(vmdesc, "page_size", qemu_target_page_size());
1292     json_start_array(vmdesc, "devices");
1293     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1294
1295         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1296             continue;
1297         }
1298         if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1299             trace_savevm_section_skip(se->idstr, se->section_id);
1300             continue;
1301         }
1302
1303         trace_savevm_section_start(se->idstr, se->section_id);
1304
1305         json_start_object(vmdesc, NULL);
1306         json_prop_str(vmdesc, "name", se->idstr);
1307         json_prop_int(vmdesc, "instance_id", se->instance_id);
1308
1309         save_section_header(f, se, QEMU_VM_SECTION_FULL);
1310         ret = vmstate_save(f, se, vmdesc);
1311         if (ret) {
1312             qemu_file_set_error(f, ret);
1313             return ret;
1314         }
1315         trace_savevm_section_end(se->idstr, se->section_id, 0);
1316         save_section_footer(f, se);
1317
1318         json_end_object(vmdesc);
1319     }
1320
1321     if (inactivate_disks) {
1322         /* Inactivate before sending QEMU_VM_EOF so that the
1323          * bdrv_invalidate_cache_all() on the other end won't fail. */
1324         ret = bdrv_inactivate_all();
1325         if (ret) {
1326             error_report("%s: bdrv_inactivate_all() failed (%d)",
1327                          __func__, ret);
1328             qemu_file_set_error(f, ret);
1329             return ret;
1330         }
1331     }
1332     if (!in_postcopy) {
1333         /* Postcopy stream will still be going */
1334         qemu_put_byte(f, QEMU_VM_EOF);
1335     }
1336
1337     json_end_array(vmdesc);
1338     qjson_finish(vmdesc);
1339     vmdesc_len = strlen(qjson_get_str(vmdesc));
1340
1341     if (should_send_vmdesc()) {
1342         qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);
1343         qemu_put_be32(f, vmdesc_len);
1344         qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);
1345     }
1346     qjson_destroy(vmdesc);
1347
1348     qemu_fflush(f);
1349     return 0;
1350 }
1351
1352 /* Give an estimate of the amount left to be transferred,
1353  * the result is split into the amount for units that can and
1354  * for units that can't do postcopy.
1355  */
1356 void qemu_savevm_state_pending(QEMUFile *f, uint64_t threshold_size,
1357                                uint64_t *res_precopy_only,
1358                                uint64_t *res_compatible,
1359                                uint64_t *res_postcopy_only)
1360 {
1361     SaveStateEntry *se;
1362
1363     *res_precopy_only = 0;
1364     *res_compatible = 0;
1365     *res_postcopy_only = 0;
1366
1367
1368     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1369         if (!se->ops || !se->ops->save_live_pending) {
1370             continue;
1371         }
1372         if (se->ops && se->ops->is_active) {
1373             if (!se->ops->is_active(se->opaque)) {
1374                 continue;
1375             }
1376         }
1377         se->ops->save_live_pending(f, se->opaque, threshold_size,
1378                                    res_precopy_only, res_compatible,
1379                                    res_postcopy_only);
1380     }
1381 }
1382
1383 void qemu_savevm_state_cleanup(void)
1384 {
1385     SaveStateEntry *se;
1386
1387     trace_savevm_state_cleanup();
1388     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1389         if (se->ops && se->ops->save_cleanup) {
1390             se->ops->save_cleanup(se->opaque);
1391         }
1392     }
1393 }
1394
1395 static int qemu_savevm_state(QEMUFile *f, Error **errp)
1396 {
1397     int ret;
1398     MigrationState *ms = migrate_get_current();
1399     MigrationStatus status;
1400
1401     if (migration_is_setup_or_active(ms->state) ||
1402         ms->state == MIGRATION_STATUS_CANCELLING ||
1403         ms->state == MIGRATION_STATUS_COLO) {
1404         error_setg(errp, QERR_MIGRATION_ACTIVE);
1405         return -EINVAL;
1406     }
1407
1408     if (migration_is_blocked(errp)) {
1409         return -EINVAL;
1410     }
1411
1412     if (migrate_use_block()) {
1413         error_setg(errp, "Block migration and snapshots are incompatible");
1414         return -EINVAL;
1415     }
1416
1417     migrate_init(ms);
1418     ms->to_dst_file = f;
1419
1420     qemu_mutex_unlock_iothread();
1421     qemu_savevm_state_header(f);
1422     qemu_savevm_state_setup(f);
1423     qemu_mutex_lock_iothread();
1424
1425     while (qemu_file_get_error(f) == 0) {
1426         if (qemu_savevm_state_iterate(f, false) > 0) {
1427             break;
1428         }
1429     }
1430
1431     ret = qemu_file_get_error(f);
1432     if (ret == 0) {
1433         qemu_savevm_state_complete_precopy(f, false, false);
1434         ret = qemu_file_get_error(f);
1435     }
1436     qemu_savevm_state_cleanup();
1437     if (ret != 0) {
1438         error_setg_errno(errp, -ret, "Error while writing VM state");
1439     }
1440
1441     if (ret != 0) {
1442         status = MIGRATION_STATUS_FAILED;
1443     } else {
1444         status = MIGRATION_STATUS_COMPLETED;
1445     }
1446     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP, status);
1447
1448     /* f is outer parameter, it should not stay in global migration state after
1449      * this function finished */
1450     ms->to_dst_file = NULL;
1451
1452     return ret;
1453 }
1454
1455 void qemu_savevm_live_state(QEMUFile *f)
1456 {
1457     /* save QEMU_VM_SECTION_END section */
1458     qemu_savevm_state_complete_precopy(f, true, false);
1459     qemu_put_byte(f, QEMU_VM_EOF);
1460 }
1461
1462 int qemu_save_device_state(QEMUFile *f)
1463 {
1464     SaveStateEntry *se;
1465
1466     if (!migration_in_colo_state()) {
1467         qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1468         qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1469     }
1470     cpu_synchronize_all_states();
1471
1472     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1473         int ret;
1474
1475         if (se->is_ram) {
1476             continue;
1477         }
1478         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1479             continue;
1480         }
1481         if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {
1482             continue;
1483         }
1484
1485         save_section_header(f, se, QEMU_VM_SECTION_FULL);
1486
1487         ret = vmstate_save(f, se, NULL);
1488         if (ret) {
1489             return ret;
1490         }
1491
1492         save_section_footer(f, se);
1493     }
1494
1495     qemu_put_byte(f, QEMU_VM_EOF);
1496
1497     return qemu_file_get_error(f);
1498 }
1499
1500 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1501 {
1502     SaveStateEntry *se;
1503
1504     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
1505         if (!strcmp(se->idstr, idstr) &&
1506             (instance_id == se->instance_id ||
1507              instance_id == se->alias_id))
1508             return se;
1509         /* Migrating from an older version? */
1510         if (strstr(se->idstr, idstr) && se->compat) {
1511             if (!strcmp(se->compat->idstr, idstr) &&
1512                 (instance_id == se->compat->instance_id ||
1513                  instance_id == se->alias_id))
1514                 return se;
1515         }
1516     }
1517     return NULL;
1518 }
1519
1520 enum LoadVMExitCodes {
1521     /* Allow a command to quit all layers of nested loadvm loops */
1522     LOADVM_QUIT     =  1,
1523 };
1524
1525 /* ------ incoming postcopy messages ------ */
1526 /* 'advise' arrives before any transfers just to tell us that a postcopy
1527  * *might* happen - it might be skipped if precopy transferred everything
1528  * quickly.
1529  */
1530 static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis,
1531                                          uint16_t len)
1532 {
1533     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1534     uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;
1535     Error *local_err = NULL;
1536
1537     trace_loadvm_postcopy_handle_advise();
1538     if (ps != POSTCOPY_INCOMING_NONE) {
1539         error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);
1540         return -1;
1541     }
1542
1543     switch (len) {
1544     case 0:
1545         if (migrate_postcopy_ram()) {
1546             error_report("RAM postcopy is enabled but have 0 byte advise");
1547             return -EINVAL;
1548         }
1549         return 0;
1550     case 8 + 8:
1551         if (!migrate_postcopy_ram()) {
1552             error_report("RAM postcopy is disabled but have 16 byte advise");
1553             return -EINVAL;
1554         }
1555         break;
1556     default:
1557         error_report("CMD_POSTCOPY_ADVISE invalid length (%d)", len);
1558         return -EINVAL;
1559     }
1560
1561     if (!postcopy_ram_supported_by_host(mis)) {
1562         postcopy_state_set(POSTCOPY_INCOMING_NONE);
1563         return -1;
1564     }
1565
1566     remote_pagesize_summary = qemu_get_be64(mis->from_src_file);
1567     local_pagesize_summary = ram_pagesize_summary();
1568
1569     if (remote_pagesize_summary != local_pagesize_summary)  {
1570         /*
1571          * This detects two potential causes of mismatch:
1572          *   a) A mismatch in host page sizes
1573          *      Some combinations of mismatch are probably possible but it gets
1574          *      a bit more complicated.  In particular we need to place whole
1575          *      host pages on the dest at once, and we need to ensure that we
1576          *      handle dirtying to make sure we never end up sending part of
1577          *      a hostpage on it's own.
1578          *   b) The use of different huge page sizes on source/destination
1579          *      a more fine grain test is performed during RAM block migration
1580          *      but this test here causes a nice early clear failure, and
1581          *      also fails when passed to an older qemu that doesn't
1582          *      do huge pages.
1583          */
1584         error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64
1585                                                              " d=%" PRIx64 ")",
1586                      remote_pagesize_summary, local_pagesize_summary);
1587         return -1;
1588     }
1589
1590     remote_tps = qemu_get_be64(mis->from_src_file);
1591     if (remote_tps != qemu_target_page_size()) {
1592         /*
1593          * Again, some differences could be dealt with, but for now keep it
1594          * simple.
1595          */
1596         error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",
1597                      (int)remote_tps, qemu_target_page_size());
1598         return -1;
1599     }
1600
1601     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_ADVISE, &local_err)) {
1602         error_report_err(local_err);
1603         return -1;
1604     }
1605
1606     if (ram_postcopy_incoming_init(mis)) {
1607         return -1;
1608     }
1609
1610     postcopy_state_set(POSTCOPY_INCOMING_ADVISE);
1611
1612     return 0;
1613 }
1614
1615 /* After postcopy we will be told to throw some pages away since they're
1616  * dirty and will have to be demand fetched.  Must happen before CPU is
1617  * started.
1618  * There can be 0..many of these messages, each encoding multiple pages.
1619  */
1620 static int loadvm_postcopy_ram_handle_discard(MigrationIncomingState *mis,
1621                                               uint16_t len)
1622 {
1623     int tmp;
1624     char ramid[256];
1625     PostcopyState ps = postcopy_state_get();
1626
1627     trace_loadvm_postcopy_ram_handle_discard();
1628
1629     switch (ps) {
1630     case POSTCOPY_INCOMING_ADVISE:
1631         /* 1st discard */
1632         tmp = postcopy_ram_prepare_discard(mis);
1633         if (tmp) {
1634             return tmp;
1635         }
1636         break;
1637
1638     case POSTCOPY_INCOMING_DISCARD:
1639         /* Expected state */
1640         break;
1641
1642     default:
1643         error_report("CMD_POSTCOPY_RAM_DISCARD in wrong postcopy state (%d)",
1644                      ps);
1645         return -1;
1646     }
1647     /* We're expecting a
1648      *    Version (0)
1649      *    a RAM ID string (length byte, name, 0 term)
1650      *    then at least 1 16 byte chunk
1651     */
1652     if (len < (1 + 1 + 1 + 1 + 2 * 8)) {
1653         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1654         return -1;
1655     }
1656
1657     tmp = qemu_get_byte(mis->from_src_file);
1658     if (tmp != postcopy_ram_discard_version) {
1659         error_report("CMD_POSTCOPY_RAM_DISCARD invalid version (%d)", tmp);
1660         return -1;
1661     }
1662
1663     if (!qemu_get_counted_string(mis->from_src_file, ramid)) {
1664         error_report("CMD_POSTCOPY_RAM_DISCARD Failed to read RAMBlock ID");
1665         return -1;
1666     }
1667     tmp = qemu_get_byte(mis->from_src_file);
1668     if (tmp != 0) {
1669         error_report("CMD_POSTCOPY_RAM_DISCARD missing nil (%d)", tmp);
1670         return -1;
1671     }
1672
1673     len -= 3 + strlen(ramid);
1674     if (len % 16) {
1675         error_report("CMD_POSTCOPY_RAM_DISCARD invalid length (%d)", len);
1676         return -1;
1677     }
1678     trace_loadvm_postcopy_ram_handle_discard_header(ramid, len);
1679     while (len) {
1680         uint64_t start_addr, block_length;
1681         start_addr = qemu_get_be64(mis->from_src_file);
1682         block_length = qemu_get_be64(mis->from_src_file);
1683
1684         len -= 16;
1685         int ret = ram_discard_range(ramid, start_addr, block_length);
1686         if (ret) {
1687             return ret;
1688         }
1689     }
1690     trace_loadvm_postcopy_ram_handle_discard_end();
1691
1692     return 0;
1693 }
1694
1695 /*
1696  * Triggered by a postcopy_listen command; this thread takes over reading
1697  * the input stream, leaving the main thread free to carry on loading the rest
1698  * of the device state (from RAM).
1699  * (TODO:This could do with being in a postcopy file - but there again it's
1700  * just another input loop, not that postcopy specific)
1701  */
1702 static void *postcopy_ram_listen_thread(void *opaque)
1703 {
1704     MigrationIncomingState *mis = migration_incoming_get_current();
1705     QEMUFile *f = mis->from_src_file;
1706     int load_res;
1707
1708     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
1709                                    MIGRATION_STATUS_POSTCOPY_ACTIVE);
1710     qemu_sem_post(&mis->listen_thread_sem);
1711     trace_postcopy_ram_listen_thread_start();
1712
1713     rcu_register_thread();
1714     /*
1715      * Because we're a thread and not a coroutine we can't yield
1716      * in qemu_file, and thus we must be blocking now.
1717      */
1718     qemu_file_set_blocking(f, true);
1719     load_res = qemu_loadvm_state_main(f, mis);
1720
1721     /*
1722      * This is tricky, but, mis->from_src_file can change after it
1723      * returns, when postcopy recovery happened. In the future, we may
1724      * want a wrapper for the QEMUFile handle.
1725      */
1726     f = mis->from_src_file;
1727
1728     /* And non-blocking again so we don't block in any cleanup */
1729     qemu_file_set_blocking(f, false);
1730
1731     trace_postcopy_ram_listen_thread_exit();
1732     if (load_res < 0) {
1733         error_report("%s: loadvm failed: %d", __func__, load_res);
1734         qemu_file_set_error(f, load_res);
1735         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1736                                        MIGRATION_STATUS_FAILED);
1737     } else {
1738         /*
1739          * This looks good, but it's possible that the device loading in the
1740          * main thread hasn't finished yet, and so we might not be in 'RUN'
1741          * state yet; wait for the end of the main thread.
1742          */
1743         qemu_event_wait(&mis->main_thread_load_event);
1744     }
1745     postcopy_ram_incoming_cleanup(mis);
1746
1747     if (load_res < 0) {
1748         /*
1749          * If something went wrong then we have a bad state so exit;
1750          * depending how far we got it might be possible at this point
1751          * to leave the guest running and fire MCEs for pages that never
1752          * arrived as a desperate recovery step.
1753          */
1754         rcu_unregister_thread();
1755         exit(EXIT_FAILURE);
1756     }
1757
1758     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1759                                    MIGRATION_STATUS_COMPLETED);
1760     /*
1761      * If everything has worked fine, then the main thread has waited
1762      * for us to start, and we're the last use of the mis.
1763      * (If something broke then qemu will have to exit anyway since it's
1764      * got a bad migration state).
1765      */
1766     migration_incoming_state_destroy();
1767     qemu_loadvm_state_cleanup();
1768
1769     rcu_unregister_thread();
1770     mis->have_listen_thread = false;
1771     return NULL;
1772 }
1773
1774 /* After this message we must be able to immediately receive postcopy data */
1775 static int loadvm_postcopy_handle_listen(MigrationIncomingState *mis)
1776 {
1777     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_LISTENING);
1778     trace_loadvm_postcopy_handle_listen();
1779     Error *local_err = NULL;
1780
1781     if (ps != POSTCOPY_INCOMING_ADVISE && ps != POSTCOPY_INCOMING_DISCARD) {
1782         error_report("CMD_POSTCOPY_LISTEN in wrong postcopy state (%d)", ps);
1783         return -1;
1784     }
1785     if (ps == POSTCOPY_INCOMING_ADVISE) {
1786         /*
1787          * A rare case, we entered listen without having to do any discards,
1788          * so do the setup that's normally done at the time of the 1st discard.
1789          */
1790         if (migrate_postcopy_ram()) {
1791             postcopy_ram_prepare_discard(mis);
1792         }
1793     }
1794
1795     /*
1796      * Sensitise RAM - can now generate requests for blocks that don't exist
1797      * However, at this point the CPU shouldn't be running, and the IO
1798      * shouldn't be doing anything yet so don't actually expect requests
1799      */
1800     if (migrate_postcopy_ram()) {
1801         if (postcopy_ram_enable_notify(mis)) {
1802             postcopy_ram_incoming_cleanup(mis);
1803             return -1;
1804         }
1805     }
1806
1807     if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_LISTEN, &local_err)) {
1808         error_report_err(local_err);
1809         return -1;
1810     }
1811
1812     if (mis->have_listen_thread) {
1813         error_report("CMD_POSTCOPY_RAM_LISTEN already has a listen thread");
1814         return -1;
1815     }
1816
1817     mis->have_listen_thread = true;
1818     /* Start up the listening thread and wait for it to signal ready */
1819     qemu_sem_init(&mis->listen_thread_sem, 0);
1820     qemu_thread_create(&mis->listen_thread, "postcopy/listen",
1821                        postcopy_ram_listen_thread, NULL,
1822                        QEMU_THREAD_DETACHED);
1823     qemu_sem_wait(&mis->listen_thread_sem);
1824     qemu_sem_destroy(&mis->listen_thread_sem);
1825
1826     return 0;
1827 }
1828
1829
1830 typedef struct {
1831     QEMUBH *bh;
1832 } HandleRunBhData;
1833
1834 static void loadvm_postcopy_handle_run_bh(void *opaque)
1835 {
1836     Error *local_err = NULL;
1837     HandleRunBhData *data = opaque;
1838     MigrationIncomingState *mis = migration_incoming_get_current();
1839
1840     /* TODO we should move all of this lot into postcopy_ram.c or a shared code
1841      * in migration.c
1842      */
1843     cpu_synchronize_all_post_init();
1844
1845     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
1846
1847     /* Make sure all file formats flush their mutable metadata.
1848      * If we get an error here, just don't restart the VM yet. */
1849     bdrv_invalidate_cache_all(&local_err);
1850     if (local_err) {
1851         error_report_err(local_err);
1852         local_err = NULL;
1853         autostart = false;
1854     }
1855
1856     trace_loadvm_postcopy_handle_run_cpu_sync();
1857     cpu_synchronize_all_post_init();
1858
1859     trace_loadvm_postcopy_handle_run_vmstart();
1860
1861     dirty_bitmap_mig_before_vm_start();
1862
1863     if (autostart) {
1864         /* Hold onto your hats, starting the CPU */
1865         vm_start();
1866     } else {
1867         /* leave it paused and let management decide when to start the CPU */
1868         runstate_set(RUN_STATE_PAUSED);
1869     }
1870
1871     qemu_bh_delete(data->bh);
1872     g_free(data);
1873 }
1874
1875 /* After all discards we can start running and asking for pages */
1876 static int loadvm_postcopy_handle_run(MigrationIncomingState *mis)
1877 {
1878     PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_RUNNING);
1879     HandleRunBhData *data;
1880
1881     trace_loadvm_postcopy_handle_run();
1882     if (ps != POSTCOPY_INCOMING_LISTENING) {
1883         error_report("CMD_POSTCOPY_RUN in wrong postcopy state (%d)", ps);
1884         return -1;
1885     }
1886
1887     data = g_new(HandleRunBhData, 1);
1888     data->bh = qemu_bh_new(loadvm_postcopy_handle_run_bh, data);
1889     qemu_bh_schedule(data->bh);
1890
1891     /* We need to finish reading the stream from the package
1892      * and also stop reading anything more from the stream that loaded the
1893      * package (since it's now being read by the listener thread).
1894      * LOADVM_QUIT will quit all the layers of nested loadvm loops.
1895      */
1896     return LOADVM_QUIT;
1897 }
1898
1899 static int loadvm_postcopy_handle_resume(MigrationIncomingState *mis)
1900 {
1901     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
1902         error_report("%s: illegal resume received", __func__);
1903         /* Don't fail the load, only for this. */
1904         return 0;
1905     }
1906
1907     /*
1908      * This means source VM is ready to resume the postcopy migration.
1909      * It's time to switch state and release the fault thread to
1910      * continue service page faults.
1911      */
1912     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1913                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
1914     qemu_sem_post(&mis->postcopy_pause_sem_fault);
1915
1916     trace_loadvm_postcopy_handle_resume();
1917
1918     /* Tell source that "we are ready" */
1919     migrate_send_rp_resume_ack(mis, MIGRATION_RESUME_ACK_VALUE);
1920
1921     return 0;
1922 }
1923
1924 /**
1925  * Immediately following this command is a blob of data containing an embedded
1926  * chunk of migration stream; read it and load it.
1927  *
1928  * @mis: Incoming state
1929  * @length: Length of packaged data to read
1930  *
1931  * Returns: Negative values on error
1932  *
1933  */
1934 static int loadvm_handle_cmd_packaged(MigrationIncomingState *mis)
1935 {
1936     int ret;
1937     size_t length;
1938     QIOChannelBuffer *bioc;
1939
1940     length = qemu_get_be32(mis->from_src_file);
1941     trace_loadvm_handle_cmd_packaged(length);
1942
1943     if (length > MAX_VM_CMD_PACKAGED_SIZE) {
1944         error_report("Unreasonably large packaged state: %zu", length);
1945         return -1;
1946     }
1947
1948     bioc = qio_channel_buffer_new(length);
1949     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-loadvm-buffer");
1950     ret = qemu_get_buffer(mis->from_src_file,
1951                           bioc->data,
1952                           length);
1953     if (ret != length) {
1954         object_unref(OBJECT(bioc));
1955         error_report("CMD_PACKAGED: Buffer receive fail ret=%d length=%zu",
1956                      ret, length);
1957         return (ret < 0) ? ret : -EAGAIN;
1958     }
1959     bioc->usage += length;
1960     trace_loadvm_handle_cmd_packaged_received(ret);
1961
1962     QEMUFile *packf = qemu_fopen_channel_input(QIO_CHANNEL(bioc));
1963
1964     ret = qemu_loadvm_state_main(packf, mis);
1965     trace_loadvm_handle_cmd_packaged_main(ret);
1966     qemu_fclose(packf);
1967     object_unref(OBJECT(bioc));
1968
1969     return ret;
1970 }
1971
1972 /*
1973  * Handle request that source requests for recved_bitmap on
1974  * destination. Payload format:
1975  *
1976  * len (1 byte) + ramblock_name (<255 bytes)
1977  */
1978 static int loadvm_handle_recv_bitmap(MigrationIncomingState *mis,
1979                                      uint16_t len)
1980 {
1981     QEMUFile *file = mis->from_src_file;
1982     RAMBlock *rb;
1983     char block_name[256];
1984     size_t cnt;
1985
1986     cnt = qemu_get_counted_string(file, block_name);
1987     if (!cnt) {
1988         error_report("%s: failed to read block name", __func__);
1989         return -EINVAL;
1990     }
1991
1992     /* Validate before using the data */
1993     if (qemu_file_get_error(file)) {
1994         return qemu_file_get_error(file);
1995     }
1996
1997     if (len != cnt + 1) {
1998         error_report("%s: invalid payload length (%d)", __func__, len);
1999         return -EINVAL;
2000     }
2001
2002     rb = qemu_ram_block_by_name(block_name);
2003     if (!rb) {
2004         error_report("%s: block '%s' not found", __func__, block_name);
2005         return -EINVAL;
2006     }
2007
2008     migrate_send_rp_recv_bitmap(mis, block_name);
2009
2010     trace_loadvm_handle_recv_bitmap(block_name);
2011
2012     return 0;
2013 }
2014
2015 static int loadvm_process_enable_colo(MigrationIncomingState *mis)
2016 {
2017     migration_incoming_enable_colo();
2018     return colo_init_ram_cache();
2019 }
2020
2021 /*
2022  * Process an incoming 'QEMU_VM_COMMAND'
2023  * 0           just a normal return
2024  * LOADVM_QUIT All good, but exit the loop
2025  * <0          Error
2026  */
2027 static int loadvm_process_command(QEMUFile *f)
2028 {
2029     MigrationIncomingState *mis = migration_incoming_get_current();
2030     uint16_t cmd;
2031     uint16_t len;
2032     uint32_t tmp32;
2033
2034     cmd = qemu_get_be16(f);
2035     len = qemu_get_be16(f);
2036
2037     /* Check validity before continue processing of cmds */
2038     if (qemu_file_get_error(f)) {
2039         return qemu_file_get_error(f);
2040     }
2041
2042     trace_loadvm_process_command(cmd, len);
2043     if (cmd >= MIG_CMD_MAX || cmd == MIG_CMD_INVALID) {
2044         error_report("MIG_CMD 0x%x unknown (len 0x%x)", cmd, len);
2045         return -EINVAL;
2046     }
2047
2048     if (mig_cmd_args[cmd].len != -1 && mig_cmd_args[cmd].len != len) {
2049         error_report("%s received with bad length - expecting %zu, got %d",
2050                      mig_cmd_args[cmd].name,
2051                      (size_t)mig_cmd_args[cmd].len, len);
2052         return -ERANGE;
2053     }
2054
2055     switch (cmd) {
2056     case MIG_CMD_OPEN_RETURN_PATH:
2057         if (mis->to_src_file) {
2058             error_report("CMD_OPEN_RETURN_PATH called when RP already open");
2059             /* Not really a problem, so don't give up */
2060             return 0;
2061         }
2062         mis->to_src_file = qemu_file_get_return_path(f);
2063         if (!mis->to_src_file) {
2064             error_report("CMD_OPEN_RETURN_PATH failed");
2065             return -1;
2066         }
2067         break;
2068
2069     case MIG_CMD_PING:
2070         tmp32 = qemu_get_be32(f);
2071         trace_loadvm_process_command_ping(tmp32);
2072         if (!mis->to_src_file) {
2073             error_report("CMD_PING (0x%x) received with no return path",
2074                          tmp32);
2075             return -1;
2076         }
2077         migrate_send_rp_pong(mis, tmp32);
2078         break;
2079
2080     case MIG_CMD_PACKAGED:
2081         return loadvm_handle_cmd_packaged(mis);
2082
2083     case MIG_CMD_POSTCOPY_ADVISE:
2084         return loadvm_postcopy_handle_advise(mis, len);
2085
2086     case MIG_CMD_POSTCOPY_LISTEN:
2087         return loadvm_postcopy_handle_listen(mis);
2088
2089     case MIG_CMD_POSTCOPY_RUN:
2090         return loadvm_postcopy_handle_run(mis);
2091
2092     case MIG_CMD_POSTCOPY_RAM_DISCARD:
2093         return loadvm_postcopy_ram_handle_discard(mis, len);
2094
2095     case MIG_CMD_POSTCOPY_RESUME:
2096         return loadvm_postcopy_handle_resume(mis);
2097
2098     case MIG_CMD_RECV_BITMAP:
2099         return loadvm_handle_recv_bitmap(mis, len);
2100
2101     case MIG_CMD_ENABLE_COLO:
2102         return loadvm_process_enable_colo(mis);
2103     }
2104
2105     return 0;
2106 }
2107
2108 /*
2109  * Read a footer off the wire and check that it matches the expected section
2110  *
2111  * Returns: true if the footer was good
2112  *          false if there is a problem (and calls error_report to say why)
2113  */
2114 static bool check_section_footer(QEMUFile *f, SaveStateEntry *se)
2115 {
2116     int ret;
2117     uint8_t read_mark;
2118     uint32_t read_section_id;
2119
2120     if (!migrate_get_current()->send_section_footer) {
2121         /* No footer to check */
2122         return true;
2123     }
2124
2125     read_mark = qemu_get_byte(f);
2126
2127     ret = qemu_file_get_error(f);
2128     if (ret) {
2129         error_report("%s: Read section footer failed: %d",
2130                      __func__, ret);
2131         return false;
2132     }
2133
2134     if (read_mark != QEMU_VM_SECTION_FOOTER) {
2135         error_report("Missing section footer for %s", se->idstr);
2136         return false;
2137     }
2138
2139     read_section_id = qemu_get_be32(f);
2140     if (read_section_id != se->load_section_id) {
2141         error_report("Mismatched section id in footer for %s -"
2142                      " read 0x%x expected 0x%x",
2143                      se->idstr, read_section_id, se->load_section_id);
2144         return false;
2145     }
2146
2147     /* All good */
2148     return true;
2149 }
2150
2151 static int
2152 qemu_loadvm_section_start_full(QEMUFile *f, MigrationIncomingState *mis)
2153 {
2154     uint32_t instance_id, version_id, section_id;
2155     SaveStateEntry *se;
2156     char idstr[256];
2157     int ret;
2158
2159     /* Read section start */
2160     section_id = qemu_get_be32(f);
2161     if (!qemu_get_counted_string(f, idstr)) {
2162         error_report("Unable to read ID string for section %u",
2163                      section_id);
2164         return -EINVAL;
2165     }
2166     instance_id = qemu_get_be32(f);
2167     version_id = qemu_get_be32(f);
2168
2169     ret = qemu_file_get_error(f);
2170     if (ret) {
2171         error_report("%s: Failed to read instance/version ID: %d",
2172                      __func__, ret);
2173         return ret;
2174     }
2175
2176     trace_qemu_loadvm_state_section_startfull(section_id, idstr,
2177             instance_id, version_id);
2178     /* Find savevm section */
2179     se = find_se(idstr, instance_id);
2180     if (se == NULL) {
2181         error_report("Unknown savevm section or instance '%s' %d. "
2182                      "Make sure that your current VM setup matches your "
2183                      "saved VM setup, including any hotplugged devices",
2184                      idstr, instance_id);
2185         return -EINVAL;
2186     }
2187
2188     /* Validate version */
2189     if (version_id > se->version_id) {
2190         error_report("savevm: unsupported version %d for '%s' v%d",
2191                      version_id, idstr, se->version_id);
2192         return -EINVAL;
2193     }
2194     se->load_version_id = version_id;
2195     se->load_section_id = section_id;
2196
2197     /* Validate if it is a device's state */
2198     if (xen_enabled() && se->is_ram) {
2199         error_report("loadvm: %s RAM loading not allowed on Xen", idstr);
2200         return -EINVAL;
2201     }
2202
2203     ret = vmstate_load(f, se);
2204     if (ret < 0) {
2205         error_report("error while loading state for instance 0x%x of"
2206                      " device '%s'", instance_id, idstr);
2207         return ret;
2208     }
2209     if (!check_section_footer(f, se)) {
2210         return -EINVAL;
2211     }
2212
2213     return 0;
2214 }
2215
2216 static int
2217 qemu_loadvm_section_part_end(QEMUFile *f, MigrationIncomingState *mis)
2218 {
2219     uint32_t section_id;
2220     SaveStateEntry *se;
2221     int ret;
2222
2223     section_id = qemu_get_be32(f);
2224
2225     ret = qemu_file_get_error(f);
2226     if (ret) {
2227         error_report("%s: Failed to read section ID: %d",
2228                      __func__, ret);
2229         return ret;
2230     }
2231
2232     trace_qemu_loadvm_state_section_partend(section_id);
2233     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2234         if (se->load_section_id == section_id) {
2235             break;
2236         }
2237     }
2238     if (se == NULL) {
2239         error_report("Unknown savevm section %d", section_id);
2240         return -EINVAL;
2241     }
2242
2243     ret = vmstate_load(f, se);
2244     if (ret < 0) {
2245         error_report("error while loading state section id %d(%s)",
2246                      section_id, se->idstr);
2247         return ret;
2248     }
2249     if (!check_section_footer(f, se)) {
2250         return -EINVAL;
2251     }
2252
2253     return 0;
2254 }
2255
2256 static int qemu_loadvm_state_setup(QEMUFile *f)
2257 {
2258     SaveStateEntry *se;
2259     int ret;
2260
2261     trace_loadvm_state_setup();
2262     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2263         if (!se->ops || !se->ops->load_setup) {
2264             continue;
2265         }
2266         if (se->ops && se->ops->is_active) {
2267             if (!se->ops->is_active(se->opaque)) {
2268                 continue;
2269             }
2270         }
2271
2272         ret = se->ops->load_setup(f, se->opaque);
2273         if (ret < 0) {
2274             qemu_file_set_error(f, ret);
2275             error_report("Load state of device %s failed", se->idstr);
2276             return ret;
2277         }
2278     }
2279     return 0;
2280 }
2281
2282 void qemu_loadvm_state_cleanup(void)
2283 {
2284     SaveStateEntry *se;
2285
2286     trace_loadvm_state_cleanup();
2287     QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
2288         if (se->ops && se->ops->load_cleanup) {
2289             se->ops->load_cleanup(se->opaque);
2290         }
2291     }
2292 }
2293
2294 /* Return true if we should continue the migration, or false. */
2295 static bool postcopy_pause_incoming(MigrationIncomingState *mis)
2296 {
2297     trace_postcopy_pause_incoming();
2298
2299     /* Clear the triggered bit to allow one recovery */
2300     mis->postcopy_recover_triggered = false;
2301
2302     assert(mis->from_src_file);
2303     qemu_file_shutdown(mis->from_src_file);
2304     qemu_fclose(mis->from_src_file);
2305     mis->from_src_file = NULL;
2306
2307     assert(mis->to_src_file);
2308     qemu_file_shutdown(mis->to_src_file);
2309     qemu_mutex_lock(&mis->rp_mutex);
2310     qemu_fclose(mis->to_src_file);
2311     mis->to_src_file = NULL;
2312     qemu_mutex_unlock(&mis->rp_mutex);
2313
2314     migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2315                       MIGRATION_STATUS_POSTCOPY_PAUSED);
2316
2317     /* Notify the fault thread for the invalidated file handle */
2318     postcopy_fault_thread_notify(mis);
2319
2320     error_report("Detected IO failure for postcopy. "
2321                  "Migration paused.");
2322
2323     while (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2324         qemu_sem_wait(&mis->postcopy_pause_sem_dst);
2325     }
2326
2327     trace_postcopy_pause_incoming_continued();
2328
2329     return true;
2330 }
2331
2332 int qemu_loadvm_state_main(QEMUFile *f, MigrationIncomingState *mis)
2333 {
2334     uint8_t section_type;
2335     int ret = 0;
2336
2337 retry:
2338     while (true) {
2339         section_type = qemu_get_byte(f);
2340
2341         if (qemu_file_get_error(f)) {
2342             ret = qemu_file_get_error(f);
2343             break;
2344         }
2345
2346         trace_qemu_loadvm_state_section(section_type);
2347         switch (section_type) {
2348         case QEMU_VM_SECTION_START:
2349         case QEMU_VM_SECTION_FULL:
2350             ret = qemu_loadvm_section_start_full(f, mis);
2351             if (ret < 0) {
2352                 goto out;
2353             }
2354             break;
2355         case QEMU_VM_SECTION_PART:
2356         case QEMU_VM_SECTION_END:
2357             ret = qemu_loadvm_section_part_end(f, mis);
2358             if (ret < 0) {
2359                 goto out;
2360             }
2361             break;
2362         case QEMU_VM_COMMAND:
2363             ret = loadvm_process_command(f);
2364             trace_qemu_loadvm_state_section_command(ret);
2365             if ((ret < 0) || (ret & LOADVM_QUIT)) {
2366                 goto out;
2367             }
2368             break;
2369         case QEMU_VM_EOF:
2370             /* This is the end of migration */
2371             goto out;
2372         default:
2373             error_report("Unknown savevm section type %d", section_type);
2374             ret = -EINVAL;
2375             goto out;
2376         }
2377     }
2378
2379 out:
2380     if (ret < 0) {
2381         qemu_file_set_error(f, ret);
2382
2383         /*
2384          * If we are during an active postcopy, then we pause instead
2385          * of bail out to at least keep the VM's dirty data.  Note
2386          * that POSTCOPY_INCOMING_LISTENING stage is still not enough,
2387          * during which we're still receiving device states and we
2388          * still haven't yet started the VM on destination.
2389          */
2390         if (postcopy_state_get() == POSTCOPY_INCOMING_RUNNING &&
2391             postcopy_pause_incoming(mis)) {
2392             /* Reset f to point to the newly created channel */
2393             f = mis->from_src_file;
2394             goto retry;
2395         }
2396     }
2397     return ret;
2398 }
2399
2400 int qemu_loadvm_state(QEMUFile *f)
2401 {
2402     MigrationIncomingState *mis = migration_incoming_get_current();
2403     Error *local_err = NULL;
2404     unsigned int v;
2405     int ret;
2406
2407     if (qemu_savevm_state_blocked(&local_err)) {
2408         error_report_err(local_err);
2409         return -EINVAL;
2410     }
2411
2412     v = qemu_get_be32(f);
2413     if (v != QEMU_VM_FILE_MAGIC) {
2414         error_report("Not a migration stream");
2415         return -EINVAL;
2416     }
2417
2418     v = qemu_get_be32(f);
2419     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2420         error_report("SaveVM v2 format is obsolete and don't work anymore");
2421         return -ENOTSUP;
2422     }
2423     if (v != QEMU_VM_FILE_VERSION) {
2424         error_report("Unsupported migration stream version");
2425         return -ENOTSUP;
2426     }
2427
2428     if (qemu_loadvm_state_setup(f) != 0) {
2429         return -EINVAL;
2430     }
2431
2432     if (migrate_get_current()->send_configuration) {
2433         if (qemu_get_byte(f) != QEMU_VM_CONFIGURATION) {
2434             error_report("Configuration section missing");
2435             qemu_loadvm_state_cleanup();
2436             return -EINVAL;
2437         }
2438         ret = vmstate_load_state(f, &vmstate_configuration, &savevm_state, 0);
2439
2440         if (ret) {
2441             qemu_loadvm_state_cleanup();
2442             return ret;
2443         }
2444     }
2445
2446     cpu_synchronize_all_pre_loadvm();
2447
2448     ret = qemu_loadvm_state_main(f, mis);
2449     qemu_event_set(&mis->main_thread_load_event);
2450
2451     trace_qemu_loadvm_state_post_main(ret);
2452
2453     if (mis->have_listen_thread) {
2454         /* Listen thread still going, can't clean up yet */
2455         return ret;
2456     }
2457
2458     if (ret == 0) {
2459         ret = qemu_file_get_error(f);
2460     }
2461
2462     /*
2463      * Try to read in the VMDESC section as well, so that dumping tools that
2464      * intercept our migration stream have the chance to see it.
2465      */
2466
2467     /* We've got to be careful; if we don't read the data and just shut the fd
2468      * then the sender can error if we close while it's still sending.
2469      * We also mustn't read data that isn't there; some transports (RDMA)
2470      * will stall waiting for that data when the source has already closed.
2471      */
2472     if (ret == 0 && should_send_vmdesc()) {
2473         uint8_t *buf;
2474         uint32_t size;
2475         uint8_t  section_type = qemu_get_byte(f);
2476
2477         if (section_type != QEMU_VM_VMDESCRIPTION) {
2478             error_report("Expected vmdescription section, but got %d",
2479                          section_type);
2480             /*
2481              * It doesn't seem worth failing at this point since
2482              * we apparently have an otherwise valid VM state
2483              */
2484         } else {
2485             buf = g_malloc(0x1000);
2486             size = qemu_get_be32(f);
2487
2488             while (size > 0) {
2489                 uint32_t read_chunk = MIN(size, 0x1000);
2490                 qemu_get_buffer(f, buf, read_chunk);
2491                 size -= read_chunk;
2492             }
2493             g_free(buf);
2494         }
2495     }
2496
2497     qemu_loadvm_state_cleanup();
2498     cpu_synchronize_all_post_init();
2499
2500     return ret;
2501 }
2502
2503 int qemu_load_device_state(QEMUFile *f)
2504 {
2505     MigrationIncomingState *mis = migration_incoming_get_current();
2506     int ret;
2507
2508     /* Load QEMU_VM_SECTION_FULL section */
2509     ret = qemu_loadvm_state_main(f, mis);
2510     if (ret < 0) {
2511         error_report("Failed to load device state: %d", ret);
2512         return ret;
2513     }
2514
2515     cpu_synchronize_all_post_init();
2516     return 0;
2517 }
2518
2519 int save_snapshot(const char *name, Error **errp)
2520 {
2521     BlockDriverState *bs, *bs1;
2522     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2523     int ret = -1;
2524     QEMUFile *f;
2525     int saved_vm_running;
2526     uint64_t vm_state_size;
2527     qemu_timeval tv;
2528     struct tm tm;
2529     AioContext *aio_context;
2530
2531     if (migration_is_blocked(errp)) {
2532         return false;
2533     }
2534
2535     if (!replay_can_snapshot()) {
2536         error_setg(errp, "Record/replay does not allow making snapshot "
2537                    "right now. Try once more later.");
2538         return ret;
2539     }
2540
2541     if (!bdrv_all_can_snapshot(&bs)) {
2542         error_setg(errp, "Device '%s' is writable but does not support "
2543                    "snapshots", bdrv_get_device_name(bs));
2544         return ret;
2545     }
2546
2547     /* Delete old snapshots of the same name */
2548     if (name) {
2549         ret = bdrv_all_delete_snapshot(name, &bs1, errp);
2550         if (ret < 0) {
2551             error_prepend(errp, "Error while deleting snapshot on device "
2552                           "'%s': ", bdrv_get_device_name(bs1));
2553             return ret;
2554         }
2555     }
2556
2557     bs = bdrv_all_find_vmstate_bs();
2558     if (bs == NULL) {
2559         error_setg(errp, "No block device can accept snapshots");
2560         return ret;
2561     }
2562     aio_context = bdrv_get_aio_context(bs);
2563
2564     saved_vm_running = runstate_is_running();
2565
2566     ret = global_state_store();
2567     if (ret) {
2568         error_setg(errp, "Error saving global state");
2569         return ret;
2570     }
2571     vm_stop(RUN_STATE_SAVE_VM);
2572
2573     bdrv_drain_all_begin();
2574
2575     aio_context_acquire(aio_context);
2576
2577     memset(sn, 0, sizeof(*sn));
2578
2579     /* fill auxiliary fields */
2580     qemu_gettimeofday(&tv);
2581     sn->date_sec = tv.tv_sec;
2582     sn->date_nsec = tv.tv_usec * 1000;
2583     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2584
2585     if (name) {
2586         ret = bdrv_snapshot_find(bs, old_sn, name);
2587         if (ret >= 0) {
2588             pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2589             pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2590         } else {
2591             pstrcpy(sn->name, sizeof(sn->name), name);
2592         }
2593     } else {
2594         /* cast below needed for OpenBSD where tv_sec is still 'long' */
2595         localtime_r((const time_t *)&tv.tv_sec, &tm);
2596         strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2597     }
2598
2599     /* save the VM state */
2600     f = qemu_fopen_bdrv(bs, 1);
2601     if (!f) {
2602         error_setg(errp, "Could not open VM state file");
2603         goto the_end;
2604     }
2605     ret = qemu_savevm_state(f, errp);
2606     vm_state_size = qemu_ftell(f);
2607     qemu_fclose(f);
2608     if (ret < 0) {
2609         goto the_end;
2610     }
2611
2612     /* The bdrv_all_create_snapshot() call that follows acquires the AioContext
2613      * for itself.  BDRV_POLL_WHILE() does not support nested locking because
2614      * it only releases the lock once.  Therefore synchronous I/O will deadlock
2615      * unless we release the AioContext before bdrv_all_create_snapshot().
2616      */
2617     aio_context_release(aio_context);
2618     aio_context = NULL;
2619
2620     ret = bdrv_all_create_snapshot(sn, bs, vm_state_size, &bs);
2621     if (ret < 0) {
2622         error_setg(errp, "Error while creating snapshot on '%s'",
2623                    bdrv_get_device_name(bs));
2624         goto the_end;
2625     }
2626
2627     ret = 0;
2628
2629  the_end:
2630     if (aio_context) {
2631         aio_context_release(aio_context);
2632     }
2633
2634     bdrv_drain_all_end();
2635
2636     if (saved_vm_running) {
2637         vm_start();
2638     }
2639     return ret;
2640 }
2641
2642 void qmp_xen_save_devices_state(const char *filename, bool has_live, bool live,
2643                                 Error **errp)
2644 {
2645     QEMUFile *f;
2646     QIOChannelFile *ioc;
2647     int saved_vm_running;
2648     int ret;
2649
2650     if (!has_live) {
2651         /* live default to true so old version of Xen tool stack can have a
2652          * successfull live migration */
2653         live = true;
2654     }
2655
2656     saved_vm_running = runstate_is_running();
2657     vm_stop(RUN_STATE_SAVE_VM);
2658     global_state_store_running();
2659
2660     ioc = qio_channel_file_new_path(filename, O_WRONLY | O_CREAT, 0660, errp);
2661     if (!ioc) {
2662         goto the_end;
2663     }
2664     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-save-state");
2665     f = qemu_fopen_channel_output(QIO_CHANNEL(ioc));
2666     object_unref(OBJECT(ioc));
2667     ret = qemu_save_device_state(f);
2668     if (ret < 0 || qemu_fclose(f) < 0) {
2669         error_setg(errp, QERR_IO_ERROR);
2670     } else {
2671         /* libxl calls the QMP command "stop" before calling
2672          * "xen-save-devices-state" and in case of migration failure, libxl
2673          * would call "cont".
2674          * So call bdrv_inactivate_all (release locks) here to let the other
2675          * side of the migration take controle of the images.
2676          */
2677         if (live && !saved_vm_running) {
2678             ret = bdrv_inactivate_all();
2679             if (ret) {
2680                 error_setg(errp, "%s: bdrv_inactivate_all() failed (%d)",
2681                            __func__, ret);
2682             }
2683         }
2684     }
2685
2686  the_end:
2687     if (saved_vm_running) {
2688         vm_start();
2689     }
2690 }
2691
2692 void qmp_xen_load_devices_state(const char *filename, Error **errp)
2693 {
2694     QEMUFile *f;
2695     QIOChannelFile *ioc;
2696     int ret;
2697
2698     /* Guest must be paused before loading the device state; the RAM state
2699      * will already have been loaded by xc
2700      */
2701     if (runstate_is_running()) {
2702         error_setg(errp, "Cannot update device state while vm is running");
2703         return;
2704     }
2705     vm_stop(RUN_STATE_RESTORE_VM);
2706
2707     ioc = qio_channel_file_new_path(filename, O_RDONLY | O_BINARY, 0, errp);
2708     if (!ioc) {
2709         return;
2710     }
2711     qio_channel_set_name(QIO_CHANNEL(ioc), "migration-xen-load-state");
2712     f = qemu_fopen_channel_input(QIO_CHANNEL(ioc));
2713     object_unref(OBJECT(ioc));
2714
2715     ret = qemu_loadvm_state(f);
2716     qemu_fclose(f);
2717     if (ret < 0) {
2718         error_setg(errp, QERR_IO_ERROR);
2719     }
2720     migration_incoming_state_destroy();
2721 }
2722
2723 int load_snapshot(const char *name, Error **errp)
2724 {
2725     BlockDriverState *bs, *bs_vm_state;
2726     QEMUSnapshotInfo sn;
2727     QEMUFile *f;
2728     int ret;
2729     AioContext *aio_context;
2730     MigrationIncomingState *mis = migration_incoming_get_current();
2731
2732     if (!replay_can_snapshot()) {
2733         error_setg(errp, "Record/replay does not allow loading snapshot "
2734                    "right now. Try once more later.");
2735         return -EINVAL;
2736     }
2737
2738     if (!bdrv_all_can_snapshot(&bs)) {
2739         error_setg(errp,
2740                    "Device '%s' is writable but does not support snapshots",
2741                    bdrv_get_device_name(bs));
2742         return -ENOTSUP;
2743     }
2744     ret = bdrv_all_find_snapshot(name, &bs);
2745     if (ret < 0) {
2746         error_setg(errp,
2747                    "Device '%s' does not have the requested snapshot '%s'",
2748                    bdrv_get_device_name(bs), name);
2749         return ret;
2750     }
2751
2752     bs_vm_state = bdrv_all_find_vmstate_bs();
2753     if (!bs_vm_state) {
2754         error_setg(errp, "No block device supports snapshots");
2755         return -ENOTSUP;
2756     }
2757     aio_context = bdrv_get_aio_context(bs_vm_state);
2758
2759     /* Don't even try to load empty VM states */
2760     aio_context_acquire(aio_context);
2761     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2762     aio_context_release(aio_context);
2763     if (ret < 0) {
2764         return ret;
2765     } else if (sn.vm_state_size == 0) {
2766         error_setg(errp, "This is a disk-only snapshot. Revert to it "
2767                    " offline using qemu-img");
2768         return -EINVAL;
2769     }
2770
2771     /* Flush all IO requests so they don't interfere with the new state.  */
2772     bdrv_drain_all_begin();
2773
2774     ret = bdrv_all_goto_snapshot(name, &bs, errp);
2775     if (ret < 0) {
2776         error_prepend(errp, "Could not load snapshot '%s' on '%s': ",
2777                       name, bdrv_get_device_name(bs));
2778         goto err_drain;
2779     }
2780
2781     /* restore the VM state */
2782     f = qemu_fopen_bdrv(bs_vm_state, 0);
2783     if (!f) {
2784         error_setg(errp, "Could not open VM state file");
2785         ret = -EINVAL;
2786         goto err_drain;
2787     }
2788
2789     qemu_system_reset(SHUTDOWN_CAUSE_NONE);
2790     mis->from_src_file = f;
2791
2792     aio_context_acquire(aio_context);
2793     ret = qemu_loadvm_state(f);
2794     migration_incoming_state_destroy();
2795     aio_context_release(aio_context);
2796
2797     bdrv_drain_all_end();
2798
2799     if (ret < 0) {
2800         error_setg(errp, "Error %d while loading VM state", ret);
2801         return ret;
2802     }
2803
2804     return 0;
2805
2806 err_drain:
2807     bdrv_drain_all_end();
2808     return ret;
2809 }
2810
2811 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2812 {
2813     qemu_ram_set_idstr(mr->ram_block,
2814                        memory_region_name(mr), dev);
2815     qemu_ram_set_migratable(mr->ram_block);
2816 }
2817
2818 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2819 {
2820     qemu_ram_unset_idstr(mr->ram_block);
2821     qemu_ram_unset_migratable(mr->ram_block);
2822 }
2823
2824 void vmstate_register_ram_global(MemoryRegion *mr)
2825 {
2826     vmstate_register_ram(mr, NULL);
2827 }
2828
2829 bool vmstate_check_only_migratable(const VMStateDescription *vmsd)
2830 {
2831     /* check needed if --only-migratable is specified */
2832     if (!migrate_get_current()->only_migratable) {
2833         return true;
2834     }
2835
2836     return !(vmsd && vmsd->unmigratable);
2837 }
This page took 0.170058 seconds and 4 git commands to generate.