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