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