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