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