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