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