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