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