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