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