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