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