xref: /qemu/migration/migration.c (revision 6ff5da16000f908140723e164d33a0b51a6c4162)
1 /*
2  * QEMU live migration
3  *
4  * Copyright IBM, Corp. 2008
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qemu/ctype.h"
18 #include "qemu/cutils.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "migration/blocker.h"
22 #include "exec.h"
23 #include "fd.h"
24 #include "file.h"
25 #include "socket.h"
26 #include "system/runstate.h"
27 #include "system/system.h"
28 #include "system/cpu-throttle.h"
29 #include "rdma.h"
30 #include "ram.h"
31 #include "migration/cpr.h"
32 #include "migration/global_state.h"
33 #include "migration/misc.h"
34 #include "migration.h"
35 #include "migration-stats.h"
36 #include "savevm.h"
37 #include "qemu-file.h"
38 #include "channel.h"
39 #include "migration/vmstate.h"
40 #include "block/block.h"
41 #include "qapi/error.h"
42 #include "qapi/clone-visitor.h"
43 #include "qapi/qapi-visit-migration.h"
44 #include "qapi/qapi-visit-sockets.h"
45 #include "qapi/qapi-commands-migration.h"
46 #include "qapi/qapi-events-migration.h"
47 #include "qapi/qmp/qerror.h"
48 #include "qobject/qnull.h"
49 #include "qemu/rcu.h"
50 #include "postcopy-ram.h"
51 #include "qemu/thread.h"
52 #include "trace.h"
53 #include "exec/target_page.h"
54 #include "io/channel-buffer.h"
55 #include "io/channel-tls.h"
56 #include "migration/colo.h"
57 #include "hw/boards.h"
58 #include "monitor/monitor.h"
59 #include "net/announce.h"
60 #include "qemu/queue.h"
61 #include "multifd.h"
62 #include "threadinfo.h"
63 #include "qemu/yank.h"
64 #include "system/cpus.h"
65 #include "yank_functions.h"
66 #include "system/qtest.h"
67 #include "options.h"
68 #include "system/dirtylimit.h"
69 #include "qemu/sockets.h"
70 #include "system/kvm.h"
71 
72 #define NOTIFIER_ELEM_INIT(array, elem)    \
73     [elem] = NOTIFIER_WITH_RETURN_LIST_INITIALIZER((array)[elem])
74 
75 #define INMIGRATE_DEFAULT_EXIT_ON_ERROR true
76 
77 static NotifierWithReturnList migration_state_notifiers[] = {
78     NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_NORMAL),
79     NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_CPR_REBOOT),
80     NOTIFIER_ELEM_INIT(migration_state_notifiers, MIG_MODE_CPR_TRANSFER),
81 };
82 
83 /* Messages sent on the return path from destination to source */
84 enum mig_rp_message_type {
85     MIG_RP_MSG_INVALID = 0,  /* Must be 0 */
86     MIG_RP_MSG_SHUT,         /* sibling will not send any more RP messages */
87     MIG_RP_MSG_PONG,         /* Response to a PING; data (seq: be32 ) */
88 
89     MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
90     MIG_RP_MSG_REQ_PAGES,    /* data (start: be64, len: be32) */
91     MIG_RP_MSG_RECV_BITMAP,  /* send recved_bitmap back to source */
92     MIG_RP_MSG_RESUME_ACK,   /* tell source that we are ready to resume */
93     MIG_RP_MSG_SWITCHOVER_ACK, /* Tell source it's OK to do switchover */
94 
95     MIG_RP_MSG_MAX
96 };
97 
98 /* When we add fault tolerance, we could have several
99    migrations at once.  For now we don't need to add
100    dynamic creation of migration */
101 
102 static MigrationState *current_migration;
103 static MigrationIncomingState *current_incoming;
104 
105 static GSList *migration_blockers[MIG_MODE__MAX];
106 
107 static bool migration_object_check(MigrationState *ms, Error **errp);
108 static bool migration_switchover_start(MigrationState *s, Error **errp);
109 static bool close_return_path_on_source(MigrationState *s);
110 static void migration_completion_end(MigrationState *s);
111 static void migrate_hup_delete(MigrationState *s);
112 
113 static void migration_downtime_start(MigrationState *s)
114 {
115     trace_vmstate_downtime_checkpoint("src-downtime-start");
116     s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
117 }
118 
119 static void migration_downtime_end(MigrationState *s)
120 {
121     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
122 
123     /*
124      * If downtime already set, should mean that postcopy already set it,
125      * then that should be the real downtime already.
126      */
127     if (!s->downtime) {
128         s->downtime = now - s->downtime_start;
129         trace_vmstate_downtime_checkpoint("src-downtime-end");
130     }
131 }
132 
133 static void precopy_notify_complete(void)
134 {
135     Error *local_err = NULL;
136 
137     if (precopy_notify(PRECOPY_NOTIFY_COMPLETE, &local_err)) {
138         error_report_err(local_err);
139     }
140 
141     trace_migration_precopy_complete();
142 }
143 
144 static bool migration_needs_multiple_sockets(void)
145 {
146     return migrate_multifd() || migrate_postcopy_preempt();
147 }
148 
149 static RunState migration_get_target_runstate(void)
150 {
151     /*
152      * When the global state is not migrated, it means we don't know the
153      * runstate of the src QEMU.  We don't have much choice but assuming
154      * the VM is running.  NOTE: this is pretty rare case, so far only Xen
155      * uses it.
156      */
157     if (!global_state_received()) {
158         return RUN_STATE_RUNNING;
159     }
160 
161     return global_state_get_runstate();
162 }
163 
164 static bool transport_supports_multi_channels(MigrationAddress *addr)
165 {
166     if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
167         SocketAddress *saddr = &addr->u.socket;
168 
169         return (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
170                 saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
171                 saddr->type == SOCKET_ADDRESS_TYPE_VSOCK);
172     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
173         return migrate_mapped_ram();
174     } else {
175         return false;
176     }
177 }
178 
179 static bool migration_needs_seekable_channel(void)
180 {
181     return migrate_mapped_ram();
182 }
183 
184 static bool migration_needs_extra_fds(void)
185 {
186     /*
187      * When doing direct-io, multifd requires two different,
188      * non-duplicated file descriptors so we can use one of them for
189      * unaligned IO.
190      */
191     return migrate_multifd() && migrate_direct_io();
192 }
193 
194 static bool transport_supports_seeking(MigrationAddress *addr)
195 {
196     if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
197         return true;
198     }
199 
200     return false;
201 }
202 
203 static bool transport_supports_extra_fds(MigrationAddress *addr)
204 {
205     /* file: works because QEMU can open it multiple times */
206     return addr->transport == MIGRATION_ADDRESS_TYPE_FILE;
207 }
208 
209 static bool
210 migration_channels_and_transport_compatible(MigrationAddress *addr,
211                                             Error **errp)
212 {
213     if (migration_needs_seekable_channel() &&
214         !transport_supports_seeking(addr)) {
215         error_setg(errp, "Migration requires seekable transport (e.g. file)");
216         return false;
217     }
218 
219     if (migration_needs_multiple_sockets() &&
220         !transport_supports_multi_channels(addr)) {
221         error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)");
222         return false;
223     }
224 
225     if (migration_needs_extra_fds() &&
226         !transport_supports_extra_fds(addr)) {
227         error_setg(errp,
228                    "Migration requires a transport that allows for extra fds (e.g. file)");
229         return false;
230     }
231 
232     if (migrate_mode() == MIG_MODE_CPR_TRANSFER &&
233         addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
234         error_setg(errp, "Migration requires streamable transport (eg unix)");
235         return false;
236     }
237 
238     return true;
239 }
240 
241 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
242 {
243     uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
244 
245     return (a > b) - (a < b);
246 }
247 
248 static int migration_stop_vm(MigrationState *s, RunState state)
249 {
250     int ret;
251 
252     migration_downtime_start(s);
253 
254     s->vm_old_state = runstate_get();
255     global_state_store();
256 
257     ret = vm_stop_force_state(state);
258 
259     trace_vmstate_downtime_checkpoint("src-vm-stopped");
260     trace_migration_completion_vm_stop(ret);
261 
262     return ret;
263 }
264 
265 void migration_object_init(void)
266 {
267     /* This can only be called once. */
268     assert(!current_migration);
269     current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
270 
271     /*
272      * Init the migrate incoming object as well no matter whether
273      * we'll use it or not.
274      */
275     assert(!current_incoming);
276     current_incoming = g_new0(MigrationIncomingState, 1);
277     current_incoming->state = MIGRATION_STATUS_NONE;
278     current_incoming->postcopy_remote_fds =
279         g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
280     qemu_mutex_init(&current_incoming->rp_mutex);
281     qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
282     qemu_event_init(&current_incoming->main_thread_load_event, false);
283     qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
284     qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
285     qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
286     qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
287 
288     qemu_mutex_init(&current_incoming->page_request_mutex);
289     qemu_cond_init(&current_incoming->page_request_cond);
290     current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
291 
292     current_incoming->exit_on_error = INMIGRATE_DEFAULT_EXIT_ON_ERROR;
293 
294     migration_object_check(current_migration, &error_fatal);
295 
296     ram_mig_init();
297     dirty_bitmap_mig_init();
298 
299     /* Initialize cpu throttle timers */
300     cpu_throttle_init();
301 }
302 
303 typedef struct {
304     QEMUBH *bh;
305     QEMUBHFunc *cb;
306     void *opaque;
307 } MigrationBH;
308 
309 static void migration_bh_dispatch_bh(void *opaque)
310 {
311     MigrationState *s = migrate_get_current();
312     MigrationBH *migbh = opaque;
313 
314     /* cleanup this BH */
315     qemu_bh_delete(migbh->bh);
316     migbh->bh = NULL;
317 
318     /* dispatch the other one */
319     migbh->cb(migbh->opaque);
320     object_unref(OBJECT(s));
321 
322     g_free(migbh);
323 }
324 
325 void migration_bh_schedule(QEMUBHFunc *cb, void *opaque)
326 {
327     MigrationState *s = migrate_get_current();
328     MigrationBH *migbh = g_new0(MigrationBH, 1);
329     QEMUBH *bh = qemu_bh_new(migration_bh_dispatch_bh, migbh);
330 
331     /* Store these to dispatch when the BH runs */
332     migbh->bh = bh;
333     migbh->cb = cb;
334     migbh->opaque = opaque;
335 
336     /*
337      * Ref the state for bh, because it may be called when
338      * there're already no other refs
339      */
340     object_ref(OBJECT(s));
341     qemu_bh_schedule(bh);
342 }
343 
344 void migration_shutdown(void)
345 {
346     /*
347      * When the QEMU main thread exit, the COLO thread
348      * may wait a semaphore. So, we should wakeup the
349      * COLO thread before migration shutdown.
350      */
351     colo_shutdown();
352     /*
353      * Cancel the current migration - that will (eventually)
354      * stop the migration using this structure
355      */
356     migration_cancel();
357     object_unref(OBJECT(current_migration));
358 
359     /*
360      * Cancel outgoing migration of dirty bitmaps. It should
361      * at least unref used block nodes.
362      */
363     dirty_bitmap_mig_cancel_outgoing();
364 
365     /*
366      * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
367      * are non-critical data, and their loss never considered as
368      * something serious.
369      */
370     dirty_bitmap_mig_cancel_incoming();
371 }
372 
373 /* For outgoing */
374 MigrationState *migrate_get_current(void)
375 {
376     /* This can only be called after the object created. */
377     assert(current_migration);
378     return current_migration;
379 }
380 
381 MigrationIncomingState *migration_incoming_get_current(void)
382 {
383     assert(current_incoming);
384     return current_incoming;
385 }
386 
387 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
388 {
389     if (mis->socket_address_list) {
390         qapi_free_SocketAddressList(mis->socket_address_list);
391         mis->socket_address_list = NULL;
392     }
393 
394     if (mis->transport_cleanup) {
395         mis->transport_cleanup(mis->transport_data);
396         mis->transport_data = mis->transport_cleanup = NULL;
397     }
398 }
399 
400 void migration_incoming_state_destroy(void)
401 {
402     struct MigrationIncomingState *mis = migration_incoming_get_current();
403 
404     multifd_recv_cleanup();
405 
406     /*
407      * RAM state cleanup needs to happen after multifd cleanup, because
408      * multifd threads can use some of its states (receivedmap).
409      * The VFIO load_cleanup() implementation is BQL-sensitive. It requires
410      * BQL must NOT be taken when recycling load threads, so that it won't
411      * block the load threads from making progress on address space
412      * modification operations.
413      *
414      * To make it work, we could try to not take BQL for all load_cleanup(),
415      * or conditionally unlock BQL only if bql_locked() in VFIO.
416      *
417      * Since most existing call sites take BQL for load_cleanup(), make
418      * it simple by taking BQL always as the rule, so that VFIO can unlock
419      * BQL and retake unconditionally.
420      */
421     assert(bql_locked());
422     qemu_loadvm_state_cleanup(mis);
423 
424     if (mis->to_src_file) {
425         /* Tell source that we are done */
426         migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
427         qemu_fclose(mis->to_src_file);
428         mis->to_src_file = NULL;
429     }
430 
431     if (mis->from_src_file) {
432         migration_ioc_unregister_yank_from_file(mis->from_src_file);
433         qemu_fclose(mis->from_src_file);
434         mis->from_src_file = NULL;
435     }
436     if (mis->postcopy_remote_fds) {
437         g_array_free(mis->postcopy_remote_fds, TRUE);
438         mis->postcopy_remote_fds = NULL;
439     }
440 
441     migration_incoming_transport_cleanup(mis);
442     qemu_event_reset(&mis->main_thread_load_event);
443 
444     if (mis->page_requested) {
445         g_tree_destroy(mis->page_requested);
446         mis->page_requested = NULL;
447     }
448 
449     if (mis->postcopy_qemufile_dst) {
450         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
451         qemu_fclose(mis->postcopy_qemufile_dst);
452         mis->postcopy_qemufile_dst = NULL;
453     }
454 
455     cpr_set_incoming_mode(MIG_MODE_NONE);
456     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
457 }
458 
459 static void migrate_generate_event(MigrationStatus new_state)
460 {
461     if (migrate_events()) {
462         qapi_event_send_migration(new_state);
463     }
464 }
465 
466 /*
467  * Send a message on the return channel back to the source
468  * of the migration.
469  */
470 static int migrate_send_rp_message(MigrationIncomingState *mis,
471                                    enum mig_rp_message_type message_type,
472                                    uint16_t len, void *data)
473 {
474     int ret = 0;
475 
476     trace_migrate_send_rp_message((int)message_type, len);
477     QEMU_LOCK_GUARD(&mis->rp_mutex);
478 
479     /*
480      * It's possible that the file handle got lost due to network
481      * failures.
482      */
483     if (!mis->to_src_file) {
484         ret = -EIO;
485         return ret;
486     }
487 
488     qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
489     qemu_put_be16(mis->to_src_file, len);
490     qemu_put_buffer(mis->to_src_file, data, len);
491     return qemu_fflush(mis->to_src_file);
492 }
493 
494 /* Request one page from the source VM at the given start address.
495  *   rb: the RAMBlock to request the page in
496  *   Start: Address offset within the RB
497  *   Len: Length in bytes required - must be a multiple of pagesize
498  */
499 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
500                                       RAMBlock *rb, ram_addr_t start)
501 {
502     uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
503     size_t msglen = 12; /* start + len */
504     size_t len = qemu_ram_pagesize(rb);
505     enum mig_rp_message_type msg_type;
506     const char *rbname;
507     int rbname_len;
508 
509     *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
510     *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
511 
512     /*
513      * We maintain the last ramblock that we requested for page.  Note that we
514      * don't need locking because this function will only be called within the
515      * postcopy ram fault thread.
516      */
517     if (rb != mis->last_rb) {
518         mis->last_rb = rb;
519 
520         rbname = qemu_ram_get_idstr(rb);
521         rbname_len = strlen(rbname);
522 
523         assert(rbname_len < 256);
524 
525         bufc[msglen++] = rbname_len;
526         memcpy(bufc + msglen, rbname, rbname_len);
527         msglen += rbname_len;
528         msg_type = MIG_RP_MSG_REQ_PAGES_ID;
529     } else {
530         msg_type = MIG_RP_MSG_REQ_PAGES;
531     }
532 
533     return migrate_send_rp_message(mis, msg_type, msglen, bufc);
534 }
535 
536 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
537                               RAMBlock *rb, ram_addr_t start, uint64_t haddr)
538 {
539     void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
540     bool received = false;
541 
542     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
543         received = ramblock_recv_bitmap_test_byte_offset(rb, start);
544         if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
545             /*
546              * The page has not been received, and it's not yet in the page
547              * request list.  Queue it.  Set the value of element to 1, so that
548              * things like g_tree_lookup() will return TRUE (1) when found.
549              */
550             g_tree_insert(mis->page_requested, aligned, (gpointer)1);
551             qatomic_inc(&mis->page_requested_count);
552             trace_postcopy_page_req_add(aligned, mis->page_requested_count);
553         }
554     }
555 
556     /*
557      * If the page is there, skip sending the message.  We don't even need the
558      * lock because as long as the page arrived, it'll be there forever.
559      */
560     if (received) {
561         return 0;
562     }
563 
564     return migrate_send_rp_message_req_pages(mis, rb, start);
565 }
566 
567 static bool migration_colo_enabled;
568 bool migration_incoming_colo_enabled(void)
569 {
570     return migration_colo_enabled;
571 }
572 
573 void migration_incoming_disable_colo(void)
574 {
575     ram_block_discard_disable(false);
576     migration_colo_enabled = false;
577 }
578 
579 int migration_incoming_enable_colo(void)
580 {
581 #ifndef CONFIG_REPLICATION
582     error_report("ENABLE_COLO command come in migration stream, but the "
583                  "replication module is not built in");
584     return -ENOTSUP;
585 #endif
586 
587     if (!migrate_colo()) {
588         error_report("ENABLE_COLO command come in migration stream, but x-colo "
589                      "capability is not set");
590         return -EINVAL;
591     }
592 
593     if (ram_block_discard_disable(true)) {
594         error_report("COLO: cannot disable RAM discard");
595         return -EBUSY;
596     }
597     migration_colo_enabled = true;
598     return 0;
599 }
600 
601 void migrate_add_address(SocketAddress *address)
602 {
603     MigrationIncomingState *mis = migration_incoming_get_current();
604 
605     QAPI_LIST_PREPEND(mis->socket_address_list,
606                       QAPI_CLONE(SocketAddress, address));
607 }
608 
609 bool migrate_is_uri(const char *uri)
610 {
611     while (*uri && *uri != ':') {
612         if (!qemu_isalpha(*uri++)) {
613             return false;
614         }
615     }
616     return *uri == ':';
617 }
618 
619 bool migrate_uri_parse(const char *uri, MigrationChannel **channel,
620                        Error **errp)
621 {
622     g_autoptr(MigrationChannel) val = g_new0(MigrationChannel, 1);
623     g_autoptr(MigrationAddress) addr = g_new0(MigrationAddress, 1);
624     InetSocketAddress *isock = &addr->u.rdma;
625     strList **tail = &addr->u.exec.args;
626 
627     if (strstart(uri, "exec:", NULL)) {
628         addr->transport = MIGRATION_ADDRESS_TYPE_EXEC;
629 #ifdef WIN32
630         QAPI_LIST_APPEND(tail, g_strdup(exec_get_cmd_path()));
631         QAPI_LIST_APPEND(tail, g_strdup("/c"));
632 #else
633         QAPI_LIST_APPEND(tail, g_strdup("/bin/sh"));
634         QAPI_LIST_APPEND(tail, g_strdup("-c"));
635 #endif
636         QAPI_LIST_APPEND(tail, g_strdup(uri + strlen("exec:")));
637     } else if (strstart(uri, "rdma:", NULL)) {
638         if (inet_parse(isock, uri + strlen("rdma:"), errp)) {
639             qapi_free_InetSocketAddress(isock);
640             return false;
641         }
642         addr->transport = MIGRATION_ADDRESS_TYPE_RDMA;
643     } else if (strstart(uri, "tcp:", NULL) ||
644                 strstart(uri, "unix:", NULL) ||
645                 strstart(uri, "vsock:", NULL) ||
646                 strstart(uri, "fd:", NULL)) {
647         addr->transport = MIGRATION_ADDRESS_TYPE_SOCKET;
648         SocketAddress *saddr = socket_parse(uri, errp);
649         if (!saddr) {
650             return false;
651         }
652         addr->u.socket.type = saddr->type;
653         addr->u.socket.u = saddr->u;
654         /* Don't free the objects inside; their ownership moved to "addr" */
655         g_free(saddr);
656     } else if (strstart(uri, "file:", NULL)) {
657         addr->transport = MIGRATION_ADDRESS_TYPE_FILE;
658         addr->u.file.filename = g_strdup(uri + strlen("file:"));
659         if (file_parse_offset(addr->u.file.filename, &addr->u.file.offset,
660                               errp)) {
661             return false;
662         }
663     } else {
664         error_setg(errp, "unknown migration protocol: %s", uri);
665         return false;
666     }
667 
668     val->channel_type = MIGRATION_CHANNEL_TYPE_MAIN;
669     val->addr = g_steal_pointer(&addr);
670     *channel = g_steal_pointer(&val);
671     return true;
672 }
673 
674 static bool
675 migration_incoming_state_setup(MigrationIncomingState *mis, Error **errp)
676 {
677     MigrationStatus current = mis->state;
678 
679     if (current == MIGRATION_STATUS_POSTCOPY_PAUSED) {
680         /*
681          * Incoming postcopy migration will stay in PAUSED state even if
682          * reconnection happened.
683          */
684         return true;
685     }
686 
687     if (current != MIGRATION_STATUS_NONE) {
688         error_setg(errp, "Illegal migration incoming state: %s",
689                    MigrationStatus_str(current));
690         return false;
691     }
692 
693     migrate_set_state(&mis->state, current, MIGRATION_STATUS_SETUP);
694     return true;
695 }
696 
697 static void qemu_start_incoming_migration(const char *uri, bool has_channels,
698                                           MigrationChannelList *channels,
699                                           Error **errp)
700 {
701     g_autoptr(MigrationChannel) channel = NULL;
702     MigrationAddress *addr = NULL;
703     MigrationIncomingState *mis = migration_incoming_get_current();
704 
705     /*
706      * Having preliminary checks for uri and channel
707      */
708     if (!uri == !channels) {
709         error_setg(errp, "need either 'uri' or 'channels' argument");
710         return;
711     }
712 
713     if (channels) {
714         /* To verify that Migrate channel list has only item */
715         if (channels->next) {
716             error_setg(errp, "Channel list must have only one entry, "
717                              "for type 'main'");
718             return;
719         }
720         addr = channels->value->addr;
721     }
722 
723     if (uri) {
724         /* caller uses the old URI syntax */
725         if (!migrate_uri_parse(uri, &channel, errp)) {
726             return;
727         }
728         addr = channel->addr;
729     }
730 
731     /* transport mechanism not suitable for migration? */
732     if (!migration_channels_and_transport_compatible(addr, errp)) {
733         return;
734     }
735 
736     if (!migration_incoming_state_setup(mis, errp)) {
737         return;
738     }
739 
740     if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
741         SocketAddress *saddr = &addr->u.socket;
742         if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
743             saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
744             saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
745             socket_start_incoming_migration(saddr, errp);
746         } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
747             fd_start_incoming_migration(saddr->u.fd.str, errp);
748         }
749 #ifdef CONFIG_RDMA
750     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
751         if (migrate_xbzrle()) {
752             error_setg(errp, "RDMA and XBZRLE can't be used together");
753             return;
754         }
755         if (migrate_multifd()) {
756             error_setg(errp, "RDMA and multifd can't be used together");
757             return;
758         }
759         rdma_start_incoming_migration(&addr->u.rdma, errp);
760 #endif
761     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
762         exec_start_incoming_migration(addr->u.exec.args, errp);
763     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
764         file_start_incoming_migration(&addr->u.file, errp);
765     } else {
766         error_setg(errp, "unknown migration protocol: %s", uri);
767     }
768 
769     /* Close cpr socket to tell source that we are listening */
770     cpr_state_close();
771 }
772 
773 static void process_incoming_migration_bh(void *opaque)
774 {
775     MigrationIncomingState *mis = opaque;
776 
777     trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
778 
779     /*
780      * This must happen after all error conditions are dealt with and
781      * we're sure the VM is going to be running on this host.
782      */
783     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
784 
785     trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
786 
787     multifd_recv_shutdown();
788 
789     dirty_bitmap_mig_before_vm_start();
790 
791     if (runstate_is_live(migration_get_target_runstate())) {
792         if (autostart) {
793             /*
794              * Block activation is always delayed until VM starts, either
795              * here (which means we need to start the dest VM right now..),
796              * or until qmp_cont() later.
797              *
798              * We used to have cap 'late-block-activate' but now we do this
799              * unconditionally, as it has no harm but only benefit.  E.g.,
800              * it's not part of migration ABI on the time of disk activation.
801              *
802              * Make sure all file formats throw away their mutable
803              * metadata.  If error, don't restart the VM yet.
804              */
805             if (migration_block_activate(NULL)) {
806                 vm_start();
807             }
808         } else {
809             runstate_set(RUN_STATE_PAUSED);
810         }
811     } else if (migration_incoming_colo_enabled()) {
812         migration_incoming_disable_colo();
813         vm_start();
814     } else {
815         runstate_set(global_state_get_runstate());
816     }
817     trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
818     /*
819      * This must happen after any state changes since as soon as an external
820      * observer sees this event they might start to prod at the VM assuming
821      * it's ready to use.
822      */
823     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
824                       MIGRATION_STATUS_COMPLETED);
825     migration_incoming_state_destroy();
826 }
827 
828 static void coroutine_fn
829 process_incoming_migration_co(void *opaque)
830 {
831     MigrationState *s = migrate_get_current();
832     MigrationIncomingState *mis = migration_incoming_get_current();
833     PostcopyState ps;
834     int ret;
835     Error *local_err = NULL;
836 
837     assert(mis->from_src_file);
838 
839     mis->largest_page_size = qemu_ram_pagesize_largest();
840     postcopy_state_set(POSTCOPY_INCOMING_NONE);
841     migrate_set_state(&mis->state, MIGRATION_STATUS_SETUP,
842                       MIGRATION_STATUS_ACTIVE);
843 
844     mis->loadvm_co = qemu_coroutine_self();
845     ret = qemu_loadvm_state(mis->from_src_file);
846     mis->loadvm_co = NULL;
847 
848     trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
849 
850     ps = postcopy_state_get();
851     trace_process_incoming_migration_co_end(ret, ps);
852     if (ps != POSTCOPY_INCOMING_NONE) {
853         if (ps == POSTCOPY_INCOMING_ADVISE) {
854             /*
855              * Where a migration had postcopy enabled (and thus went to advise)
856              * but managed to complete within the precopy period, we can use
857              * the normal exit.
858              */
859             postcopy_ram_incoming_cleanup(mis);
860         } else if (ret >= 0) {
861             /*
862              * Postcopy was started, cleanup should happen at the end of the
863              * postcopy thread.
864              */
865             trace_process_incoming_migration_co_postcopy_end_main();
866             return;
867         }
868         /* Else if something went wrong then just fall out of the normal exit */
869     }
870 
871     if (ret < 0) {
872         error_setg(&local_err, "load of migration failed: %s", strerror(-ret));
873         goto fail;
874     }
875 
876     if (migration_incoming_colo_enabled()) {
877         /* yield until COLO exit */
878         colo_incoming_co();
879     }
880 
881     migration_bh_schedule(process_incoming_migration_bh, mis);
882     return;
883 fail:
884     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
885                       MIGRATION_STATUS_FAILED);
886     migrate_set_error(s, local_err);
887     error_free(local_err);
888 
889     migration_incoming_state_destroy();
890 
891     if (mis->exit_on_error) {
892         WITH_QEMU_LOCK_GUARD(&s->error_mutex) {
893             error_report_err(s->error);
894             s->error = NULL;
895         }
896 
897         exit(EXIT_FAILURE);
898     }
899 }
900 
901 /**
902  * migration_incoming_setup: Setup incoming migration
903  * @f: file for main migration channel
904  */
905 static void migration_incoming_setup(QEMUFile *f)
906 {
907     MigrationIncomingState *mis = migration_incoming_get_current();
908 
909     if (!mis->from_src_file) {
910         mis->from_src_file = f;
911     }
912     qemu_file_set_blocking(f, false);
913 }
914 
915 void migration_incoming_process(void)
916 {
917     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
918     qemu_coroutine_enter(co);
919 }
920 
921 /* Returns true if recovered from a paused migration, otherwise false */
922 static bool postcopy_try_recover(void)
923 {
924     MigrationIncomingState *mis = migration_incoming_get_current();
925 
926     if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
927         /* Resumed from a paused postcopy migration */
928 
929         /* This should be set already in migration_incoming_setup() */
930         assert(mis->from_src_file);
931         /* Postcopy has standalone thread to do vm load */
932         qemu_file_set_blocking(mis->from_src_file, true);
933 
934         /* Re-configure the return path */
935         mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
936 
937         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
938                           MIGRATION_STATUS_POSTCOPY_RECOVER);
939 
940         /*
941          * Here, we only wake up the main loading thread (while the
942          * rest threads will still be waiting), so that we can receive
943          * commands from source now, and answer it if needed. The
944          * rest threads will be woken up afterwards until we are sure
945          * that source is ready to reply to page requests.
946          */
947         qemu_sem_post(&mis->postcopy_pause_sem_dst);
948         return true;
949     }
950 
951     return false;
952 }
953 
954 void migration_fd_process_incoming(QEMUFile *f)
955 {
956     migration_incoming_setup(f);
957     if (postcopy_try_recover()) {
958         return;
959     }
960     migration_incoming_process();
961 }
962 
963 /*
964  * Returns true when we want to start a new incoming migration process,
965  * false otherwise.
966  */
967 static bool migration_should_start_incoming(bool main_channel)
968 {
969     /* Multifd doesn't start unless all channels are established */
970     if (migrate_multifd()) {
971         return migration_has_all_channels();
972     }
973 
974     /* Preempt channel only starts when the main channel is created */
975     if (migrate_postcopy_preempt()) {
976         return main_channel;
977     }
978 
979     /*
980      * For all the rest types of migration, we should only reach here when
981      * it's the main channel that's being created, and we should always
982      * proceed with this channel.
983      */
984     assert(main_channel);
985     return true;
986 }
987 
988 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
989 {
990     MigrationIncomingState *mis = migration_incoming_get_current();
991     Error *local_err = NULL;
992     QEMUFile *f;
993     bool default_channel = true;
994     uint32_t channel_magic = 0;
995     int ret = 0;
996 
997     if (migrate_multifd() && !migrate_mapped_ram() &&
998         !migrate_postcopy_ram() &&
999         qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
1000         /*
1001          * With multiple channels, it is possible that we receive channels
1002          * out of order on destination side, causing incorrect mapping of
1003          * source channels on destination side. Check channel MAGIC to
1004          * decide type of channel. Please note this is best effort, postcopy
1005          * preempt channel does not send any magic number so avoid it for
1006          * postcopy live migration. Also tls live migration already does
1007          * tls handshake while initializing main channel so with tls this
1008          * issue is not possible.
1009          */
1010         ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
1011                                           sizeof(channel_magic), errp);
1012 
1013         if (ret != 0) {
1014             return;
1015         }
1016 
1017         default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
1018     } else {
1019         default_channel = !mis->from_src_file;
1020     }
1021 
1022     if (multifd_recv_setup(errp) != 0) {
1023         return;
1024     }
1025 
1026     if (default_channel) {
1027         f = qemu_file_new_input(ioc);
1028         migration_incoming_setup(f);
1029     } else {
1030         /* Multiple connections */
1031         assert(migration_needs_multiple_sockets());
1032         if (migrate_multifd()) {
1033             multifd_recv_new_channel(ioc, &local_err);
1034         } else {
1035             assert(migrate_postcopy_preempt());
1036             f = qemu_file_new_input(ioc);
1037             postcopy_preempt_new_channel(mis, f);
1038         }
1039         if (local_err) {
1040             error_propagate(errp, local_err);
1041             return;
1042         }
1043     }
1044 
1045     if (migration_should_start_incoming(default_channel)) {
1046         /* If it's a recovery, we're done */
1047         if (postcopy_try_recover()) {
1048             return;
1049         }
1050         migration_incoming_process();
1051     }
1052 }
1053 
1054 /**
1055  * @migration_has_all_channels: We have received all channels that we need
1056  *
1057  * Returns true when we have got connections to all the channels that
1058  * we need for migration.
1059  */
1060 bool migration_has_all_channels(void)
1061 {
1062     MigrationIncomingState *mis = migration_incoming_get_current();
1063 
1064     if (!mis->from_src_file) {
1065         return false;
1066     }
1067 
1068     if (migrate_multifd()) {
1069         return multifd_recv_all_channels_created();
1070     }
1071 
1072     if (migrate_postcopy_preempt()) {
1073         return mis->postcopy_qemufile_dst != NULL;
1074     }
1075 
1076     return true;
1077 }
1078 
1079 int migrate_send_rp_switchover_ack(MigrationIncomingState *mis)
1080 {
1081     return migrate_send_rp_message(mis, MIG_RP_MSG_SWITCHOVER_ACK, 0, NULL);
1082 }
1083 
1084 /*
1085  * Send a 'SHUT' message on the return channel with the given value
1086  * to indicate that we've finished with the RP.  Non-0 value indicates
1087  * error.
1088  */
1089 void migrate_send_rp_shut(MigrationIncomingState *mis,
1090                           uint32_t value)
1091 {
1092     uint32_t buf;
1093 
1094     buf = cpu_to_be32(value);
1095     migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
1096 }
1097 
1098 /*
1099  * Send a 'PONG' message on the return channel with the given value
1100  * (normally in response to a 'PING')
1101  */
1102 void migrate_send_rp_pong(MigrationIncomingState *mis,
1103                           uint32_t value)
1104 {
1105     uint32_t buf;
1106 
1107     buf = cpu_to_be32(value);
1108     migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
1109 }
1110 
1111 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
1112                                  char *block_name)
1113 {
1114     char buf[512];
1115     int len;
1116     int64_t res;
1117 
1118     /*
1119      * First, we send the header part. It contains only the len of
1120      * idstr, and the idstr itself.
1121      */
1122     len = strlen(block_name);
1123     buf[0] = len;
1124     memcpy(buf + 1, block_name, len);
1125 
1126     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
1127         error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
1128                      __func__);
1129         return;
1130     }
1131 
1132     migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
1133 
1134     /*
1135      * Next, we dump the received bitmap to the stream.
1136      *
1137      * TODO: currently we are safe since we are the only one that is
1138      * using the to_src_file handle (fault thread is still paused),
1139      * and it's ok even not taking the mutex. However the best way is
1140      * to take the lock before sending the message header, and release
1141      * the lock after sending the bitmap.
1142      */
1143     qemu_mutex_lock(&mis->rp_mutex);
1144     res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
1145     qemu_mutex_unlock(&mis->rp_mutex);
1146 
1147     trace_migrate_send_rp_recv_bitmap(block_name, res);
1148 }
1149 
1150 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
1151 {
1152     uint32_t buf;
1153 
1154     buf = cpu_to_be32(value);
1155     migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
1156 }
1157 
1158 bool migration_is_running(void)
1159 {
1160     MigrationState *s = current_migration;
1161 
1162     if (!s) {
1163         return false;
1164     }
1165 
1166     switch (s->state) {
1167     case MIGRATION_STATUS_ACTIVE:
1168     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1169     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1170     case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
1171     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1172     case MIGRATION_STATUS_SETUP:
1173     case MIGRATION_STATUS_PRE_SWITCHOVER:
1174     case MIGRATION_STATUS_DEVICE:
1175     case MIGRATION_STATUS_WAIT_UNPLUG:
1176     case MIGRATION_STATUS_CANCELLING:
1177     case MIGRATION_STATUS_COLO:
1178         return true;
1179     default:
1180         return false;
1181     }
1182 }
1183 
1184 static bool migration_is_active(void)
1185 {
1186     MigrationState *s = current_migration;
1187 
1188     return (s->state == MIGRATION_STATUS_ACTIVE ||
1189             s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1190 }
1191 
1192 static bool migrate_show_downtime(MigrationState *s)
1193 {
1194     return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
1195 }
1196 
1197 static void populate_time_info(MigrationInfo *info, MigrationState *s)
1198 {
1199     info->has_status = true;
1200     info->has_setup_time = true;
1201     info->setup_time = s->setup_time;
1202 
1203     if (s->state == MIGRATION_STATUS_COMPLETED) {
1204         info->has_total_time = true;
1205         info->total_time = s->total_time;
1206     } else {
1207         info->has_total_time = true;
1208         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
1209                            s->start_time;
1210     }
1211 
1212     if (migrate_show_downtime(s)) {
1213         info->has_downtime = true;
1214         info->downtime = s->downtime;
1215     } else {
1216         info->has_expected_downtime = true;
1217         info->expected_downtime = s->expected_downtime;
1218     }
1219 }
1220 
1221 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
1222 {
1223     size_t page_size = qemu_target_page_size();
1224 
1225     info->ram = g_malloc0(sizeof(*info->ram));
1226     info->ram->transferred = migration_transferred_bytes();
1227     info->ram->total = ram_bytes_total();
1228     info->ram->duplicate = stat64_get(&mig_stats.zero_pages);
1229     info->ram->normal = stat64_get(&mig_stats.normal_pages);
1230     info->ram->normal_bytes = info->ram->normal * page_size;
1231     info->ram->mbps = s->mbps;
1232     info->ram->dirty_sync_count =
1233         stat64_get(&mig_stats.dirty_sync_count);
1234     info->ram->dirty_sync_missed_zero_copy =
1235         stat64_get(&mig_stats.dirty_sync_missed_zero_copy);
1236     info->ram->postcopy_requests =
1237         stat64_get(&mig_stats.postcopy_requests);
1238     info->ram->page_size = page_size;
1239     info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes);
1240     info->ram->pages_per_second = s->pages_per_second;
1241     info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes);
1242     info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes);
1243     info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes);
1244 
1245     if (migrate_xbzrle()) {
1246         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
1247         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
1248         info->xbzrle_cache->bytes = xbzrle_counters.bytes;
1249         info->xbzrle_cache->pages = xbzrle_counters.pages;
1250         info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
1251         info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
1252         info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
1253         info->xbzrle_cache->overflow = xbzrle_counters.overflow;
1254     }
1255 
1256     if (cpu_throttle_active()) {
1257         info->has_cpu_throttle_percentage = true;
1258         info->cpu_throttle_percentage = cpu_throttle_get_percentage();
1259     }
1260 
1261     if (s->state != MIGRATION_STATUS_COMPLETED) {
1262         info->ram->remaining = ram_bytes_remaining();
1263         info->ram->dirty_pages_rate =
1264            stat64_get(&mig_stats.dirty_pages_rate);
1265     }
1266 
1267     if (migrate_dirty_limit() && dirtylimit_in_service()) {
1268         info->has_dirty_limit_throttle_time_per_round = true;
1269         info->dirty_limit_throttle_time_per_round =
1270                             dirtylimit_throttle_time_per_round();
1271 
1272         info->has_dirty_limit_ring_full_time = true;
1273         info->dirty_limit_ring_full_time = dirtylimit_ring_full_time();
1274     }
1275 }
1276 
1277 static void fill_source_migration_info(MigrationInfo *info)
1278 {
1279     MigrationState *s = migrate_get_current();
1280     int state = qatomic_read(&s->state);
1281     GSList *cur_blocker = migration_blockers[migrate_mode()];
1282 
1283     info->blocked_reasons = NULL;
1284 
1285     /*
1286      * There are two types of reasons a migration might be blocked;
1287      * a) devices marked in VMState as non-migratable, and
1288      * b) Explicit migration blockers
1289      * We need to add both of them here.
1290      */
1291     qemu_savevm_non_migratable_list(&info->blocked_reasons);
1292 
1293     while (cur_blocker) {
1294         QAPI_LIST_PREPEND(info->blocked_reasons,
1295                           g_strdup(error_get_pretty(cur_blocker->data)));
1296         cur_blocker = g_slist_next(cur_blocker);
1297     }
1298     info->has_blocked_reasons = info->blocked_reasons != NULL;
1299 
1300     switch (state) {
1301     case MIGRATION_STATUS_NONE:
1302         /* no migration has happened ever */
1303         /* do not overwrite destination migration status */
1304         return;
1305     case MIGRATION_STATUS_SETUP:
1306         info->has_status = true;
1307         info->has_total_time = false;
1308         break;
1309     case MIGRATION_STATUS_ACTIVE:
1310     case MIGRATION_STATUS_CANCELLING:
1311     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1312     case MIGRATION_STATUS_PRE_SWITCHOVER:
1313     case MIGRATION_STATUS_DEVICE:
1314     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1315     case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
1316     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1317         /* TODO add some postcopy stats */
1318         populate_time_info(info, s);
1319         populate_ram_info(info, s);
1320         migration_populate_vfio_info(info);
1321         break;
1322     case MIGRATION_STATUS_COLO:
1323         info->has_status = true;
1324         /* TODO: display COLO specific information (checkpoint info etc.) */
1325         break;
1326     case MIGRATION_STATUS_COMPLETED:
1327         populate_time_info(info, s);
1328         populate_ram_info(info, s);
1329         migration_populate_vfio_info(info);
1330         break;
1331     case MIGRATION_STATUS_FAILED:
1332         info->has_status = true;
1333         break;
1334     case MIGRATION_STATUS_CANCELLED:
1335         info->has_status = true;
1336         break;
1337     case MIGRATION_STATUS_WAIT_UNPLUG:
1338         info->has_status = true;
1339         break;
1340     }
1341     info->status = state;
1342 
1343     QEMU_LOCK_GUARD(&s->error_mutex);
1344     if (s->error) {
1345         info->error_desc = g_strdup(error_get_pretty(s->error));
1346     }
1347 }
1348 
1349 static void fill_destination_migration_info(MigrationInfo *info)
1350 {
1351     MigrationIncomingState *mis = migration_incoming_get_current();
1352 
1353     if (mis->socket_address_list) {
1354         info->has_socket_address = true;
1355         info->socket_address =
1356             QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1357     }
1358 
1359     switch (mis->state) {
1360     case MIGRATION_STATUS_SETUP:
1361     case MIGRATION_STATUS_CANCELLING:
1362     case MIGRATION_STATUS_CANCELLED:
1363     case MIGRATION_STATUS_ACTIVE:
1364     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1365     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1366     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1367     case MIGRATION_STATUS_FAILED:
1368     case MIGRATION_STATUS_COLO:
1369         info->has_status = true;
1370         break;
1371     case MIGRATION_STATUS_COMPLETED:
1372         info->has_status = true;
1373         fill_destination_postcopy_migration_info(info);
1374         break;
1375     default:
1376         return;
1377     }
1378     info->status = mis->state;
1379 
1380     if (!info->error_desc) {
1381         MigrationState *s = migrate_get_current();
1382         QEMU_LOCK_GUARD(&s->error_mutex);
1383 
1384         if (s->error) {
1385             info->error_desc = g_strdup(error_get_pretty(s->error));
1386         }
1387     }
1388 }
1389 
1390 MigrationInfo *qmp_query_migrate(Error **errp)
1391 {
1392     MigrationInfo *info = g_malloc0(sizeof(*info));
1393 
1394     fill_destination_migration_info(info);
1395     fill_source_migration_info(info);
1396 
1397     return info;
1398 }
1399 
1400 void qmp_migrate_start_postcopy(Error **errp)
1401 {
1402     MigrationState *s = migrate_get_current();
1403 
1404     if (!migrate_postcopy()) {
1405         error_setg(errp, "Enable postcopy with migrate_set_capability before"
1406                          " the start of migration");
1407         return;
1408     }
1409 
1410     if (s->state == MIGRATION_STATUS_NONE) {
1411         error_setg(errp, "Postcopy must be started after migration has been"
1412                          " started");
1413         return;
1414     }
1415     /*
1416      * we don't error if migration has finished since that would be racy
1417      * with issuing this command.
1418      */
1419     qatomic_set(&s->start_postcopy, true);
1420 }
1421 
1422 /* shared migration helpers */
1423 
1424 void migrate_set_state(MigrationStatus *state, MigrationStatus old_state,
1425                        MigrationStatus new_state)
1426 {
1427     assert(new_state < MIGRATION_STATUS__MAX);
1428     if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1429         trace_migrate_set_state(MigrationStatus_str(new_state));
1430         migrate_generate_event(new_state);
1431     }
1432 }
1433 
1434 static void migration_cleanup_json_writer(MigrationState *s)
1435 {
1436     g_clear_pointer(&s->vmdesc, json_writer_free);
1437 }
1438 
1439 static void migration_cleanup(MigrationState *s)
1440 {
1441     MigrationEventType type;
1442     QEMUFile *tmp = NULL;
1443 
1444     trace_migration_cleanup();
1445 
1446     migration_cleanup_json_writer(s);
1447 
1448     g_free(s->hostname);
1449     s->hostname = NULL;
1450 
1451     qemu_savevm_state_cleanup();
1452     cpr_state_close();
1453     migrate_hup_delete(s);
1454 
1455     close_return_path_on_source(s);
1456 
1457     if (s->migration_thread_running) {
1458         bql_unlock();
1459         qemu_thread_join(&s->thread);
1460         s->migration_thread_running = false;
1461         bql_lock();
1462     }
1463 
1464     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1465         /*
1466          * Close the file handle without the lock to make sure the critical
1467          * section won't block for long.
1468          */
1469         tmp = s->to_dst_file;
1470         s->to_dst_file = NULL;
1471     }
1472 
1473     if (tmp) {
1474         /*
1475          * We only need to shutdown multifd if tmp!=NULL, because if
1476          * tmp==NULL, it means the main channel isn't established, while
1477          * multifd is only setup after that (in migration_thread()).
1478          */
1479         multifd_send_shutdown();
1480         migration_ioc_unregister_yank_from_file(tmp);
1481         qemu_fclose(tmp);
1482     }
1483 
1484     assert(!migration_is_active());
1485 
1486     if (s->state == MIGRATION_STATUS_CANCELLING) {
1487         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1488                           MIGRATION_STATUS_CANCELLED);
1489     }
1490 
1491     if (s->error) {
1492         /* It is used on info migrate.  We can't free it */
1493         error_report_err(error_copy(s->error));
1494     }
1495     type = migration_has_failed(s) ? MIG_EVENT_PRECOPY_FAILED :
1496                                      MIG_EVENT_PRECOPY_DONE;
1497     migration_call_notifiers(s, type, NULL);
1498     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1499 }
1500 
1501 static void migration_cleanup_bh(void *opaque)
1502 {
1503     migration_cleanup(opaque);
1504 }
1505 
1506 void migrate_set_error(MigrationState *s, const Error *error)
1507 {
1508     QEMU_LOCK_GUARD(&s->error_mutex);
1509 
1510     trace_migrate_error(error_get_pretty(error));
1511 
1512     if (!s->error) {
1513         s->error = error_copy(error);
1514     }
1515 }
1516 
1517 bool migrate_has_error(MigrationState *s)
1518 {
1519     /* The lock is not helpful here, but still follow the rule */
1520     QEMU_LOCK_GUARD(&s->error_mutex);
1521     return qatomic_read(&s->error);
1522 }
1523 
1524 static void migrate_error_free(MigrationState *s)
1525 {
1526     QEMU_LOCK_GUARD(&s->error_mutex);
1527     if (s->error) {
1528         error_free(s->error);
1529         s->error = NULL;
1530     }
1531 }
1532 
1533 static void migration_connect_set_error(MigrationState *s, const Error *error)
1534 {
1535     MigrationStatus current = s->state;
1536     MigrationStatus next;
1537 
1538     assert(s->to_dst_file == NULL);
1539 
1540     switch (current) {
1541     case MIGRATION_STATUS_SETUP:
1542         next = MIGRATION_STATUS_FAILED;
1543         break;
1544     case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
1545         /* Never fail a postcopy migration; switch back to PAUSED instead */
1546         next = MIGRATION_STATUS_POSTCOPY_PAUSED;
1547         break;
1548     default:
1549         /*
1550          * This really shouldn't happen. Just be careful to not crash a VM
1551          * just for this.  Instead, dump something.
1552          */
1553         error_report("%s: Illegal migration status (%s) detected",
1554                      __func__, MigrationStatus_str(current));
1555         return;
1556     }
1557 
1558     migrate_set_state(&s->state, current, next);
1559     migrate_set_error(s, error);
1560 }
1561 
1562 void migration_cancel(void)
1563 {
1564     MigrationState *s = migrate_get_current();
1565     int old_state ;
1566     bool setup = (s->state == MIGRATION_STATUS_SETUP);
1567 
1568     trace_migration_cancel();
1569 
1570     if (migrate_dirty_limit()) {
1571         qmp_cancel_vcpu_dirty_limit(false, -1, NULL);
1572     }
1573 
1574     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1575         if (s->rp_state.from_dst_file) {
1576             /* shutdown the rp socket, so causing the rp thread to shutdown */
1577             qemu_file_shutdown(s->rp_state.from_dst_file);
1578         }
1579     }
1580 
1581     do {
1582         old_state = s->state;
1583         if (!migration_is_running()) {
1584             break;
1585         }
1586         /* If the migration is paused, kick it out of the pause */
1587         if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1588             qemu_sem_post(&s->pause_sem);
1589         }
1590         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1591     } while (s->state != MIGRATION_STATUS_CANCELLING);
1592 
1593     /*
1594      * If we're unlucky the migration code might be stuck somewhere in a
1595      * send/write while the network has failed and is waiting to timeout;
1596      * if we've got shutdown(2) available then we can force it to quit.
1597      */
1598     if (s->state == MIGRATION_STATUS_CANCELLING) {
1599         WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1600             if (s->to_dst_file) {
1601                 qemu_file_shutdown(s->to_dst_file);
1602             }
1603         }
1604     }
1605 
1606     /*
1607      * If qmp_migrate_finish has not been called, then there is no path that
1608      * will complete the cancellation.  Do it now.
1609      */
1610     if (setup && !s->to_dst_file) {
1611         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1612                           MIGRATION_STATUS_CANCELLED);
1613         cpr_state_close();
1614         migrate_hup_delete(s);
1615     }
1616 }
1617 
1618 void migration_add_notifier_mode(NotifierWithReturn *notify,
1619                                  MigrationNotifyFunc func, MigMode mode)
1620 {
1621     notify->notify = (NotifierWithReturnFunc)func;
1622     notifier_with_return_list_add(&migration_state_notifiers[mode], notify);
1623 }
1624 
1625 void migration_add_notifier(NotifierWithReturn *notify,
1626                             MigrationNotifyFunc func)
1627 {
1628     migration_add_notifier_mode(notify, func, MIG_MODE_NORMAL);
1629 }
1630 
1631 void migration_remove_notifier(NotifierWithReturn *notify)
1632 {
1633     if (notify->notify) {
1634         notifier_with_return_remove(notify);
1635         notify->notify = NULL;
1636     }
1637 }
1638 
1639 int migration_call_notifiers(MigrationState *s, MigrationEventType type,
1640                              Error **errp)
1641 {
1642     MigMode mode = s->parameters.mode;
1643     MigrationEvent e;
1644     int ret;
1645 
1646     e.type = type;
1647     ret = notifier_with_return_list_notify(&migration_state_notifiers[mode],
1648                                            &e, errp);
1649     assert(!ret || type == MIG_EVENT_PRECOPY_SETUP);
1650     return ret;
1651 }
1652 
1653 bool migration_has_failed(MigrationState *s)
1654 {
1655     return (s->state == MIGRATION_STATUS_CANCELLED ||
1656             s->state == MIGRATION_STATUS_FAILED);
1657 }
1658 
1659 bool migration_in_postcopy(void)
1660 {
1661     MigrationState *s = migrate_get_current();
1662 
1663     switch (s->state) {
1664     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1665     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1666     case MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP:
1667     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1668         return true;
1669     default:
1670         return false;
1671     }
1672 }
1673 
1674 bool migration_postcopy_is_alive(MigrationStatus state)
1675 {
1676     switch (state) {
1677     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1678     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1679         return true;
1680     default:
1681         return false;
1682     }
1683 }
1684 
1685 bool migration_in_incoming_postcopy(void)
1686 {
1687     PostcopyState ps = postcopy_state_get();
1688 
1689     return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1690 }
1691 
1692 bool migration_incoming_postcopy_advised(void)
1693 {
1694     PostcopyState ps = postcopy_state_get();
1695 
1696     return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
1697 }
1698 
1699 bool migration_in_bg_snapshot(void)
1700 {
1701     return migrate_background_snapshot() && migration_is_running();
1702 }
1703 
1704 bool migration_thread_is_self(void)
1705 {
1706     MigrationState *s = current_migration;
1707 
1708     return qemu_thread_is_self(&s->thread);
1709 }
1710 
1711 bool migrate_mode_is_cpr(MigrationState *s)
1712 {
1713     MigMode mode = s->parameters.mode;
1714     return mode == MIG_MODE_CPR_REBOOT ||
1715            mode == MIG_MODE_CPR_TRANSFER;
1716 }
1717 
1718 int migrate_init(MigrationState *s, Error **errp)
1719 {
1720     int ret;
1721 
1722     ret = qemu_savevm_state_prepare(errp);
1723     if (ret) {
1724         return ret;
1725     }
1726 
1727     /*
1728      * Reinitialise all migration state, except
1729      * parameters/capabilities that the user set, and
1730      * locks.
1731      */
1732     s->to_dst_file = NULL;
1733     s->state = MIGRATION_STATUS_NONE;
1734     s->rp_state.from_dst_file = NULL;
1735     s->mbps = 0.0;
1736     s->pages_per_second = 0.0;
1737     s->downtime = 0;
1738     s->expected_downtime = 0;
1739     s->setup_time = 0;
1740     s->start_postcopy = false;
1741     s->migration_thread_running = false;
1742     error_free(s->error);
1743     s->error = NULL;
1744 
1745     if (should_send_vmdesc()) {
1746         s->vmdesc = json_writer_new(false);
1747     }
1748 
1749     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1750 
1751     s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1752     s->total_time = 0;
1753     s->vm_old_state = -1;
1754     s->iteration_initial_bytes = 0;
1755     s->threshold_size = 0;
1756     s->switchover_acked = false;
1757     s->rdma_migration = false;
1758     /*
1759      * set mig_stats memory to zero for a new migration
1760      */
1761     memset(&mig_stats, 0, sizeof(mig_stats));
1762     migration_reset_vfio_bytes_transferred();
1763 
1764     return 0;
1765 }
1766 
1767 static bool is_busy(Error **reasonp, Error **errp)
1768 {
1769     ERRP_GUARD();
1770 
1771     /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1772     if (runstate_check(RUN_STATE_SAVE_VM) || migration_is_running()) {
1773         error_propagate_prepend(errp, *reasonp,
1774                                 "disallowing migration blocker "
1775                                 "(migration/snapshot in progress) for: ");
1776         *reasonp = NULL;
1777         return true;
1778     }
1779     return false;
1780 }
1781 
1782 static bool is_only_migratable(Error **reasonp, Error **errp, int modes)
1783 {
1784     ERRP_GUARD();
1785 
1786     if (only_migratable && (modes & BIT(MIG_MODE_NORMAL))) {
1787         error_propagate_prepend(errp, *reasonp,
1788                                 "disallowing migration blocker "
1789                                 "(--only-migratable) for: ");
1790         *reasonp = NULL;
1791         return true;
1792     }
1793     return false;
1794 }
1795 
1796 static int get_modes(MigMode mode, va_list ap)
1797 {
1798     int modes = 0;
1799 
1800     while (mode != -1 && mode != MIG_MODE_ALL) {
1801         assert(mode >= MIG_MODE_NORMAL && mode < MIG_MODE__MAX);
1802         modes |= BIT(mode);
1803         mode = va_arg(ap, MigMode);
1804     }
1805     if (mode == MIG_MODE_ALL) {
1806         modes = BIT(MIG_MODE__MAX) - 1;
1807     }
1808     return modes;
1809 }
1810 
1811 static int add_blockers(Error **reasonp, Error **errp, int modes)
1812 {
1813     for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
1814         if (modes & BIT(mode)) {
1815             migration_blockers[mode] = g_slist_prepend(migration_blockers[mode],
1816                                                        *reasonp);
1817         }
1818     }
1819     return 0;
1820 }
1821 
1822 int migrate_add_blocker(Error **reasonp, Error **errp)
1823 {
1824     return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_ALL);
1825 }
1826 
1827 int migrate_add_blocker_normal(Error **reasonp, Error **errp)
1828 {
1829     return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_NORMAL, -1);
1830 }
1831 
1832 int migrate_add_blocker_modes(Error **reasonp, Error **errp, MigMode mode, ...)
1833 {
1834     int modes;
1835     va_list ap;
1836 
1837     va_start(ap, mode);
1838     modes = get_modes(mode, ap);
1839     va_end(ap);
1840 
1841     if (is_only_migratable(reasonp, errp, modes)) {
1842         return -EACCES;
1843     } else if (is_busy(reasonp, errp)) {
1844         return -EBUSY;
1845     }
1846     return add_blockers(reasonp, errp, modes);
1847 }
1848 
1849 int migrate_add_blocker_internal(Error **reasonp, Error **errp)
1850 {
1851     int modes = BIT(MIG_MODE__MAX) - 1;
1852 
1853     if (is_busy(reasonp, errp)) {
1854         return -EBUSY;
1855     }
1856     return add_blockers(reasonp, errp, modes);
1857 }
1858 
1859 void migrate_del_blocker(Error **reasonp)
1860 {
1861     if (*reasonp) {
1862         for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
1863             migration_blockers[mode] = g_slist_remove(migration_blockers[mode],
1864                                                       *reasonp);
1865         }
1866         error_free(*reasonp);
1867         *reasonp = NULL;
1868     }
1869 }
1870 
1871 void qmp_migrate_incoming(const char *uri, bool has_channels,
1872                           MigrationChannelList *channels,
1873                           bool has_exit_on_error, bool exit_on_error,
1874                           Error **errp)
1875 {
1876     Error *local_err = NULL;
1877     static bool once = true;
1878     MigrationIncomingState *mis = migration_incoming_get_current();
1879 
1880     if (!once) {
1881         error_setg(errp, "The incoming migration has already been started");
1882         return;
1883     }
1884     if (!runstate_check(RUN_STATE_INMIGRATE)) {
1885         error_setg(errp, "'-incoming' was not specified on the command line");
1886         return;
1887     }
1888 
1889     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1890         return;
1891     }
1892 
1893     mis->exit_on_error =
1894         has_exit_on_error ? exit_on_error : INMIGRATE_DEFAULT_EXIT_ON_ERROR;
1895 
1896     qemu_start_incoming_migration(uri, has_channels, channels, &local_err);
1897 
1898     if (local_err) {
1899         yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1900         error_propagate(errp, local_err);
1901         return;
1902     }
1903 
1904     once = false;
1905 }
1906 
1907 void qmp_migrate_recover(const char *uri, Error **errp)
1908 {
1909     MigrationIncomingState *mis = migration_incoming_get_current();
1910 
1911     /*
1912      * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1913      * callers (no one should ignore a recover failure); if there is, it's a
1914      * programming error.
1915      */
1916     assert(errp);
1917 
1918     if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1919         error_setg(errp, "Migrate recover can only be run "
1920                    "when postcopy is paused.");
1921         return;
1922     }
1923 
1924     /* If there's an existing transport, release it */
1925     migration_incoming_transport_cleanup(mis);
1926 
1927     /*
1928      * Note that this call will never start a real migration; it will
1929      * only re-setup the migration stream and poke existing migration
1930      * to continue using that newly established channel.
1931      */
1932     qemu_start_incoming_migration(uri, false, NULL, errp);
1933 }
1934 
1935 void qmp_migrate_pause(Error **errp)
1936 {
1937     MigrationState *ms = migrate_get_current();
1938     MigrationIncomingState *mis = migration_incoming_get_current();
1939     int ret = 0;
1940 
1941     if (migration_postcopy_is_alive(ms->state)) {
1942         /* Source side, during postcopy */
1943         Error *error = NULL;
1944 
1945         /* Tell the core migration that we're pausing */
1946         error_setg(&error, "Postcopy migration is paused by the user");
1947         migrate_set_error(ms, error);
1948         error_free(error);
1949 
1950         qemu_mutex_lock(&ms->qemu_file_lock);
1951         if (ms->to_dst_file) {
1952             ret = qemu_file_shutdown(ms->to_dst_file);
1953         }
1954         qemu_mutex_unlock(&ms->qemu_file_lock);
1955         if (ret) {
1956             error_setg(errp, "Failed to pause source migration");
1957         }
1958 
1959         /*
1960          * Kick the migration thread out of any waiting windows (on behalf
1961          * of the rp thread).
1962          */
1963         migration_rp_kick(ms);
1964 
1965         return;
1966     }
1967 
1968     if (migration_postcopy_is_alive(mis->state)) {
1969         ret = qemu_file_shutdown(mis->from_src_file);
1970         if (ret) {
1971             error_setg(errp, "Failed to pause destination migration");
1972         }
1973         return;
1974     }
1975 
1976     error_setg(errp, "migrate-pause is currently only supported "
1977                "during postcopy-active or postcopy-recover state");
1978 }
1979 
1980 bool migration_is_blocked(Error **errp)
1981 {
1982     GSList *blockers = migration_blockers[migrate_mode()];
1983 
1984     if (qemu_savevm_state_blocked(errp)) {
1985         return true;
1986     }
1987 
1988     if (blockers) {
1989         error_propagate(errp, error_copy(blockers->data));
1990         return true;
1991     }
1992 
1993     return false;
1994 }
1995 
1996 /* Returns true if continue to migrate, or false if error detected */
1997 static bool migrate_prepare(MigrationState *s, bool resume, Error **errp)
1998 {
1999     if (resume) {
2000         if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2001             error_setg(errp, "Cannot resume if there is no "
2002                        "paused migration");
2003             return false;
2004         }
2005 
2006         /*
2007          * Postcopy recovery won't work well with release-ram
2008          * capability since release-ram will drop the page buffer as
2009          * long as the page is put into the send buffer.  So if there
2010          * is a network failure happened, any page buffers that have
2011          * not yet reached the destination VM but have already been
2012          * sent from the source VM will be lost forever.  Let's refuse
2013          * the client from resuming such a postcopy migration.
2014          * Luckily release-ram was designed to only be used when src
2015          * and destination VMs are on the same host, so it should be
2016          * fine.
2017          */
2018         if (migrate_release_ram()) {
2019             error_setg(errp, "Postcopy recovery cannot work "
2020                        "when release-ram capability is set");
2021             return false;
2022         }
2023 
2024         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
2025                           MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
2026 
2027         /* This is a resume, skip init status */
2028         return true;
2029     }
2030 
2031     if (migration_is_running()) {
2032         error_setg(errp, "There's a migration process in progress");
2033         return false;
2034     }
2035 
2036     if (runstate_check(RUN_STATE_INMIGRATE)) {
2037         error_setg(errp, "Guest is waiting for an incoming migration");
2038         return false;
2039     }
2040 
2041     if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2042         error_setg(errp, "Can't migrate the vm that was paused due to "
2043                    "previous migration");
2044         return false;
2045     }
2046 
2047     if (kvm_hwpoisoned_mem()) {
2048         error_setg(errp, "Can't migrate this vm with hardware poisoned memory, "
2049                    "please reboot the vm and try again");
2050         return false;
2051     }
2052 
2053     if (migration_is_blocked(errp)) {
2054         return false;
2055     }
2056 
2057     if (migrate_mapped_ram()) {
2058         if (migrate_tls()) {
2059             error_setg(errp, "Cannot use TLS with mapped-ram");
2060             return false;
2061         }
2062 
2063         if (migrate_multifd_compression()) {
2064             error_setg(errp, "Cannot use compression with mapped-ram");
2065             return false;
2066         }
2067     }
2068 
2069     if (migrate_mode_is_cpr(s)) {
2070         const char *conflict = NULL;
2071 
2072         if (migrate_postcopy()) {
2073             conflict = "postcopy";
2074         } else if (migrate_background_snapshot()) {
2075             conflict = "background snapshot";
2076         } else if (migrate_colo()) {
2077             conflict = "COLO";
2078         }
2079 
2080         if (conflict) {
2081             error_setg(errp, "Cannot use %s with CPR", conflict);
2082             return false;
2083         }
2084     }
2085 
2086     if (migrate_init(s, errp)) {
2087         return false;
2088     }
2089 
2090     return true;
2091 }
2092 
2093 static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
2094                                Error **errp);
2095 
2096 static void migrate_hup_add(MigrationState *s, QIOChannel *ioc, GSourceFunc cb,
2097                             void *opaque)
2098 {
2099         s->hup_source = qio_channel_create_watch(ioc, G_IO_HUP);
2100         g_source_set_callback(s->hup_source, cb, opaque, NULL);
2101         g_source_attach(s->hup_source, NULL);
2102 }
2103 
2104 static void migrate_hup_delete(MigrationState *s)
2105 {
2106     if (s->hup_source) {
2107         g_source_destroy(s->hup_source);
2108         g_source_unref(s->hup_source);
2109         s->hup_source = NULL;
2110     }
2111 }
2112 
2113 static gboolean qmp_migrate_finish_cb(QIOChannel *channel,
2114                                       GIOCondition cond,
2115                                       void *opaque)
2116 {
2117     MigrationAddress *addr = opaque;
2118 
2119     qmp_migrate_finish(addr, false, NULL);
2120 
2121     cpr_state_close();
2122     migrate_hup_delete(migrate_get_current());
2123     qapi_free_MigrationAddress(addr);
2124     return G_SOURCE_REMOVE;
2125 }
2126 
2127 void qmp_migrate(const char *uri, bool has_channels,
2128                  MigrationChannelList *channels, bool has_detach, bool detach,
2129                  bool has_resume, bool resume, Error **errp)
2130 {
2131     bool resume_requested;
2132     Error *local_err = NULL;
2133     MigrationState *s = migrate_get_current();
2134     g_autoptr(MigrationChannel) channel = NULL;
2135     MigrationAddress *addr = NULL;
2136     MigrationChannel *channelv[MIGRATION_CHANNEL_TYPE__MAX] = { NULL };
2137     MigrationChannel *cpr_channel = NULL;
2138 
2139     /*
2140      * Having preliminary checks for uri and channel
2141      */
2142     if (!uri == !channels) {
2143         error_setg(errp, "need either 'uri' or 'channels' argument");
2144         return;
2145     }
2146 
2147     if (channels) {
2148         for ( ; channels; channels = channels->next) {
2149             MigrationChannelType type = channels->value->channel_type;
2150 
2151             if (channelv[type]) {
2152                 error_setg(errp, "Channel list has more than one %s entry",
2153                            MigrationChannelType_str(type));
2154                 return;
2155             }
2156             channelv[type] = channels->value;
2157         }
2158         cpr_channel = channelv[MIGRATION_CHANNEL_TYPE_CPR];
2159         addr = channelv[MIGRATION_CHANNEL_TYPE_MAIN]->addr;
2160         if (!addr) {
2161             error_setg(errp, "Channel list has no main entry");
2162             return;
2163         }
2164     }
2165 
2166     if (uri) {
2167         /* caller uses the old URI syntax */
2168         if (!migrate_uri_parse(uri, &channel, errp)) {
2169             return;
2170         }
2171         addr = channel->addr;
2172     }
2173 
2174     /* transport mechanism not suitable for migration? */
2175     if (!migration_channels_and_transport_compatible(addr, errp)) {
2176         return;
2177     }
2178 
2179     if (s->parameters.mode == MIG_MODE_CPR_TRANSFER && !cpr_channel) {
2180         error_setg(errp, "missing 'cpr' migration channel");
2181         return;
2182     }
2183 
2184     resume_requested = has_resume && resume;
2185     if (!migrate_prepare(s, resume_requested, errp)) {
2186         /* Error detected, put into errp */
2187         return;
2188     }
2189 
2190     if (cpr_state_save(cpr_channel, &local_err)) {
2191         goto out;
2192     }
2193 
2194     /*
2195      * For cpr-transfer, the target may not be listening yet on the migration
2196      * channel, because first it must finish cpr_load_state.  The target tells
2197      * us it is listening by closing the cpr-state socket.  Wait for that HUP
2198      * event before connecting in qmp_migrate_finish.
2199      *
2200      * The HUP could occur because the target fails while reading CPR state,
2201      * in which case the target will not listen for the incoming migration
2202      * connection, so qmp_migrate_finish will fail to connect, and then recover.
2203      */
2204     if (s->parameters.mode == MIG_MODE_CPR_TRANSFER) {
2205         migrate_hup_add(s, cpr_state_ioc(), (GSourceFunc)qmp_migrate_finish_cb,
2206                         QAPI_CLONE(MigrationAddress, addr));
2207 
2208     } else {
2209         qmp_migrate_finish(addr, resume_requested, errp);
2210     }
2211 
2212 out:
2213     if (local_err) {
2214         migration_connect_set_error(s, local_err);
2215         error_propagate(errp, local_err);
2216     }
2217 }
2218 
2219 static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
2220                                Error **errp)
2221 {
2222     MigrationState *s = migrate_get_current();
2223     Error *local_err = NULL;
2224 
2225     if (!resume_requested) {
2226         if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2227             return;
2228         }
2229     }
2230 
2231     if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
2232         SocketAddress *saddr = &addr->u.socket;
2233         if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
2234             saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
2235             saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
2236             socket_start_outgoing_migration(s, saddr, &local_err);
2237         } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
2238             fd_start_outgoing_migration(s, saddr->u.fd.str, &local_err);
2239         }
2240 #ifdef CONFIG_RDMA
2241     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
2242         rdma_start_outgoing_migration(s, &addr->u.rdma, &local_err);
2243 #endif
2244     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
2245         exec_start_outgoing_migration(s, addr->u.exec.args, &local_err);
2246     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
2247         file_start_outgoing_migration(s, &addr->u.file, &local_err);
2248     } else {
2249         error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
2250                    "a valid migration protocol");
2251         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2252                           MIGRATION_STATUS_FAILED);
2253     }
2254 
2255     if (local_err) {
2256         if (!resume_requested) {
2257             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2258         }
2259         migration_connect_set_error(s, local_err);
2260         error_propagate(errp, local_err);
2261         return;
2262     }
2263 }
2264 
2265 void qmp_migrate_cancel(Error **errp)
2266 {
2267     /*
2268      * After postcopy migration has started, the source machine is not
2269      * recoverable in case of a migration error. This also means the
2270      * cancel command cannot be used as cancel should allow the
2271      * machine to continue operation.
2272      */
2273     if (migration_in_postcopy()) {
2274         error_setg(errp, "Postcopy migration in progress, cannot cancel.");
2275         return;
2276     }
2277 
2278     migration_cancel();
2279 }
2280 
2281 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2282 {
2283     MigrationState *s = migrate_get_current();
2284     if (s->state != state) {
2285         error_setg(errp,  "Migration not in expected state: %s",
2286                    MigrationStatus_str(s->state));
2287         return;
2288     }
2289     qemu_sem_post(&s->pause_sem);
2290 }
2291 
2292 int migration_rp_wait(MigrationState *s)
2293 {
2294     /* If migration has failure already, ignore the wait */
2295     if (migrate_has_error(s)) {
2296         return -1;
2297     }
2298 
2299     qemu_sem_wait(&s->rp_state.rp_sem);
2300 
2301     /* After wait, double check that there's no failure */
2302     if (migrate_has_error(s)) {
2303         return -1;
2304     }
2305 
2306     return 0;
2307 }
2308 
2309 void migration_rp_kick(MigrationState *s)
2310 {
2311     qemu_sem_post(&s->rp_state.rp_sem);
2312 }
2313 
2314 static struct rp_cmd_args {
2315     ssize_t     len; /* -1 = variable */
2316     const char *name;
2317 } rp_cmd_args[] = {
2318     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2319     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2320     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2321     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2322     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2323     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2324     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2325     [MIG_RP_MSG_SWITCHOVER_ACK] = { .len =  0, .name = "SWITCHOVER_ACK" },
2326     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2327 };
2328 
2329 /*
2330  * Process a request for pages received on the return path,
2331  * We're allowed to send more than requested (e.g. to round to our page size)
2332  * and we don't need to send pages that have already been sent.
2333  */
2334 static void
2335 migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2336                             ram_addr_t start, size_t len, Error **errp)
2337 {
2338     long our_host_ps = qemu_real_host_page_size();
2339 
2340     trace_migrate_handle_rp_req_pages(rbname, start, len);
2341 
2342     /*
2343      * Since we currently insist on matching page sizes, just sanity check
2344      * we're being asked for whole host pages.
2345      */
2346     if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2347         !QEMU_IS_ALIGNED(len, our_host_ps)) {
2348         error_setg(errp, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2349                    RAM_ADDR_FMT " len: %zd", start, len);
2350         return;
2351     }
2352 
2353     ram_save_queue_pages(rbname, start, len, errp);
2354 }
2355 
2356 static bool migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name,
2357                                           Error **errp)
2358 {
2359     RAMBlock *block = qemu_ram_block_by_name(block_name);
2360 
2361     if (!block) {
2362         error_setg(errp, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2363                    block_name);
2364         return false;
2365     }
2366 
2367     /* Fetch the received bitmap and refresh the dirty bitmap */
2368     return ram_dirty_bitmap_reload(s, block, errp);
2369 }
2370 
2371 static bool migrate_handle_rp_resume_ack(MigrationState *s,
2372                                          uint32_t value, Error **errp)
2373 {
2374     trace_source_return_path_thread_resume_ack(value);
2375 
2376     if (value != MIGRATION_RESUME_ACK_VALUE) {
2377         error_setg(errp, "illegal resume_ack value %"PRIu32, value);
2378         return false;
2379     }
2380 
2381     /* Now both sides are active. */
2382     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2383                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2384 
2385     /* Notify send thread that time to continue send pages */
2386     migration_rp_kick(s);
2387 
2388     return true;
2389 }
2390 
2391 /*
2392  * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2393  * existed) in a safe way.
2394  */
2395 static void migration_release_dst_files(MigrationState *ms)
2396 {
2397     QEMUFile *file = NULL;
2398 
2399     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2400         /*
2401          * Reset the from_dst_file pointer first before releasing it, as we
2402          * can't block within lock section
2403          */
2404         file = ms->rp_state.from_dst_file;
2405         ms->rp_state.from_dst_file = NULL;
2406     }
2407 
2408     /*
2409      * Do the same to postcopy fast path socket too if there is.  No
2410      * locking needed because this qemufile should only be managed by
2411      * return path thread.
2412      */
2413     if (ms->postcopy_qemufile_src) {
2414         migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2415         qemu_file_shutdown(ms->postcopy_qemufile_src);
2416         qemu_fclose(ms->postcopy_qemufile_src);
2417         ms->postcopy_qemufile_src = NULL;
2418     }
2419 
2420     qemu_fclose(file);
2421 }
2422 
2423 /*
2424  * Handles messages sent on the return path towards the source VM
2425  *
2426  */
2427 static void *source_return_path_thread(void *opaque)
2428 {
2429     MigrationState *ms = opaque;
2430     QEMUFile *rp = ms->rp_state.from_dst_file;
2431     uint16_t header_len, header_type;
2432     uint8_t buf[512];
2433     uint32_t tmp32, sibling_error;
2434     ram_addr_t start = 0; /* =0 to silence warning */
2435     size_t  len = 0, expected_len;
2436     Error *err = NULL;
2437     int res;
2438 
2439     trace_source_return_path_thread_entry();
2440     rcu_register_thread();
2441 
2442     while (migration_is_running()) {
2443         trace_source_return_path_thread_loop_top();
2444 
2445         header_type = qemu_get_be16(rp);
2446         header_len = qemu_get_be16(rp);
2447 
2448         if (qemu_file_get_error(rp)) {
2449             qemu_file_get_error_obj(rp, &err);
2450             goto out;
2451         }
2452 
2453         if (header_type >= MIG_RP_MSG_MAX ||
2454             header_type == MIG_RP_MSG_INVALID) {
2455             error_setg(&err, "Received invalid message 0x%04x length 0x%04x",
2456                        header_type, header_len);
2457             goto out;
2458         }
2459 
2460         if ((rp_cmd_args[header_type].len != -1 &&
2461             header_len != rp_cmd_args[header_type].len) ||
2462             header_len > sizeof(buf)) {
2463             error_setg(&err, "Received '%s' message (0x%04x) with"
2464                        "incorrect length %d expecting %zu",
2465                        rp_cmd_args[header_type].name, header_type, header_len,
2466                        (size_t)rp_cmd_args[header_type].len);
2467             goto out;
2468         }
2469 
2470         /* We know we've got a valid header by this point */
2471         res = qemu_get_buffer(rp, buf, header_len);
2472         if (res != header_len) {
2473             error_setg(&err, "Failed reading data for message 0x%04x"
2474                        " read %d expected %d",
2475                        header_type, res, header_len);
2476             goto out;
2477         }
2478 
2479         /* OK, we have the message and the data */
2480         switch (header_type) {
2481         case MIG_RP_MSG_SHUT:
2482             sibling_error = ldl_be_p(buf);
2483             trace_source_return_path_thread_shut(sibling_error);
2484             if (sibling_error) {
2485                 error_setg(&err, "Sibling indicated error %d", sibling_error);
2486             }
2487             /*
2488              * We'll let the main thread deal with closing the RP
2489              * we could do a shutdown(2) on it, but we're the only user
2490              * anyway, so there's nothing gained.
2491              */
2492             goto out;
2493 
2494         case MIG_RP_MSG_PONG:
2495             tmp32 = ldl_be_p(buf);
2496             trace_source_return_path_thread_pong(tmp32);
2497             qemu_sem_post(&ms->rp_state.rp_pong_acks);
2498             break;
2499 
2500         case MIG_RP_MSG_REQ_PAGES:
2501             start = ldq_be_p(buf);
2502             len = ldl_be_p(buf + 8);
2503             migrate_handle_rp_req_pages(ms, NULL, start, len, &err);
2504             if (err) {
2505                 goto out;
2506             }
2507             break;
2508 
2509         case MIG_RP_MSG_REQ_PAGES_ID:
2510             expected_len = 12 + 1; /* header + termination */
2511 
2512             if (header_len >= expected_len) {
2513                 start = ldq_be_p(buf);
2514                 len = ldl_be_p(buf + 8);
2515                 /* Now we expect an idstr */
2516                 tmp32 = buf[12]; /* Length of the following idstr */
2517                 buf[13 + tmp32] = '\0';
2518                 expected_len += tmp32;
2519             }
2520             if (header_len != expected_len) {
2521                 error_setg(&err, "Req_Page_id with length %d expecting %zd",
2522                            header_len, expected_len);
2523                 goto out;
2524             }
2525             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len,
2526                                         &err);
2527             if (err) {
2528                 goto out;
2529             }
2530             break;
2531 
2532         case MIG_RP_MSG_RECV_BITMAP:
2533             if (header_len < 1) {
2534                 error_setg(&err, "MIG_RP_MSG_RECV_BITMAP missing block name");
2535                 goto out;
2536             }
2537             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2538             buf[buf[0] + 1] = '\0';
2539             if (!migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1), &err)) {
2540                 goto out;
2541             }
2542             break;
2543 
2544         case MIG_RP_MSG_RESUME_ACK:
2545             tmp32 = ldl_be_p(buf);
2546             if (!migrate_handle_rp_resume_ack(ms, tmp32, &err)) {
2547                 goto out;
2548             }
2549             break;
2550 
2551         case MIG_RP_MSG_SWITCHOVER_ACK:
2552             ms->switchover_acked = true;
2553             trace_source_return_path_thread_switchover_acked();
2554             break;
2555 
2556         default:
2557             break;
2558         }
2559     }
2560 
2561 out:
2562     if (err) {
2563         migrate_set_error(ms, err);
2564         error_free(err);
2565         trace_source_return_path_thread_bad_end();
2566     }
2567 
2568     if (ms->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2569         /*
2570          * this will be extremely unlikely: that we got yet another network
2571          * issue during recovering of the 1st network failure.. during this
2572          * period the main migration thread can be waiting on rp_sem for
2573          * this thread to sync with the other side.
2574          *
2575          * When this happens, explicitly kick the migration thread out of
2576          * RECOVER stage and back to PAUSED, so the admin can try
2577          * everything again.
2578          */
2579         migration_rp_kick(ms);
2580     }
2581 
2582     trace_source_return_path_thread_end();
2583     rcu_unregister_thread();
2584 
2585     return NULL;
2586 }
2587 
2588 static int open_return_path_on_source(MigrationState *ms)
2589 {
2590     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2591     if (!ms->rp_state.from_dst_file) {
2592         return -1;
2593     }
2594 
2595     trace_open_return_path_on_source();
2596 
2597     qemu_thread_create(&ms->rp_state.rp_thread, MIGRATION_THREAD_SRC_RETURN,
2598                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2599     ms->rp_state.rp_thread_created = true;
2600 
2601     trace_open_return_path_on_source_continue();
2602 
2603     return 0;
2604 }
2605 
2606 /* Return true if error detected, or false otherwise */
2607 static bool close_return_path_on_source(MigrationState *ms)
2608 {
2609     if (!ms->rp_state.rp_thread_created) {
2610         return false;
2611     }
2612 
2613     trace_migration_return_path_end_before();
2614 
2615     /*
2616      * If this is a normal exit then the destination will send a SHUT
2617      * and the rp_thread will exit, however if there's an error we
2618      * need to cause it to exit. shutdown(2), if we have it, will
2619      * cause it to unblock if it's stuck waiting for the destination.
2620      */
2621     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2622         if (migrate_has_error(ms) && ms->rp_state.from_dst_file) {
2623             qemu_file_shutdown(ms->rp_state.from_dst_file);
2624         }
2625     }
2626 
2627     qemu_thread_join(&ms->rp_state.rp_thread);
2628     ms->rp_state.rp_thread_created = false;
2629     migration_release_dst_files(ms);
2630     trace_migration_return_path_end_after();
2631 
2632     /* Return path will persist the error in MigrationState when quit */
2633     return migrate_has_error(ms);
2634 }
2635 
2636 static inline void
2637 migration_wait_main_channel(MigrationState *ms)
2638 {
2639     /* Wait until one PONG message received */
2640     qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2641 }
2642 
2643 /*
2644  * Switch from normal iteration to postcopy
2645  * Returns non-0 on error
2646  */
2647 static int postcopy_start(MigrationState *ms, Error **errp)
2648 {
2649     int ret;
2650     QIOChannelBuffer *bioc;
2651     QEMUFile *fb;
2652 
2653     /*
2654      * Now we're 100% sure to switch to postcopy, so JSON writer won't be
2655      * useful anymore.  Free the resources early if it is there.  Clearing
2656      * the vmdesc also means any follow up vmstate_save()s will start to
2657      * skip all JSON operations, which can shrink postcopy downtime.
2658      */
2659     migration_cleanup_json_writer(ms);
2660 
2661     if (migrate_postcopy_preempt()) {
2662         migration_wait_main_channel(ms);
2663         if (postcopy_preempt_establish_channel(ms)) {
2664             if (ms->state != MIGRATION_STATUS_CANCELLING) {
2665                 migrate_set_state(&ms->state, ms->state,
2666                                   MIGRATION_STATUS_FAILED);
2667             }
2668             error_setg(errp, "%s: Failed to establish preempt channel",
2669                        __func__);
2670             return -1;
2671         }
2672     }
2673 
2674     trace_postcopy_start();
2675     bql_lock();
2676     trace_postcopy_start_set_run();
2677 
2678     ret = migration_stop_vm(ms, RUN_STATE_FINISH_MIGRATE);
2679     if (ret < 0) {
2680         error_setg_errno(errp, -ret, "%s: Failed to stop the VM", __func__);
2681         goto fail;
2682     }
2683 
2684     if (!migration_switchover_start(ms, errp)) {
2685         goto fail;
2686     }
2687 
2688     /*
2689      * Cause any non-postcopiable, but iterative devices to
2690      * send out their final data.
2691      */
2692     ret = qemu_savevm_state_complete_precopy_iterable(ms->to_dst_file, true);
2693     if (ret) {
2694         error_setg(errp, "Postcopy save non-postcopiable iterables failed");
2695         goto fail;
2696     }
2697 
2698     /*
2699      * in Finish migrate and with the io-lock held everything should
2700      * be quiet, but we've potentially still got dirty pages and we
2701      * need to tell the destination to throw any pages it's already received
2702      * that are dirty
2703      */
2704     if (migrate_postcopy_ram()) {
2705         ram_postcopy_send_discard_bitmap(ms);
2706     }
2707 
2708     if (migrate_postcopy_ram()) {
2709         /* Ping just for debugging, helps line traces up */
2710         qemu_savevm_send_ping(ms->to_dst_file, 2);
2711     }
2712 
2713     /*
2714      * While loading the device state we may trigger page transfer
2715      * requests and the fd must be free to process those, and thus
2716      * the destination must read the whole device state off the fd before
2717      * it starts processing it.  Unfortunately the ad-hoc migration format
2718      * doesn't allow the destination to know the size to read without fully
2719      * parsing it through each devices load-state code (especially the open
2720      * coded devices that use get/put).
2721      * So we wrap the device state up in a package with a length at the start;
2722      * to do this we use a qemu_buf to hold the whole of the device state.
2723      */
2724     bioc = qio_channel_buffer_new(4096);
2725     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2726     fb = qemu_file_new_output(QIO_CHANNEL(bioc));
2727     object_unref(OBJECT(bioc));
2728 
2729     /*
2730      * Make sure the receiver can get incoming pages before we send the rest
2731      * of the state
2732      */
2733     qemu_savevm_send_postcopy_listen(fb);
2734 
2735     ret = qemu_savevm_state_complete_precopy_non_iterable(fb, true);
2736     if (ret) {
2737         error_setg(errp, "Postcopy save non-iterable device states failed");
2738         goto fail_closefb;
2739     }
2740 
2741     if (migrate_postcopy_ram()) {
2742         qemu_savevm_send_ping(fb, 3);
2743     }
2744 
2745     qemu_savevm_send_postcopy_run(fb);
2746 
2747     /* <><> end of stuff going into the package */
2748 
2749     /* Last point of recovery; as soon as we send the package the destination
2750      * can open devices and potentially start running.
2751      * Lets just check again we've not got any errors.
2752      */
2753     ret = qemu_file_get_error(ms->to_dst_file);
2754     if (ret) {
2755         error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
2756         goto fail_closefb;
2757     }
2758 
2759     /* Now send that blob */
2760     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2761         error_setg(errp, "%s: Failed to send packaged data", __func__);
2762         goto fail_closefb;
2763     }
2764     qemu_fclose(fb);
2765 
2766     /* Send a notify to give a chance for anything that needs to happen
2767      * at the transition to postcopy and after the device state; in particular
2768      * spice needs to trigger a transition now
2769      */
2770     migration_call_notifiers(ms, MIG_EVENT_PRECOPY_DONE, NULL);
2771 
2772     migration_downtime_end(ms);
2773 
2774     if (migrate_postcopy_ram()) {
2775         /*
2776          * Although this ping is just for debug, it could potentially be
2777          * used for getting a better measurement of downtime at the source.
2778          */
2779         qemu_savevm_send_ping(ms->to_dst_file, 4);
2780     }
2781 
2782     if (migrate_release_ram()) {
2783         ram_postcopy_migrated_memory_release(ms);
2784     }
2785 
2786     ret = qemu_file_get_error(ms->to_dst_file);
2787     if (ret) {
2788         error_setg_errno(errp, -ret, "postcopy_start: Migration stream error");
2789         goto fail;
2790     }
2791     trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2792 
2793     /*
2794      * Now postcopy officially started, switch to postcopy bandwidth that
2795      * user specified.
2796      */
2797     migration_rate_set(migrate_max_postcopy_bandwidth());
2798 
2799     /* Now, switchover looks all fine, switching to postcopy-active */
2800     migrate_set_state(&ms->state, MIGRATION_STATUS_DEVICE,
2801                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2802 
2803     bql_unlock();
2804 
2805     return ret;
2806 
2807 fail_closefb:
2808     qemu_fclose(fb);
2809 fail:
2810     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2811                           MIGRATION_STATUS_FAILED);
2812     migration_block_activate(NULL);
2813     migration_call_notifiers(ms, MIG_EVENT_PRECOPY_FAILED, NULL);
2814     bql_unlock();
2815     return -1;
2816 }
2817 
2818 /**
2819  * @migration_switchover_prepare: Start VM switchover procedure
2820  *
2821  * @s: The migration state object pointer
2822  *
2823  * Prepares for the switchover, depending on "pause-before-switchover"
2824  * capability.
2825  *
2826  * If cap set, state machine goes like:
2827  *   [postcopy-]active -> pre-switchover -> device
2828  *
2829  * If cap not set:
2830  *   [postcopy-]active -> device
2831  *
2832  * Returns: true on success, false on interruptions.
2833  */
2834 static bool migration_switchover_prepare(MigrationState *s)
2835 {
2836     /* Concurrent cancellation?  Quit */
2837     if (s->state == MIGRATION_STATUS_CANCELLING) {
2838         return false;
2839     }
2840 
2841     /*
2842      * No matter precopy or postcopy, since we still hold BQL it must not
2843      * change concurrently to CANCELLING, so it must be either ACTIVE or
2844      * POSTCOPY_ACTIVE.
2845      */
2846     assert(migration_is_active());
2847 
2848     /* If the pre stage not requested, directly switch to DEVICE */
2849     if (!migrate_pause_before_switchover()) {
2850         migrate_set_state(&s->state, s->state, MIGRATION_STATUS_DEVICE);
2851         return true;
2852     }
2853 
2854     /* Since leaving this state is not atomic with posting the semaphore
2855      * it's possible that someone could have issued multiple migrate_continue
2856      * and the semaphore is incorrectly positive at this point;
2857      * the docs say it's undefined to reinit a semaphore that's already
2858      * init'd, so use timedwait to eat up any existing posts.
2859      */
2860     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2861         /* This block intentionally left blank */
2862     }
2863 
2864     /* Update [POSTCOPY_]ACTIVE to PRE_SWITCHOVER */
2865     migrate_set_state(&s->state, s->state, MIGRATION_STATUS_PRE_SWITCHOVER);
2866     bql_unlock();
2867 
2868     qemu_sem_wait(&s->pause_sem);
2869 
2870     bql_lock();
2871     /*
2872      * After BQL released and retaken, the state can be CANCELLING if it
2873      * happend during sem_wait().. Only change the state if it's still
2874      * pre-switchover.
2875      */
2876     migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2877                       MIGRATION_STATUS_DEVICE);
2878 
2879     return s->state == MIGRATION_STATUS_DEVICE;
2880 }
2881 
2882 static bool migration_switchover_start(MigrationState *s, Error **errp)
2883 {
2884     ERRP_GUARD();
2885 
2886     if (!migration_switchover_prepare(s)) {
2887         error_setg(errp, "Switchover is interrupted");
2888         return false;
2889     }
2890 
2891     /* Inactivate disks except in COLO */
2892     if (!migrate_colo()) {
2893         /*
2894          * Inactivate before sending QEMU_VM_EOF so that the
2895          * bdrv_activate_all() on the other end won't fail.
2896          */
2897         if (!migration_block_inactivate()) {
2898             error_setg(errp, "Block inactivate failed during switchover");
2899             return false;
2900         }
2901     }
2902 
2903     migration_rate_set(RATE_LIMIT_DISABLED);
2904 
2905     precopy_notify_complete();
2906 
2907     qemu_savevm_maybe_send_switchover_start(s->to_dst_file);
2908 
2909     return true;
2910 }
2911 
2912 static int migration_completion_precopy(MigrationState *s)
2913 {
2914     int ret;
2915 
2916     bql_lock();
2917 
2918     if (!migrate_mode_is_cpr(s)) {
2919         ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
2920         if (ret < 0) {
2921             goto out_unlock;
2922         }
2923     }
2924 
2925     if (!migration_switchover_start(s, NULL)) {
2926         ret = -EFAULT;
2927         goto out_unlock;
2928     }
2929 
2930     ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false);
2931 out_unlock:
2932     bql_unlock();
2933     return ret;
2934 }
2935 
2936 static void migration_completion_postcopy(MigrationState *s)
2937 {
2938     trace_migration_completion_postcopy_end();
2939 
2940     bql_lock();
2941     qemu_savevm_state_complete_postcopy(s->to_dst_file);
2942     bql_unlock();
2943 
2944     /*
2945      * Shutdown the postcopy fast path thread.  This is only needed when dest
2946      * QEMU binary is old (7.1/7.2).  QEMU 8.0+ doesn't need this.
2947      */
2948     if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2949         postcopy_preempt_shutdown_file(s);
2950     }
2951 
2952     trace_migration_completion_postcopy_end_after_complete();
2953 }
2954 
2955 /**
2956  * migration_completion: Used by migration_thread when there's not much left.
2957  *   The caller 'breaks' the loop when this returns.
2958  *
2959  * @s: Current migration state
2960  */
2961 static void migration_completion(MigrationState *s)
2962 {
2963     int ret = 0;
2964     Error *local_err = NULL;
2965 
2966     if (s->state == MIGRATION_STATUS_ACTIVE) {
2967         ret = migration_completion_precopy(s);
2968     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2969         migration_completion_postcopy(s);
2970     } else {
2971         ret = -1;
2972     }
2973 
2974     if (ret < 0) {
2975         goto fail;
2976     }
2977 
2978     if (close_return_path_on_source(s)) {
2979         goto fail;
2980     }
2981 
2982     if (qemu_file_get_error(s->to_dst_file)) {
2983         trace_migration_completion_file_err();
2984         goto fail;
2985     }
2986 
2987     if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
2988         /* COLO does not support postcopy */
2989         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
2990                           MIGRATION_STATUS_COLO);
2991     } else {
2992         migration_completion_end(s);
2993     }
2994 
2995     return;
2996 
2997 fail:
2998     if (qemu_file_get_error_obj(s->to_dst_file, &local_err)) {
2999         migrate_set_error(s, local_err);
3000         error_free(local_err);
3001     } else if (ret) {
3002         error_setg_errno(&local_err, -ret, "Error in migration completion");
3003         migrate_set_error(s, local_err);
3004         error_free(local_err);
3005     }
3006 
3007     if (s->state != MIGRATION_STATUS_CANCELLING) {
3008         migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3009     }
3010 }
3011 
3012 /**
3013  * bg_migration_completion: Used by bg_migration_thread when after all the
3014  *   RAM has been saved. The caller 'breaks' the loop when this returns.
3015  *
3016  * @s: Current migration state
3017  */
3018 static void bg_migration_completion(MigrationState *s)
3019 {
3020     int current_active_state = s->state;
3021 
3022     if (s->state == MIGRATION_STATUS_ACTIVE) {
3023         /*
3024          * By this moment we have RAM content saved into the migration stream.
3025          * The next step is to flush the non-RAM content (device state)
3026          * right after the ram content. The device state has been stored into
3027          * the temporary buffer before RAM saving started.
3028          */
3029         qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3030         qemu_fflush(s->to_dst_file);
3031     } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3032         return;
3033     }
3034 
3035     if (qemu_file_get_error(s->to_dst_file)) {
3036         trace_migration_completion_file_err();
3037         goto fail;
3038     }
3039 
3040     migration_completion_end(s);
3041     return;
3042 
3043 fail:
3044     migrate_set_state(&s->state, current_active_state,
3045                       MIGRATION_STATUS_FAILED);
3046 }
3047 
3048 typedef enum MigThrError {
3049     /* No error detected */
3050     MIG_THR_ERR_NONE = 0,
3051     /* Detected error, but resumed successfully */
3052     MIG_THR_ERR_RECOVERED = 1,
3053     /* Detected fatal error, need to exit */
3054     MIG_THR_ERR_FATAL = 2,
3055 } MigThrError;
3056 
3057 static int postcopy_resume_handshake(MigrationState *s)
3058 {
3059     qemu_savevm_send_postcopy_resume(s->to_dst_file);
3060 
3061     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3062         if (migration_rp_wait(s)) {
3063             return -1;
3064         }
3065     }
3066 
3067     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3068         return 0;
3069     }
3070 
3071     return -1;
3072 }
3073 
3074 /* Return zero if success, or <0 for error */
3075 static int postcopy_do_resume(MigrationState *s)
3076 {
3077     int ret;
3078 
3079     /*
3080      * Call all the resume_prepare() hooks, so that modules can be
3081      * ready for the migration resume.
3082      */
3083     ret = qemu_savevm_state_resume_prepare(s);
3084     if (ret) {
3085         error_report("%s: resume_prepare() failure detected: %d",
3086                      __func__, ret);
3087         return ret;
3088     }
3089 
3090     /*
3091      * If preempt is enabled, re-establish the preempt channel.  Note that
3092      * we do it after resume prepare to make sure the main channel will be
3093      * created before the preempt channel.  E.g. with weak network, the
3094      * dest QEMU may get messed up with the preempt and main channels on
3095      * the order of connection setup.  This guarantees the correct order.
3096      */
3097     ret = postcopy_preempt_establish_channel(s);
3098     if (ret) {
3099         error_report("%s: postcopy_preempt_establish_channel(): %d",
3100                      __func__, ret);
3101         return ret;
3102     }
3103 
3104     /*
3105      * Last handshake with destination on the resume (destination will
3106      * switch to postcopy-active afterwards)
3107      */
3108     ret = postcopy_resume_handshake(s);
3109     if (ret) {
3110         error_report("%s: handshake failed: %d", __func__, ret);
3111         return ret;
3112     }
3113 
3114     return 0;
3115 }
3116 
3117 /*
3118  * We don't return until we are in a safe state to continue current
3119  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
3120  * MIG_THR_ERR_FATAL if unrecovery failure happened.
3121  */
3122 static MigThrError postcopy_pause(MigrationState *s)
3123 {
3124     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3125 
3126     while (true) {
3127         QEMUFile *file;
3128 
3129         /*
3130          * We're already pausing, so ignore any errors on the return
3131          * path and just wait for the thread to finish. It will be
3132          * re-created when we resume.
3133          */
3134         close_return_path_on_source(s);
3135 
3136         /*
3137          * Current channel is possibly broken. Release it.  Note that this is
3138          * guaranteed even without lock because to_dst_file should only be
3139          * modified by the migration thread.  That also guarantees that the
3140          * unregister of yank is safe too without the lock.  It should be safe
3141          * even to be within the qemu_file_lock, but we didn't do that to avoid
3142          * taking more mutex (yank_lock) within qemu_file_lock.  TL;DR: we make
3143          * the qemu_file_lock critical section as small as possible.
3144          */
3145         assert(s->to_dst_file);
3146         migration_ioc_unregister_yank_from_file(s->to_dst_file);
3147         qemu_mutex_lock(&s->qemu_file_lock);
3148         file = s->to_dst_file;
3149         s->to_dst_file = NULL;
3150         qemu_mutex_unlock(&s->qemu_file_lock);
3151 
3152         qemu_file_shutdown(file);
3153         qemu_fclose(file);
3154 
3155         migrate_set_state(&s->state, s->state,
3156                           MIGRATION_STATUS_POSTCOPY_PAUSED);
3157 
3158         error_report("Detected IO failure for postcopy. "
3159                      "Migration paused.");
3160 
3161         /*
3162          * We wait until things fixed up. Then someone will setup the
3163          * status back for us.
3164          */
3165         do {
3166             qemu_sem_wait(&s->postcopy_pause_sem);
3167         } while (postcopy_is_paused(s->state));
3168 
3169         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3170             /* Woken up by a recover procedure. Give it a shot */
3171 
3172             /* Do the resume logic */
3173             if (postcopy_do_resume(s) == 0) {
3174                 /* Let's continue! */
3175                 trace_postcopy_pause_continued();
3176                 return MIG_THR_ERR_RECOVERED;
3177             } else {
3178                 /*
3179                  * Something wrong happened during the recovery, let's
3180                  * pause again. Pause is always better than throwing
3181                  * data away.
3182                  */
3183                 continue;
3184             }
3185         } else {
3186             /* This is not right... Time to quit. */
3187             return MIG_THR_ERR_FATAL;
3188         }
3189     }
3190 }
3191 
3192 void migration_file_set_error(int ret, Error *err)
3193 {
3194     MigrationState *s = current_migration;
3195 
3196     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
3197         if (s->to_dst_file) {
3198             qemu_file_set_error_obj(s->to_dst_file, ret, err);
3199         } else if (err) {
3200             error_report_err(err);
3201         }
3202     }
3203 }
3204 
3205 static MigThrError migration_detect_error(MigrationState *s)
3206 {
3207     int ret;
3208     int state = s->state;
3209     Error *local_error = NULL;
3210 
3211     if (state == MIGRATION_STATUS_CANCELLING ||
3212         state == MIGRATION_STATUS_CANCELLED) {
3213         /* End the migration, but don't set the state to failed */
3214         return MIG_THR_ERR_FATAL;
3215     }
3216 
3217     /*
3218      * Try to detect any file errors.  Note that postcopy_qemufile_src will
3219      * be NULL when postcopy preempt is not enabled.
3220      */
3221     ret = qemu_file_get_error_obj_any(s->to_dst_file,
3222                                       s->postcopy_qemufile_src,
3223                                       &local_error);
3224     if (!ret) {
3225         /* Everything is fine */
3226         assert(!local_error);
3227         return MIG_THR_ERR_NONE;
3228     }
3229 
3230     if (local_error) {
3231         migrate_set_error(s, local_error);
3232         error_free(local_error);
3233     }
3234 
3235     if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3236         /*
3237          * For postcopy, we allow the network to be down for a
3238          * while. After that, it can be continued by a
3239          * recovery phase.
3240          */
3241         return postcopy_pause(s);
3242     } else {
3243         /*
3244          * For precopy (or postcopy with error outside IO), we fail
3245          * with no time.
3246          */
3247         migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3248         trace_migration_thread_file_err();
3249 
3250         /* Time to stop the migration, now. */
3251         return MIG_THR_ERR_FATAL;
3252     }
3253 }
3254 
3255 static void migration_completion_end(MigrationState *s)
3256 {
3257     uint64_t bytes = migration_transferred_bytes();
3258     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3259     int64_t transfer_time;
3260 
3261     /*
3262      * Take the BQL here so that query-migrate on the QMP thread sees:
3263      * - atomic update of s->total_time and s->mbps;
3264      * - correct ordering of s->mbps update vs. s->state;
3265      */
3266     bql_lock();
3267     migration_downtime_end(s);
3268     s->total_time = end_time - s->start_time;
3269     transfer_time = s->total_time - s->setup_time;
3270     if (transfer_time) {
3271         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3272     }
3273 
3274     migrate_set_state(&s->state, s->state,
3275                       MIGRATION_STATUS_COMPLETED);
3276     bql_unlock();
3277 }
3278 
3279 static void update_iteration_initial_status(MigrationState *s)
3280 {
3281     /*
3282      * Update these three fields at the same time to avoid mismatch info lead
3283      * wrong speed calculation.
3284      */
3285     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3286     s->iteration_initial_bytes = migration_transferred_bytes();
3287     s->iteration_initial_pages = ram_get_total_transferred_pages();
3288 }
3289 
3290 static void migration_update_counters(MigrationState *s,
3291                                       int64_t current_time)
3292 {
3293     uint64_t transferred, transferred_pages, time_spent;
3294     uint64_t current_bytes; /* bytes transferred since the beginning */
3295     uint64_t switchover_bw;
3296     /* Expected bandwidth when switching over to destination QEMU */
3297     double expected_bw_per_ms;
3298     double bandwidth;
3299 
3300     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3301         return;
3302     }
3303 
3304     switchover_bw = migrate_avail_switchover_bandwidth();
3305     current_bytes = migration_transferred_bytes();
3306     transferred = current_bytes - s->iteration_initial_bytes;
3307     time_spent = current_time - s->iteration_start_time;
3308     bandwidth = (double)transferred / time_spent;
3309 
3310     if (switchover_bw) {
3311         /*
3312          * If the user specified a switchover bandwidth, let's trust the
3313          * user so that can be more accurate than what we estimated.
3314          */
3315         expected_bw_per_ms = switchover_bw / 1000;
3316     } else {
3317         /* If the user doesn't specify bandwidth, we use the estimated */
3318         expected_bw_per_ms = bandwidth;
3319     }
3320 
3321     s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
3322 
3323     s->mbps = (((double) transferred * 8.0) /
3324                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3325 
3326     transferred_pages = ram_get_total_transferred_pages() -
3327                             s->iteration_initial_pages;
3328     s->pages_per_second = (double) transferred_pages /
3329                              (((double) time_spent / 1000.0));
3330 
3331     /*
3332      * if we haven't sent anything, we don't want to
3333      * recalculate. 10000 is a small enough number for our purposes
3334      */
3335     if (stat64_get(&mig_stats.dirty_pages_rate) &&
3336         transferred > 10000) {
3337         s->expected_downtime =
3338             stat64_get(&mig_stats.dirty_bytes_last_sync) / expected_bw_per_ms;
3339     }
3340 
3341     migration_rate_reset();
3342 
3343     update_iteration_initial_status(s);
3344 
3345     trace_migrate_transferred(transferred, time_spent,
3346                               /* Both in unit bytes/ms */
3347                               bandwidth, switchover_bw / 1000,
3348                               s->threshold_size);
3349 }
3350 
3351 static bool migration_can_switchover(MigrationState *s)
3352 {
3353     if (!migrate_switchover_ack()) {
3354         return true;
3355     }
3356 
3357     /* No reason to wait for switchover ACK if VM is stopped */
3358     if (!runstate_is_running()) {
3359         return true;
3360     }
3361 
3362     return s->switchover_acked;
3363 }
3364 
3365 /* Migration thread iteration status */
3366 typedef enum {
3367     MIG_ITERATE_RESUME,         /* Resume current iteration */
3368     MIG_ITERATE_SKIP,           /* Skip current iteration */
3369     MIG_ITERATE_BREAK,          /* Break the loop */
3370 } MigIterateState;
3371 
3372 /*
3373  * Return true if continue to the next iteration directly, false
3374  * otherwise.
3375  */
3376 static MigIterateState migration_iteration_run(MigrationState *s)
3377 {
3378     uint64_t must_precopy, can_postcopy, pending_size;
3379     Error *local_err = NULL;
3380     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3381     bool can_switchover = migration_can_switchover(s);
3382 
3383     qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
3384     pending_size = must_precopy + can_postcopy;
3385     trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
3386 
3387     if (pending_size < s->threshold_size) {
3388         qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
3389         pending_size = must_precopy + can_postcopy;
3390         trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
3391     }
3392 
3393     if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
3394         trace_migration_thread_low_pending(pending_size);
3395         migration_completion(s);
3396         return MIG_ITERATE_BREAK;
3397     }
3398 
3399     /* Still a significant amount to transfer */
3400     if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
3401         qatomic_read(&s->start_postcopy)) {
3402         if (postcopy_start(s, &local_err)) {
3403             migrate_set_error(s, local_err);
3404             error_report_err(local_err);
3405         }
3406         return MIG_ITERATE_SKIP;
3407     }
3408 
3409     /* Just another iteration step */
3410     qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3411     return MIG_ITERATE_RESUME;
3412 }
3413 
3414 static void migration_iteration_finish(MigrationState *s)
3415 {
3416     bql_lock();
3417 
3418     /*
3419      * If we enabled cpu throttling for auto-converge, turn it off.
3420      * Stopping CPU throttle should be serialized by BQL to avoid
3421      * racing for the throttle_dirty_sync_timer.
3422      */
3423     if (migrate_auto_converge()) {
3424         cpu_throttle_stop();
3425     }
3426 
3427     switch (s->state) {
3428     case MIGRATION_STATUS_COMPLETED:
3429         runstate_set(RUN_STATE_POSTMIGRATE);
3430         break;
3431     case MIGRATION_STATUS_COLO:
3432         assert(migrate_colo());
3433         migrate_start_colo_process(s);
3434         s->vm_old_state = RUN_STATE_RUNNING;
3435         /* Fallthrough */
3436     case MIGRATION_STATUS_FAILED:
3437     case MIGRATION_STATUS_CANCELLED:
3438     case MIGRATION_STATUS_CANCELLING:
3439         /*
3440          * Re-activate the block drives if they're inactivated.  Note, COLO
3441          * shouldn't use block_active at all, so it should be no-op there.
3442          */
3443         migration_block_activate(NULL);
3444         if (runstate_is_live(s->vm_old_state)) {
3445             if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3446                 vm_start();
3447             }
3448         } else {
3449             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3450                 runstate_set(s->vm_old_state);
3451             }
3452         }
3453         break;
3454 
3455     default:
3456         /* Should not reach here, but if so, forgive the VM. */
3457         error_report("%s: Unknown ending state %d", __func__, s->state);
3458         break;
3459     }
3460 
3461     migration_bh_schedule(migration_cleanup_bh, s);
3462     bql_unlock();
3463 }
3464 
3465 static void bg_migration_iteration_finish(MigrationState *s)
3466 {
3467     /*
3468      * Stop tracking RAM writes - un-protect memory, un-register UFFD
3469      * memory ranges, flush kernel wait queues and wake up threads
3470      * waiting for write fault to be resolved.
3471      */
3472     ram_write_tracking_stop();
3473 
3474     bql_lock();
3475     switch (s->state) {
3476     case MIGRATION_STATUS_COMPLETED:
3477     case MIGRATION_STATUS_ACTIVE:
3478     case MIGRATION_STATUS_FAILED:
3479     case MIGRATION_STATUS_CANCELLED:
3480     case MIGRATION_STATUS_CANCELLING:
3481         break;
3482 
3483     default:
3484         /* Should not reach here, but if so, forgive the VM. */
3485         error_report("%s: Unknown ending state %d", __func__, s->state);
3486         break;
3487     }
3488 
3489     migration_bh_schedule(migration_cleanup_bh, s);
3490     bql_unlock();
3491 }
3492 
3493 /*
3494  * Return true if continue to the next iteration directly, false
3495  * otherwise.
3496  */
3497 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3498 {
3499     int res;
3500 
3501     res = qemu_savevm_state_iterate(s->to_dst_file, false);
3502     if (res > 0) {
3503         bg_migration_completion(s);
3504         return MIG_ITERATE_BREAK;
3505     }
3506 
3507     return MIG_ITERATE_RESUME;
3508 }
3509 
3510 void migration_make_urgent_request(void)
3511 {
3512     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3513 }
3514 
3515 void migration_consume_urgent_request(void)
3516 {
3517     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3518 }
3519 
3520 /* Returns true if the rate limiting was broken by an urgent request */
3521 bool migration_rate_limit(void)
3522 {
3523     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3524     MigrationState *s = migrate_get_current();
3525 
3526     bool urgent = false;
3527     migration_update_counters(s, now);
3528     if (migration_rate_exceeded(s->to_dst_file)) {
3529 
3530         if (qemu_file_get_error(s->to_dst_file)) {
3531             return false;
3532         }
3533         /*
3534          * Wait for a delay to do rate limiting OR
3535          * something urgent to post the semaphore.
3536          */
3537         int ms = s->iteration_start_time + BUFFER_DELAY - now;
3538         trace_migration_rate_limit_pre(ms);
3539         if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3540             /*
3541              * We were woken by one or more urgent things but
3542              * the timedwait will have consumed one of them.
3543              * The service routine for the urgent wake will dec
3544              * the semaphore itself for each item it consumes,
3545              * so add this one we just eat back.
3546              */
3547             qemu_sem_post(&s->rate_limit_sem);
3548             urgent = true;
3549         }
3550         trace_migration_rate_limit_post(urgent);
3551     }
3552     return urgent;
3553 }
3554 
3555 /*
3556  * if failover devices are present, wait they are completely
3557  * unplugged
3558  */
3559 
3560 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3561                                     int new_state)
3562 {
3563     if (qemu_savevm_state_guest_unplug_pending()) {
3564         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3565 
3566         while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3567                qemu_savevm_state_guest_unplug_pending()) {
3568             qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3569         }
3570         if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3571             int timeout = 120; /* 30 seconds */
3572             /*
3573              * migration has been canceled
3574              * but as we have started an unplug we must wait the end
3575              * to be able to plug back the card
3576              */
3577             while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3578                 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3579             }
3580             if (qemu_savevm_state_guest_unplug_pending() &&
3581                 !qtest_enabled()) {
3582                 warn_report("migration: partially unplugged device on "
3583                             "failure");
3584             }
3585         }
3586 
3587         migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3588     } else {
3589         migrate_set_state(&s->state, old_state, new_state);
3590     }
3591 }
3592 
3593 /*
3594  * Master migration thread on the source VM.
3595  * It drives the migration and pumps the data down the outgoing channel.
3596  */
3597 static void *migration_thread(void *opaque)
3598 {
3599     MigrationState *s = opaque;
3600     MigrationThread *thread = NULL;
3601     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3602     MigThrError thr_error;
3603     bool urgent = false;
3604     Error *local_err = NULL;
3605     int ret;
3606 
3607     thread = migration_threads_add(MIGRATION_THREAD_SRC_MAIN,
3608                                    qemu_get_thread_id());
3609 
3610     rcu_register_thread();
3611 
3612     update_iteration_initial_status(s);
3613 
3614     if (!multifd_send_setup()) {
3615         goto out;
3616     }
3617 
3618     bql_lock();
3619     qemu_savevm_state_header(s->to_dst_file);
3620     bql_unlock();
3621 
3622     /*
3623      * If we opened the return path, we need to make sure dst has it
3624      * opened as well.
3625      */
3626     if (s->rp_state.rp_thread_created) {
3627         /* Now tell the dest that it should open its end so it can reply */
3628         qemu_savevm_send_open_return_path(s->to_dst_file);
3629 
3630         /* And do a ping that will make stuff easier to debug */
3631         qemu_savevm_send_ping(s->to_dst_file, 1);
3632     }
3633 
3634     if (migrate_postcopy()) {
3635         /*
3636          * Tell the destination that we *might* want to do postcopy later;
3637          * if the other end can't do postcopy it should fail now, nice and
3638          * early.
3639          */
3640         qemu_savevm_send_postcopy_advise(s->to_dst_file);
3641     }
3642 
3643     if (migrate_colo()) {
3644         /* Notify migration destination that we enable COLO */
3645         qemu_savevm_send_colo_enable(s->to_dst_file);
3646     }
3647 
3648     if (migrate_auto_converge()) {
3649         /* Start RAMBlock dirty bitmap sync timer */
3650         cpu_throttle_dirty_sync_timer(true);
3651     }
3652 
3653     bql_lock();
3654     ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
3655     bql_unlock();
3656 
3657     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3658                                MIGRATION_STATUS_ACTIVE);
3659 
3660     /*
3661      * Handle SETUP failures after waiting for virtio-net-failover
3662      * devices to unplug. This to preserve migration state transitions.
3663      */
3664     if (ret) {
3665         migrate_set_error(s, local_err);
3666         error_free(local_err);
3667         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3668                           MIGRATION_STATUS_FAILED);
3669         goto out;
3670     }
3671 
3672     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3673 
3674     trace_migration_thread_setup_complete();
3675 
3676     while (migration_is_active()) {
3677         if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
3678             MigIterateState iter_state = migration_iteration_run(s);
3679             if (iter_state == MIG_ITERATE_SKIP) {
3680                 continue;
3681             } else if (iter_state == MIG_ITERATE_BREAK) {
3682                 break;
3683             }
3684         }
3685 
3686         /*
3687          * Try to detect any kind of failures, and see whether we
3688          * should stop the migration now.
3689          */
3690         thr_error = migration_detect_error(s);
3691         if (thr_error == MIG_THR_ERR_FATAL) {
3692             /* Stop migration */
3693             break;
3694         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3695             /*
3696              * Just recovered from a e.g. network failure, reset all
3697              * the local variables. This is important to avoid
3698              * breaking transferred_bytes and bandwidth calculation
3699              */
3700             update_iteration_initial_status(s);
3701         }
3702 
3703         urgent = migration_rate_limit();
3704     }
3705 
3706 out:
3707     trace_migration_thread_after_loop();
3708     migration_iteration_finish(s);
3709     object_unref(OBJECT(s));
3710     rcu_unregister_thread();
3711     migration_threads_remove(thread);
3712     return NULL;
3713 }
3714 
3715 static void bg_migration_vm_start_bh(void *opaque)
3716 {
3717     MigrationState *s = opaque;
3718 
3719     vm_resume(s->vm_old_state);
3720     migration_downtime_end(s);
3721 }
3722 
3723 /**
3724  * Background snapshot thread, based on live migration code.
3725  * This is an alternative implementation of live migration mechanism
3726  * introduced specifically to support background snapshots.
3727  *
3728  * It takes advantage of userfault_fd write protection mechanism introduced
3729  * in v5.7 kernel. Compared to existing dirty page logging migration much
3730  * lesser stream traffic is produced resulting in smaller snapshot images,
3731  * simply cause of no page duplicates can get into the stream.
3732  *
3733  * Another key point is that generated vmstate stream reflects machine state
3734  * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3735  * mechanism, which effectively results in that saved snapshot is the state of VM
3736  * at the end of the process.
3737  */
3738 static void *bg_migration_thread(void *opaque)
3739 {
3740     MigrationState *s = opaque;
3741     int64_t setup_start;
3742     MigThrError thr_error;
3743     QEMUFile *fb;
3744     bool early_fail = true;
3745     Error *local_err = NULL;
3746     int ret;
3747 
3748     rcu_register_thread();
3749 
3750     migration_rate_set(RATE_LIMIT_DISABLED);
3751 
3752     setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3753     /*
3754      * We want to save vmstate for the moment when migration has been
3755      * initiated but also we want to save RAM content while VM is running.
3756      * The RAM content should appear first in the vmstate. So, we first
3757      * stash the non-RAM part of the vmstate to the temporary buffer,
3758      * then write RAM part of the vmstate to the migration stream
3759      * with vCPUs running and, finally, write stashed non-RAM part of
3760      * the vmstate from the buffer to the migration stream.
3761      */
3762     s->bioc = qio_channel_buffer_new(512 * 1024);
3763     qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
3764     fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
3765     object_unref(OBJECT(s->bioc));
3766 
3767     update_iteration_initial_status(s);
3768 
3769     /*
3770      * Prepare for tracking memory writes with UFFD-WP - populate
3771      * RAM pages before protecting.
3772      */
3773 #ifdef __linux__
3774     ram_write_tracking_prepare();
3775 #endif
3776 
3777     bql_lock();
3778     qemu_savevm_state_header(s->to_dst_file);
3779     ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
3780     bql_unlock();
3781 
3782     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3783                                MIGRATION_STATUS_ACTIVE);
3784 
3785     /*
3786      * Handle SETUP failures after waiting for virtio-net-failover
3787      * devices to unplug. This to preserve migration state transitions.
3788      */
3789     if (ret) {
3790         migrate_set_error(s, local_err);
3791         error_free(local_err);
3792         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3793                           MIGRATION_STATUS_FAILED);
3794         goto fail_setup;
3795     }
3796 
3797     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3798 
3799     trace_migration_thread_setup_complete();
3800 
3801     bql_lock();
3802 
3803     if (migration_stop_vm(s, RUN_STATE_PAUSED)) {
3804         goto fail;
3805     }
3806 
3807     if (qemu_savevm_state_complete_precopy_non_iterable(fb, false)) {
3808         goto fail;
3809     }
3810     /*
3811      * Since we are going to get non-iterable state data directly
3812      * from s->bioc->data, explicit flush is needed here.
3813      */
3814     qemu_fflush(fb);
3815 
3816     /* Now initialize UFFD context and start tracking RAM writes */
3817     if (ram_write_tracking_start()) {
3818         goto fail;
3819     }
3820     early_fail = false;
3821 
3822     /*
3823      * Start VM from BH handler to avoid write-fault lock here.
3824      * UFFD-WP protection for the whole RAM is already enabled so
3825      * calling VM state change notifiers from vm_start() would initiate
3826      * writes to virtio VQs memory which is in write-protected region.
3827      */
3828     migration_bh_schedule(bg_migration_vm_start_bh, s);
3829     bql_unlock();
3830 
3831     while (migration_is_active()) {
3832         MigIterateState iter_state = bg_migration_iteration_run(s);
3833         if (iter_state == MIG_ITERATE_SKIP) {
3834             continue;
3835         } else if (iter_state == MIG_ITERATE_BREAK) {
3836             break;
3837         }
3838 
3839         /*
3840          * Try to detect any kind of failures, and see whether we
3841          * should stop the migration now.
3842          */
3843         thr_error = migration_detect_error(s);
3844         if (thr_error == MIG_THR_ERR_FATAL) {
3845             /* Stop migration */
3846             break;
3847         }
3848 
3849         migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3850     }
3851 
3852     trace_migration_thread_after_loop();
3853 
3854 fail:
3855     if (early_fail) {
3856         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3857                 MIGRATION_STATUS_FAILED);
3858         bql_unlock();
3859     }
3860 
3861 fail_setup:
3862     bg_migration_iteration_finish(s);
3863 
3864     qemu_fclose(fb);
3865     object_unref(OBJECT(s));
3866     rcu_unregister_thread();
3867 
3868     return NULL;
3869 }
3870 
3871 void migration_connect(MigrationState *s, Error *error_in)
3872 {
3873     Error *local_err = NULL;
3874     uint64_t rate_limit;
3875     bool resume = (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
3876     int ret;
3877 
3878     /*
3879      * If there's a previous error, free it and prepare for another one.
3880      * Meanwhile if migration completes successfully, there won't have an error
3881      * dumped when calling migration_cleanup().
3882      */
3883     migrate_error_free(s);
3884 
3885     s->expected_downtime = migrate_downtime_limit();
3886     if (error_in) {
3887         migration_connect_set_error(s, error_in);
3888         if (resume) {
3889             /*
3890              * Don't do cleanup for resume if channel is invalid, but only dump
3891              * the error.  We wait for another channel connect from the user.
3892              * The error_report still gives HMP user a hint on what failed.
3893              * It's normally done in migration_cleanup(), but call it here
3894              * explicitly.
3895              */
3896             error_report_err(error_copy(s->error));
3897         } else {
3898             migration_cleanup(s);
3899         }
3900         return;
3901     }
3902 
3903     if (resume) {
3904         /* This is a resumed migration */
3905         rate_limit = migrate_max_postcopy_bandwidth();
3906     } else {
3907         /* This is a fresh new migration */
3908         rate_limit = migrate_max_bandwidth();
3909 
3910         /* Notify before starting migration thread */
3911         if (migration_call_notifiers(s, MIG_EVENT_PRECOPY_SETUP, &local_err)) {
3912             goto fail;
3913         }
3914     }
3915 
3916     migration_rate_set(rate_limit);
3917     qemu_file_set_blocking(s->to_dst_file, true);
3918 
3919     /*
3920      * Open the return path. For postcopy, it is used exclusively. For
3921      * precopy, only if user specified "return-path" capability would
3922      * QEMU uses the return path.
3923      */
3924     if (migrate_postcopy_ram() || migrate_return_path()) {
3925         if (open_return_path_on_source(s)) {
3926             error_setg(&local_err, "Unable to open return-path for postcopy");
3927             goto fail;
3928         }
3929     }
3930 
3931     /*
3932      * This needs to be done before resuming a postcopy.  Note: for newer
3933      * QEMUs we will delay the channel creation until postcopy_start(), to
3934      * avoid disorder of channel creations.
3935      */
3936     if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3937         postcopy_preempt_setup(s);
3938     }
3939 
3940     if (resume) {
3941         /* Wakeup the main migration thread to do the recovery */
3942         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP,
3943                           MIGRATION_STATUS_POSTCOPY_RECOVER);
3944         qemu_sem_post(&s->postcopy_pause_sem);
3945         return;
3946     }
3947 
3948     if (migrate_mode_is_cpr(s)) {
3949         ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
3950         if (ret < 0) {
3951             error_setg(&local_err, "migration_stop_vm failed, error %d", -ret);
3952             goto fail;
3953         }
3954     }
3955 
3956     /*
3957      * Take a refcount to make sure the migration object won't get freed by
3958      * the main thread already in migration_shutdown().
3959      *
3960      * The refcount will be released at the end of the thread function.
3961      */
3962     object_ref(OBJECT(s));
3963 
3964     if (migrate_background_snapshot()) {
3965         qemu_thread_create(&s->thread, MIGRATION_THREAD_SNAPSHOT,
3966                 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
3967     } else {
3968         qemu_thread_create(&s->thread, MIGRATION_THREAD_SRC_MAIN,
3969                 migration_thread, s, QEMU_THREAD_JOINABLE);
3970     }
3971     s->migration_thread_running = true;
3972     return;
3973 
3974 fail:
3975     migrate_set_error(s, local_err);
3976     if (s->state != MIGRATION_STATUS_CANCELLING) {
3977         migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3978     }
3979     error_report_err(local_err);
3980     migration_cleanup(s);
3981 }
3982 
3983 static void migration_class_init(ObjectClass *klass, void *data)
3984 {
3985     DeviceClass *dc = DEVICE_CLASS(klass);
3986 
3987     dc->user_creatable = false;
3988     device_class_set_props_n(dc, migration_properties,
3989                              migration_properties_count);
3990 }
3991 
3992 static void migration_instance_finalize(Object *obj)
3993 {
3994     MigrationState *ms = MIGRATION_OBJ(obj);
3995 
3996     qemu_mutex_destroy(&ms->error_mutex);
3997     qemu_mutex_destroy(&ms->qemu_file_lock);
3998     qemu_sem_destroy(&ms->wait_unplug_sem);
3999     qemu_sem_destroy(&ms->rate_limit_sem);
4000     qemu_sem_destroy(&ms->pause_sem);
4001     qemu_sem_destroy(&ms->postcopy_pause_sem);
4002     qemu_sem_destroy(&ms->rp_state.rp_sem);
4003     qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
4004     qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
4005     error_free(ms->error);
4006 }
4007 
4008 static void migration_instance_init(Object *obj)
4009 {
4010     MigrationState *ms = MIGRATION_OBJ(obj);
4011 
4012     ms->state = MIGRATION_STATUS_NONE;
4013     ms->mbps = -1;
4014     ms->pages_per_second = -1;
4015     qemu_sem_init(&ms->pause_sem, 0);
4016     qemu_mutex_init(&ms->error_mutex);
4017 
4018     migrate_params_init(&ms->parameters);
4019 
4020     qemu_sem_init(&ms->postcopy_pause_sem, 0);
4021     qemu_sem_init(&ms->rp_state.rp_sem, 0);
4022     qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
4023     qemu_sem_init(&ms->rate_limit_sem, 0);
4024     qemu_sem_init(&ms->wait_unplug_sem, 0);
4025     qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4026     qemu_mutex_init(&ms->qemu_file_lock);
4027 }
4028 
4029 /*
4030  * Return true if check pass, false otherwise. Error will be put
4031  * inside errp if provided.
4032  */
4033 static bool migration_object_check(MigrationState *ms, Error **errp)
4034 {
4035     /* Assuming all off */
4036     bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
4037 
4038     if (!migrate_params_check(&ms->parameters, errp)) {
4039         return false;
4040     }
4041 
4042     return migrate_caps_check(old_caps, ms->capabilities, errp);
4043 }
4044 
4045 static const TypeInfo migration_type = {
4046     .name = TYPE_MIGRATION,
4047     /*
4048      * NOTE: TYPE_MIGRATION is not really a device, as the object is
4049      * not created using qdev_new(), it is not attached to the qdev
4050      * device tree, and it is never realized.
4051      *
4052      * TODO: Make this TYPE_OBJECT once QOM provides something like
4053      * TYPE_DEVICE's "-global" properties.
4054      */
4055     .parent = TYPE_DEVICE,
4056     .class_init = migration_class_init,
4057     .class_size = sizeof(MigrationClass),
4058     .instance_size = sizeof(MigrationState),
4059     .instance_init = migration_instance_init,
4060     .instance_finalize = migration_instance_finalize,
4061 };
4062 
4063 static void register_migration_types(void)
4064 {
4065     type_register_static(&migration_type);
4066 }
4067 
4068 type_init(register_migration_types);
4069