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