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