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