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